code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services.protobuf; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.util.Beta; import java.io.IOException; /** * {@link Beta} <br/> * Google protocol buffer client request initializer implementation for setting properties like key * and userIp. * * <p> * The simplest usage is to use it to set the key parameter: * </p> * * <pre> public static final GoogleClientRequestInitializer KEY_INITIALIZER = new CommonGoogleProtoClientRequestInitializer(KEY); * </pre> * * <p> * There is also a constructor to set both the key and userIp parameters: * </p> * * <pre> public static final GoogleClientRequestInitializer INITIALIZER = new CommonGoogleProtoClientRequestInitializer(KEY, USER_IP); * </pre> * * <p> * If you want to implement custom logic, extend it like this: * </p> * * <pre> public static class MyRequestInitializer extends CommonGoogleProtoClientRequestInitializer { {@literal @}Override public void initialize(AbstractGoogleProtoClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: * </p> * * <pre> public static class MyKeyRequestInitializer extends CommonGoogleProtoClientRequestInitializer { public MyKeyRequestInitializer() { super(KEY, USER_IP); } {@literal @}Override public void initializeProtoRequest( AbstractGoogleProtoClientRequest{@literal <}?{@literal >} request) throws IOException { // custom logic } } * </pre> * * <p> * Subclasses should be thread-safe. * </p> * * @since 1.16 * @author Yaniv Inbar */ @Beta public class CommonGoogleProtoClientRequestInitializer extends CommonGoogleClientRequestInitializer { public CommonGoogleProtoClientRequestInitializer() { super(); } /** * @param key API key or {@code null} to leave it unchanged */ public CommonGoogleProtoClientRequestInitializer(String key) { super(key); } /** * @param key API key or {@code null} to leave it unchanged * @param userIp user IP or {@code null} to leave it unchanged */ public CommonGoogleProtoClientRequestInitializer(String key, String userIp) { super(key, userIp); } @Override public final void initialize(AbstractGoogleClientRequest<?> request) throws IOException { super.initialize(request); initializeProtoRequest((AbstractGoogleProtoClientRequest<?>) request); } /** * Initializes a Google protocol buffer client request. * * <p> * Default implementation does nothing. Called from * {@link #initialize(AbstractGoogleClientRequest)}. * </p> * * @throws IOException I/O exception */ protected void initializeProtoRequest(AbstractGoogleProtoClientRequest<?> request) throws IOException { } }
0912116-hsncloudnotes
google-api-client-protobuf/src/main/java/com/google/api/client/googleapis/services/protobuf/CommonGoogleProtoClientRequestInitializer.java
Java
asf20
3,658
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services.protobuf; import com.google.api.client.googleapis.services.AbstractGoogleClient; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.protobuf.ProtoObjectParser; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe Google protocol buffer client. * * @since 1.16 * @author Yaniv Inbar */ @Beta public abstract class AbstractGoogleProtoClient extends AbstractGoogleClient { /** * @param builder builder */ protected AbstractGoogleProtoClient(Builder builder) { super(builder); } @Override public ProtoObjectParser getObjectParser() { return (ProtoObjectParser) super.getObjectParser(); } /** * {@link Beta} <br/> * Builder for {@link AbstractGoogleProtoClient}. * * <p> * Implementation is not thread-safe. * </p> * @since 1.16 */ @Beta public abstract static class Builder extends AbstractGoogleClient.Builder { /** * @param transport HTTP transport * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ protected Builder(HttpTransport transport, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer) { super(transport, rootUrl, servicePath, new ProtoObjectParser(), httpRequestInitializer); } @Override public final ProtoObjectParser getObjectParser() { return (ProtoObjectParser) super.getObjectParser(); } @Override public abstract AbstractGoogleProtoClient build(); @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
0912116-hsncloudnotes
google-api-client-protobuf/src/main/java/com/google/api/client/googleapis/services/protobuf/AbstractGoogleProtoClient.java
Java
asf20
3,783
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Contains the basis for the generated service-specific libraries based on the Protobuf format. * * @since 1.16 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.services.protobuf;
0912116-hsncloudnotes
google-api-client-protobuf/src/main/java/com/google/api/client/googleapis/services/protobuf/package-info.java
Java
asf20
879
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.services.protobuf; import com.google.api.client.googleapis.batch.BatchCallback; import com.google.api.client.googleapis.batch.BatchRequest; import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.http.protobuf.ProtoHttpContent; import com.google.api.client.util.Beta; import com.google.protobuf.MessageLite; import java.io.IOException; /** * {@link Beta} <br/> * Google protocol buffer request for a {@link AbstractGoogleProtoClient}. * * <p> * Implementation is not thread-safe. * </p> * * @param <T> type of the response * @since 1.16 * @author Yaniv Inbar */ @Beta public abstract class AbstractGoogleProtoClientRequest<T> extends AbstractGoogleClientRequest<T> { /** Message to serialize or {@code null} for none. */ private final MessageLite message; /** * @param abstractGoogleProtoClient Google protocol buffer client * @param requestMethod HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param message message to serialize or {@code null} for none * @param responseClass response class to parse into */ protected AbstractGoogleProtoClientRequest(AbstractGoogleProtoClient abstractGoogleProtoClient, String requestMethod, String uriTemplate, MessageLite message, Class<T> responseClass) { super(abstractGoogleProtoClient, requestMethod, uriTemplate, message == null ? null : new ProtoHttpContent(message), responseClass); this.message = message; } @Override public AbstractGoogleProtoClient getAbstractGoogleClient() { return (AbstractGoogleProtoClient) super.getAbstractGoogleClient(); } @Override public AbstractGoogleProtoClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (AbstractGoogleProtoClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public AbstractGoogleProtoClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (AbstractGoogleProtoClientRequest<T>) super.setRequestHeaders(headers); } /** * Queues the request into the specified batch request container. * * <p> * Batched requests are then executed when {@link BatchRequest#execute()} is called. * </p> * <p> * Example usage: * </p> * * <pre> * request.queue(batchRequest, new BatchCallback{@literal <}SomeResponseType, Void{@literal >}() { public void onSuccess(SomeResponseType content, HttpHeaders responseHeaders) { log("Success"); } public void onFailure(Void unused, HttpHeaders responseHeaders) { log(e.getMessage()); } }); * </pre> * * * @param batchRequest batch request container * @param callback batch callback */ public final void queue(BatchRequest batchRequest, BatchCallback<T, Void> callback) throws IOException { super.queue(batchRequest, Void.class, callback); } /** Returns the message to serialize or {@code null} for none. */ public Object getMessage() { return message; } @Override public AbstractGoogleProtoClientRequest<T> set(String fieldName, Object value) { return (AbstractGoogleProtoClientRequest<T>) super.set(fieldName, value); } }
0912116-hsncloudnotes
google-api-client-protobuf/src/main/java/com/google/api/client/googleapis/services/protobuf/AbstractGoogleProtoClientRequest.java
Java
asf20
4,208
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.testing.services.protobuf; import com.google.api.client.googleapis.services.GoogleClientRequestInitializer; import com.google.api.client.googleapis.services.protobuf.AbstractGoogleProtoClient; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Thread-safe mock Google protocol buffer client. * * @since 1.16 * @author Yaniv Inbar */ @Beta public class MockGoogleProtoClient extends AbstractGoogleProtoClient { /** * @param builder builder */ protected MockGoogleProtoClient(Builder builder) { super(builder); } /** * @param transport HTTP transport * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ public MockGoogleProtoClient(HttpTransport transport, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, rootUrl, servicePath, httpRequestInitializer)); } /** * {@link Beta} <br/> * Builder for {@link MockGoogleProtoClient}. * * <p> * Implementation is not thread-safe. * </p> */ @Beta public static class Builder extends AbstractGoogleProtoClient.Builder { /** * @param transport HTTP transport * @param rootUrl root URL of the service * @param servicePath service path * @param httpRequestInitializer HTTP request initializer or {@code null} for none */ public Builder(HttpTransport transport, String rootUrl, String servicePath, HttpRequestInitializer httpRequestInitializer) { super(transport, rootUrl, servicePath, httpRequestInitializer); } @Override public MockGoogleProtoClient build() { return new MockGoogleProtoClient(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setGoogleClientRequestInitializer( GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } @Override public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } } }
0912116-hsncloudnotes
google-api-client-protobuf/src/main/java/com/google/api/client/googleapis/testing/services/protobuf/MockGoogleProtoClient.java
Java
asf20
3,921
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Test utilities for the {@code com.google.api.client.googleapis.protobuf} package. * * @since 1.16 * @author Yaniv Inbar */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.testing.services.protobuf;
0912116-hsncloudnotes
google-api-client-protobuf/src/main/java/com/google/api/client/googleapis/testing/services/protobuf/package-info.java
Java
asf20
875
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.testing.services.protobuf; import com.google.api.client.googleapis.services.protobuf.AbstractGoogleProtoClient; import com.google.api.client.googleapis.services.protobuf.AbstractGoogleProtoClientRequest; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.UriTemplate; import com.google.api.client.util.Beta; import com.google.protobuf.MessageLite; /** * {@link Beta} <br/> * Thread-safe mock Google protocol buffer request. * * @param <T> type of the response * @since 1.16 * @author Yaniv Inbar */ @Beta public class MockGoogleProtoClientRequest<T> extends AbstractGoogleProtoClientRequest<T> { /** * @param client Google client * @param method HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link UriTemplate#expand(String, String, Object, boolean)} * @param message message to serialize or {@code null} for none * @param responseClass response class to parse into */ public MockGoogleProtoClientRequest(AbstractGoogleProtoClient client, String method, String uriTemplate, MessageLite message, Class<T> responseClass) { super(client, method, uriTemplate, message, responseClass); } @Override public MockGoogleProtoClient getAbstractGoogleClient() { return (MockGoogleProtoClient) super.getAbstractGoogleClient(); } @Override public MockGoogleProtoClientRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (MockGoogleProtoClientRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public MockGoogleProtoClientRequest<T> setRequestHeaders(HttpHeaders headers) { return (MockGoogleProtoClientRequest<T>) super.setRequestHeaders(headers); } }
0912116-hsncloudnotes
google-api-client-protobuf/src/main/java/com/google/api/client/googleapis/testing/services/protobuf/MockGoogleProtoClientRequest.java
Java
asf20
2,548
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * Google OAuth 2.0 utilities that help simplify the authorization flow on Java 6. * * @since 1.11 * @author Yaniv Inbar */ package com.google.api.client.googleapis.extensions.java6.auth.oauth2;
0912116-hsncloudnotes
google-api-client-java6/src/main/java/com/google/api/client/googleapis/extensions/java6/auth/oauth2/package-info.java
Java
asf20
794
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.extensions.java6.auth.oauth2; import com.google.api.client.extensions.java6.auth.oauth2.AbstractPromptReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants; import java.io.IOException; /** * Google OAuth 2.0 abstract verification code receiver that prompts user to paste the code copied * from the browser. * * <p> * Implementation is thread-safe. * </p> * * @since 1.11 * @author Yaniv Inbar */ public class GooglePromptReceiver extends AbstractPromptReceiver { @Override public String getRedirectUri() throws IOException { return GoogleOAuthConstants.OOB_REDIRECT_URI; } }
0912116-hsncloudnotes
google-api-client-java6/src/main/java/com/google/api/client/googleapis/extensions/java6/auth/oauth2/GooglePromptReceiver.java
Java
asf20
1,259
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.extensions.servlet.notifications; import com.google.api.client.googleapis.notifications.StoredChannel; import com.google.api.client.googleapis.notifications.UnparsedNotification; import com.google.api.client.googleapis.notifications.UnparsedNotificationCallback; import com.google.api.client.util.Beta; import com.google.api.client.util.LoggingInputStream; import com.google.api.client.util.Preconditions; import com.google.api.client.util.StringUtils; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * Utilities for Webhook notifications. * * @author Yaniv Inbar * @since 1.16 */ @Beta public final class WebhookUtils { static final Logger LOGGER = Logger.getLogger(WebhookUtils.class.getName()); /** Webhook notification channel type to use in the watch request. */ public static final String TYPE = "web_hook"; /** * Utility method to process the webhook notification from {@link HttpServlet#doPost} by finding * the notification channel in the given data store factory. * * <p> * It is a wrapper around * {@link #processWebhookNotification(HttpServletRequest, HttpServletResponse, DataStore)} that * uses the data store from {@link StoredChannel#getDefaultDataStore(DataStoreFactory)}. * </p> * * @param req an {@link HttpServletRequest} object that contains the request the client has made * of the servlet * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends * to the client * @param dataStoreFactory data store factory * @exception IOException if an input or output error is detected when the servlet handles the * request * @exception ServletException if the request for the POST could not be handled */ public static void processWebhookNotification( HttpServletRequest req, HttpServletResponse resp, DataStoreFactory dataStoreFactory) throws ServletException, IOException { processWebhookNotification(req, resp, StoredChannel.getDefaultDataStore(dataStoreFactory)); } /** * Utility method to process the webhook notification from {@link HttpServlet#doPost}. * * <p> * The {@link HttpServletRequest#getInputStream()} is closed in a finally block inside this * method. If it is not detected to be a webhook notification, an * {@link HttpServletResponse#SC_BAD_REQUEST} error will be displayed. If the notification channel * is found in the given notification channel data store, it will call * {@link UnparsedNotificationCallback#onNotification} for the registered notification callback * method. * </p> * * @param req an {@link HttpServletRequest} object that contains the request the client has made * of the servlet * @param resp an {@link HttpServletResponse} object that contains the response the servlet sends * to the client * @param channelDataStore notification channel data store * @exception IOException if an input or output error is detected when the servlet handles the * request * @exception ServletException if the request for the POST could not be handled */ public static void processWebhookNotification( HttpServletRequest req, HttpServletResponse resp, DataStore<StoredChannel> channelDataStore) throws ServletException, IOException { Preconditions.checkArgument("POST".equals(req.getMethod())); InputStream contentStream = req.getInputStream(); try { // log headers if (LOGGER.isLoggable(Level.CONFIG)) { StringBuilder builder = new StringBuilder(); Enumeration<?> e = req.getHeaderNames(); if (e != null) { while (e.hasMoreElements()) { Object nameObj = e.nextElement(); if (nameObj instanceof String) { String name = (String) nameObj; Enumeration<?> ev = req.getHeaders(name); if (ev != null) { while (ev.hasMoreElements()) { builder.append(name) .append(": ").append(ev.nextElement()).append(StringUtils.LINE_SEPARATOR); } } } } } LOGGER.config(builder.toString()); contentStream = new LoggingInputStream(contentStream, LOGGER, Level.CONFIG, 0x4000); // TODO(yanivi): allow to override logging content limit } // parse the relevant headers, and create a notification Long messageNumber; try { messageNumber = Long.valueOf(req.getHeader(WebhookHeaders.MESSAGE_NUMBER)); } catch (NumberFormatException e) { messageNumber = null; } String resourceState = req.getHeader(WebhookHeaders.RESOURCE_STATE); String resourceId = req.getHeader(WebhookHeaders.RESOURCE_ID); String resourceUri = req.getHeader(WebhookHeaders.RESOURCE_URI); String channelId = req.getHeader(WebhookHeaders.CHANNEL_ID); String channelExpiration = req.getHeader(WebhookHeaders.CHANNEL_EXPIRATION); String channelToken = req.getHeader(WebhookHeaders.CHANNEL_TOKEN); String changed = req.getHeader(WebhookHeaders.CHANGED); if (messageNumber == null || resourceState == null || resourceId == null || resourceUri == null || channelId == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Notification did not contain all required information."); return; } UnparsedNotification notification = new UnparsedNotification(messageNumber, resourceState, resourceId, resourceUri, channelId).setChannelExpiration(channelExpiration) .setChannelToken(channelToken) .setChanged(changed) .setContentType(req.getContentType()) .setContentStream(contentStream); // check if we know about the channel, hand over the notification to the notification callback StoredChannel storedChannel = channelDataStore.get(notification.getChannelId()); if (storedChannel != null) { storedChannel.getNotificationCallback().onNotification(storedChannel, notification); } } finally { contentStream.close(); } } private WebhookUtils() { } }
0912116-hsncloudnotes
google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/notifications/WebhookUtils.java
Java
asf20
7,231
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for subscribing to topics and receiving notifications on servlet-based platforms. * * @author Yaniv Inbar * @since 1.16 */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.servlet.notifications;
0912116-hsncloudnotes
google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/notifications/package-info.java
Java
asf20
890
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.extensions.servlet.notifications; import com.google.api.client.googleapis.notifications.StoredChannel; import com.google.api.client.util.Beta; import com.google.api.client.util.store.DataStore; import com.google.api.client.util.store.DataStoreFactory; import com.google.api.client.util.store.MemoryDataStoreFactory; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * Thread-safe Webhook Servlet to receive notifications. * * <p> * In order to use this servlet you should create a class inheriting from * {@link NotificationServlet} and register the servlet in your web.xml. * </p> * * <p> * It is a simple wrapper around {@link WebhookUtils#processWebhookNotification}, so if you you may * alternatively call that method instead from your {@link HttpServlet#doPost} with no loss of * functionality. * </p> * * <b>Example usage:</b> * * <pre> public class MyNotificationServlet extends NotificationServlet { private static final long serialVersionUID = 1L; public MyNotificationServlet() throws IOException { super(new SomeDataStoreFactory()); } } * </pre> * * <b>Sample web.xml setup:</b> * * <pre> {@literal <}servlet{@literal >} {@literal <}servlet-name{@literal >}MyNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}servlet-class{@literal >}com.mypackage.MyNotificationServlet{@literal <}/servlet-class{@literal >} {@literal <}/servlet{@literal >} {@literal <}servlet-mapping{@literal >} {@literal <}servlet-name{@literal >}MyNotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}url-pattern{@literal >}/notifications{@literal <}/url-pattern{@literal >} {@literal <}/servlet-mapping{@literal >} * </pre> * * <p> * WARNING: by default it uses {@link MemoryDataStoreFactory#getDefaultInstance()} which means it * will NOT persist the notification channels when the servlet process dies, so it is a BAD CHOICE * for a production application. But it is a convenient choice when testing locally, in which case * you don't need to override it, and can simply reference it directly in your web.xml file. For * example: * </p> * * <pre> {@literal <}servlet{@literal >} {@literal <}servlet-name{@literal >}NotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}servlet-class{@literal >}com.google.api.client.googleapis.extensions.servlet.notificationsNotificationServlet{@literal <}/servlet-class{@literal >} {@literal <}/servlet{@literal >} {@literal <}servlet-mapping{@literal >} {@literal <}servlet-name{@literal >}NotificationServlet{@literal <}/servlet-name{@literal >} {@literal <}url-pattern{@literal >}/notifications{@literal <}/url-pattern{@literal >} {@literal <}/servlet-mapping{@literal >} * </pre> * * @author Yaniv Inbar * @since 1.16 */ @Beta public class NotificationServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** Notification channel data store. */ private final transient DataStore<StoredChannel> channelDataStore; /** * Constructor to be used for testing and demo purposes that uses * {@link MemoryDataStoreFactory#getDefaultInstance()} which means it will NOT persist the * notification channels when the servlet process dies, so it is a bad choice for a production * application. */ public NotificationServlet() throws IOException { this(MemoryDataStoreFactory.getDefaultInstance()); } /** * Constructor which uses {@link StoredChannel#getDefaultDataStore(DataStoreFactory)} on the given * data store factory, which is the normal use case. * * @param dataStoreFactory data store factory */ protected NotificationServlet(DataStoreFactory dataStoreFactory) throws IOException { this(StoredChannel.getDefaultDataStore(dataStoreFactory)); } /** * Constructor that allows a specific notification data store to be specified. * * @param channelDataStore notification channel data store */ protected NotificationServlet(DataStore<StoredChannel> channelDataStore) { this.channelDataStore = channelDataStore; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { WebhookUtils.processWebhookNotification(req, resp, channelDataStore); } }
0912116-hsncloudnotes
google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/notifications/NotificationServlet.java
Java
asf20
5,131
/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.extensions.servlet.notifications; import com.google.api.client.googleapis.notifications.ResourceStates; import com.google.api.client.util.Beta; /** * {@link Beta} <br/> * Headers for Webhook notifications. * * @author Yaniv Inbar * @since 1.16 */ @Beta public final class WebhookHeaders { /** Name of header for the message number (a monotonically increasing value starting with 1). */ public static final String MESSAGE_NUMBER = "X-Goog-Message-Number"; /** Name of header for the {@link ResourceStates resource state}. */ public static final String RESOURCE_STATE = "X-Goog-Resource-State"; /** * Name of header for the opaque ID for the watched resource that is stable across API versions. */ public static final String RESOURCE_ID = "X-Goog-Resource-ID"; /** * Name of header for the opaque ID (in the form of a canonicalized URI) for the watched resource * that is sensitive to the API version. */ public static final String RESOURCE_URI = "X-Goog-Resource-URI"; /** * Name of header for the notification channel UUID provided by the client in the watch request. */ public static final String CHANNEL_ID = "X-Goog-Channel-ID"; /** Name of header for the notification channel expiration time. */ public static final String CHANNEL_EXPIRATION = "X-Goog-Channel-Expiration"; /** * Name of header for the notification channel token (an opaque string) provided by the client in * the watch request. */ public static final String CHANNEL_TOKEN = "X-Goog-Channel-Token"; /** Name of header for the type of change performed on the resource. */ public static final String CHANGED = "X-Goog-Changed"; private WebhookHeaders() { } }
0912116-hsncloudnotes
google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/notifications/WebhookHeaders.java
Java
asf20
2,341
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /** * {@link com.google.api.client.util.Beta} <br/> * Support for subscribing to topics and receiving notifications on servlet-based platforms. * * @since 1.14 * @author Matthias Linder (mlinder) */ @com.google.api.client.util.Beta package com.google.api.client.googleapis.extensions.servlet.subscriptions;
0912116-hsncloudnotes
google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/subscriptions/package-info.java
Java
asf20
904
/* * Copyright (c) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.extensions.servlet.subscriptions; import com.google.api.client.googleapis.subscriptions.StoredSubscription; import com.google.api.client.googleapis.subscriptions.SubscriptionStore; import com.google.api.client.util.Beta; import com.google.api.client.util.Lists; import com.google.api.client.util.Preconditions; import java.util.List; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * {@link Beta} <br/> * {@link SubscriptionStore} making use of JDO. * * <p> * Implementation is thread-safe. * </p> * * <b>Example usage:</b> * * <pre> service.setSubscriptionStore(new JdoSubscriptionStore()); * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @Beta public final class JdoSubscriptionStore implements SubscriptionStore { /** Persistence manager factory. */ private final PersistenceManagerFactory persistenceManagerFactory; /** * @param persistenceManagerFactory persistence manager factory */ public JdoSubscriptionStore(PersistenceManagerFactory persistenceManagerFactory) { this.persistenceManagerFactory = persistenceManagerFactory; } /** Container class for storing subscriptions in the JDO DataStore. */ @PersistenceCapable @Beta private static final class JdoStoredSubscription { @Persistent(serialized = "true") private StoredSubscription subscription; @Persistent @PrimaryKey private String subscriptionId; @SuppressWarnings("unused") JdoStoredSubscription() { } /** * Creates a stored subscription from an existing subscription. * * @param s subscription to store */ public JdoStoredSubscription(StoredSubscription s) { setSubscription(s); } /** * Returns the stored subscription. */ public StoredSubscription getSubscription() { return subscription; } /** * Returns the subscription ID. */ @SuppressWarnings("unused") public String getSubscriptionId() { return subscriptionId; } /** * Changes the subscription stored in this database entry. * * @param subscription The new subscription to store */ public void setSubscription(StoredSubscription subscription) { this.subscription = subscription; this.subscriptionId = subscription.getId(); } } public void storeSubscription(StoredSubscription subscription) { Preconditions.checkNotNull(subscription); JdoStoredSubscription dbEntry = getStoredSubscription(subscription.getId()); PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager(); try { // Check if this subscription is being updated or newly created if (dbEntry != null) { // Existing entry dbEntry.setSubscription(subscription); } else { // New entry dbEntry = new JdoStoredSubscription(subscription); persistenceManager.makePersistent(dbEntry); } } finally { persistenceManager.close(); } } public void removeSubscription(StoredSubscription subscription) { JdoStoredSubscription dbEntry = getStoredSubscription(subscription.getId()); if (dbEntry != null) { PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager(); try { persistenceManager.deletePersistent(dbEntry); } finally { persistenceManager.close(); } } } @SuppressWarnings("unchecked") public List<StoredSubscription> listSubscriptions() { // Copy the results into a db-detached list. List<StoredSubscription> list = Lists.newArrayList(); PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager(); try { Query listQuery = persistenceManager.newQuery(JdoStoredSubscription.class); Iterable<JdoStoredSubscription> resultList = (Iterable<JdoStoredSubscription>) listQuery.execute(); for (JdoStoredSubscription dbEntry : resultList) { list.add(dbEntry.getSubscription()); } } finally { persistenceManager.close(); } return list; } @SuppressWarnings("unchecked") private JdoStoredSubscription getStoredSubscription(String subscriptionID) { Iterable<JdoStoredSubscription> results = null; PersistenceManager persistenceManager = persistenceManagerFactory.getPersistenceManager(); try { Query getByIDQuery = persistenceManager.newQuery(JdoStoredSubscription.class); getByIDQuery.setFilter("subscriptionId == idParam"); getByIDQuery.declareParameters("String idParam"); getByIDQuery.setRange(0, 1); results = (Iterable<JdoStoredSubscription>) getByIDQuery.execute(subscriptionID); // return the first result for (JdoStoredSubscription dbEntry : results) { return dbEntry; } return null; } finally { persistenceManager.close(); } } public StoredSubscription getSubscription(String subscriptionID) { JdoStoredSubscription dbEntry = getStoredSubscription(subscriptionID); return dbEntry == null ? null : dbEntry.getSubscription(); } }
0912116-hsncloudnotes
google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/subscriptions/JdoSubscriptionStore.java
Java
asf20
5,919
/* * Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.api.client.googleapis.extensions.servlet.subscriptions; import com.google.api.client.googleapis.subscriptions.NotificationHeaders; import com.google.api.client.googleapis.subscriptions.SubscriptionStore; import com.google.api.client.googleapis.subscriptions.UnparsedNotification; import com.google.api.client.util.Beta; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * {@link Beta} <br/> * WebHook Servlet to receive {@link UnparsedNotification}. * * <p> * In order to use this servlet you should create a class inheriting from * {@link AbstractWebHookServlet} and register the servlet in your web.xml. * </p> * * <p> * Implementation is thread-safe. * </p> * * <b>Example usage:</b> * * <pre> public class NotificationServlet extends AbstractWebHookServlet { private static final long serialVersionUID = 1L; {@literal @}Override protected SubscriptionStore createSubscriptionStore() { return new CachedAppEngineSubscriptionStore(); } } * </pre> * * <b>web.xml setup:</b> * * <pre> &lt;servlet&gt; &lt;servlet-name&gt;NotificationServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;com.mypackage.NotificationServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;NotificationServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/notificiations&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;security-constraint&gt; &lt;!-- Lift any ACL imposed upon the servlet --&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;any&lt;/web-resource-name&gt; &lt;url-pattern&gt;/notifications&lt;/url-pattern&gt; &lt;/web-resource-collection&gt; &lt;/security-constraint&gt; * </pre> * * @author Matthias Linder (mlinder) * @since 1.14 */ @SuppressWarnings("serial") @Beta public abstract class AbstractWebHookServlet extends HttpServlet { /** * Name of header for the ID of the subscription for which you no longer wish to receive * notifications (used in the response to a WebHook notification). */ public static final String UNSUBSCRIBE_HEADER = "X-Goog-Unsubscribe"; /** Subscription store or {@code null} before initialized in {@link #getSubscriptionStore()}. */ private static SubscriptionStore subscriptionStore; /** * Used to get access to the subscription store in order to handle incoming notifications. */ protected abstract SubscriptionStore createSubscriptionStore(); /** Returns the (cached) subscription store. */ public final synchronized SubscriptionStore getSubscriptionStore() { if (subscriptionStore == null) { subscriptionStore = createSubscriptionStore(); } return subscriptionStore; } /** * Responds to a notification with a 200 OK response with the X-Unsubscribe header which causes * the subscription to be removed. */ protected void sendUnsubscribeResponse( HttpServletResponse resp, UnparsedNotification notification) { // Subscriptions can be removed by sending an 200 OK with the X-Unsubscribe header. resp.setStatus(HttpServletResponse.SC_OK); resp.setHeader(UNSUBSCRIBE_HEADER, notification.getSubscriptionId()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Parse the relevant headers and create an unparsed notification. String subscriptionId = req.getHeader(NotificationHeaders.SUBSCRIPTION_ID); String topicId = req.getHeader(NotificationHeaders.TOPIC_ID); String topicUri = req.getHeader(NotificationHeaders.TOPIC_URI); String eventType = req.getHeader(NotificationHeaders.EVENT_TYPE_HEADER); String clientToken = req.getHeader(NotificationHeaders.CLIENT_TOKEN); String messageNumber = req.getHeader(NotificationHeaders.MESSAGE_NUMBER_HEADER); String changeType = req.getHeader(NotificationHeaders.CHANGED_HEADER); if (subscriptionId == null || topicId == null || topicUri == null || eventType == null || messageNumber == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Notification did not contain all required information."); return; } // Hand over the unparsed notification to the subscription manager. InputStream contentStream = req.getInputStream(); try { UnparsedNotification notification = new UnparsedNotification(subscriptionId, topicId, topicUri, clientToken, Long.valueOf(messageNumber), eventType, changeType, req.getContentType(), contentStream); if (!notification.deliverNotification(getSubscriptionStore())) { sendUnsubscribeResponse(resp, notification); } } finally { contentStream.close(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } }
0912116-hsncloudnotes
google-api-client-servlet/src/main/java/com/google/api/client/googleapis/extensions/servlet/subscriptions/AbstractWebHookServlet.java
Java
asf20
5,855
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_ordenes.java * * Created on 10/04/2011, 05:29:28 PM */ package vistas; import controladores.controlador_ordenes; import controladores.controlador_productos; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class vista_ordenes extends javax.swing.JFrame { DefaultTableModel modelo_tabla= new DefaultTableModel(); /** Creates new form vista_producto */ public vista_ordenes() { initComponents(); jTable_ordenes.setModel(modelo_tabla); Vector<String> a = new Vector<String>(); a.add("producto"); a.add("cantidad"); a.add("precio"); modelo_tabla.setColumnIdentifiers(a); listen_botones(); cancelar(); } public void cancelar() { modelo_tabla.setRowCount(0); jtxt_nombre.setText(""); } public void listen_botones() { controlador_ordenes co = new controlador_ordenes(this); co.cargar_producto(); boton_mas.addActionListener (co); boton_mas.setActionCommand("mas"); boton_menos.addActionListener(co); boton_menos.setActionCommand("menos"); boton_registrar.addActionListener(co); boton_registrar.setActionCommand("registrar"); } public JButton getBoton_mas() { return boton_mas; } public void setBoton_mas(JButton boton_mas) { this.boton_mas = boton_mas; } public JButton getBoton_menos() { return boton_menos; } public void setBoton_menos(JButton boton_menos) { this.boton_menos = boton_menos; } public JButton getBoton_registrar() { return boton_registrar; } public void setBoton_registrar(JButton boton_registrar) { this.boton_registrar = boton_registrar; } public JComboBox getCmb_producto() { return cmb_producto; } public void setCmb_producto(JComboBox cmb_producto) { this.cmb_producto = cmb_producto; } public JTable getjTable_ordenes() { return jTable_ordenes; } public void setjTable_ordenes(JTable jTable_ordenes) { this.jTable_ordenes = jTable_ordenes; } public JTextField getJtxt_nombre() { return jtxt_nombre; } public void setJtxt_nombre(JTextField jtxt_nombre) { this.jtxt_nombre = jtxt_nombre; } public JTextField getJtxt_total() { return jtxt_total; } public void setJtxt_total(JTextField jtxt_total) { this.jtxt_total = jtxt_total; } public JSpinner getJtxtcantidad() { return jtxtcantidad; } public void setJtxtcantidad(JSpinner jtxtcantidad) { this.jtxtcantidad = jtxtcantidad; } public DefaultTableModel getModelo_tabla() { return modelo_tabla; } public void setModelo_tabla(DefaultTableModel modelo_tabla) { this.modelo_tabla = modelo_tabla; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel2 = new javax.swing.JLabel(); jtxt_nombre = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); cmb_producto = new javax.swing.JComboBox(); boton_mas = new javax.swing.JButton(); boton_menos = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_ordenes = new javax.swing.JTable(); boton_registrar = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); jtxtcantidad = new javax.swing.JSpinner(); jLabel8 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jtxt_total = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); jLabel2.setText("Cliente"); getContentPane().add(jLabel2); jLabel2.setBounds(10, 90, 90, 18); getContentPane().add(jtxt_nombre); jtxt_nombre.setBounds(100, 80, 240, 28); jLabel6.setText("producto"); getContentPane().add(jLabel6); jLabel6.setBounds(10, 120, 120, 20); cmb_producto.setModel(new javax.swing.DefaultComboBoxModel(new String[] {})); cmb_producto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmb_productoActionPerformed(evt); } }); getContentPane().add(cmb_producto); cmb_producto.setBounds(100, 120, 410, 30); boton_mas.setText("+"); boton_mas.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_masActionPerformed(evt); } }); getContentPane().add(boton_mas); boton_mas.setBounds(530, 120, 40, 30); boton_menos.setText("-"); getContentPane().add(boton_menos); boton_menos.setBounds(580, 120, 40, 30); jTable_ordenes.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "producto", "precio", "cantidad" } )); jScrollPane1.setViewportView(jTable_ordenes); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(10, 160, 780, 330); boton_registrar.setText("registrar"); getContentPane().add(boton_registrar); boton_registrar.setBounds(310, 500, 150, 40); jLabel9.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel9.setText("Registrar Ordenes"); getContentPane().add(jLabel9); jLabel9.setBounds(250, 10, 290, 40); getContentPane().add(jtxtcantidad); jtxtcantidad.setBounds(710, 120, 40, 28); jLabel8.setText("cantidad"); getContentPane().add(jLabel8); jLabel8.setBounds(630, 120, 120, 20); jLabel1.setText("Total a pagar"); getContentPane().add(jLabel1); jLabel1.setBounds(470, 520, 280, 18); jtxt_total.setEditable(false); getContentPane().add(jtxt_total); jtxt_total.setBounds(600, 510, 160, 50); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-630)/2, 802, 630); }// </editor-fold>//GEN-END:initComponents private void cmb_productoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmb_productoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cmb_productoActionPerformed private void boton_masActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_masActionPerformed // TODO add your handling code here: }//GEN-LAST:event_boton_masActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_ordenes().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_mas; private javax.swing.JButton boton_menos; private javax.swing.JButton boton_registrar; private javax.swing.JComboBox cmb_producto; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_ordenes; private javax.swing.JTextField jtxt_nombre; private javax.swing.JTextField jtxt_total; private javax.swing.JSpinner jtxtcantidad; // End of variables declaration//GEN-END:variables }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/vistas/vista_ordenes.java
Java
asf20
8,666
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_ingredientes.java * * Created on 08/04/2011, 10:46:47 AM */ package vistas; import controladores.controlador_ingredientes; import javax.swing.JButton; import javax.swing.JTextField; public class vista_ingredientes extends javax.swing.JFrame { /** Creates new form vista_ingredientes */ public vista_ingredientes() { initComponents(); cancenlar(); listen_botones(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jtxt_descripcion = new javax.swing.JTextField(); jtxt_stock = new javax.swing.JTextField(); jtxt_id = new javax.swing.JTextField(); boton_cancelar = new javax.swing.JButton(); boton_modificar = new javax.swing.JButton(); boton_buscar = new javax.swing.JButton(); boton_registrar = new javax.swing.JButton(); boton_grabar = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jtxt_nombre = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); jLabel1.setText("ID Ingrediente"); getContentPane().add(jLabel1); jLabel1.setBounds(50, 110, 100, 18); jLabel2.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Registrar Ingredientes"); getContentPane().add(jLabel2); jLabel2.setBounds(270, 20, 290, 60); jLabel3.setText("Nombre"); getContentPane().add(jLabel3); jLabel3.setBounds(50, 160, 60, 20); jLabel4.setText("Descripcion"); getContentPane().add(jLabel4); jLabel4.setBounds(380, 110, 90, 18); getContentPane().add(jtxt_descripcion); jtxt_descripcion.setBounds(480, 110, 230, 120); getContentPane().add(jtxt_stock); jtxt_stock.setBounds(170, 200, 190, 30); getContentPane().add(jtxt_id); jtxt_id.setBounds(170, 110, 190, 30); boton_cancelar.setText("Cancelar"); boton_cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_cancelarActionPerformed(evt); } }); getContentPane().add(boton_cancelar); boton_cancelar.setBounds(570, 320, 160, 40); boton_modificar.setText("Modificar"); getContentPane().add(boton_modificar); boton_modificar.setBounds(400, 320, 160, 40); boton_buscar.setText("Buscar"); getContentPane().add(boton_buscar); boton_buscar.setBounds(60, 320, 160, 40); boton_registrar.setText("Registrar"); getContentPane().add(boton_registrar); boton_registrar.setBounds(230, 320, 160, 40); boton_grabar.setText("Grabar"); getContentPane().add(boton_grabar); boton_grabar.setBounds(400, 270, 160, 40); jLabel5.setText("stock"); getContentPane().add(jLabel5); jLabel5.setBounds(50, 210, 70, 20); getContentPane().add(jtxt_nombre); jtxt_nombre.setBounds(170, 160, 190, 30); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-430)/2, 802, 430); }// </editor-fold>//GEN-END:initComponents private void boton_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_cancelarActionPerformed // TODO add your handling code here: cancenlar(); }//GEN-LAST:event_boton_cancelarActionPerformed /** * @param args the command line arguments */ public void cancenlar() { boton_grabar.setEnabled(false); boton_modificar.setEnabled(false); boton_registrar.setEnabled(false); boton_buscar.setEnabled(true); jtxt_id.setEnabled(true); jtxt_nombre.setEnabled(false); jtxt_stock.setEnabled(false); jtxt_descripcion.setEnabled(false); jtxt_id.setText(""); jtxt_nombre.setText(""); jtxt_descripcion.setText(""); jtxt_stock.setText(""); } public void modificar() { jtxt_descripcion.setEnabled(true); jtxt_nombre.setEnabled(true); jtxt_stock.setEnabled(true); jtxt_id.setEnabled(false); boton_modificar.setEnabled(false); boton_grabar.setEnabled(true); } public void listen_botones() { controlador_ingredientes ci = new controlador_ingredientes(this); boton_buscar.addActionListener (ci); boton_buscar.setActionCommand("buscar"); boton_grabar.addActionListener(ci); boton_grabar.setActionCommand("grabar"); boton_modificar.addActionListener(ci); boton_modificar.setActionCommand("modificar"); boton_registrar.addActionListener(ci); boton_registrar.setActionCommand("registrar"); } public JButton getBoton_buscar() { return boton_buscar; } public void setBoton_buscar(JButton boton_buscar) { this.boton_buscar = boton_buscar; } public JButton getBoton_cancelar() { return boton_cancelar; } public void setBoton_cancelar(JButton boton_cancelar) { this.boton_cancelar = boton_cancelar; } public JButton getBoton_grabar() { return boton_grabar; } public void setBoton_grabar(JButton boton_grabar) { this.boton_grabar = boton_grabar; } public JButton getBoton_modificar() { return boton_modificar; } public void setBoton_modificar(JButton boton_modificar) { this.boton_modificar = boton_modificar; } public JButton getBoton_registrar() { return boton_registrar; } public void setBoton_registrar(JButton boton_registrar) { this.boton_registrar = boton_registrar; } public JTextField getJtxt_stock() { return jtxt_stock; } public void setJtxt_stock(JTextField jtxt_stock) { this.jtxt_stock = jtxt_stock; } public JTextField getJtxt_descripcion() { return jtxt_descripcion; } public void setJtxt_descripcion(JTextField jtxt_descripcion) { this.jtxt_descripcion = jtxt_descripcion; } public JTextField getJtxt_id() { return jtxt_id; } public void setJtxt_id(JTextField jtxt_id) { this.jtxt_id = jtxt_id; } public JTextField getJtxt_nombre() { return jtxt_nombre; } public void setJtxt_nombre(JTextField jtxt_nombre) { this.jtxt_nombre = jtxt_nombre; } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_ingredientes().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_buscar; private javax.swing.JButton boton_cancelar; private javax.swing.JButton boton_grabar; private javax.swing.JButton boton_modificar; private javax.swing.JButton boton_registrar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JTextField jtxt_descripcion; private javax.swing.JTextField jtxt_id; private javax.swing.JTextField jtxt_nombre; private javax.swing.JTextField jtxt_stock; // End of variables declaration//GEN-END:variables }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/vistas/vista_ingredientes.java
Java
asf20
8,296
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_producto.java * * Created on 10/04/2011, 12:21:37 PM */ package vistas; import controladores.controlador_productos; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class vista_producto extends javax.swing.JFrame { DefaultTableModel modelo_tabla= new DefaultTableModel(); /** Creates new form vista_producto */ public vista_producto() { initComponents(); jTable_producto.setModel(modelo_tabla); Vector<String> a = new Vector<String>(); a.add("nombre"); a.add("cantidad"); modelo_tabla.setColumnIdentifiers(a); listen_botones(); cancelar(); } public void cancelar() { modelo_tabla.setRowCount(0); jtxt_codigo.setText(""); jtxt_descripcion.setText(""); jtxt_nombre.setText(""); jtxt_precio.setText(""); jtxtcantidad.setValue(0); } public void listen_botones() { controlador_productos cp = new controlador_productos(this); cp.cargar_categoria(); cp.cargar_ingredientes(); boton_mas.addActionListener (cp); boton_mas.setActionCommand("mas"); boton_menos.addActionListener(cp); boton_menos.setActionCommand("menos"); boton_registrar.addActionListener(cp); boton_registrar.setActionCommand("registrar"); } public JButton getBoton_mas() { return boton_mas; } public void setBoton_mas(JButton boton_mas) { this.boton_mas = boton_mas; } public JButton getBoton_menos() { return boton_menos; } public void setBoton_menos(JButton boton_menos) { this.boton_menos = boton_menos; } public JButton getBoton_registrar() { return boton_registrar; } public void setBoton_registrar(JButton boton_registrar) { this.boton_registrar = boton_registrar; } public JComboBox getCmb_categoria() { return cmb_categoria; } public void setCmb_categoria(JComboBox cmb_categoria) { this.cmb_categoria = cmb_categoria; } public JComboBox getCmb_ingrediente() { return cmb_ingrediente; } public void setCmb_ingrediente(JComboBox cmb_ingrediente) { this.cmb_ingrediente = cmb_ingrediente; } public JTable getjTable_producto() { return jTable_producto; } public void setjTable_producto(JTable jTable_producto) { this.jTable_producto = jTable_producto; } public JTextField getJtxt_codigo() { return jtxt_codigo; } public void setJtxt_codigo(JTextField jtxt_codigo) { this.jtxt_codigo = jtxt_codigo; } public JTextField getJtxt_descripcion() { return jtxt_descripcion; } public void setJtxt_descripcion(JTextField jtxt_descripcion) { this.jtxt_descripcion = jtxt_descripcion; } public JTextField getJtxt_nombre() { return jtxt_nombre; } public void setJtxt_nombre(JTextField jtxt_nombre) { this.jtxt_nombre = jtxt_nombre; } public JTextField getJtxt_precio() { return jtxt_precio; } public void setJtxt_precio(JTextField jtxt_precio) { this.jtxt_precio = jtxt_precio; } public JSpinner getJtxtcantidad() { return jtxtcantidad; } public void setJtxtcantidad(JSpinner jtxtcantidad) { this.jtxtcantidad = jtxtcantidad; } public DefaultTableModel getModelo_tabla() { return modelo_tabla; } public void setModelo_tabla(DefaultTableModel modelo_tabla) { this.modelo_tabla = modelo_tabla; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel3 = new javax.swing.JLabel(); jtxt_codigo = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jtxt_nombre = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jtxt_precio = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); cmb_categoria = new javax.swing.JComboBox(); jLabel1 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); cmb_ingrediente = new javax.swing.JComboBox(); boton_mas = new javax.swing.JButton(); boton_menos = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); jtxt_descripcion = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); jtxtcantidad = new javax.swing.JSpinner(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_producto = new javax.swing.JTable(); jLabel9 = new javax.swing.JLabel(); boton_registrar = new javax.swing.JButton(); getContentPane().setLayout(null); jLabel3.setText("Codigo"); getContentPane().add(jLabel3); jLabel3.setBounds(10, 70, 60, 30); jtxt_codigo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jtxt_codigoActionPerformed(evt); } }); getContentPane().add(jtxt_codigo); jtxt_codigo.setBounds(110, 80, 160, 28); jLabel2.setText("nombre"); getContentPane().add(jLabel2); jLabel2.setBounds(10, 120, 90, 18); getContentPane().add(jtxt_nombre); jtxt_nombre.setBounds(110, 120, 240, 30); jLabel4.setText("precio"); getContentPane().add(jLabel4); jLabel4.setBounds(10, 220, 44, 18); getContentPane().add(jtxt_precio); jtxt_precio.setBounds(110, 210, 160, 30); jLabel5.setText("Categoria"); getContentPane().add(jLabel5); jLabel5.setBounds(10, 170, 110, 20); cmb_categoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] {})); getContentPane().add(cmb_categoria); cmb_categoria.setBounds(110, 170, 240, 28); jLabel1.setText("descripcion"); getContentPane().add(jLabel1); jLabel1.setBounds(10, 260, 100, 18); jLabel6.setText("Ingrediente"); getContentPane().add(jLabel6); jLabel6.setBounds(390, 70, 120, 20); cmb_ingrediente.setModel(new javax.swing.DefaultComboBoxModel(new String[] {})); cmb_ingrediente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmb_ingredienteActionPerformed(evt); } }); getContentPane().add(cmb_ingrediente); cmb_ingrediente.setBounds(480, 70, 190, 30); boton_mas.setText("+"); boton_mas.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_masActionPerformed(evt); } }); getContentPane().add(boton_mas); boton_mas.setBounds(680, 70, 40, 30); boton_menos.setText("-"); getContentPane().add(boton_menos); boton_menos.setBounds(730, 70, 40, 30); jLabel7.setText("Bs.F"); getContentPane().add(jLabel7); jLabel7.setBounds(280, 220, 90, 18); getContentPane().add(jtxt_descripcion); jtxt_descripcion.setBounds(110, 260, 240, 90); jLabel8.setText("cantidad"); getContentPane().add(jLabel8); jLabel8.setBounds(390, 110, 120, 20); getContentPane().add(jtxtcantidad); jtxtcantidad.setBounds(480, 110, 40, 28); jTable_producto.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "nombre", "cantidad" } )); jScrollPane1.setViewportView(jTable_producto); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(390, 160, 400, 190); jLabel9.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel9.setText("Registrar Productos"); getContentPane().add(jLabel9); jLabel9.setBounds(250, 10, 290, 40); boton_registrar.setText("registrar"); getContentPane().add(boton_registrar); boton_registrar.setBounds(390, 360, 150, 50); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-447)/2, 802, 447); }// </editor-fold>//GEN-END:initComponents private void jtxt_codigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtxt_codigoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jtxt_codigoActionPerformed private void cmb_ingredienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmb_ingredienteActionPerformed // TODO add your handling code here: }//GEN-LAST:event_cmb_ingredienteActionPerformed private void boton_masActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_masActionPerformed // TODO add your handling code here: }//GEN-LAST:event_boton_masActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_producto().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_mas; private javax.swing.JButton boton_menos; private javax.swing.JButton boton_registrar; private javax.swing.JComboBox cmb_categoria; private javax.swing.JComboBox cmb_ingrediente; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_producto; private javax.swing.JTextField jtxt_codigo; private javax.swing.JTextField jtxt_descripcion; private javax.swing.JTextField jtxt_nombre; private javax.swing.JTextField jtxt_precio; private javax.swing.JSpinner jtxtcantidad; // End of variables declaration//GEN-END:variables }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/vistas/vista_producto.java
Java
asf20
11,217
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_categorias.java * * Created on 08/04/2011, 10:46:59 AM */ package vistas; import controladores.controlador_categorias; import javax.swing.JButton; import javax.swing.JTextField; public class vista_categorias extends javax.swing.JFrame { /** Creates new form vista_categorias */ public vista_categorias() { initComponents(); cancenlar(); listen_botones(); } public void cancenlar() { boton_grabar.setEnabled(false); boton_modificar.setEnabled(false); boton_registrar.setEnabled(false); boton_buscar.setEnabled(true); jtxt_id.setEnabled(true); jtxt_nombre.setEnabled(false); jtxt_descripcion.setEnabled(false); jtxt_id.setText(""); jtxt_nombre.setText(""); jtxt_descripcion.setText(""); } public void modificar() { jtxt_descripcion.setEnabled(true); jtxt_nombre.setEnabled(true); jtxt_id.setEnabled(false); boton_modificar.setEnabled(false); boton_grabar.setEnabled(true); } public void listen_botones() { controlador_categorias cc = new controlador_categorias(this); boton_buscar.addActionListener (cc); boton_buscar.setActionCommand("buscar"); boton_grabar.addActionListener(cc); boton_grabar.setActionCommand("grabar"); boton_modificar.addActionListener(cc); boton_modificar.setActionCommand("modificar"); boton_registrar.addActionListener(cc); boton_registrar.setActionCommand("registrar"); } public JButton getBoton_buscar() { return boton_buscar; } public void setBoton_buscar(JButton boton_buscar) { this.boton_buscar = boton_buscar; } public JButton getBoton_cancelar() { return boton_cancelar; } public void setBoton_cancelar(JButton boton_cancelar) { this.boton_cancelar = boton_cancelar; } public JButton getBoton_grabar() { return boton_grabar; } public void setBoton_grabar(JButton boton_grabar) { this.boton_grabar = boton_grabar; } public JButton getBoton_modificar() { return boton_modificar; } public void setBoton_modificar(JButton boton_modificar) { this.boton_modificar = boton_modificar; } public JButton getBoton_registrar() { return boton_registrar; } public void setBoton_registrar(JButton boton_registrar) { this.boton_registrar = boton_registrar; } public JTextField getJtxt_descripcion() { return jtxt_descripcion; } public void setJtxt_descripcion(JTextField jtxt_descripcion) { this.jtxt_descripcion = jtxt_descripcion; } public JTextField getJtxt_id() { return jtxt_id; } public void setJtxt_id(JTextField jtxt_id) { this.jtxt_id = jtxt_id; } public JTextField getJtxt_nombre() { return jtxt_nombre; } public void setJtxt_nombre(JTextField jtxt_nombre) { this.jtxt_nombre = jtxt_nombre; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jtxt_descripcion = new javax.swing.JTextField(); jtxt_id = new javax.swing.JTextField(); boton_cancelar = new javax.swing.JButton(); boton_modificar = new javax.swing.JButton(); boton_buscar = new javax.swing.JButton(); boton_registrar = new javax.swing.JButton(); boton_grabar = new javax.swing.JButton(); jtxt_nombre = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); jLabel1.setText("ID Categoria"); getContentPane().add(jLabel1); jLabel1.setBounds(50, 110, 100, 18); jLabel2.setFont(new java.awt.Font("Ubuntu", 0, 24)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Registrar Categorias"); getContentPane().add(jLabel2); jLabel2.setBounds(270, 20, 290, 60); jLabel3.setText("Nombre"); getContentPane().add(jLabel3); jLabel3.setBounds(50, 160, 60, 20); jLabel4.setText("Descripcion"); getContentPane().add(jLabel4); jLabel4.setBounds(380, 110, 90, 18); getContentPane().add(jtxt_descripcion); jtxt_descripcion.setBounds(480, 110, 230, 120); getContentPane().add(jtxt_id); jtxt_id.setBounds(170, 110, 190, 30); boton_cancelar.setText("Cancelar"); boton_cancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_cancelarActionPerformed(evt); } }); getContentPane().add(boton_cancelar); boton_cancelar.setBounds(570, 320, 160, 40); boton_modificar.setText("Modificar"); getContentPane().add(boton_modificar); boton_modificar.setBounds(400, 320, 160, 40); boton_buscar.setText("Buscar"); getContentPane().add(boton_buscar); boton_buscar.setBounds(60, 320, 160, 40); boton_registrar.setText("Registrar"); getContentPane().add(boton_registrar); boton_registrar.setBounds(230, 320, 160, 40); boton_grabar.setText("Grabar"); getContentPane().add(boton_grabar); boton_grabar.setBounds(400, 270, 160, 40); getContentPane().add(jtxt_nombre); jtxt_nombre.setBounds(170, 160, 190, 30); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-430)/2, 802, 430); }// </editor-fold>//GEN-END:initComponents private void boton_cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_cancelarActionPerformed // TODO add your handling code here: cancenlar(); }//GEN-LAST:event_boton_cancelarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_categorias().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_buscar; private javax.swing.JButton boton_cancelar; private javax.swing.JButton boton_grabar; private javax.swing.JButton boton_modificar; private javax.swing.JButton boton_registrar; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JTextField jtxt_descripcion; private javax.swing.JTextField jtxt_id; private javax.swing.JTextField jtxt_nombre; // End of variables declaration//GEN-END:variables }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/vistas/vista_categorias.java
Java
asf20
7,576
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_listado_ingredientes.java * * Created on 10/04/2011, 07:59:25 PM */ package vistas; import controladores.controlador_listado_ingredientes; import java.util.Vector; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class vista_listado_ingredientes extends javax.swing.JFrame { DefaultTableModel modelo_tabla= new DefaultTableModel(); controlador_listado_ingredientes cli; /** Creates new form vista_listado_ingredientes */ public vista_listado_ingredientes() { Vector<String> a = new Vector<String>(); a.add("nombre"); a.add("cantidad"); modelo_tabla.setColumnIdentifiers(a); initComponents(); listen_botones(); } void listen_botones() { cli = new controlador_listado_ingredientes(this); jTable_productos.setModel(modelo_tabla); boton_consultar.addActionListener(cli); boton_consultar.setActionCommand("consultar"); } public JButton getBoton_consultar() { return boton_consultar; } public void setBoton_consultar(JButton boton_consultar) { this.boton_consultar = boton_consultar; } public controlador_listado_ingredientes getCli() { return cli; } public void setCli(controlador_listado_ingredientes cli) { this.cli = cli; } public JLabel getjLabel1() { return jLabel1; } public void setjLabel1(JLabel jLabel1) { this.jLabel1 = jLabel1; } public JScrollPane getjScrollPane1() { return jScrollPane1; } public void setjScrollPane1(JScrollPane jScrollPane1) { this.jScrollPane1 = jScrollPane1; } public JTable getjTable_productos() { return jTable_productos; } public void setjTable_productos(JTable jTable_productos) { this.jTable_productos = jTable_productos; } public DefaultTableModel getModelo_tabla() { return modelo_tabla; } public void setModelo_tabla(DefaultTableModel modelo_tabla) { this.modelo_tabla = modelo_tabla; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { boton_consultar = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable_productos = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); boton_consultar.setText("Consultar"); getContentPane().add(boton_consultar); boton_consultar.setBounds(620, 80, 140, 40); jTable_productos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable_productos); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(20, 150, 740, 430); jLabel1.setText("consultar cantidad de ingredientes"); getContentPane().add(jLabel1); jLabel1.setBounds(220, 20, 400, 18); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-630)/2, 802, 630); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_listado_ingredientes().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_consultar; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_productos; // End of variables declaration//GEN-END:variables }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/vistas/vista_listado_ingredientes.java
Java
asf20
4,680
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * vista_listado_productos.java * * Created on 10/04/2011, 07:59:07 PM */ package vistas; import controladores.controlador_listado_productos; import java.util.Vector; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class vista_listado_productos extends javax.swing.JFrame { DefaultTableModel modelo_tabla= new DefaultTableModel(); controlador_listado_productos clp; /** Creates new form vista_listado_productos */ public vista_listado_productos() { Vector<String> a = new Vector<String>(); a.add("nombre"); a.add("cantidad"); a.add("precio"); modelo_tabla.setColumnIdentifiers(a); initComponents(); listen_botones(); } void listen_botones() { clp = new controlador_listado_productos(this); jTable_productos.setModel(modelo_tabla); boton_consultar.addActionListener(clp); boton_consultar.setActionCommand("consultar"); } public JButton getBoton_consultar() { return boton_consultar; } public void setBoton_consultar(JButton boton_consultar) { this.boton_consultar = boton_consultar; } public controlador_listado_productos getClp() { return clp; } public void setClp(controlador_listado_productos clp) { this.clp = clp; } public JLabel getjLabel1() { return jLabel1; } public void setjLabel1(JLabel jLabel1) { this.jLabel1 = jLabel1; } public JScrollPane getjScrollPane1() { return jScrollPane1; } public void setjScrollPane1(JScrollPane jScrollPane1) { this.jScrollPane1 = jScrollPane1; } public JTable getjTable_productos() { return jTable_productos; } public void setjTable_productos(JTable jTable_productos) { this.jTable_productos = jTable_productos; } public DefaultTableModel getModelo_tabla() { return modelo_tabla; } public void setModelo_tabla(DefaultTableModel modelo_tabla) { this.modelo_tabla = modelo_tabla; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable_productos = new javax.swing.JTable(); boton_consultar = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); getContentPane().setLayout(null); jTable_productos.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(jTable_productos); getContentPane().add(jScrollPane1); jScrollPane1.setBounds(20, 150, 740, 430); boton_consultar.setText("Consultar"); getContentPane().add(boton_consultar); boton_consultar.setBounds(620, 80, 140, 40); jLabel1.setText("Consultar ventas de productos"); getContentPane().add(jLabel1); jLabel1.setBounds(220, 20, 400, 18); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-802)/2, (screenSize.height-630)/2, 802, 630); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new vista_listado_productos().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton boton_consultar; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable_productos; // End of variables declaration//GEN-END:variables }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/vistas/vista_listado_productos.java
Java
asf20
4,674
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Vector; import javax.swing.JOptionPane; import modelos.*; import vistas.vista_producto; public class controlador_productos implements ActionListener { vista_producto v_pro; modelo_productos m_pro; modelo_categorias m_cat; modelo_ingredientes m_ing; ArrayList<modelo_ingredientes> lista_ingredientes; ArrayList<modelo_ingredientes> lista_ingredientes_guardar; ArrayList<modelo_categorias> lista_categorias; modelo_ingredientes m_ing_guardar; public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("mas")) mas(); else if (comando.equals("menos")) menos(); else if (comando.equals("registrar")) registrar(); } public controlador_productos(vista_producto v_pro) { this.v_pro = v_pro; m_cat = new modelo_categorias(); m_ing = new modelo_ingredientes(); m_pro = new modelo_productos(); lista_ingredientes_guardar =new ArrayList<modelo_ingredientes>(); } void mas() { Vector<String> fila = new Vector<String>(); m_ing_guardar = new modelo_ingredientes(); int posi_ingrediente=v_pro.getCmb_ingrediente().getSelectedIndex(); m_ing_guardar.setId(lista_ingredientes.get(posi_ingrediente).getId().toString()); m_ing_guardar.setNombre(lista_ingredientes.get(posi_ingrediente).getNombre().toString()); m_ing_guardar.setStock(Float.parseFloat(v_pro.getJtxtcantidad().getValue().toString())); fila.add(m_ing_guardar.getNombre()); fila.add(String.valueOf(m_ing_guardar.getStock())); v_pro.getModelo_tabla().addRow(fila); lista_ingredientes_guardar.add(m_ing_guardar); } void menos() { if(v_pro.getModelo_tabla().getRowCount()>0) { v_pro.getModelo_tabla().removeRow(v_pro.getjTable_producto().getSelectedRow()); lista_ingredientes_guardar.remove(v_pro.getjTable_producto().getSelectedRow()); } } void registrar() { if(hayVacio()) { m_pro.insertar(v_pro.getJtxt_codigo().getText(),v_pro.getJtxt_nombre().getText(),v_pro.getJtxt_descripcion().getText(),lista_categorias.get(v_pro.getCmb_categoria().getSelectedIndex()).getId(),v_pro.getJtxt_precio().getText(),lista_ingredientes_guardar); aviso("se ha registrado el producto exitosamente"); v_pro.cancelar(); } else { aviso("verifique, faltan por llenar datos"); } } public void cargar_categoria() { lista_categorias = m_cat.lista(); for (int i = 0; i < lista_categorias.size(); i++) { v_pro.getCmb_categoria().addItem(lista_categorias.get(i).getNombre()); } } public void cargar_ingredientes() { lista_ingredientes = m_ing.lista(); for (int i = 0; i < lista_ingredientes.size(); i++) { v_pro.getCmb_ingrediente().addItem(lista_ingredientes.get(i).getNombre()); } } void aviso(String mensaje) { JOptionPane.showMessageDialog(v_pro, mensaje,"aviso",JOptionPane.INFORMATION_MESSAGE); } int pregunta(String mensaje) { int i =JOptionPane.showConfirmDialog(v_pro, mensaje); return i; } public boolean hayVacio() { if(v_pro.getJtxt_codigo().getText().isEmpty() || v_pro.getJtxt_nombre().getText().isEmpty() || v_pro.getJtxt_descripcion().getText().isEmpty() || v_pro.getJtxt_precio().getText().isEmpty()) return false; else return true; } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/controladores/controlador_productos.java
Java
asf20
3,766
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Vector; import modelos.modelo_ingredientes; import modelos.modelo_listado_ingredientes; import vistas.vista_listado_ingredientes; public class controlador_listado_ingredientes implements ActionListener{ vista_listado_ingredientes v_l_i; modelo_ingredientes m_ing = new modelo_ingredientes(); ArrayList<modelo_ingredientes> listado_ingredientes = new ArrayList<modelo_ingredientes>(); public controlador_listado_ingredientes (vista_listado_ingredientes v_l_i) { this.v_l_i = v_l_i; } public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("consultar")) { consultar(); } } void consultar() { v_l_i.getModelo_tabla().setRowCount(0); listado_ingredientes=m_ing.lista(); Vector<String> a; for (int i = 0; i < listado_ingredientes.size(); i++) { a = new Vector<String>(); a.add(listado_ingredientes.get(i).getNombre()); a.add(String.valueOf(listado_ingredientes.get(i).getStock())); v_l_i.getModelo_tabla().addRow(a); } } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/controladores/controlador_listado_ingredientes.java
Java
asf20
1,397
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import modelos.*; import vistas.*; public class controlador_ingredientes implements ActionListener { vista_ingredientes v_ing; modelo_ingredientes m_ing; public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("buscar")) buscar(); else if (comando.equals("grabar")) grabar(); else if (comando.equals("modificar")) modificar(); else if (comando.equals("registrar")) registrar(); } public controlador_ingredientes(vista_ingredientes v_ing ) { this.v_ing = v_ing; m_ing = new modelo_ingredientes(); } void buscar() { if(v_ing.getJtxt_id().getText().isEmpty()) { aviso("introduzca una ID"); } else { if(m_ing.buscar(v_ing.getJtxt_id().getText())) { v_ing.getJtxt_id().setEnabled(false); v_ing.getBoton_modificar().setEnabled(true); v_ing.getBoton_buscar().setEnabled(false); v_ing.getJtxt_nombre().setText(m_ing.getNombre()); v_ing.getJtxt_descripcion().setText(m_ing.getDescripcion()); v_ing.getJtxt_stock().setText(String.valueOf(m_ing.getStock())); } else { int seleccion=pregunta("el usuario no existe, desea registrarlo?"); System.out.print(seleccion); if(seleccion ==0) { v_ing.getBoton_registrar().setEnabled(true); v_ing.getBoton_buscar().setEnabled(false); v_ing.getJtxt_id().setEnabled(false); v_ing.getJtxt_nombre().setEnabled(true); v_ing.getJtxt_descripcion().setEnabled(true); v_ing.getJtxt_stock().setEnabled(true); } else v_ing.cancenlar(); } } } void modificar() { if (v_ing.getJtxt_id().getText().isEmpty() || v_ing.getJtxt_nombre().getText().isEmpty()) { JOptionPane.showMessageDialog(v_ing, " verifique, no hay un id, ni un nombre"); } else { v_ing.modificar(); } } void grabar() { if(v_ing.getJtxt_id().getText().isEmpty() || v_ing.getJtxt_nombre().getText().isEmpty()) { aviso("hay campos en blanco, por favor verifique"); } else { m_ing.modificar(v_ing.getJtxt_id().getText(),v_ing.getJtxt_nombre().getText(),v_ing.getJtxt_descripcion().getText(),v_ing.getJtxt_stock().getText()); aviso("se ha guardado exitosamente"); } v_ing.cancenlar(); } void registrar() { if(v_ing.getJtxt_id().getText().isEmpty() || v_ing.getJtxt_nombre().getText().isEmpty()) { aviso("hay campos en blanco, por favor verifique"); } else { m_ing.insertar(v_ing.getJtxt_id().getText(),v_ing.getJtxt_nombre().getText(),v_ing.getJtxt_descripcion().getText(),v_ing.getJtxt_stock().getText()); aviso("se ha registrado exitosamente"); } v_ing.cancenlar(); } void aviso(String mensaje) { JOptionPane.showMessageDialog(v_ing, mensaje,"aviso",JOptionPane.INFORMATION_MESSAGE); } int pregunta(String mensaje) { int i =JOptionPane.showConfirmDialog(v_ing, mensaje); return i; } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/controladores/controlador_ingredientes.java
Java
asf20
3,807
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import modelos.*; import vistas.*; public class controlador_categorias implements ActionListener { vista_categorias v_cat; modelo_categorias m_cat; public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("buscar")) buscar(); else if (comando.equals("grabar")) grabar(); else if (comando.equals("modificar")) modificar(); else if (comando.equals("registrar")) registrar(); } public controlador_categorias(vista_categorias v_cat ) { this.v_cat = v_cat; m_cat = new modelo_categorias(); } void buscar() { if(v_cat.getJtxt_id().getText().isEmpty()) { aviso("introduzca una ID"); } else { if(m_cat.buscar(v_cat.getJtxt_id().getText())) { v_cat.getJtxt_id().setEnabled(false); v_cat.getBoton_modificar().setEnabled(true); v_cat.getBoton_buscar().setEnabled(false); v_cat.getJtxt_nombre().setText(m_cat.getNombre()); v_cat.getJtxt_descripcion().setText(m_cat.getDescripcion()); } else { int seleccion=pregunta("la categoria no existe, desea registrarlo?"); System.out.print(seleccion); if(seleccion ==0) { v_cat.getBoton_registrar().setEnabled(true); v_cat.getBoton_buscar().setEnabled(false); v_cat.getJtxt_id().setEnabled(false); v_cat.getJtxt_nombre().setEnabled(true); v_cat.getJtxt_descripcion().setEnabled(true); } else v_cat.cancenlar(); } } } void modificar() { if (v_cat.getJtxt_id().getText().isEmpty() || v_cat.getJtxt_nombre().getText().isEmpty()) { JOptionPane.showMessageDialog(v_cat, " verifique, no hay un id, ni un nombre"); } else { v_cat.modificar(); } } void grabar() { if(v_cat.getJtxt_id().getText().isEmpty() || v_cat.getJtxt_nombre().getText().isEmpty()) { aviso("hay campos en blanco, por favor verifique"); } else { m_cat.modificar(v_cat.getJtxt_id().getText(),v_cat.getJtxt_nombre().getText(),v_cat.getJtxt_descripcion().getText()); aviso("se ha guardado exitosamente"); } v_cat.cancenlar(); } void registrar() { if(v_cat.getJtxt_id().getText().isEmpty() || v_cat.getJtxt_nombre().getText().isEmpty()) { aviso("hay campos en blanco, por favor verifique"); } else { m_cat.insertar(v_cat.getJtxt_id().getText(),v_cat.getJtxt_nombre().getText(),v_cat.getJtxt_descripcion().getText()); aviso("se ha registrado exitosamente"); } v_cat.cancenlar(); } void aviso(String mensaje) { JOptionPane.showMessageDialog(v_cat, mensaje,"aviso",JOptionPane.INFORMATION_MESSAGE); } int pregunta(String mensaje) { int i =JOptionPane.showConfirmDialog(v_cat, mensaje); return i; } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/controladores/controlador_categorias.java
Java
asf20
3,564
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Vector; import modelos.modelo_listado_productos; import modelos.modelo_ordenes; import vistas.vista_listado_productos; public class controlador_listado_productos implements ActionListener{ vista_listado_productos v_l_p;; modelos.modelo_ordenes m_ord = new modelo_ordenes(); ArrayList<modelo_listado_productos> listado_producto = new ArrayList<modelo_listado_productos>(); public controlador_listado_productos (vista_listado_productos v_l_p) { this.v_l_p = v_l_p; } public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("consultar")) { consultar(); } } void consultar() { v_l_p.getModelo_tabla().setRowCount(0); listado_producto=m_ord.listado(); Vector<String> a; for (int i = 0; i < listado_producto.size(); i++) { a = new Vector<String>(); a.add(listado_producto.get(i).getNombre_producto()); a.add(String.valueOf(listado_producto.get(i).getCantidad_producto())); a.add(String.valueOf(listado_producto.get(i).getPrecio_orden())); v_l_p.getModelo_tabla().addRow(a); } } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/controladores/controlador_listado_productos.java
Java
asf20
1,464
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package controladores; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Vector; import javax.swing.JOptionPane; import modelos.modelo_ingredientes; import modelos.modelo_ordenes; import modelos.modelo_productos; import vistas.vista_ordenes; public class controlador_ordenes implements ActionListener { vista_ordenes v_ord ; modelo_ordenes m_ord = new modelo_ordenes(); modelo_productos m_pro = new modelo_productos(); modelo_productos m_pro_guardar = new modelo_productos(); modelo_ingredientes m_ing_guardar = new modelo_ingredientes(); ArrayList<modelo_productos> lista_productos = new ArrayList<modelo_productos>(); ArrayList<modelo_ingredientes> lista_ingredientes_guardar = new ArrayList<modelo_ingredientes>(); ArrayList<modelo_productos> lista_productos_guardar= new ArrayList<modelo_productos>(); public void actionPerformed(ActionEvent e) { String comando = e.getActionCommand(); if (comando.equals("mas")) mas(); else if (comando.equals("menos")) menos(); else if (comando.equals("registrar")) registrar(); } public controlador_ordenes(vista_ordenes v_ord) { this.v_ord = v_ord; } void mas() { Vector<String> fila = new Vector<String>(); int posi_producto = v_ord.getCmb_producto().getSelectedIndex(); m_pro_guardar.setId(lista_productos.get(posi_producto).getId().toString()); m_pro_guardar.setNombre(lista_productos.get(posi_producto).getNombre().toString()); m_pro_guardar.setPrecio(lista_productos.get(posi_producto).getPrecio()); m_ing_guardar.setStock(Float.parseFloat(v_ord.getJtxtcantidad().getValue().toString())); fila.add(m_pro_guardar.getNombre()); fila.add(String.valueOf(m_pro_guardar.getPrecio())); fila.add(String.valueOf(v_ord.getJtxtcantidad().getValue())); v_ord.getModelo_tabla().addRow(fila); lista_productos_guardar.add(m_pro_guardar); lista_ingredientes_guardar.add(m_ing_guardar); } void menos() { if(v_ord.getModelo_tabla().getRowCount()>0) { v_ord.getModelo_tabla().removeRow(v_ord.getjTable_ordenes().getSelectedRow()); lista_productos_guardar.remove(v_ord.getjTable_ordenes().getSelectedRow()); lista_ingredientes_guardar.remove(v_ord.getjTable_ordenes().getSelectedRow()); System.out.print(lista_ingredientes_guardar.size()); } } void registrar() { if(hayVacio()) { float total_general=total_general(); v_ord.getJtxt_total().setText(String.valueOf(total_general)); aviso("se ha registrado la orden con exito"); m_ord.registrar(v_ord.getJtxt_nombre().getText().toString(),Float.parseFloat(v_ord.getJtxt_total().getText().toString()),lista_productos_guardar,lista_ingredientes_guardar); v_ord.cancelar(); } else { aviso("faltan campos por llenar"); } } public void cargar_producto() { lista_productos = m_pro.lista(); for (int i = 0; i < lista_productos.size(); i++) { v_ord.getCmb_producto().addItem(lista_productos.get(i).getNombre()); } } void aviso(String mensaje) { JOptionPane.showMessageDialog(v_ord, mensaje,"aviso",JOptionPane.INFORMATION_MESSAGE); } int pregunta(String mensaje) { int i =JOptionPane.showConfirmDialog(v_ord, mensaje); return i; } public boolean hayVacio() { if(v_ord.getJtxt_nombre().getText().isEmpty()) return false; else return true; } public float total_general() { float total_general=0; float total_general2=0; for (int i = 0; i < v_ord.getModelo_tabla().getRowCount(); i++) { total_general= Float.parseFloat(v_ord.getjTable_ordenes().getValueAt(i, 2).toString())*Float.parseFloat(v_ord.getjTable_ordenes().getValueAt(i, 1).toString()); total_general2+=total_general; } return total_general2; } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/controladores/controlador_ordenes.java
Java
asf20
4,194
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * MenuPrincipal.java * */ /** Integrantes : * Rosbely Gonzalez * Jaily Leon * Mariant Barroeta * Maria Alejandra Leal * */ package general; import vistas.vista_categorias; import vistas.vista_ingredientes; import vistas.vista_listado_ingredientes; import vistas.vista_listado_productos; import vistas.vista_ordenes; import vistas.vista_producto; public class MenuPrincipal extends javax.swing.JFrame { /** Creates new form MenuPrincipal */ public MenuPrincipal() { initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { desktopPane = new javax.swing.JDesktopPane(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); boton_ingrediente = new javax.swing.JMenuItem(); editMenu = new javax.swing.JMenu(); boton_categoria = new javax.swing.JMenuItem(); helpMenu = new javax.swing.JMenu(); boton_ordenes = new javax.swing.JMenuItem(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); fileMenu.setText("Ingrediente"); boton_ingrediente.setText("Registrar"); boton_ingrediente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_ingredienteActionPerformed(evt); } }); fileMenu.add(boton_ingrediente); menuBar.add(fileMenu); editMenu.setText("Categoria"); boton_categoria.setText("registrar"); boton_categoria.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_categoriaActionPerformed(evt); } }); editMenu.add(boton_categoria); menuBar.add(editMenu); helpMenu.setText("Producto"); boton_ordenes.setText("Registrar"); boton_ordenes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { boton_ordenesActionPerformed(evt); } }); helpMenu.add(boton_ordenes); menuBar.add(helpMenu); jMenu1.setText("Ordenes"); jMenuItem1.setText("registrar"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); menuBar.add(jMenu1); jMenu2.setText("listados"); jMenuItem2.setText("Ventas por productos"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jMenu2.add(jMenuItem2); jMenuItem3.setText("cantidad Ingredientes"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu2.add(jMenuItem3); menuBar.add(jMenu2); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(desktopPane, javax.swing.GroupLayout.PREFERRED_SIZE, 536, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(desktopPane, javax.swing.GroupLayout.PREFERRED_SIZE, 371, javax.swing.GroupLayout.PREFERRED_SIZE)) ); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-562)/2, (screenSize.height-440)/2, 562, 440); }// </editor-fold>//GEN-END:initComponents private void boton_ingredienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_ingredienteActionPerformed // TODO add your handling code here: vista_ingredientes vi = new vista_ingredientes(); vi.show(); }//GEN-LAST:event_boton_ingredienteActionPerformed private void boton_categoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_categoriaActionPerformed // TODO add your handling code here: vista_categorias vc = new vista_categorias(); vc.show(); }//GEN-LAST:event_boton_categoriaActionPerformed private void boton_ordenesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boton_ordenesActionPerformed // TODO add your handling code here: vista_producto vp = new vista_producto(); vp.show(); }//GEN-LAST:event_boton_ordenesActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed // TODO add your handling code here: vista_ordenes vo = new vista_ordenes(); vo.show(); }//GEN-LAST:event_jMenuItem1ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed // TODO add your handling code here: vista_listado_productos vlp = new vista_listado_productos(); vlp.show(); }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed // TODO add your handling code here: vista_listado_ingredientes vli = new vista_listado_ingredientes(); vli.show(); }//GEN-LAST:event_jMenuItem3ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MenuPrincipal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JMenuItem boton_categoria; private javax.swing.JMenuItem boton_ingrediente; private javax.swing.JMenuItem boton_ordenes; private javax.swing.JDesktopPane desktopPane; private javax.swing.JMenu editMenu; private javax.swing.JMenu fileMenu; private javax.swing.JMenu helpMenu; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenuBar menuBar; // End of variables declaration//GEN-END:variables }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/general/MenuPrincipal.java
Java
asf20
8,029
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package general; import java.sql.Statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; public class conectarBD { public ResultSet rs; public Connection con; public Statement stmt; public String driver; public String conneccionString; public String usuario; public String clave; public boolean conectar() { driver = "org.postgresql.Driver"; conneccionString = "jdbc:postgresql://localhost:5432/labUno"; usuario = "postgres"; clave = "123456";// try { Class.forName(driver); return true; } catch (ClassNotFoundException ex) { Logger.getLogger(conectarBD.class.getName()).log(Level.SEVERE, null, ex); return false; } } public void desconectar() { try { con.close(); } catch (SQLException ex) { Logger.getLogger(conectarBD.class.getName()).log(Level.SEVERE, null, ex); } } public boolean accionSql(String sql) { try { con = DriverManager.getConnection(conneccionString, usuario, clave); stmt = (Statement) con.createStatement(); rs = stmt.executeQuery(sql); return true; } catch (SQLException ex) { Logger.getLogger(conectarBD.class.getName()).log(Level.SEVERE, null, ex); return false; } } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/general/conectarBD.java
Java
asf20
1,709
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; import general.conectarBD; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class modelo_ingredientes extends conectarBD{ String id,nombre,descripcion; float stock; public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public float getStock() { return stock; } public void setStock(float stock) { this.stock = stock; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getConneccionString() { return conneccionString; } public void setConneccionString(String conneccionString) { this.conneccionString = conneccionString; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public boolean buscar(String id) { try { conectar();// base de datos String sql = " Select * from t_ingredientes where id_ingrediente = '" + id + "'"; accionSql(sql); while (rs.next()) { if(rs.getString("id_ingrediente").isEmpty()) { return false; } else { id = rs.getString("id_ingrediente"); nombre = rs.getString("nombre_ingrediente"); descripcion = rs.getString("Descripcion_ingrediente"); stock = Float.parseFloat(rs.getString("stock_ingrediente")); desconectar(); return true; } } desconectar(); return false; } catch (SQLException ex) { Logger.getLogger(modelo_ingredientes.class.getName()).log(Level.SEVERE, null, ex); desconectar(); return false; } } public boolean insertar(String id, String Nombre, String Descripcion,String stock) { conectar();// base de datos String sql = " insert into t_ingredientes (id_ingrediente,nombre_ingrediente,descripcion_ingrediente,stock_ingrediente) values ('"+id+"','"+Nombre+"','"+Descripcion+"',"+stock+")"; accionSql(sql); desconectar(); return true; } public boolean modificar(String id, String Nombre, String Descripcion,String stock) { conectar();// base de datos String sql = " update t_ingredientes SET nombre_ingrediente='"+Nombre+"',descripcion_ingrediente='"+Descripcion+"',stock_ingrediente="+stock+" where id_ingrediente='"+id+"'"; accionSql(sql); desconectar(); return true; } public ArrayList<modelo_ingredientes> lista(){ ArrayList<modelo_ingredientes> lista_ingredientes = new ArrayList<modelo_ingredientes>(); String sql="select * from t_ingredientes"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_ingredientes m_ing = new modelo_ingredientes(); m_ing.id = rs.getString("id_ingrediente"); m_ing.nombre = rs.getString("nombre_ingrediente"); System.out.print(nombre); m_ing.stock = rs.getFloat("stock_ingrediente"); m_ing.descripcion = rs.getString("descripcion_ingrediente"); lista_ingredientes.add(m_ing); System.out.print("si entra"); } } catch (SQLException ex) { Logger.getLogger(modelo_ingredientes.class.getName()).log(Level.SEVERE, null, ex); } desconectar(); System.out.print(lista_ingredientes.isEmpty()); return lista_ingredientes; } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/modelos/modelo_ingredientes.java
Java
asf20
4,828
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; public class modelo_listado_ingredientes { String nombre; float cantidad; public float getCantidad() { return cantidad; } public void setCantidad(float cantidad) { this.cantidad = cantidad; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/modelos/modelo_listado_ingredientes.java
Java
asf20
504
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; import general.conectarBD; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class modelo_productos extends conectarBD { String id,nombre,descripcion,id_categorias; float precio; public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getId_categorias() { return id_categorias; } public void setId_categorias(String id_categorias) { this.id_categorias = id_categorias; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public float getPrecio() { return precio; } public void setPrecio(float precio) { this.precio = precio; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getConneccionString() { return conneccionString; } public void setConneccionString(String conneccionString) { this.conneccionString = conneccionString; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public boolean insertar(String id, String nombre, String descripcion,String id_categoria,String precio,ArrayList<modelo_ingredientes> lista_ingredientes) { conectar();// base de datos String sql = " insert into t_productos (id_producto,nombre_producto,descripcion_producto,precio_producto,id_categoria) values ('"+id+"','"+nombre+"','"+descripcion+"',"+precio+",'"+id_categoria+"')"; accionSql(sql); desconectar(); for (int i = 0; i < lista_ingredientes.size(); i++) { String sqlAutoIncremento1 = "SELECT COUNT(DISTINCT id_ing_prod) FROM t_ingredientes_productos"; int id_ing_prod= autoIncremento(sqlAutoIncremento1); String sql2 = " insert into t_ingredientes_productos(id_ing_prod,stock_ing_prod,id_ingredientes,id_productos) values ('"+id_ing_prod+"',"+lista_ingredientes.get(i).getStock()+",'"+lista_ingredientes.get(i).getId()+"','"+id+"')"; System.out.print(sql2); conectar();// base de datos accionSql(sql2); desconectar(); } return true; } public ArrayList<modelo_productos> lista(){ ArrayList<modelo_productos> lista_productos = new ArrayList<modelo_productos>(); String sql="select * from t_productos"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_productos productos = new modelo_productos(); productos.setId(rs.getString("id_producto")); productos.setNombre(rs.getString("nombre_producto")); productos.setDescripcion(rs.getString("Descripcion_producto")); productos.setId_categorias(rs.getString("id_categoria")); productos.setPrecio(rs.getFloat("precio_producto")); lista_productos.add(productos); } } catch (SQLException ex) { Logger.getLogger(modelo_productos.class.getName()).log(Level.SEVERE, null, ex); } return lista_productos; } public int autoIncremento (String sql) { int ID=0; try { conectar(); // base de datos accionSql(sql); while (rs.next()) { ID =rs.getInt(1)+1; } return ID; } catch (SQLException ex) { Logger.getLogger(modelo_productos.class.getName()).log(Level.SEVERE, null, ex); return ID; } } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/modelos/modelo_productos.java
Java
asf20
4,678
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; import general.conectarBD; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class modelo_ordenes extends conectarBD{ String id_producto,nombre,id_orden,id_ordenes_productos; float total; int cantidad; public int getCantidad() { return cantidad; } public void setCantidad(int cantidad) { this.cantidad = cantidad; } public String getId_orden() { return id_orden; } public void setId_orden(String id_orden) { this.id_orden = id_orden; } public String getId_ordenes_productos() { return id_ordenes_productos; } public void setId_ordenes_productos(String id_ordenes_productos) { this.id_ordenes_productos = id_ordenes_productos; } public String getId_producto() { return id_producto; } public void setId_producto(String id_producto) { this.id_producto = id_producto; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public float getTotal() { return total; } public void setTotal(float total) { this.total = total; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getConneccionString() { return conneccionString; } public void setConneccionString(String conneccionString) { this.conneccionString = conneccionString; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public boolean registrar(String nombre,float total,ArrayList<modelo_productos> lista_productos,ArrayList<modelo_ingredientes> lista_ingredientes) { String sqlAutoincremento1 = "SELECT COUNT(DISTINCT id_orden) FROM t_ordenes"; id_orden= String.valueOf(autoIncremento(sqlAutoincremento1)); conectar();// base de datos String sql = " insert into t_ordenes (id_orden,nombre_cliente,total_general) values ('"+id_orden+"','"+nombre+"',"+total+")"; accionSql(sql); desconectar(); for (int i = 0; i < lista_productos.size(); i++) { System.out.print("entro" + i); String sqlAutoincremento2 = "SELECT COUNT(DISTINCT id_ordenes_productos) FROM t_productos_orden"; id_ordenes_productos= String.valueOf(autoIncremento(sqlAutoincremento2)); conectar();// base de datos System.out.print("en la tira sql"); System.out.print(lista_ingredientes.get(i).getStock()); System.out.print(lista_productos.get(i).getId()); String sql2= "insert into t_productos_orden(id_ordenes_productos,stock_prod_ord,id_productos,id_orden) values ('"+id_ordenes_productos+"',"+lista_ingredientes.get(i).getStock()+",'"+lista_productos.get(i).getId()+"','"+id_orden+"')"; System.out.print(sql2); accionSql(sql2); desconectar(); } return true; } public ArrayList<modelo_ordenes> lista(){ ArrayList<modelo_ordenes> lista_ordenes = new ArrayList<modelo_ordenes>(); String sql="select * from t_ordenes"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_ordenes m_ord = new modelo_ordenes(); m_ord.setId_orden(rs.getString("id_orden")); m_ord.setNombre(rs.getString("nombre_cliente")); m_ord.setTotal(rs.getInt("total_general")); lista_ordenes.add(m_ord); } } catch (SQLException ex) { Logger.getLogger(modelo_ordenes.class.getName()).log(Level.SEVERE, null, ex); } return lista_ordenes; } public ArrayList<modelo_listado_productos> listado(){ ArrayList<modelo_listado_productos> listado_ordenes = new ArrayList<modelo_listado_productos>(); String sql="SELECT id_producto,nombre_producto,listado_ventas.cantidad_ventas,(precio_producto*listado_ventas.cantidad_ventas) as precio_ventas FROM t_productos, (SELECT sum(t_productos_orden.stock_prod_ord) as cantidad_ventas,t_productos_orden.id_productos AS codigo_ventas FROM t_productos_orden GROUP BY t_productos_orden.id_productos) listado_ventas WHERE listado_ventas.codigo_ventas=id_producto"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_listado_productos listado = new modelo_listado_productos(); listado.setCantidad_producto(Float.parseFloat(rs.getString("cantidad_ventas"))); listado.setNombre_producto(rs.getString("nombre_producto")); listado.setPrecio_orden(Float.parseFloat(rs.getString("precio_ventas"))); listado_ordenes.add(listado); } } catch (SQLException ex) { Logger.getLogger(modelo_listado_productos.class.getName()).log(Level.SEVERE, null, ex); } return listado_ordenes; } public int autoIncremento (String sql) { int ID=1; try { conectar(); // base de datos accionSql(sql); while (rs.next()) { ID =rs.getInt(1)+1; } return ID; } catch (SQLException ex) { Logger.getLogger(modelo_ordenes.class.getName()).log(Level.SEVERE, null, ex); return ID; } } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/modelos/modelo_ordenes.java
Java
asf20
6,297
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; import general.conectarBD; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import general.conectarBD; public class modelo_categorias extends conectarBD { String id,nombre,descripcion; public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getClave() { return clave; } public void setClave(String clave) { this.clave = clave; } public Connection getCon() { return con; } public void setCon(Connection con) { this.con = con; } public String getConneccionString() { return conneccionString; } public void setConneccionString(String conneccionString) { this.conneccionString = conneccionString; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public Statement getStmt() { return stmt; } public void setStmt(Statement stmt) { this.stmt = stmt; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public boolean buscar(String id) { try { conectar();// base de datos String sql = " Select * from t_categorias where id_categoria = '" + id + "'"; accionSql(sql); while (rs.next()) { if(rs.getString("id_categoria").isEmpty()) { return false; } else { id = rs.getString("id_categoria"); nombre = rs.getString("nombre_categoria"); descripcion = rs.getString("Descripcion_categoria"); desconectar(); return true; } } desconectar(); return false; } catch (SQLException ex) { Logger.getLogger(modelo_categorias.class.getName()).log(Level.SEVERE, null, ex); desconectar(); return false; } } public boolean insertar(String id, String Nombre, String Descripcion) { conectar();// base de datos String sql = " insert into t_categorias (id_categoria,nombre_categoria,descripcion_categoria) values ('"+id+"','"+Nombre+"','"+Descripcion+"')"; accionSql(sql); desconectar(); return true; } public boolean modificar(String id, String Nombre, String Descripcion) { conectar();// base de datos String sql = " update t_categorias SET nombre_categoria='"+Nombre+"',descripcion_categoria='"+Descripcion+"' where id_categoria='"+id+"'"; accionSql(sql); desconectar(); return true; } public ArrayList<modelo_categorias> lista(){ ArrayList<modelo_categorias> lista_categorias = new ArrayList<modelo_categorias>(); String sql="select * from t_categorias"; conectar(); accionSql(sql); try{ while (rs.next()){ modelo_categorias m_cat = new modelo_categorias(); m_cat.id = rs.getString("id_categoria"); m_cat.nombre = rs.getString("nombre_categoria"); m_cat.descripcion = rs.getString("descripcion_categoria"); lista_categorias.add(m_cat); } } catch (SQLException ex) { Logger.getLogger(modelo_categorias.class.getName()).log(Level.SEVERE, null, ex); } desconectar(); return lista_categorias; } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/modelos/modelo_categorias.java
Java
asf20
4,290
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package modelos; public class modelo_listado_productos { String nombre_producto; float cantidad_producto; float precio_orden; public float getCantidad_producto() { return cantidad_producto; } public void setCantidad_producto(float cantidad_producto) { this.cantidad_producto = cantidad_producto; } public String getNombre_producto() { return nombre_producto; } public void setNombre_producto(String nombre_producto) { this.nombre_producto = nombre_producto; } public float getPrecio_orden() { return precio_orden; } public void setPrecio_orden(float precio_orden) { this.precio_orden = precio_orden; } }
03-05-tercera-entrega
trunk/Proyecto2lab1/src/modelos/modelo_listado_productos.java
Java
asf20
828
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Highstock Example</title> <SCRIPT SRC="ADS.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="ALV.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="BAS.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="BAYN.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="BEI.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="CON.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="CBK.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="DAI.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="DAX_UTC.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="DB1.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="DBK.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="EOAN.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="FME.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="FRE.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="HEI.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="LHA.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="LIN.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="LXS.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="MRK.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="MUV2.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="SAP.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="SDF.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="SIE.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="TKA.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="VOW3.js" TYPE="text/javascript"></SCRIPT> <SCRIPT SRC="OMXSPI_UTC.js" TYPE="text/javascript"></SCRIPT> <script src="data.js" type="text/javascript"></script> <script type="text/javascript"> //var series_ = [mydata, mydataCBK, mydataADS]; //var symb_ = ["CBK", "ADS"]; var tombminta = { "ADS": [ [1381160289,79.996,"2013-10-07 15:38:09", "ADS" ], [1381160310,79.996,"2013-10-07 15:38:30", "ADS" ], [1381160331,79.996,"2013-10-07 15:38:51", "ADS" ],] , "CBK": [ [1381160289,8.902,"2013-10-07 15:38:09", "CBK" ], [1381160310,8.902,"2013-10-07 15:38:30", "CBK" ], [1381160331,8.902,"2013-10-07 15:38:51", "CBK" ], ] </script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script type="text/javascript"> $(function() { var chart = new Highcharts.StockChart( { chart: { renderTo: 'container' }, series: [{ name: 'New Series', //mydata data: mydata }] }, function(chart) { $('#btn').click(function(){ while(chart.series.length > 0) chart.series[0].remove(true); chart.setTitle({text:'DAX'}); chart.addSeries({ data: tombx["CBK"] //mydata }) //chart.series[0].setData(mydata,true); alert(chart.series[0]["name"]); }); $('#selectem').change(function() { //alert('tomb:'+tomb[$('#selectem').val()]); while(chart.series.length > 0) chart.series[0].remove(true); chart.setTitle({text:$('#selectem').val()}); chart.addSeries( { data: tombyYY[$('#selectem').val()] //data: tomby[$('#selectem').val()] }); chart.series[0].name=$('#selectem').val(); //chart.redraw(); //alert('tomb:'+tombyYY["BAYN"]); //alert('#selectem).val():'+$('#selectem').val()+' ###\n tomb val :'+tombyYY[$('#selectem').val()]); }); $('#selectemNETFONDS').change(function() { //alert('tomb:'+tomb[$('#selectem').val()]); while(chart.series.length > 0) chart.series[0].remove(true); chart.setTitle({text:$('#selectemNETFONDS').val()}); chart.addSeries( { data: tombyYY[$('#selectemNETFONDS').val()] //data: tomby[$('#selectem').val()] }); chart.series[0].name=$('#selectemNETFONDS').val(); //chart.redraw(); //alert('tomb:'+tombyYY["BAYN"]); //alert('#selectem).val():'+$('#selectem').val()+' ###\n tomb val :'+tombyYY[$('#selectem').val()]); }); var tombProbara = { "ADSwwwww": [ [1381160289000,71.996,"2013-10-07 15:38:09", "ADS" ], [1381160310000,69.996,"2013-10-07 15:38:30", "ADS" ], [1381160331000,59.996,"2013-10-07 15:38:51", "ADS" ],] , "ALV": [ [1381160289000,8.902,"2013-10-07 15:38:09", "CBK" ], [1381160310000,6.902,"2013-10-07 15:38:30", "CBK" ], [1381160331000,7.902,"2013-10-07 15:38:51", "CBK" ], ] , "ADS2": [ [1381160289000,71.996,"2013-10-07 15:38:09", "ADS" ], [1381160310000,69.996,"2013-10-07 15:38:30", "ADS" ], [1381160331000,59.996,"2013-10-07 15:38:51", "ADS" ],] } var tombyYYmente = { "BAYN": mydataBAYN , } var tombyYY = { "ADS": mydataADS, "ALV": mydataALV, "BAS": mydataBAS, "BAYN": mydataBAYN, "BEI": mydataBEI, "CON": mydataCON, "CBK": mydataCBK, "DAI": mydataDAI, "DAX_UTC": mydataDAX_UTC, "DB1": mydataDB1, "DBK": mydataDBK, "EOAN": mydataEOAN, "FME": mydataFME, "FRE": mydataFRE, "HEI": mydataHEI, "LHA": mydataLHA, "LIN": mydataLIN, "LXS": mydataLXS, "MRK": mydataMRK, "MUV2": mydataMUV2, "SAP": mydataSAP, "SDF": mydataSDF, "SIE": mydataSIE, "TKA": mydataTKA, "VOW3": mydataVOW3, "OMXSPI_UTC": mydataOMXSPI_UTC, } var stk="elemm tartalom"; var art="neve"; elements = {}; // JOOO elements[art] = stk; elements[art] = mydataADS.join(); } ); }); </script> </head> <body> <script src="../../js/highstock.js"></script> <script src="../../js/modules/exporting.js"></script> <div id="container" style="height: 500px; min-width: 500px"></div> <select id="selectem" multiple> <option value="ADS">ADS</OPTION> <option value="ALV">ALV</OPTION> <option value="BAS">BAS</OPTION> <option value="BAYN">BAYN</OPTION> <option value="BEI">BEI</OPTION> <option value="CON">CON</OPTION> <option value="CBK">CBK</OPTION> <option value="DAI">DAI</OPTION> <option value="DAX_UTC">DAX_UTC</OPTION> <option value="DB1">DB1</OPTION> <option value="DBK">DBK</OPTION> <option value="EOAN">EOAN</OPTION> <option value="FME">FME</OPTION> <option value="FRE">FRE</OPTION> <option value="HEI">HEI</OPTION> <option value="LHA">LHA</OPTION> <option value="LIN">LIN</OPTION> <option value="LXS">LXS</OPTION> <option value="MRK">MRK</OPTION> <option value="MUV2">MUV2</OPTION> <option value="SAP">SAP</OPTION> <option value="SDF">SDF</OPTION> <option value="SIE">SIE</OPTION> <option value="TKA">TKA</OPTION> <option value="VOW3">VOW3</OPTION> <option value="OMXSPI_UTC">OMXSPI_UTC</OPTION> </select> <button id="btn">update</button> </body> </html>
0omxhtml0
0omx0_02joo.html
HTML
gpl2
6,879
// Base32 implementation // // Copyright 2010 Google Inc. // Author: Markus Gutschke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Encode and decode from base32 encoding using the following alphabet: // ABCDEFGHIJKLMNOPQRSTUVWXYZ234567 // This alphabet is documented in RFC 4668/3548 // // We allow white-space and hyphens, but all other characters are considered // invalid. // // All functions return the number of output bytes or -1 on error. If the // output buffer is too small, the result will silently be truncated. #ifndef _BASE32_H_ #define _BASE32_H_ #include <stdint.h> int base32_decode(const uint8_t *encoded, uint8_t *result, int bufSize) __attribute__((visibility("hidden"))); int base32_encode(const uint8_t *data, int length, uint8_t *result, int bufSize) __attribute__((visibility("hidden"))); #endif /* _BASE32_H_ */
001coldblade-authenticator
libpam/base32.h
C
asf20
1,387
// Demo wrapper for the PAM module. This is part of the Google Authenticator // project. // // Copyright 2011 Google Inc. // Author: Markus Gutschke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <assert.h> #include <fcntl.h> #include <security/pam_appl.h> #include <security/pam_modules.h> #include <setjmp.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/resource.h> #include <sys/time.h> #include <termios.h> #include <unistd.h> #if !defined(PAM_BAD_ITEM) // FreeBSD does not know about PAM_BAD_ITEM. And PAM_SYMBOL_ERR is an "enum", // we can't test for it at compile-time. #define PAM_BAD_ITEM PAM_SYMBOL_ERR #endif static struct termios old_termios; static int jmpbuf_valid; static sigjmp_buf jmpbuf; static int conversation(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr) { if (num_msg == 1 && (msg[0]->msg_style == PAM_PROMPT_ECHO_OFF || msg[0]->msg_style == PAM_PROMPT_ECHO_ON)) { *resp = malloc(sizeof(struct pam_response)); assert(*resp); (*resp)->resp = calloc(1024, 0); struct termios termios = old_termios; if (msg[0]->msg_style == PAM_PROMPT_ECHO_OFF) { termios.c_lflag &= ~(ECHO|ECHONL); } sigsetjmp(jmpbuf, 1); jmpbuf_valid = 1; sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGTSTP); assert(!sigprocmask(SIG_UNBLOCK, &mask, NULL)); printf("%s ", msg[0]->msg); assert(!tcsetattr(0, TCSAFLUSH, &termios)); assert(fgets((*resp)->resp, 1024, stdin)); assert(!tcsetattr(0, TCSAFLUSH, &old_termios)); puts(""); assert(!sigprocmask(SIG_BLOCK, &mask, NULL)); jmpbuf_valid = 0; char *ptr = strrchr((*resp)->resp, '\n'); if (ptr) { *ptr = '\000'; } (*resp)->resp_retcode = 0; return PAM_SUCCESS; } return PAM_CONV_ERR; } #ifdef sun #define PAM_CONST #else #define PAM_CONST const #endif int pam_get_item(const pam_handle_t *pamh, int item_type, PAM_CONST void **item) { switch (item_type) { case PAM_SERVICE: { static const char *service = "google_authenticator_demo"; memcpy(item, &service, sizeof(&service)); return PAM_SUCCESS; } case PAM_USER: { char *user = getenv("USER"); memcpy(item, &user, sizeof(&user)); return PAM_SUCCESS; } case PAM_CONV: { static struct pam_conv conv = { .conv = conversation }, *p_conv = &conv; memcpy(item, &p_conv, sizeof(p_conv)); return PAM_SUCCESS; } default: return PAM_BAD_ITEM; } } int pam_set_item(pam_handle_t *pamh, int item_type, PAM_CONST void *item) { switch (item_type) { case PAM_AUTHTOK: return PAM_SUCCESS; default: return PAM_BAD_ITEM; } } static void print_diagnostics(int signo) { extern const char *get_error_msg(void); assert(!tcsetattr(0, TCSAFLUSH, &old_termios)); fprintf(stderr, "%s\n", get_error_msg()); _exit(1); } static void reset_console(int signo) { assert(!tcsetattr(0, TCSAFLUSH, &old_termios)); puts(""); _exit(1); } static void stop(int signo) { assert(!tcsetattr(0, TCSAFLUSH, &old_termios)); puts(""); raise(SIGSTOP); } static void cont(int signo) { if (jmpbuf_valid) { siglongjmp(jmpbuf, 0); } } int main(int argc, char *argv[]) { extern int pam_sm_open_session(pam_handle_t *, int, int, const char **); // Try to redirect stdio to /dev/tty int fd = open("/dev/tty", O_RDWR); if (fd >= 0) { dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); close(fd); } // Disable core files assert(!setrlimit(RLIMIT_CORE, (struct rlimit []){ { 0, 0 } })); // Set up error and job control handlers assert(!tcgetattr(0, &old_termios)); sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGTSTP); assert(!sigprocmask(SIG_BLOCK, &mask, NULL)); assert(!signal(SIGABRT, print_diagnostics)); assert(!signal(SIGINT, reset_console)); assert(!signal(SIGTSTP, stop)); assert(!signal(SIGCONT, cont)); // Attempt login if (pam_sm_open_session(NULL, 0, argc-1, (const char **)argv+1) != PAM_SUCCESS) { fprintf(stderr, "Login failed\n"); abort(); } return 0; }
001coldblade-authenticator
libpam/demo.c
C
asf20
4,737
# Copyright 2010 Google Inc. # Author: Markus Gutschke # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. VERSION := 1.0 .SUFFIXES: .so ifeq ($(origin CC), default) CC := gcc endif DEF_CFLAGS := $(shell [ `uname` = SunOS ] && \ echo ' -D_POSIX_PTHREAD_SEMANTICS -D_REENTRANT') \ -fvisibility=hidden $(CFLAGS) DEF_LDFLAGS := $(shell [ `uname` = SunOS ] && echo ' -mimpure-text') $(LDFLAGS) LDL_LDFLAGS := $(shell $(CC) -shared -ldl -xc -o /dev/null /dev/null \ >/dev/null 2>&1 && echo ' -ldl') all: google-authenticator pam_google_authenticator.so demo \ pam_google_authenticator_unittest test: pam_google_authenticator_unittest ./pam_google_authenticator_unittest dist: clean all test $(RM) libpam-google-authenticator-$(VERSION)-source.tar.bz2 tar jfc libpam-google-authenticator-$(VERSION)-source.tar.bz2 \ --xform="s,^,libpam-google-authenticator-$(VERSION)/," \ --owner=root --group=root \ *.c *.h *.html Makefile FILEFORMAT README utc-time install: all @dst="`find /lib*/security /lib*/*/security -maxdepth 1 \ -name pam_unix.so -printf '%H' -quit 2>/dev/null`"; \ [ -d "$${dst}" ] || dst=/lib/security; \ [ -d "$${dst}" ] || dst=/usr/lib; \ sudo=; if [ $$(id -u) -ne 0 ]; then \ echo "You need to be root to install this module."; \ if [ -x /usr/bin/sudo ]; then \ echo "Invoking sudo:"; \ sudo=sudo; \ else \ exit 1; \ fi; \ fi; \ echo cp pam_google_authenticator.so $${dst}; \ tar fc - pam_google_authenticator.so | $${sudo} tar ofxC - $${dst}; \ \ echo cp google-authenticator /usr/local/bin; \ tar fc - google-authenticator | $${sudo} tar ofxC - /usr/local/bin; \ $${sudo} chmod 755 $${dst}/pam_google_authenticator.so \ /usr/local/bin/google-authenticator clean: $(RM) *.o *.so core google-authenticator demo \ pam_google_authenticator_unittest \ libpam-google-authenticator-*-source.tar.bz2 google-authenticator: google-authenticator.o base32.o hmac.o sha1.o $(CC) -g $(DEF_LDFLAGS) -o $@ $+ $(LDL_LDFLAGS) demo: demo.o pam_google_authenticator_demo.o base32.o hmac.o sha1.o $(CC) -g $(DEF_LDFLAGS) -rdynamic -o $@ $+ $(LDL_LDFLAGS) pam_google_authenticator_unittest: pam_google_authenticator_unittest.o \ base32.o hmac.o sha1.o $(CC) -g $(DEF_LDFLAGS) -rdynamic -o $@ $+ -lc $(LDL_LDFLAGS) pam_google_authenticator.so: base32.o hmac.o sha1.o pam_google_authenticator_testing.so: base32.o hmac.o sha1.o pam_google_authenticator.o: pam_google_authenticator.c base32.h hmac.h sha1.h pam_google_authenticator_demo.o: pam_google_authenticator.c base32.h hmac.h \ sha1.h $(CC) -DDEMO --std=gnu99 -Wall -O2 -g -fPIC -c $(DEF_CFLAGS) -o $@ $< pam_google_authenticator_testing.o: pam_google_authenticator.c base32.h \ hmac.h sha1.h $(CC) -DTESTING --std=gnu99 -Wall -O2 -g -fPIC -c $(DEF_CFLAGS) \ -o $@ $< pam_google_authenticator_unittest.o: pam_google_authenticator_unittest.c \ pam_google_authenticator_testing.so \ base32.h hmac.h sha1.h google-authenticator.o: google-authenticator.c base32.h hmac.h sha1.h demo.o: demo.c base32.h hmac.h sha1.h base32.o: base32.c base32.h hmac.o: hmac.c hmac.h sha1.h sha1.o: sha1.c sha1.h .c.o: $(CC) --std=gnu99 -Wall -O2 -g -fPIC -c $(DEF_CFLAGS) -o $@ $< .o.so: $(CC) -shared -g $(DEF_LDFLAGS) -o $@ $+ -lpam
001coldblade-authenticator
libpam/Makefile
Makefile
asf20
4,915
// SHA1 header file // // Copyright 2010 Google Inc. // Author: Markus Gutschke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SHA1_H__ #define SHA1_H__ #include <stdint.h> #define SHA1_BLOCKSIZE 64 #define SHA1_DIGEST_LENGTH 20 typedef struct { uint32_t digest[8]; uint32_t count_lo, count_hi; uint8_t data[SHA1_BLOCKSIZE]; int local; } SHA1_INFO; void sha1_init(SHA1_INFO *sha1_info) __attribute__((visibility("hidden"))); void sha1_update(SHA1_INFO *sha1_info, const uint8_t *buffer, int count) __attribute__((visibility("hidden"))); void sha1_final(SHA1_INFO *sha1_info, uint8_t digest[20]) __attribute__((visibility("hidden"))); #endif
001coldblade-authenticator
libpam/sha1.h
C
asf20
1,189
#!/usr/bin/env python import time t = time.time() u = time.gmtime(t) s = time.strftime('%a, %e %b %Y %T GMT', u) print 'Content-Type: text/javascript' print 'Cache-Control: no-cache' print 'Date: ' + s print 'Expires: ' + s print '' print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
001coldblade-authenticator
libpam/utc-time/utc-time.py
Python
asf20
300
// Base32 implementation // // Copyright 2010 Google Inc. // Author: Markus Gutschke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string.h> #include "base32.h" int base32_decode(const uint8_t *encoded, uint8_t *result, int bufSize) { int buffer = 0; int bitsLeft = 0; int count = 0; for (const uint8_t *ptr = encoded; count < bufSize && *ptr; ++ptr) { uint8_t ch = *ptr; if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-') { continue; } buffer <<= 5; // Deal with commonly mistyped characters if (ch == '0') { ch = 'O'; } else if (ch == '1') { ch = 'L'; } else if (ch == '8') { ch = 'B'; } // Look up one base32 digit if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { ch = (ch & 0x1F) - 1; } else if (ch >= '2' && ch <= '7') { ch -= '2' - 26; } else { return -1; } buffer |= ch; bitsLeft += 5; if (bitsLeft >= 8) { result[count++] = buffer >> (bitsLeft - 8); bitsLeft -= 8; } } if (count < bufSize) { result[count] = '\000'; } return count; } int base32_encode(const uint8_t *data, int length, uint8_t *result, int bufSize) { if (length < 0 || length > (1 << 28)) { return -1; } int count = 0; if (length > 0) { int buffer = data[0]; int next = 1; int bitsLeft = 8; while (count < bufSize && (bitsLeft > 0 || next < length)) { if (bitsLeft < 5) { if (next < length) { buffer <<= 8; buffer |= data[next++] & 0xFF; bitsLeft += 8; } else { int pad = 5 - bitsLeft; buffer <<= pad; bitsLeft += pad; } } int index = 0x1F & (buffer >> (bitsLeft - 5)); bitsLeft -= 5; result[count++] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"[index]; } } if (count < bufSize) { result[count] = '\000'; } return count; }
001coldblade-authenticator
libpam/base32.c
C
asf20
2,471
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <!-- TOTP Debugger -- -- Copyright 2011 Google Inc. -- Author: Markus Gutschke -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. --> <head> <link rel="shortcut icon" href="http://code.google.com/p/google-authenticator/logo" type="image/png"> <title>TOTP Debugger</title> <script src="https://utc-time.appspot.com"></script> <!-- Returns a line of the form: -- var timeskew = new Date().getTime() - XXX.XX; --> <script> <!-- // Given a secret key "K" and a timestamp "t" (in 30s units since the // beginning of the epoch), return a TOTP code. function totp(K,t) { function sha1(C){ function L(x,b){return x<<b|x>>>32-b;} var l=C.length,D=C.concat([1<<31]),V=0x67452301,W=0x88888888, Y=271733878,X=Y^W,Z=0xC3D2E1F0;W^=V; do D.push(0);while(D.length+1&15);D.push(32*l); while (D.length){ var E=D.splice(0,16),a=V,b=W,c=X,d=Y,e=Z,f,k,i=12; function I(x){var t=L(a,5)+f+e+k+E[x];e=d;d=c;c=L(b,30);b=a;a=t;} for(;++i<77;)E.push(L(E[i]^E[i-5]^E[i-11]^E[i-13],1)); k=0x5A827999;for(i=0;i<20;I(i++))f=b&c|~b&d; k=0x6ED9EBA1;for(;i<40;I(i++))f=b^c^d; k=0x8F1BBCDC;for(;i<60;I(i++))f=b&c|b&d|c&d; k=0xCA62C1D6;for(;i<80;I(i++))f=b^c^d; V+=a;W+=b;X+=c;Y+=d;Z+=e;} return[V,W,X,Y,Z]; } var k=[],l=[],i=0,j=0,c=0; for (;i<K.length;){ c=c*32+'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'. indexOf(K.charAt(i++).toUpperCase()); if((j+=5)>31)k.push(Math.floor(c/(1<<(j-=32)))),c&=31;} j&&k.push(c<<(32-j)); for(i=0;i<16;++i)l.push(0x6A6A6A6A^(k[i]=k[i]^0x5C5C5C5C)); var s=sha1(k.concat(sha1(l.concat([0,t])))),o=s[4]&0xF; return ((s[o>>2]<<8*(o&3)|(o&3?s[(o>>2)+1]>>>8*(4-o&3):0))&-1>>>1)%1000000; } // Periodically check whether we need to update the UI. It would be a little // more efficient to only call this function as a direct result of // significant state changes. But polling is cheap, and keeps the code a // little easier. var lastsecret,lastlabel,lastepochseconds,lastoverrideepoch; var lasttimestamp,lastoverride,lastsearch; function refresh() { // Compute current TOTP code var k=document.getElementById('secret').value. replace(/[^ABCDEFGHIJKLMNOPQRSTUVWXYZ234567]/gi, ''); var d=document.getElementById('overrideepoch').value.replace(/[^0-9]/g, ''); if (d) e=parseInt(d); else e=Math.floor(new Date().getTime()/1000); var t=Math.floor(e/30); var s=document.getElementById('override').value.replace(/[^0-9]/g, ''); if (s) { t=parseInt(s); e=30*t; } var label=escape(document.getElementById('label').value); var search=document.getElementById('search').value; // If TOTP code has changed (either because of user edits, or // because of elapsed time), update the user interface. if (k != lastsecret || label != lastlabel || e != lastepochseconds || d != lastoverrideepoch || t != lasttimestamp || s != lastoverride || search != lastsearch) { if (d != lastoverrideepoch) { document.getElementById('override').value = ''; s = ''; } else if (s != lastoverride) { document.getElementById('overrideepoch').value = ''; d = ''; } lastsecret=k; lastlabel=label; lastepochseconds=e; lastoverrideepoch=d; lasttimestamp=t; lastoverride=s; lastsearch=search; var code=totp(k,t); // Compute the OTPAuth URL and the associated QR code var h='https://www.google.com/chart?chs=200x200&chld=M|0&'+ 'cht=qr&chl=otpauth://totp/'+encodeURI(label)+'%3Fsecret%3D'+k; var a=document.getElementById('authurl') a.innerHTML='otpauth://totp/'+label+'?secret='+k; a.href=h; document.getElementById('aqr').href=h; var q=document.getElementById('qr'); q.src=h; q.alt=label+' '+k; q.title=label+' '+k; // Show the current time in seconds and in 30s increments since midnight // Jan 1st, 1970. Optionally, let the user override this timestamp. document.getElementById('epoch').innerHTML=e; document.getElementById('ts').innerHTML=t; // Show the current TOTP code. document.getElementById('totp').innerHTML=code; // If the user manually entered a TOTP code, try to find a matching code // within a 25h window. var result=''; if (search && !!(search=parseInt(search))) { for (var i=0; i < 25*120; ++i) { if (search == totp(k, t+(i&1?-Math.floor(i/2):Math.floor(i/2)))) { if (i<2) { result='&nbsp;'; break; } if (i >= 120) { result=result + Math.floor(i/120) + 'h '; i%=120; } if (i >= 4) { result=result + Math.floor(i/4) + 'min '; i%=4; } if (i&2) { result=result + '30s '; } if (i&1) { result='Code was valid ' + result + 'ago'; } else { result='Code will be valid in ' + result; } break; } } if (!result) { result='No such code within a &#177;12h window'; } } document.getElementById('searchresult').innerHTML=result + '&nbsp;'; // If possible, compare the current time as reported by Javascript // to "official" time as reported by AppEngine. If there is any significant // difference, show a warning message. We always expect at least a minor // time skew due to round trip delays, which we are not bothering to // compensate for. if (typeof timeskew != undefined) { var ts=document.getElementById('timeskew'); if (Math.abs(timeskew) < 2000) { ts.style.color=''; ts.innerHTML="Your computer's time is set correctly. TOTP codes " + "will be computed accurately."; } else if (Math.abs(timeskew) < 30000) { ts.style.color=''; ts.innerHTML="Your computer's time is off by " + (Math.round(Math.abs(timeskew)/1000)) + " seconds. This is within " + "acceptable tolerances. Computed TOTP codes might be different " + "from the ones in the mobile application, but they will be " + "accepted by the server."; } else { ts.style.color='#dd0000'; ts.innerHTML="<b>Your computer's time is off by " + (Math.round(Math.abs(timeskew)/1000)) + " seconds. Computed TOTP " + "codes are probably incorrect.</b>"; } } } } --></script> </head> <body style="font-family: sans-serif" onload="setInterval(refresh, 100)"> <h1>TOTP Debugger</h1> <table> <tr><td colspan="7"><a style="text-decoration: none; color: black" id="authurl"></a></td></tr> <tr><td colspan="3">Enter&nbsp;secret&nbsp;key&nbsp;in&nbsp;BASE32:&nbsp;</td> <td><input type="text" id="secret" /></td> <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> <td rowspan="8"><a style="text-decoration: none" id="aqr"> <img id="qr" border="0"></a></td><td width="100%">&nbsp;</td></tr> <tr><td colspan="3">Account&nbsp;label:&nbsp;</td> <td><input type="text" id="label" /></td></tr> <tr><td>Interval:&nbsp;</td><td align="right">30s</td><td>&nbsp;</td></tr> <tr><td>Time:&nbsp;</td><td align="right"> <span id="epoch"></span></td><td>&nbsp;</td><td> <input type="text" id="overrideepoch" /></td></tr> <tr><td>Timestamp:&nbsp;</td><td align="right"><span id="ts"></span></td> <td>&nbsp;</td><td><input type="text" id="override" /></td></tr> <tr><td>TOTP:&nbsp;</td><td align="right"><span id="totp"></span></td> <td>&nbsp;</td><td><input type="text" id="search" /></td></tr> <tr><td colspan="4" id="searchresult"></td></tr> </table> <br /> <div id="timeskew" style="width: 80%"></div> <br /> <br /> <div style="width: 80%; color: #dd0000; font-size: small"> <p><b>WARNING!</b> This website is a development and debugging tool only. Do <b>not</b> use it to generate security tokens for logging into your account. You should never store, process or otherwise access the secret key on the same machine that you use for accessing your account. Doing so completely defeats the security of two-step verification.</p> <p>Instead, use one of the mobile phone clients made available by the <a href="http://code.google.com/p/google-authenticator">Google Authenticator</a> project. Or follow the <a href="http://www.google.com/support/accounts/bin/static.py?hl=en&page=guide.cs&guide=1056283&topic=1056285">instructions</a> provided by Google.</p> <p>If you ever entered your real secret key into this website, please immediately <a href="https://www.google.com/accounts/SmsAuthConfig">reset your secret key</a>.</p> </div> </body> </html>
001coldblade-authenticator
libpam/totp.html
HTML
asf20
9,422
// HMAC_SHA1 implementation // // Copyright 2010 Google Inc. // Author: Markus Gutschke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string.h> #include "hmac.h" #include "sha1.h" void hmac_sha1(const uint8_t *key, int keyLength, const uint8_t *data, int dataLength, uint8_t *result, int resultLength) { SHA1_INFO ctx; uint8_t hashed_key[SHA1_DIGEST_LENGTH]; if (keyLength > 64) { // The key can be no bigger than 64 bytes. If it is, we'll hash it down to // 20 bytes. sha1_init(&ctx); sha1_update(&ctx, key, keyLength); sha1_final(&ctx, hashed_key); key = hashed_key; keyLength = SHA1_DIGEST_LENGTH; } // The key for the inner digest is derived from our key, by padding the key // the full length of 64 bytes, and then XOR'ing each byte with 0x36. uint8_t tmp_key[64]; for (int i = 0; i < keyLength; ++i) { tmp_key[i] = key[i] ^ 0x36; } memset(tmp_key + keyLength, 0x36, 64 - keyLength); // Compute inner digest sha1_init(&ctx); sha1_update(&ctx, tmp_key, 64); sha1_update(&ctx, data, dataLength); uint8_t sha[SHA1_DIGEST_LENGTH]; sha1_final(&ctx, sha); // The key for the outer digest is derived from our key, by padding the key // the full length of 64 bytes, and then XOR'ing each byte with 0x5C. for (int i = 0; i < keyLength; ++i) { tmp_key[i] = key[i] ^ 0x5C; } memset(tmp_key + keyLength, 0x5C, 64 - keyLength); // Compute outer digest sha1_init(&ctx); sha1_update(&ctx, tmp_key, 64); sha1_update(&ctx, sha, SHA1_DIGEST_LENGTH); sha1_final(&ctx, sha); // Copy result to output buffer and truncate or pad as necessary memset(result, 0, resultLength); if (resultLength > SHA1_DIGEST_LENGTH) { resultLength = SHA1_DIGEST_LENGTH; } memcpy(result, sha, resultLength); // Zero out all internal data structures memset(hashed_key, 0, sizeof(hashed_key)); memset(sha, 0, sizeof(sha)); memset(tmp_key, 0, sizeof(tmp_key)); }
001coldblade-authenticator
libpam/hmac.c
C
asf20
2,495
/* * Copyright 2010 Google Inc. * Author: Markus Gutschke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * An earlier version of this file was originally released into the public * domain by its authors. It has been modified to make the code compile and * link as part of the Google Authenticator project. These changes are * copyrighted by Google Inc. and released under the Apache License, * Version 2.0. * * The previous authors' terms are included below: */ /***************************************************************************** * * File: sha1.c * * Purpose: Implementation of the SHA1 message-digest algorithm. * * NIST Secure Hash Algorithm * Heavily modified by Uwe Hollerbach <uh@alumni.caltech edu> * from Peter C. Gutmann's implementation as found in * Applied Cryptography by Bruce Schneier * Further modifications to include the "UNRAVEL" stuff, below * * This code is in the public domain * ***************************************************************************** */ #define _BSD_SOURCE #include <sys/types.h> // Defines BYTE_ORDER, iff _BSD_SOURCE is defined #include <string.h> #include "sha1.h" #if !defined(BYTE_ORDER) #if defined(_BIG_ENDIAN) #define BYTE_ORDER 4321 #elif defined(_LITTLE_ENDIAN) #define BYTE_ORDER 1234 #else #error Need to define BYTE_ORDER #endif #endif #ifndef TRUNC32 #define TRUNC32(x) ((x) & 0xffffffffL) #endif /* SHA f()-functions */ #define f1(x,y,z) ((x & y) | (~x & z)) #define f2(x,y,z) (x ^ y ^ z) #define f3(x,y,z) ((x & y) | (x & z) | (y & z)) #define f4(x,y,z) (x ^ y ^ z) /* SHA constants */ #define CONST1 0x5a827999L #define CONST2 0x6ed9eba1L #define CONST3 0x8f1bbcdcL #define CONST4 0xca62c1d6L /* truncate to 32 bits -- should be a null op on 32-bit machines */ #define T32(x) ((x) & 0xffffffffL) /* 32-bit rotate */ #define R32(x,n) T32(((x << n) | (x >> (32 - n)))) /* the generic case, for when the overall rotation is not unraveled */ #define FG(n) \ T = T32(R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n); \ E = D; D = C; C = R32(B,30); B = A; A = T /* specific cases, for when the overall rotation is unraveled */ #define FA(n) \ T = T32(R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n); B = R32(B,30) #define FB(n) \ E = T32(R32(T,5) + f##n(A,B,C) + D + *WP++ + CONST##n); A = R32(A,30) #define FC(n) \ D = T32(R32(E,5) + f##n(T,A,B) + C + *WP++ + CONST##n); T = R32(T,30) #define FD(n) \ C = T32(R32(D,5) + f##n(E,T,A) + B + *WP++ + CONST##n); E = R32(E,30) #define FE(n) \ B = T32(R32(C,5) + f##n(D,E,T) + A + *WP++ + CONST##n); D = R32(D,30) #define FT(n) \ A = T32(R32(B,5) + f##n(C,D,E) + T + *WP++ + CONST##n); C = R32(C,30) static void sha1_transform(SHA1_INFO *sha1_info) { int i; uint8_t *dp; uint32_t T, A, B, C, D, E, W[80], *WP; dp = sha1_info->data; #undef SWAP_DONE #if BYTE_ORDER == 1234 #define SWAP_DONE for (i = 0; i < 16; ++i) { T = *((uint32_t *) dp); dp += 4; W[i] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); } #endif #if BYTE_ORDER == 4321 #define SWAP_DONE for (i = 0; i < 16; ++i) { T = *((uint32_t *) dp); dp += 4; W[i] = TRUNC32(T); } #endif #if BYTE_ORDER == 12345678 #define SWAP_DONE for (i = 0; i < 16; i += 2) { T = *((uint32_t *) dp); dp += 8; W[i] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); T >>= 32; W[i+1] = ((T << 24) & 0xff000000) | ((T << 8) & 0x00ff0000) | ((T >> 8) & 0x0000ff00) | ((T >> 24) & 0x000000ff); } #endif #if BYTE_ORDER == 87654321 #define SWAP_DONE for (i = 0; i < 16; i += 2) { T = *((uint32_t *) dp); dp += 8; W[i] = TRUNC32(T >> 32); W[i+1] = TRUNC32(T); } #endif #ifndef SWAP_DONE #define SWAP_DONE for (i = 0; i < 16; ++i) { T = *((uint32_t *) dp); dp += 4; W[i] = TRUNC32(T); } #endif /* SWAP_DONE */ for (i = 16; i < 80; ++i) { W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16]; W[i] = R32(W[i], 1); } A = sha1_info->digest[0]; B = sha1_info->digest[1]; C = sha1_info->digest[2]; D = sha1_info->digest[3]; E = sha1_info->digest[4]; WP = W; #ifdef UNRAVEL FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(1); FD(1); FE(1); FT(1); FA(1); FB(1); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(2); FT(2); FA(2); FB(2); FC(2); FD(2); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(3); FB(3); FC(3); FD(3); FE(3); FT(3); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); FC(4); FD(4); FE(4); FT(4); FA(4); FB(4); sha1_info->digest[0] = T32(sha1_info->digest[0] + E); sha1_info->digest[1] = T32(sha1_info->digest[1] + T); sha1_info->digest[2] = T32(sha1_info->digest[2] + A); sha1_info->digest[3] = T32(sha1_info->digest[3] + B); sha1_info->digest[4] = T32(sha1_info->digest[4] + C); #else /* !UNRAVEL */ #ifdef UNROLL_LOOPS FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(1); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(2); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(3); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); FG(4); #else /* !UNROLL_LOOPS */ for (i = 0; i < 20; ++i) { FG(1); } for (i = 20; i < 40; ++i) { FG(2); } for (i = 40; i < 60; ++i) { FG(3); } for (i = 60; i < 80; ++i) { FG(4); } #endif /* !UNROLL_LOOPS */ sha1_info->digest[0] = T32(sha1_info->digest[0] + A); sha1_info->digest[1] = T32(sha1_info->digest[1] + B); sha1_info->digest[2] = T32(sha1_info->digest[2] + C); sha1_info->digest[3] = T32(sha1_info->digest[3] + D); sha1_info->digest[4] = T32(sha1_info->digest[4] + E); #endif /* !UNRAVEL */ } /* initialize the SHA digest */ void sha1_init(SHA1_INFO *sha1_info) { sha1_info->digest[0] = 0x67452301L; sha1_info->digest[1] = 0xefcdab89L; sha1_info->digest[2] = 0x98badcfeL; sha1_info->digest[3] = 0x10325476L; sha1_info->digest[4] = 0xc3d2e1f0L; sha1_info->count_lo = 0L; sha1_info->count_hi = 0L; sha1_info->local = 0; } /* update the SHA digest */ void sha1_update(SHA1_INFO *sha1_info, const uint8_t *buffer, int count) { int i; uint32_t clo; clo = T32(sha1_info->count_lo + ((uint32_t) count << 3)); if (clo < sha1_info->count_lo) { ++sha1_info->count_hi; } sha1_info->count_lo = clo; sha1_info->count_hi += (uint32_t) count >> 29; if (sha1_info->local) { i = SHA1_BLOCKSIZE - sha1_info->local; if (i > count) { i = count; } memcpy(((uint8_t *) sha1_info->data) + sha1_info->local, buffer, i); count -= i; buffer += i; sha1_info->local += i; if (sha1_info->local == SHA1_BLOCKSIZE) { sha1_transform(sha1_info); } else { return; } } while (count >= SHA1_BLOCKSIZE) { memcpy(sha1_info->data, buffer, SHA1_BLOCKSIZE); buffer += SHA1_BLOCKSIZE; count -= SHA1_BLOCKSIZE; sha1_transform(sha1_info); } memcpy(sha1_info->data, buffer, count); sha1_info->local = count; } static void sha1_transform_and_copy(unsigned char digest[20], SHA1_INFO *sha1_info) { sha1_transform(sha1_info); digest[ 0] = (unsigned char) ((sha1_info->digest[0] >> 24) & 0xff); digest[ 1] = (unsigned char) ((sha1_info->digest[0] >> 16) & 0xff); digest[ 2] = (unsigned char) ((sha1_info->digest[0] >> 8) & 0xff); digest[ 3] = (unsigned char) ((sha1_info->digest[0] ) & 0xff); digest[ 4] = (unsigned char) ((sha1_info->digest[1] >> 24) & 0xff); digest[ 5] = (unsigned char) ((sha1_info->digest[1] >> 16) & 0xff); digest[ 6] = (unsigned char) ((sha1_info->digest[1] >> 8) & 0xff); digest[ 7] = (unsigned char) ((sha1_info->digest[1] ) & 0xff); digest[ 8] = (unsigned char) ((sha1_info->digest[2] >> 24) & 0xff); digest[ 9] = (unsigned char) ((sha1_info->digest[2] >> 16) & 0xff); digest[10] = (unsigned char) ((sha1_info->digest[2] >> 8) & 0xff); digest[11] = (unsigned char) ((sha1_info->digest[2] ) & 0xff); digest[12] = (unsigned char) ((sha1_info->digest[3] >> 24) & 0xff); digest[13] = (unsigned char) ((sha1_info->digest[3] >> 16) & 0xff); digest[14] = (unsigned char) ((sha1_info->digest[3] >> 8) & 0xff); digest[15] = (unsigned char) ((sha1_info->digest[3] ) & 0xff); digest[16] = (unsigned char) ((sha1_info->digest[4] >> 24) & 0xff); digest[17] = (unsigned char) ((sha1_info->digest[4] >> 16) & 0xff); digest[18] = (unsigned char) ((sha1_info->digest[4] >> 8) & 0xff); digest[19] = (unsigned char) ((sha1_info->digest[4] ) & 0xff); } /* finish computing the SHA digest */ void sha1_final(SHA1_INFO *sha1_info, uint8_t digest[20]) { int count; uint32_t lo_bit_count, hi_bit_count; lo_bit_count = sha1_info->count_lo; hi_bit_count = sha1_info->count_hi; count = (int) ((lo_bit_count >> 3) & 0x3f); ((uint8_t *) sha1_info->data)[count++] = 0x80; if (count > SHA1_BLOCKSIZE - 8) { memset(((uint8_t *) sha1_info->data) + count, 0, SHA1_BLOCKSIZE - count); sha1_transform(sha1_info); memset((uint8_t *) sha1_info->data, 0, SHA1_BLOCKSIZE - 8); } else { memset(((uint8_t *) sha1_info->data) + count, 0, SHA1_BLOCKSIZE - 8 - count); } sha1_info->data[56] = (uint8_t)((hi_bit_count >> 24) & 0xff); sha1_info->data[57] = (uint8_t)((hi_bit_count >> 16) & 0xff); sha1_info->data[58] = (uint8_t)((hi_bit_count >> 8) & 0xff); sha1_info->data[59] = (uint8_t)((hi_bit_count >> 0) & 0xff); sha1_info->data[60] = (uint8_t)((lo_bit_count >> 24) & 0xff); sha1_info->data[61] = (uint8_t)((lo_bit_count >> 16) & 0xff); sha1_info->data[62] = (uint8_t)((lo_bit_count >> 8) & 0xff); sha1_info->data[63] = (uint8_t)((lo_bit_count >> 0) & 0xff); sha1_transform_and_copy(digest, sha1_info); } /***EOF***/
001coldblade-authenticator
libpam/sha1.c
C
asf20
11,201
// Helper program to generate a new secret for use in two-factor // authentication. // // Copyright 2010 Google Inc. // Author: Markus Gutschke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #define _GNU_SOURCE #include <assert.h> #include <errno.h> #include <dlfcn.h> #include <fcntl.h> #include <getopt.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "base32.h" #include "hmac.h" #include "sha1.h" #define SECRET "/.google_authenticator" #define SECRET_BITS 80 // Must be divisible by eight #define VERIFICATION_CODE_MODULUS (1000*1000) // Six digits #define SCRATCHCODES 5 // Number of initial scratchcodes #define SCRATCHCODE_LENGTH 8 // Eight digits per scratchcode #define BYTES_PER_SCRATCHCODE 4 // 32bit of randomness is enough #define BITS_PER_BASE32_CHAR 5 // Base32 expands space by 8/5 static enum { QR_UNSET=0, QR_NONE, QR_ANSI, QR_UTF8 } qr_mode = QR_UNSET; static int generateCode(const char *key, unsigned long tm) { uint8_t challenge[8]; for (int i = 8; i--; tm >>= 8) { challenge[i] = tm; } // Estimated number of bytes needed to represent the decoded secret. Because // of white-space and separators, this is an upper bound of the real number, // which we later get as a return-value from base32_decode() int secretLen = (strlen(key) + 7)/8*BITS_PER_BASE32_CHAR; // Sanity check, that our secret will fixed into a reasonably-sized static // array. if (secretLen <= 0 || secretLen > 100) { return -1; } // Decode secret from Base32 to a binary representation, and check that we // have at least one byte's worth of secret data. uint8_t secret[100]; if ((secretLen = base32_decode((const uint8_t *)key, secret, secretLen))<1) { return -1; } // Compute the HMAC_SHA1 of the secrete and the challenge. uint8_t hash[SHA1_DIGEST_LENGTH]; hmac_sha1(secret, secretLen, challenge, 8, hash, SHA1_DIGEST_LENGTH); // Pick the offset where to sample our hash value for the actual verification // code. int offset = hash[SHA1_DIGEST_LENGTH - 1] & 0xF; // Compute the truncated hash in a byte-order independent loop. unsigned int truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; truncatedHash |= hash[offset + i]; } // Truncate to a smaller number of digits. truncatedHash &= 0x7FFFFFFF; truncatedHash %= VERIFICATION_CODE_MODULUS; return truncatedHash; } static const char *getUserName(uid_t uid) { struct passwd pwbuf, *pw; char *buf; #ifdef _SC_GETPW_R_SIZE_MAX int len = sysconf(_SC_GETPW_R_SIZE_MAX); if (len <= 0) { len = 4096; } #else int len = 4096; #endif buf = malloc(len); char *user; if (getpwuid_r(uid, &pwbuf, buf, len, &pw) || !pw) { user = malloc(32); snprintf(user, 32, "%d", uid); } else { user = strdup(pw->pw_name); if (!user) { perror("malloc()"); _exit(1); } } free(buf); return user; } static const char *urlEncode(const char *s) { char *ret = malloc(3*strlen(s) + 1); char *d = ret; do { switch (*s) { case '%': case '&': case '?': case '=': encode: sprintf(d, "%%%02X", (unsigned char)*s); d += 3; break; default: if ((*s && *s <= ' ') || *s >= '\x7F') { goto encode; } *d++ = *s; break; } } while (*s++); ret = realloc(ret, strlen(ret) + 1); return ret; } static const char *getURL(const char *secret, const char *label, char **encoderURL, const int use_totp) { const char *encodedLabel = urlEncode(label); char *url = malloc(strlen(encodedLabel) + strlen(secret) + 80); char totp = 'h'; if (use_totp) { totp = 't'; } sprintf(url, "otpauth://%cotp/%s?secret=%s", totp, encodedLabel, secret); if (encoderURL) { const char *encoder = "https://www.google.com/chart?chs=200x200&" "chld=M|0&cht=qr&chl="; const char *encodedURL = urlEncode(url); *encoderURL = strcat(strcpy(malloc(strlen(encoder) + strlen(encodedURL) + 1), encoder), encodedURL); free((void *)encodedURL); } free((void *)encodedLabel); return url; } #define ANSI_RESET "\x1B[0m" #define ANSI_BLACKONGREY "\x1B[30;47;27m" #define ANSI_WHITE "\x1B[27m" #define ANSI_BLACK "\x1B[7m" #define UTF8_BOTH "\xE2\x96\x88" #define UTF8_TOPHALF "\xE2\x96\x80" #define UTF8_BOTTOMHALF "\xE2\x96\x84" static void displayQRCode(const char *secret, const char *label, const int use_totp) { if (qr_mode == QR_NONE) { return; } char *encoderURL; const char *url = getURL(secret, label, &encoderURL, use_totp); puts(encoderURL); // Only newer systems have support for libqrencode. So, instead of requiring // it at build-time, we look for it at run-time. If it cannot be found, the // user can still type the code in manually, or he can copy the URL into // his browser. if (isatty(1)) { void *qrencode = dlopen("libqrencode.so.2", RTLD_NOW | RTLD_LOCAL); if (!qrencode) { qrencode = dlopen("libqrencode.so.3", RTLD_NOW | RTLD_LOCAL); } if (qrencode) { typedef struct { int version; int width; unsigned char *data; } QRcode; QRcode *(*QRcode_encodeString8bit)(const char *, int, int) = (QRcode *(*)(const char *, int, int)) dlsym(qrencode, "QRcode_encodeString8bit"); void (*QRcode_free)(QRcode *qrcode) = (void (*)(QRcode *))dlsym(qrencode, "QRcode_free"); if (QRcode_encodeString8bit && QRcode_free) { QRcode *qrcode = QRcode_encodeString8bit(url, 0, 1); char *ptr = (char *)qrcode->data; // Output QRCode using ANSI colors. Instead of black on white, we // output black on grey, as that works independently of whether the // user runs his terminals in a black on white or white on black color // scheme. // But this requires that we print a border around the entire QR Code. // Otherwise, readers won't be able to recognize it. if (qr_mode != QR_UTF8) { for (int i = 0; i < 2; ++i) { printf(ANSI_BLACKONGREY); for (int x = 0; x < qrcode->width + 4; ++x) printf(" "); puts(ANSI_RESET); } for (int y = 0; y < qrcode->width; ++y) { printf(ANSI_BLACKONGREY" "); int isBlack = 0; for (int x = 0; x < qrcode->width; ++x) { if (*ptr++ & 1) { if (!isBlack) { printf(ANSI_BLACK); } isBlack = 1; } else { if (isBlack) { printf(ANSI_WHITE); } isBlack = 0; } printf(" "); } if (isBlack) { printf(ANSI_WHITE); } puts(" "ANSI_RESET); } for (int i = 0; i < 2; ++i) { printf(ANSI_BLACKONGREY); for (int x = 0; x < qrcode->width + 4; ++x) printf(" "); puts(ANSI_RESET); } } else { // Drawing the QRCode with Unicode block elements is desirable as // it makes the code much smaller, which is often easier to scan. // Unfortunately, many terminal emulators do not display these // Unicode characters properly. printf(ANSI_BLACKONGREY); for (int i = 0; i < qrcode->width + 4; ++i) { printf(" "); } puts(ANSI_RESET); for (int y = 0; y < qrcode->width; y += 2) { printf(ANSI_BLACKONGREY" "); for (int x = 0; x < qrcode->width; ++x) { int top = qrcode->data[y*qrcode->width + x] & 1; int bottom = 0; if (y+1 < qrcode->width) { bottom = qrcode->data[(y+1)*qrcode->width + x] & 1; } if (top) { if (bottom) { printf(UTF8_BOTH); } else { printf(UTF8_TOPHALF); } } else { if (bottom) { printf(UTF8_BOTTOMHALF); } else { printf(" "); } } } puts(" "ANSI_RESET); } printf(ANSI_BLACKONGREY); for (int i = 0; i < qrcode->width + 4; ++i) { printf(" "); } puts(ANSI_RESET); } QRcode_free(qrcode); } dlclose(qrencode); } } free((char *)url); free(encoderURL); } static int maybe(const char *msg) { printf("\n%s (y/n) ", msg); fflush(stdout); char ch; do { ch = getchar(); } while (ch == ' ' || ch == '\r' || ch == '\n'); if (ch == 'y' || ch == 'Y') { return 1; } return 0; } static char *addOption(char *buf, size_t nbuf, const char *option) { assert(strlen(buf) + strlen(option) < nbuf); char *scratchCodes = strchr(buf, '\n'); assert(scratchCodes); scratchCodes++; memmove(scratchCodes + strlen(option), scratchCodes, strlen(scratchCodes) + 1); memcpy(scratchCodes, option, strlen(option)); return buf; } static char *maybeAddOption(const char *msg, char *buf, size_t nbuf, const char *option) { if (maybe(msg)) { buf = addOption(buf, nbuf, option); } return buf; } static void usage(void) { puts( "google-authenticator [<options>]\n" " -h, --help Print this message\n" " -c, --counter-based Set up counter-based (HOTP) verification\n" " -t, --time-based Set up time-based (TOTP) verification\n" " -d, --disallow-reuse Disallow reuse of previously used TOTP tokens\n" " -D, --allow-reuse Allow reuse of previously used TOTP tokens\n" " -f, --force Write file without first confirming with user\n" " -l, --label=<label> Override the default label in \"otpauth://\" URL\n" " -q, --quiet Quiet mode\n" " -Q, --qr-mode={NONE,ANSI,UTF8}\n" " -r, --rate-limit=N Limit logins to N per every M seconds\n" " -R, --rate-time=M Limit logins to N per every M seconds\n" " -u, --no-rate-limit Disable rate-limiting\n" " -s, --secret=<file> Specify a non-standard file location\n" " -w, --window-size=W Set window of concurrently valid codes\n" " -W, --minimal-window Disable window of concurrently valid codes"); } int main(int argc, char *argv[]) { uint8_t buf[SECRET_BITS/8 + SCRATCHCODES*BYTES_PER_SCRATCHCODE]; static const char hotp[] = "\" HOTP_COUNTER 1\n"; static const char totp[] = "\" TOTP_AUTH\n"; static const char disallow[] = "\" DISALLOW_REUSE\n"; static const char window[] = "\" WINDOW_SIZE 17\n"; static const char ratelimit[] = "\" RATE_LIMIT 3 30\n"; char secret[(SECRET_BITS + BITS_PER_BASE32_CHAR-1)/BITS_PER_BASE32_CHAR + 1 /* newline */ + sizeof(hotp) + // hotp and totp are mutually exclusive. sizeof(disallow) + sizeof(window) + sizeof(ratelimit) + 5 + // NN MMM (total of five digits) SCRATCHCODE_LENGTH*(SCRATCHCODES + 1 /* newline */) + 1 /* NUL termination character */]; enum { ASK_MODE, HOTP_MODE, TOTP_MODE } mode = ASK_MODE; enum { ASK_REUSE, DISALLOW_REUSE, ALLOW_REUSE } reuse = ASK_REUSE; int force = 0, quiet = 0; int r_limit = 0, r_time = 0; char *secret_fn = NULL; char *label = NULL; int window_size = 0; int idx; for (;;) { static const char optstring[] = "+hctdDfl:qQ:r:R:us:w:W"; static struct option options[] = { { "help", 0, 0, 'h' }, { "counter-based", 0, 0, 'c' }, { "time-based", 0, 0, 't' }, { "disallow-reuse", 0, 0, 'd' }, { "allow-reuse", 0, 0, 'D' }, { "force", 0, 0, 'f' }, { "label", 1, 0, 'l' }, { "quiet", 0, 0, 'q' }, { "qr-mode", 1, 0, 'Q' }, { "rate-limit", 1, 0, 'r' }, { "rate-time", 1, 0, 'R' }, { "no-rate-limit", 0, 0, 'u' }, { "secret", 1, 0, 's' }, { "window-size", 1, 0, 'w' }, { "minimal-window", 0, 0, 'W' }, { 0, 0, 0, 0 } }; idx = -1; int c = getopt_long(argc, argv, optstring, options, &idx); if (c > 0) { for (int i = 0; options[i].name; i++) { if (options[i].val == c) { idx = i; break; } } } else if (c < 0) { break; } if (idx-- <= 0) { // Help (or invalid argument) err: usage(); if (idx < -1) { fprintf(stderr, "Failed to parse command line\n"); _exit(1); } exit(0); } else if (!idx--) { // counter-based if (mode != ASK_MODE) { fprintf(stderr, "Duplicate -c and/or -t option detected\n"); _exit(1); } if (reuse != ASK_REUSE) { reuse_err: fprintf(stderr, "Reuse of tokens is not a meaningful parameter " "when in counter-based mode\n"); _exit(1); } mode = HOTP_MODE; } else if (!idx--) { // time-based if (mode != ASK_MODE) { fprintf(stderr, "Duplicate -c and/or -t option detected\n"); _exit(1); } mode = TOTP_MODE; } else if (!idx--) { // disallow-reuse if (reuse != ASK_REUSE) { fprintf(stderr, "Duplicate -d and/or -D option detected\n"); _exit(1); } if (mode == HOTP_MODE) { goto reuse_err; } reuse = DISALLOW_REUSE; } else if (!idx--) { // allow-reuse if (reuse != ASK_REUSE) { fprintf(stderr, "Duplicate -d and/or -D option detected\n"); _exit(1); } if (mode == HOTP_MODE) { goto reuse_err; } reuse = ALLOW_REUSE; } else if (!idx--) { // force if (force) { fprintf(stderr, "Duplicate -f option detected\n"); _exit(1); } force = 1; } else if (!idx--) { // label if (label) { fprintf(stderr, "Duplicate -l option detected\n"); _exit(1); } label = strdup(optarg); } else if (!idx--) { // quiet if (quiet) { fprintf(stderr, "Duplicate -q option detected\n"); _exit(1); } quiet = 1; } else if (!idx--) { // qr-mode if (qr_mode != QR_UNSET) { fprintf(stderr, "Duplicate -Q option detected\n"); _exit(1); } if (!strcasecmp(optarg, "none")) { qr_mode = QR_NONE; } else if (!strcasecmp(optarg, "ansi")) { qr_mode = QR_ANSI; } else if (!strcasecmp(optarg, "utf8")) { qr_mode = QR_UTF8; } else { fprintf(stderr, "Invalid qr-mode \"%s\"\n", optarg); _exit(1); } } else if (!idx--) { // rate-limit if (r_limit > 0) { fprintf(stderr, "Duplicate -r option detected\n"); _exit(1); } else if (r_limit < 0) { fprintf(stderr, "-u is mutually exclusive with -r\n"); _exit(1); } char *endptr; errno = 0; long l = strtol(optarg, &endptr, 10); if (errno || endptr == optarg || *endptr || l < 1 || l > 10) { fprintf(stderr, "-r requires an argument in the range 1..10\n"); _exit(1); } r_limit = (int)l; } else if (!idx--) { // rate-time if (r_time > 0) { fprintf(stderr, "Duplicate -R option detected\n"); _exit(1); } else if (r_time < 0) { fprintf(stderr, "-u is mutually exclusive with -R\n"); _exit(1); } char *endptr; errno = 0; long l = strtol(optarg, &endptr, 10); if (errno || endptr == optarg || *endptr || l < 15 || l > 600) { fprintf(stderr, "-R requires an argument in the range 15..600\n"); _exit(1); } r_time = (int)l; } else if (!idx--) { // no-rate-limit if (r_limit > 0 || r_time > 0) { fprintf(stderr, "-u is mutually exclusive with -r/-R\n"); _exit(1); } if (r_limit < 0) { fprintf(stderr, "Duplicate -u option detected\n"); _exit(1); } r_limit = r_time = -1; } else if (!idx--) { // secret if (secret_fn) { fprintf(stderr, "Duplicate -s option detected\n"); _exit(1); } if (!*optarg) { fprintf(stderr, "-s must be followed by a filename\n"); _exit(1); } secret_fn = strdup(optarg); if (!secret_fn) { perror("malloc()"); _exit(1); } } else if (!idx--) { // window-size if (window_size) { fprintf(stderr, "Duplicate -w/-W option detected\n"); _exit(1); } char *endptr; errno = 0; long l = strtol(optarg, &endptr, 10); if (errno || endptr == optarg || *endptr || l < 1 || l > 21) { fprintf(stderr, "-w requires an argument in the range 1..21\n"); _exit(1); } window_size = (int)l; } else if (!idx--) { // minimal-window if (window_size) { fprintf(stderr, "Duplicate -w/-W option detected\n"); _exit(1); } window_size = -1; } else { fprintf(stderr, "Error\n"); _exit(1); } } idx = -1; if (optind != argc) { goto err; } if (reuse != ASK_REUSE && mode != TOTP_MODE) { fprintf(stderr, "Must select time-based mode, when using -d or -D\n"); _exit(1); } if ((r_time && !r_limit) || (!r_time && r_limit)) { fprintf(stderr, "Must set -r when setting -R, and vice versa\n"); _exit(1); } if (!label) { uid_t uid = getuid(); const char *user = getUserName(uid); char hostname[128] = { 0 }; if (gethostname(hostname, sizeof(hostname)-1)) { strcpy(hostname, "unix"); } label = strcat(strcat(strcpy(malloc(strlen(user) + strlen(hostname) + 2), user), "@"), hostname); free((char *)user); } int fd = open("/dev/urandom", O_RDONLY); if (fd < 0) { perror("Failed to open \"/dev/urandom\""); return 1; } if (read(fd, buf, sizeof(buf)) != sizeof(buf)) { urandom_failure: perror("Failed to read from \"/dev/urandom\""); return 1; } base32_encode(buf, SECRET_BITS/8, (uint8_t *)secret, sizeof(secret)); int use_totp; if (mode == ASK_MODE) { use_totp = maybe("Do you want authentication tokens to be time-based"); } else { use_totp = mode == TOTP_MODE; } if (!quiet) { displayQRCode(secret, label, use_totp); printf("Your new secret key is: %s\n", secret); printf("Your verification code is %06d\n", generateCode(secret, 0)); printf("Your emergency scratch codes are:\n"); } free(label); strcat(secret, "\n"); if (use_totp) { strcat(secret, totp); } else { strcat(secret, hotp); } for (int i = 0; i < SCRATCHCODES; ++i) { new_scratch_code:; int scratch = 0; for (int j = 0; j < BYTES_PER_SCRATCHCODE; ++j) { scratch = 256*scratch + buf[SECRET_BITS/8 + BYTES_PER_SCRATCHCODE*i + j]; } int modulus = 1; for (int j = 0; j < SCRATCHCODE_LENGTH; j++) { modulus *= 10; } scratch = (scratch & 0x7FFFFFFF) % modulus; if (scratch < modulus/10) { // Make sure that scratch codes are always exactly eight digits. If they // start with a sequence of zeros, just generate a new scratch code. if (read(fd, buf + (SECRET_BITS/8 + BYTES_PER_SCRATCHCODE*i), BYTES_PER_SCRATCHCODE) != BYTES_PER_SCRATCHCODE) { goto urandom_failure; } goto new_scratch_code; } if (!quiet) { printf(" %08d\n", scratch); } snprintf(strrchr(secret, '\000'), sizeof(secret) - strlen(secret), "%08d\n", scratch); } close(fd); if (!secret_fn) { char *home = getenv("HOME"); if (!home || *home != '/') { fprintf(stderr, "Cannot determine home directory\n"); return 1; } secret_fn = malloc(strlen(home) + strlen(SECRET) + 1); if (!secret_fn) { perror("malloc()"); _exit(1); } strcat(strcpy(secret_fn, home), SECRET); } if (!force) { printf("\nDo you want me to update your \"%s\" file (y/n) ", secret_fn); fflush(stdout); char ch; do { ch = getchar(); } while (ch == ' ' || ch == '\r' || ch == '\n'); if (ch != 'y' && ch != 'Y') { exit(0); } } secret_fn = realloc(secret_fn, 2*strlen(secret_fn) + 3); if (!secret_fn) { perror("malloc()"); _exit(1); } char *tmp_fn = strrchr(secret_fn, '\000') + 1; strcat(strcpy(tmp_fn, secret_fn), "~"); // Add optional flags. if (use_totp) { if (reuse == ASK_REUSE) { maybeAddOption("Do you want to disallow multiple uses of the same " "authentication\ntoken? This restricts you to one login " "about every 30s, but it increases\nyour chances to " "notice or even prevent man-in-the-middle attacks", secret, sizeof(secret), disallow); } else if (reuse == DISALLOW_REUSE) { addOption(secret, sizeof(secret), disallow); } if (!window_size) { maybeAddOption("By default, tokens are good for 30 seconds and in order " "to compensate for\npossible time-skew between the " "client and the server, we allow an extra\ntoken before " "and after the current time. If you experience problems " "with poor\ntime synchronization, you can increase the " "window from its default\nsize of 1:30min to about 4min. " "Do you want to do so", secret, sizeof(secret), window); } else { char buf[80]; sprintf(buf, "\" WINDOW_SIZE %d\n", window_size); addOption(secret, sizeof(secret), buf); } } else { if (!window_size) { maybeAddOption("By default, three tokens are valid at any one time. " "This accounts for\ngenerated-but-not-used tokens and " "failed login attempts. In order to\ndecrease the " "likelihood of synchronization problems, this window " "can be\nincreased from its default size of 3 to 17. Do " "you want to do so", secret, sizeof(secret), window); } else { char buf[80]; sprintf(buf, "\" WINDOW_SIZE %d\n", window_size > 0 ? window_size : use_totp ? 3 : 1); addOption(secret, sizeof(secret), buf); } } if (!r_limit && !r_time) { maybeAddOption("If the computer that you are logging into isn't hardened " "against brute-force\nlogin attempts, you can enable " "rate-limiting for the authentication module.\nBy default, " "this limits attackers to no more than 3 login attempts " "every 30s.\nDo you want to enable rate-limiting", secret, sizeof(secret), ratelimit); } else if (r_limit > 0 && r_time > 0) { char buf[80]; sprintf(buf, "\"RATE_LIMIT %d %d\n", r_limit, r_time); addOption(secret, sizeof(secret), buf); } fd = open(tmp_fn, O_WRONLY|O_EXCL|O_CREAT|O_NOFOLLOW|O_TRUNC, 0400); if (fd < 0) { fprintf(stderr, "Failed to create \"%s\" (%s)", secret_fn, strerror(errno)); free(secret_fn); return 1; } if (write(fd, secret, strlen(secret)) != (ssize_t)strlen(secret) || rename(tmp_fn, secret_fn)) { perror("Failed to write new secret"); unlink(secret_fn); close(fd); free(secret_fn); return 1; } free(secret_fn); close(fd); return 0; }
001coldblade-authenticator
libpam/google-authenticator.c
C
asf20
24,608
// PAM module for two-factor authentication. // // Copyright 2010 Google Inc. // Author: Markus Gutschke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #define _GNU_SOURCE #include <errno.h> #include <fcntl.h> #include <limits.h> #include <pwd.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <syslog.h> #include <time.h> #include <unistd.h> #ifdef linux // We much rather prefer to use setfsuid(), but this function is unfortunately // not available on all systems. #include <sys/fsuid.h> #define HAS_SETFSUID #endif #ifndef PAM_EXTERN #define PAM_EXTERN #endif #if !defined(LOG_AUTHPRIV) && defined(LOG_AUTH) #define LOG_AUTHPRIV LOG_AUTH #endif #define PAM_SM_AUTH #define PAM_SM_SESSION #include <security/pam_appl.h> #include <security/pam_modules.h> #include "base32.h" #include "hmac.h" #include "sha1.h" #define MODULE_NAME "pam_google_authenticator" #define SECRET "~/.google_authenticator" typedef struct Params { const char *secret_filename_spec; enum { NULLERR=0, NULLOK, SECRETNOTFOUND } nullok; int noskewadj; int echocode; int fixed_uid; uid_t uid; enum { PROMPT = 0, TRY_FIRST_PASS, USE_FIRST_PASS } pass_mode; int forward_pass; } Params; static char oom; #if defined(DEMO) || defined(TESTING) static char error_msg[128]; const char *get_error_msg(void) __attribute__((visibility("default"))); const char *get_error_msg(void) { return error_msg; } #endif static void log_message(int priority, pam_handle_t *pamh, const char *format, ...) { char *service = NULL; if (pamh) pam_get_item(pamh, PAM_SERVICE, (void *)&service); if (!service) service = ""; char logname[80]; snprintf(logname, sizeof(logname), "%s(" MODULE_NAME ")", service); va_list args; va_start(args, format); #if !defined(DEMO) && !defined(TESTING) openlog(logname, LOG_CONS | LOG_PID, LOG_AUTHPRIV); vsyslog(priority, format, args); closelog(); #else if (!*error_msg) { vsnprintf(error_msg, sizeof(error_msg), format, args); } #endif va_end(args); if (priority == LOG_EMERG) { // Something really bad happened. There is no way we can proceed safely. _exit(1); } } static int converse(pam_handle_t *pamh, int nargs, const struct pam_message **message, struct pam_response **response) { struct pam_conv *conv; int retval = pam_get_item(pamh, PAM_CONV, (void *)&conv); if (retval != PAM_SUCCESS) { return retval; } return conv->conv(nargs, message, response, conv->appdata_ptr); } static const char *get_user_name(pam_handle_t *pamh) { // Obtain the user's name const char *username; if (pam_get_item(pamh, PAM_USER, (void *)&username) != PAM_SUCCESS || !username || !*username) { log_message(LOG_ERR, pamh, "No user name available when checking verification code"); return NULL; } return username; } static char *get_secret_filename(pam_handle_t *pamh, const Params *params, const char *username, int *uid) { // Check whether the administrator decided to override the default location // for the secret file. const char *spec = params->secret_filename_spec ? params->secret_filename_spec : SECRET; // Obtain the user's id and home directory struct passwd pwbuf, *pw = NULL; char *buf = NULL; char *secret_filename = NULL; if (!params->fixed_uid) { #ifdef _SC_GETPW_R_SIZE_MAX int len = sysconf(_SC_GETPW_R_SIZE_MAX); if (len <= 0) { len = 4096; } #else int len = 4096; #endif buf = malloc(len); *uid = -1; if (buf == NULL || getpwnam_r(username, &pwbuf, buf, len, &pw) || !pw || !pw->pw_dir || *pw->pw_dir != '/') { err: log_message(LOG_ERR, pamh, "Failed to compute location of secret file"); free(buf); free(secret_filename); return NULL; } } // Expand filename specification to an actual filename. if ((secret_filename = strdup(spec)) == NULL) { goto err; } int allow_tilde = 1; for (int offset = 0; secret_filename[offset];) { char *cur = secret_filename + offset; char *var = NULL; size_t var_len = 0; const char *subst = NULL; if (allow_tilde && *cur == '~') { var_len = 1; if (!pw) { goto err; } subst = pw->pw_dir; var = cur; } else if (secret_filename[offset] == '$') { if (!memcmp(cur, "${HOME}", 7)) { var_len = 7; if (!pw) { goto err; } subst = pw->pw_dir; var = cur; } else if (!memcmp(cur, "${USER}", 7)) { var_len = 7; subst = username; var = cur; } } if (var) { size_t subst_len = strlen(subst); char *resized = realloc(secret_filename, strlen(secret_filename) + subst_len); if (!resized) { goto err; } var += resized - secret_filename; secret_filename = resized; memmove(var + subst_len, var + var_len, strlen(var + var_len) + 1); memmove(var, subst, subst_len); offset = var + subst_len - resized; allow_tilde = 0; } else { allow_tilde = *cur == '/'; ++offset; } } *uid = params->fixed_uid ? params->uid : pw->pw_uid; free(buf); return secret_filename; } static int setuser(int uid) { #ifdef HAS_SETFSUID // The semantics for setfsuid() are a little unusual. On success, the // previous user id is returned. On failure, the current user id is returned. int old_uid = setfsuid(uid); if (uid != setfsuid(uid)) { setfsuid(old_uid); return -1; } #else int old_uid = geteuid(); if (old_uid != uid && seteuid(uid)) { return -1; } #endif return old_uid; } static int setgroup(int gid) { #ifdef HAS_SETFSUID // The semantics of setfsgid() are a little unusual. On success, the // previous group id is returned. On failure, the current groupd id is // returned. int old_gid = setfsgid(gid); if (gid != setfsgid(gid)) { setfsgid(old_gid); return -1; } #else int old_gid = getegid(); if (old_gid != gid && setegid(gid)) { return -1; } #endif return old_gid; } static int drop_privileges(pam_handle_t *pamh, const char *username, int uid, int *old_uid, int *old_gid) { // Try to become the new user. This might be necessary for NFS mounted home // directories. // First, look up the user's default group #ifdef _SC_GETPW_R_SIZE_MAX int len = sysconf(_SC_GETPW_R_SIZE_MAX); if (len <= 0) { len = 4096; } #else int len = 4096; #endif char *buf = malloc(len); if (!buf) { log_message(LOG_ERR, pamh, "Out of memory"); return -1; } struct passwd pwbuf, *pw; if (getpwuid_r(uid, &pwbuf, buf, len, &pw) || !pw) { log_message(LOG_ERR, pamh, "Cannot look up user id %d", uid); free(buf); return -1; } gid_t gid = pw->pw_gid; free(buf); int gid_o = setgroup(gid); int uid_o = setuser(uid); if (uid_o < 0) { if (gid_o >= 0) { if (setgroup(gid_o) < 0 || setgroup(gid_o) != gid_o) { // Inform the caller that we were unsuccessful in resetting the group. *old_gid = gid_o; } } log_message(LOG_ERR, pamh, "Failed to change user id to \"%s\"", username); return -1; } if (gid_o < 0 && (gid_o = setgroup(gid)) < 0) { // In most typical use cases, the PAM module will end up being called // while uid=0. This allows the module to change to an arbitrary group // prior to changing the uid. But there are many ways that PAM modules // can be invoked and in some scenarios this might not work. So, we also // try changing the group _after_ changing the uid. It might just work. if (setuser(uid_o) < 0 || setuser(uid_o) != uid_o) { // Inform the caller that we were unsuccessful in resetting the uid. *old_uid = uid_o; } log_message(LOG_ERR, pamh, "Failed to change group id for user \"%s\" to %d", username, (int)gid); return -1; } *old_uid = uid_o; *old_gid = gid_o; return 0; } static int open_secret_file(pam_handle_t *pamh, const char *secret_filename, struct Params *params, const char *username, int uid, off_t *size, time_t *mtime) { // Try to open "~/.google_authenticator" *size = 0; *mtime = 0; int fd = open(secret_filename, O_RDONLY); struct stat sb; if (fd < 0 || fstat(fd, &sb) < 0) { if (params->nullok != NULLERR && errno == ENOENT) { // The user doesn't have a state file, but the admininistrator said // that this is OK. We still return an error from open_secret_file(), // but we remember that this was the result of a missing state file. params->nullok = SECRETNOTFOUND; } else { log_message(LOG_ERR, pamh, "Failed to read \"%s\"", secret_filename); } error: if (fd >= 0) { close(fd); } return -1; } // Check permissions on "~/.google_authenticator" if ((sb.st_mode & 03577) != 0400 || !S_ISREG(sb.st_mode) || sb.st_uid != (uid_t)uid) { char buf[80]; if (params->fixed_uid) { sprintf(buf, "user id %d", params->uid); username = buf; } log_message(LOG_ERR, pamh, "Secret file \"%s\" must only be accessible by %s", secret_filename, username); goto error; } // Sanity check for file length if (sb.st_size < 1 || sb.st_size > 64*1024) { log_message(LOG_ERR, pamh, "Invalid file size for \"%s\"", secret_filename); goto error; } *size = sb.st_size; *mtime = sb.st_mtime; return fd; } static char *read_file_contents(pam_handle_t *pamh, const char *secret_filename, int *fd, off_t filesize) { // Read file contents char *buf = malloc(filesize + 1); if (!buf || read(*fd, buf, filesize) != filesize) { close(*fd); *fd = -1; log_message(LOG_ERR, pamh, "Could not read \"%s\"", secret_filename); error: if (buf) { memset(buf, 0, filesize); free(buf); } return NULL; } close(*fd); *fd = -1; // The rest of the code assumes that there are no NUL bytes in the file. if (memchr(buf, 0, filesize)) { log_message(LOG_ERR, pamh, "Invalid file contents in \"%s\"", secret_filename); goto error; } // Terminate the buffer with a NUL byte. buf[filesize] = '\000'; return buf; } static int is_totp(const char *buf) { return !!strstr(buf, "\" TOTP_AUTH"); } static int write_file_contents(pam_handle_t *pamh, const char *secret_filename, off_t old_size, time_t old_mtime, const char *buf) { // Safely overwrite the old secret file. char *tmp_filename = malloc(strlen(secret_filename) + 2); if (tmp_filename == NULL) { removal_failure: log_message(LOG_ERR, pamh, "Failed to update secret file \"%s\"", secret_filename); return -1; } strcat(strcpy(tmp_filename, secret_filename), "~"); int fd = open(tmp_filename, O_WRONLY|O_CREAT|O_NOFOLLOW|O_TRUNC|O_EXCL, 0400); if (fd < 0) { goto removal_failure; } // Make sure the secret file is still the same. This prevents attackers // from opening a lot of pending sessions and then reusing the same // scratch code multiple times. struct stat sb; if (stat(secret_filename, &sb) != 0 || sb.st_size != old_size || sb.st_mtime != old_mtime) { log_message(LOG_ERR, pamh, "Secret file \"%s\" changed while trying to use " "scratch code\n", secret_filename); unlink(tmp_filename); free(tmp_filename); close(fd); return -1; } // Write the new file contents if (write(fd, buf, strlen(buf)) != (ssize_t)strlen(buf) || rename(tmp_filename, secret_filename) != 0) { unlink(tmp_filename); free(tmp_filename); close(fd); goto removal_failure; } free(tmp_filename); close(fd); return 0; } static uint8_t *get_shared_secret(pam_handle_t *pamh, const char *secret_filename, const char *buf, int *secretLen) { // Decode secret key int base32Len = strcspn(buf, "\n"); *secretLen = (base32Len*5 + 7)/8; uint8_t *secret = malloc(base32Len + 1); if (secret == NULL) { *secretLen = 0; return NULL; } memcpy(secret, buf, base32Len); secret[base32Len] = '\000'; if ((*secretLen = base32_decode(secret, secret, base32Len)) < 1) { log_message(LOG_ERR, pamh, "Could not find a valid BASE32 encoded secret in \"%s\"", secret_filename); memset(secret, 0, base32Len); free(secret); return NULL; } memset(secret + *secretLen, 0, base32Len + 1 - *secretLen); return secret; } #ifdef TESTING static time_t current_time; void set_time(time_t t) __attribute__((visibility("default"))); void set_time(time_t t) { current_time = t; } static time_t get_time(void) { return current_time; } #else static time_t get_time(void) { return time(NULL); } #endif static int get_timestamp(void) { return get_time()/30; } static int comparator(const void *a, const void *b) { return *(unsigned int *)a - *(unsigned int *)b; } static char *get_cfg_value(pam_handle_t *pamh, const char *key, const char *buf) { size_t key_len = strlen(key); for (const char *line = buf; *line; ) { const char *ptr; if (line[0] == '"' && line[1] == ' ' && !memcmp(line+2, key, key_len) && (!*(ptr = line+2+key_len) || *ptr == ' ' || *ptr == '\t' || *ptr == '\r' || *ptr == '\n')) { ptr += strspn(ptr, " \t"); size_t val_len = strcspn(ptr, "\r\n"); char *val = malloc(val_len + 1); if (!val) { log_message(LOG_ERR, pamh, "Out of memory"); return &oom; } else { memcpy(val, ptr, val_len); val[val_len] = '\000'; return val; } } else { line += strcspn(line, "\r\n"); line += strspn(line, "\r\n"); } } return NULL; } static int set_cfg_value(pam_handle_t *pamh, const char *key, const char *val, char **buf) { size_t key_len = strlen(key); char *start = NULL; char *stop = NULL; // Find an existing line, if any. for (char *line = *buf; *line; ) { char *ptr; if (line[0] == '"' && line[1] == ' ' && !memcmp(line+2, key, key_len) && (!*(ptr = line+2+key_len) || *ptr == ' ' || *ptr == '\t' || *ptr == '\r' || *ptr == '\n')) { start = line; stop = start + strcspn(start, "\r\n"); stop += strspn(stop, "\r\n"); break; } else { line += strcspn(line, "\r\n"); line += strspn(line, "\r\n"); } } // If no existing line, insert immediately after the first line. if (!start) { start = *buf + strcspn(*buf, "\r\n"); start += strspn(start, "\r\n"); stop = start; } // Replace [start..stop] with the new contents. size_t val_len = strlen(val); size_t total_len = key_len + val_len + 4; if (total_len <= stop - start) { // We are decreasing out space requirements. Shrink the buffer and pad with // NUL characters. size_t tail_len = strlen(stop); memmove(start + total_len, stop, tail_len + 1); memset(start + total_len + tail_len, 0, stop - start - total_len + 1); } else { // Must resize existing buffer. We cannot call realloc(), as it could // leave parts of the buffer content in unused parts of the heap. size_t buf_len = strlen(*buf); size_t tail_len = buf_len - (stop - *buf); char *resized = malloc(buf_len - (stop - start) + total_len + 1); if (!resized) { log_message(LOG_ERR, pamh, "Out of memory"); return -1; } memcpy(resized, *buf, start - *buf); memcpy(resized + (start - *buf) + total_len, stop, tail_len + 1); memset(*buf, 0, buf_len); free(*buf); start = start - *buf + resized; *buf = resized; } // Fill in new contents. start[0] = '"'; start[1] = ' '; memcpy(start + 2, key, key_len); start[2+key_len] = ' '; memcpy(start+3+key_len, val, val_len); start[3+key_len+val_len] = '\n'; // Check if there are any other occurrences of "value". If so, delete them. for (char *line = start + 4 + key_len + val_len; *line; ) { char *ptr; if (line[0] == '"' && line[1] == ' ' && !memcmp(line+2, key, key_len) && (!*(ptr = line+2+key_len) || *ptr == ' ' || *ptr == '\t' || *ptr == '\r' || *ptr == '\n')) { start = line; stop = start + strcspn(start, "\r\n"); stop += strspn(stop, "\r\n"); size_t tail_len = strlen(stop); memmove(start, stop, tail_len + 1); memset(start + tail_len, 0, stop - start); line = start; } else { line += strcspn(line, "\r\n"); line += strspn(line, "\r\n"); } } return 0; } static long get_hotp_counter(pam_handle_t *pamh, const char *buf) { const char *counter_str = get_cfg_value(pamh, "HOTP_COUNTER", buf); if (counter_str == &oom) { // Out of memory. This is a fatal error return -1; } long counter = 0; if (counter_str) { counter = strtol(counter_str, NULL, 10); } free((void *)counter_str); return counter; } static int rate_limit(pam_handle_t *pamh, const char *secret_filename, int *updated, char **buf) { const char *value = get_cfg_value(pamh, "RATE_LIMIT", *buf); if (!value) { // Rate limiting is not enabled for this account return 0; } else if (value == &oom) { // Out of memory. This is a fatal error. return -1; } // Parse both the maximum number of login attempts and the time interval // that we are looking at. const char *endptr = value, *ptr; int attempts, interval; errno = 0; if (((attempts = (int)strtoul(ptr = endptr, (char **)&endptr, 10)) < 1) || ptr == endptr || attempts > 100 || errno || (*endptr != ' ' && *endptr != '\t') || ((interval = (int)strtoul(ptr = endptr, (char **)&endptr, 10)) < 1) || ptr == endptr || interval > 3600 || errno) { free((void *)value); log_message(LOG_ERR, pamh, "Invalid RATE_LIMIT option. Check \"%s\".", secret_filename); return -1; } // Parse the time stamps of all previous login attempts. unsigned int now = get_time(); unsigned int *timestamps = malloc(sizeof(int)); if (!timestamps) { oom: free((void *)value); log_message(LOG_ERR, pamh, "Out of memory"); return -1; } timestamps[0] = now; int num_timestamps = 1; while (*endptr && *endptr != '\r' && *endptr != '\n') { unsigned int timestamp; errno = 0; if ((*endptr != ' ' && *endptr != '\t') || ((timestamp = (int)strtoul(ptr = endptr, (char **)&endptr, 10)), errno) || ptr == endptr) { free((void *)value); free(timestamps); log_message(LOG_ERR, pamh, "Invalid list of timestamps in RATE_LIMIT. " "Check \"%s\".", secret_filename); return -1; } num_timestamps++; unsigned int *tmp = (unsigned int *)realloc(timestamps, sizeof(int) * num_timestamps); if (!tmp) { free(timestamps); goto oom; } timestamps = tmp; timestamps[num_timestamps-1] = timestamp; } free((void *)value); value = NULL; // Sort time stamps, then prune all entries outside of the current time // interval. qsort(timestamps, num_timestamps, sizeof(int), comparator); int start = 0, stop = -1; for (int i = 0; i < num_timestamps; ++i) { if (timestamps[i] < now - interval) { start = i+1; } else if (timestamps[i] > now) { break; } stop = i; } // Error out, if there are too many login attempts. int exceeded = 0; if (stop - start + 1 > attempts) { exceeded = 1; start = stop - attempts + 1; } // Construct new list of timestamps within the current time interval. char *list = malloc(25 * (2 + (stop - start + 1)) + 4); if (!list) { free(timestamps); goto oom; } sprintf(list, "%d %d", attempts, interval); char *prnt = strchr(list, '\000'); for (int i = start; i <= stop; ++i) { prnt += sprintf(prnt, " %u", timestamps[i]); } free(timestamps); // Try to update RATE_LIMIT line. if (set_cfg_value(pamh, "RATE_LIMIT", list, buf) < 0) { free(list); return -1; } free(list); // Mark the state file as changed. *updated = 1; // If necessary, notify the user of the rate limiting that is in effect. if (exceeded) { log_message(LOG_ERR, pamh, "Too many concurrent login attempts. Please try again."); return -1; } return 0; } static char *get_first_pass(pam_handle_t *pamh) { const void *password = NULL; if (pam_get_item(pamh, PAM_AUTHTOK, &password) == PAM_SUCCESS && password) { return strdup((const char *)password); } return NULL; } static char *request_pass(pam_handle_t *pamh, int echocode, const char *prompt) { // Query user for verification code const struct pam_message msg = { .msg_style = echocode, .msg = prompt }; const struct pam_message *msgs = &msg; struct pam_response *resp = NULL; int retval = converse(pamh, 1, &msgs, &resp); char *ret = NULL; if (retval != PAM_SUCCESS || resp == NULL || resp->resp == NULL || *resp->resp == '\000') { log_message(LOG_ERR, pamh, "Did not receive verification code from user"); if (retval == PAM_SUCCESS && resp && resp->resp) { ret = resp->resp; } } else { ret = resp->resp; } // Deallocate temporary storage if (resp) { if (!ret) { free(resp->resp); } free(resp); } return ret; } /* Checks for possible use of scratch codes. Returns -1 on error, 0 on success, * and 1, if no scratch code had been entered, and subsequent tests should be * applied. */ static int check_scratch_codes(pam_handle_t *pamh, const char *secret_filename, int *updated, char *buf, int code) { // Skip the first line. It contains the shared secret. char *ptr = buf + strcspn(buf, "\n"); // Check if this is one of the scratch codes char *endptr = NULL; for (;;) { // Skip newlines and blank lines while (*ptr == '\r' || *ptr == '\n') { ptr++; } // Skip any lines starting with double-quotes. They contain option fields if (*ptr == '"') { ptr += strcspn(ptr, "\n"); continue; } // Try to interpret the line as a scratch code errno = 0; int scratchcode = (int)strtoul(ptr, &endptr, 10); // Sanity check that we read a valid scratch code. Scratchcodes are all // numeric eight-digit codes. There must not be any other information on // that line. if (errno || ptr == endptr || (*endptr != '\r' && *endptr != '\n' && *endptr) || scratchcode < 10*1000*1000 || scratchcode >= 100*1000*1000) { break; } // Check if the code matches if (scratchcode == code) { // Remove scratch code after using it while (*endptr == '\n' || *endptr == '\r') { ++endptr; } memmove(ptr, endptr, strlen(endptr) + 1); memset(strrchr(ptr, '\000'), 0, endptr - ptr + 1); // Mark the state file as changed *updated = 1; // Successfully removed scratch code. Allow user to log in. return 0; } ptr = endptr; } // No scratch code has been used. Continue checking other types of codes. return 1; } static int window_size(pam_handle_t *pamh, const char *secret_filename, const char *buf) { const char *value = get_cfg_value(pamh, "WINDOW_SIZE", buf); if (!value) { // Default window size is 3. This gives us one 30s window before and // after the current one. free((void *)value); return 3; } else if (value == &oom) { // Out of memory. This is a fatal error. return 0; } char *endptr; errno = 0; int window = (int)strtoul(value, &endptr, 10); if (errno || !*value || value == endptr || (*endptr && *endptr != ' ' && *endptr != '\t' && *endptr != '\n' && *endptr != '\r') || window < 1 || window > 100) { free((void *)value); log_message(LOG_ERR, pamh, "Invalid WINDOW_SIZE option in \"%s\"", secret_filename); return 0; } free((void *)value); return window; } /* If the DISALLOW_REUSE option has been set, record timestamps have been * used to log in successfully and disallow their reuse. * * Returns -1 on error, and 0 on success. */ static int invalidate_timebased_code(int tm, pam_handle_t *pamh, const char *secret_filename, int *updated, char **buf) { char *disallow = get_cfg_value(pamh, "DISALLOW_REUSE", *buf); if (!disallow) { // Reuse of tokens is not explicitly disallowed. Allow the login request // to proceed. return 0; } else if (disallow == &oom) { // Out of memory. This is a fatal error. return -1; } // Allow the user to customize the window size parameter. int window = window_size(pamh, secret_filename, *buf); if (!window) { // The user configured a non-standard window size, but there was some // error with the value of this parameter. free((void *)disallow); return -1; } // The DISALLOW_REUSE option is followed by all known timestamps that are // currently unavailable for login. for (char *ptr = disallow; *ptr;) { // Skip white-space, if any ptr += strspn(ptr, " \t\r\n"); if (!*ptr) { break; } // Parse timestamp value. char *endptr; errno = 0; int blocked = (int)strtoul(ptr, &endptr, 10); // Treat syntactically invalid options as an error if (errno || ptr == endptr || (*endptr != ' ' && *endptr != '\t' && *endptr != '\r' && *endptr != '\n' && *endptr)) { free((void *)disallow); return -1; } if (tm == blocked) { // The code is currently blocked from use. Disallow login. free((void *)disallow); log_message(LOG_ERR, pamh, "Trying to reuse a previously used time-based code. " "Retry again in 30 seconds. " "Warning! This might mean, you are currently subject to a " "man-in-the-middle attack."); return -1; } // If the blocked code is outside of the possible window of timestamps, // remove it from the file. if (blocked - tm >= window || tm - blocked >= window) { endptr += strspn(endptr, " \t"); memmove(ptr, endptr, strlen(endptr) + 1); } else { ptr = endptr; } } // Add the current timestamp to the list of disallowed timestamps. char *resized = realloc(disallow, strlen(disallow) + 40); if (!resized) { free((void *)disallow); log_message(LOG_ERR, pamh, "Failed to allocate memory when updating \"%s\"", secret_filename); return -1; } disallow = resized; sprintf(strrchr(disallow, '\000'), " %d" + !*disallow, tm); if (set_cfg_value(pamh, "DISALLOW_REUSE", disallow, buf) < 0) { free((void *)disallow); return -1; } free((void *)disallow); // Mark the state file as changed *updated = 1; // Allow access. return 0; } /* Given an input value, this function computes the hash code that forms the * expected authentication token. */ #ifdef TESTING int compute_code(const uint8_t *secret, int secretLen, unsigned long value) __attribute__((visibility("default"))); #else static #endif int compute_code(const uint8_t *secret, int secretLen, unsigned long value) { uint8_t val[8]; for (int i = 8; i--; value >>= 8) { val[i] = value; } uint8_t hash[SHA1_DIGEST_LENGTH]; hmac_sha1(secret, secretLen, val, 8, hash, SHA1_DIGEST_LENGTH); memset(val, 0, sizeof(val)); int offset = hash[SHA1_DIGEST_LENGTH - 1] & 0xF; unsigned int truncatedHash = 0; for (int i = 0; i < 4; ++i) { truncatedHash <<= 8; truncatedHash |= hash[offset + i]; } memset(hash, 0, sizeof(hash)); truncatedHash &= 0x7FFFFFFF; truncatedHash %= 1000000; return truncatedHash; } /* If a user repeated attempts to log in with the same time skew, remember * this skew factor for future login attempts. */ static int check_time_skew(pam_handle_t *pamh, const char *secret_filename, int *updated, char **buf, int skew, int tm) { int rc = -1; // Parse current RESETTING_TIME_SKEW line, if any. char *resetting = get_cfg_value(pamh, "RESETTING_TIME_SKEW", *buf); if (resetting == &oom) { // Out of memory. This is a fatal error. return -1; } // If the user can produce a sequence of three consecutive codes that fall // within a day of the current time. And if he can enter these codes in // quick succession, then we allow the time skew to be reset. // N.B. the number "3" was picked so that it would not trigger the rate // limiting limit if set up with default parameters. unsigned int tms[3]; int skews[sizeof(tms)/sizeof(int)]; int num_entries = 0; if (resetting) { char *ptr = resetting; // Read the three most recent pairs of time stamps and skew values into // our arrays. while (*ptr && *ptr != '\r' && *ptr != '\n') { char *endptr; errno = 0; unsigned int i = (int)strtoul(ptr, &endptr, 10); if (errno || ptr == endptr || (*endptr != '+' && *endptr != '-')) { break; } ptr = endptr; int j = (int)strtoul(ptr + 1, &endptr, 10); if (errno || ptr == endptr || (*endptr != ' ' && *endptr != '\t' && *endptr != '\r' && *endptr != '\n' && *endptr)) { break; } if (*ptr == '-') { j = -j; } if (num_entries == sizeof(tms)/sizeof(int)) { memmove(tms, tms+1, sizeof(tms)-sizeof(int)); memmove(skews, skews+1, sizeof(skews)-sizeof(int)); } else { ++num_entries; } tms[num_entries-1] = i; skews[num_entries-1] = j; ptr = endptr; } // If the user entered an identical code, assume they are just getting // desperate. This doesn't actually provide us with any useful data, // though. Don't change any state and hope the user keeps trying a few // more times. if (num_entries && tm + skew == tms[num_entries-1] + skews[num_entries-1]) { free((void *)resetting); return -1; } } free((void *)resetting); // Append new timestamp entry if (num_entries == sizeof(tms)/sizeof(int)) { memmove(tms, tms+1, sizeof(tms)-sizeof(int)); memmove(skews, skews+1, sizeof(skews)-sizeof(int)); } else { ++num_entries; } tms[num_entries-1] = tm; skews[num_entries-1] = skew; // Check if we have the required amount of valid entries. if (num_entries == sizeof(tms)/sizeof(int)) { unsigned int last_tm = tms[0]; int last_skew = skews[0]; int avg_skew = last_skew; for (int i = 1; i < sizeof(tms)/sizeof(int); ++i) { // Check that we have a consecutive sequence of timestamps with no big // gaps in between. Also check that the time skew stays constant. Allow // a minor amount of fuzziness on all parameters. if (tms[i] <= last_tm || tms[i] > last_tm+2 || last_skew - skew < -1 || last_skew - skew > 1) { goto keep_trying; } last_tm = tms[i]; last_skew = skews[i]; avg_skew += last_skew; } avg_skew /= (int)(sizeof(tms)/sizeof(int)); // The user entered the required number of valid codes in quick // succession. Establish a new valid time skew for all future login // attempts. char time_skew[40]; sprintf(time_skew, "%d", avg_skew); if (set_cfg_value(pamh, "TIME_SKEW", time_skew, buf) < 0) { return -1; } rc = 0; keep_trying:; } // Set the new RESETTING_TIME_SKEW line, while the user is still trying // to reset the time skew. char reset[80 * (sizeof(tms)/sizeof(int))]; *reset = '\000'; if (rc) { for (int i = 0; i < num_entries; ++i) { sprintf(strrchr(reset, '\000'), " %d%+d" + !*reset, tms[i], skews[i]); } } if (set_cfg_value(pamh, "RESETTING_TIME_SKEW", reset, buf) < 0) { return -1; } // Mark the state file as changed *updated = 1; return rc; } /* Checks for time based verification code. Returns -1 on error, 0 on success, * and 1, if no time based code had been entered, and subsequent tests should * be applied. */ static int check_timebased_code(pam_handle_t *pamh, const char*secret_filename, int *updated, char **buf, const uint8_t*secret, int secretLen, int code, Params *params) { if (!is_totp(*buf)) { // The secret file does not actually contain information for a time-based // code. Return to caller and see if any other authentication methods // apply. return 1; } if (code < 0 || code >= 1000000) { // All time based verification codes are no longer than six digits. return 1; } // Compute verification codes and compare them with user input const int tm = get_timestamp(); const char *skew_str = get_cfg_value(pamh, "TIME_SKEW", *buf); if (skew_str == &oom) { // Out of memory. This is a fatal error return -1; } int skew = 0; if (skew_str) { skew = (int)strtol(skew_str, NULL, 10); } free((void *)skew_str); int window = window_size(pamh, secret_filename, *buf); if (!window) { return -1; } for (int i = -((window-1)/2); i <= window/2; ++i) { unsigned int hash = compute_code(secret, secretLen, tm + skew + i); if (hash == (unsigned int)code) { return invalidate_timebased_code(tm + skew + i, pamh, secret_filename, updated, buf); } } if (!params->noskewadj) { // The most common failure mode is for the clocks to be insufficiently // synchronized. We can detect this and store a skew value for future // use. skew = 1000000; for (int i = 0; i < 25*60; ++i) { unsigned int hash = compute_code(secret, secretLen, tm - i); if (hash == (unsigned int)code && skew == 1000000) { // Don't short-circuit out of the loop as the obvious difference in // computation time could be a signal that is valuable to an attacker. skew = -i; } hash = compute_code(secret, secretLen, tm + i); if (hash == (unsigned int)code && skew == 1000000) { skew = i; } } if (skew != 1000000) { return check_time_skew(pamh, secret_filename, updated, buf, skew, tm); } } return 1; } /* Checks for counter based verification code. Returns -1 on error, 0 on * success, and 1, if no counter based code had been entered, and subsequent * tests should be applied. */ static int check_counterbased_code(pam_handle_t *pamh, const char*secret_filename, int *updated, char **buf, const uint8_t*secret, int secretLen, int code, Params *params, long hotp_counter, int *must_advance_counter) { if (hotp_counter < 1) { // The secret file did not actually contain information for a counter-based // code. Return to caller and see if any other authentication methods // apply. return 1; } if (code < 0 || code >= 1000000) { // All counter based verification codes are no longer than six digits. return 1; } // Compute [window_size] verification codes and compare them with user input. // Future codes are allowed in case the user computed but did not use a code. int window = window_size(pamh, secret_filename, *buf); if (!window) { return -1; } for (int i = 0; i < window; ++i) { unsigned int hash = compute_code(secret, secretLen, hotp_counter + i); if (hash == (unsigned int)code) { char counter_str[40]; sprintf(counter_str, "%ld", hotp_counter + i + 1); if (set_cfg_value(pamh, "HOTP_COUNTER", counter_str, buf) < 0) { return -1; } *updated = 1; *must_advance_counter = 0; return 0; } } *must_advance_counter = 1; return 1; } static int parse_user(pam_handle_t *pamh, const char *name, uid_t *uid) { char *endptr; errno = 0; long l = strtol(name, &endptr, 10); if (!errno && endptr != name && l >= 0 && l <= INT_MAX) { *uid = (uid_t)l; return 0; } #ifdef _SC_GETPW_R_SIZE_MAX int len = sysconf(_SC_GETPW_R_SIZE_MAX); if (len <= 0) { len = 4096; } #else int len = 4096; #endif char *buf = malloc(len); if (!buf) { log_message(LOG_ERR, pamh, "Out of memory"); return -1; } struct passwd pwbuf, *pw; if (getpwnam_r(name, &pwbuf, buf, len, &pw) || !pw) { free(buf); log_message(LOG_ERR, pamh, "Failed to look up user \"%s\"", name); return -1; } *uid = pw->pw_uid; free(buf); return 0; } static int parse_args(pam_handle_t *pamh, int argc, const char **argv, Params *params) { params->echocode = PAM_PROMPT_ECHO_OFF; for (int i = 0; i < argc; ++i) { if (!memcmp(argv[i], "secret=", 7)) { free((void *)params->secret_filename_spec); params->secret_filename_spec = argv[i] + 7; } else if (!memcmp(argv[i], "user=", 5)) { uid_t uid; if (parse_user(pamh, argv[i] + 5, &uid) < 0) { return -1; } params->fixed_uid = 1; params->uid = uid; } else if (!strcmp(argv[i], "try_first_pass")) { params->pass_mode = TRY_FIRST_PASS; } else if (!strcmp(argv[i], "use_first_pass")) { params->pass_mode = USE_FIRST_PASS; } else if (!strcmp(argv[i], "forward_pass")) { params->forward_pass = 1; } else if (!strcmp(argv[i], "noskewadj")) { params->noskewadj = 1; } else if (!strcmp(argv[i], "nullok")) { params->nullok = NULLOK; } else if (!strcmp(argv[i], "echo-verification-code") || !strcmp(argv[i], "echo_verification_code")) { params->echocode = PAM_PROMPT_ECHO_ON; } else { log_message(LOG_ERR, pamh, "Unrecognized option \"%s\"", argv[i]); return -1; } } return 0; } static int google_authenticator(pam_handle_t *pamh, int flags, int argc, const char **argv) { int rc = PAM_SESSION_ERR; const char *username; char *secret_filename = NULL; int uid = -1, old_uid = -1, old_gid = -1, fd = -1; off_t filesize = 0; time_t mtime = 0; char *buf = NULL; uint8_t *secret = NULL; int secretLen = 0; #if defined(DEMO) || defined(TESTING) *error_msg = '\000'; #endif // Handle optional arguments that configure our PAM module Params params = { 0 }; if (parse_args(pamh, argc, argv, &params) < 0) { return rc; } // Read and process status file, then ask the user for the verification code. int early_updated = 0, updated = 0; if ((username = get_user_name(pamh)) && (secret_filename = get_secret_filename(pamh, &params, username, &uid)) && !drop_privileges(pamh, username, uid, &old_uid, &old_gid) && (fd = open_secret_file(pamh, secret_filename, &params, username, uid, &filesize, &mtime)) >= 0 && (buf = read_file_contents(pamh, secret_filename, &fd, filesize)) && (secret = get_shared_secret(pamh, secret_filename, buf, &secretLen)) && rate_limit(pamh, secret_filename, &early_updated, &buf) >= 0) { long hotp_counter = get_hotp_counter(pamh, buf); int must_advance_counter = 0; char *pw = NULL, *saved_pw = NULL; for (int mode = 0; mode < 4; ++mode) { // In the case of TRY_FIRST_PASS, we don't actually know whether we // get the verification code from the system password or from prompting // the user. We need to attempt both. // This only works correctly, if all failed attempts leave the global // state unchanged. if (updated || pw) { // Oops. There is something wrong with the internal logic of our // code. This error should never trigger. The unittest checks for // this. if (pw) { memset(pw, 0, strlen(pw)); free(pw); pw = NULL; } rc = PAM_SESSION_ERR; break; } switch (mode) { case 0: // Extract possible verification code case 1: // Extract possible scratch code if (params.pass_mode == USE_FIRST_PASS || params.pass_mode == TRY_FIRST_PASS) { pw = get_first_pass(pamh); } break; default: if (mode != 2 && // Prompt for pw and possible verification code mode != 3) { // Prompt for pw and possible scratch code rc = PAM_SESSION_ERR; continue; } if (params.pass_mode == PROMPT || params.pass_mode == TRY_FIRST_PASS) { if (!saved_pw) { // If forwarding the password to the next stacked PAM module, // we cannot tell the difference between an eight digit scratch // code or a two digit password immediately followed by a six // digit verification code. We have to loop and try both // options. saved_pw = request_pass(pamh, params.echocode, params.forward_pass ? "Password & verification code: " : "Verification code: "); } if (saved_pw) { pw = strdup(saved_pw); } } break; } if (!pw) { continue; } // We are often dealing with a combined password and verification // code. Separate them now. int pw_len = strlen(pw); int expected_len = mode & 1 ? 8 : 6; char ch; if (pw_len < expected_len || // Verification are six digits starting with '0'..'9', // scratch codes are eight digits starting with '1'..'9' (ch = pw[pw_len - expected_len]) > '9' || ch < (expected_len == 8 ? '1' : '0')) { invalid: memset(pw, 0, pw_len); free(pw); pw = NULL; continue; } char *endptr; errno = 0; long l = strtol(pw + pw_len - expected_len, &endptr, 10); if (errno || l < 0 || *endptr) { goto invalid; } int code = (int)l; memset(pw + pw_len - expected_len, 0, expected_len); if ((mode == 2 || mode == 3) && !params.forward_pass) { // We are explicitly configured so that we don't try to share // the password with any other stacked PAM module. We must // therefore verify that the user entered just the verification // code, but no password. if (*pw) { goto invalid; } } // Check all possible types of verification codes. switch (check_scratch_codes(pamh, secret_filename, &updated, buf, code)){ case 1: if (hotp_counter > 0) { switch (check_counterbased_code(pamh, secret_filename, &updated, &buf, secret, secretLen, code, &params, hotp_counter, &must_advance_counter)) { case 0: rc = PAM_SUCCESS; break; case 1: goto invalid; default: break; } } else { switch (check_timebased_code(pamh, secret_filename, &updated, &buf, secret, secretLen, code, &params)) { case 0: rc = PAM_SUCCESS; break; case 1: goto invalid; default: break; } } break; case 0: rc = PAM_SUCCESS; break; default: break; } break; } // Update the system password, if we were asked to forward // the system password. We already removed the verification // code from the end of the password. if (rc == PAM_SUCCESS && params.forward_pass) { if (!pw || pam_set_item(pamh, PAM_AUTHTOK, pw) != PAM_SUCCESS) { rc = PAM_SESSION_ERR; } } // Clear out password and deallocate memory if (pw) { memset(pw, 0, strlen(pw)); free(pw); } if (saved_pw) { memset(saved_pw, 0, strlen(saved_pw)); free(saved_pw); } // If an hotp login attempt has been made, the counter must always be // advanced by at least one. if (must_advance_counter) { char counter_str[40]; sprintf(counter_str, "%ld", hotp_counter + 1); if (set_cfg_value(pamh, "HOTP_COUNTER", counter_str, &buf) < 0) { rc = PAM_SESSION_ERR; } updated = 1; } // If nothing matched, display an error message if (rc != PAM_SUCCESS) { log_message(LOG_ERR, pamh, "Invalid verification code"); } } // If the user has not created a state file with a shared secret, and if // the administrator set the "nullok" option, this PAM module completes // successfully, without ever prompting the user. if (params.nullok == SECRETNOTFOUND) { rc = PAM_SUCCESS; } // Persist the new state. if (early_updated || updated) { if (write_file_contents(pamh, secret_filename, filesize, mtime, buf) < 0) { // Could not persist new state. Deny access. rc = PAM_SESSION_ERR; } } if (fd >= 0) { close(fd); } if (old_gid >= 0) { if (setgroup(old_gid) >= 0 && setgroup(old_gid) == old_gid) { old_gid = -1; } } if (old_uid >= 0) { if (setuser(old_uid) < 0 || setuser(old_uid) != old_uid) { log_message(LOG_EMERG, pamh, "We switched users from %d to %d, " "but can't switch back", old_uid, uid); } } free(secret_filename); // Clean up if (buf) { memset(buf, 0, strlen(buf)); free(buf); } if (secret) { memset(secret, 0, secretLen); free(secret); } return rc; } PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) __attribute__((visibility("default"))); PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) { return google_authenticator(pamh, flags, argc, argv); } PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv) __attribute__((visibility("default"))); PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags, int argc, const char **argv) { return PAM_SUCCESS; } PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, const char **argv) __attribute__((visibility("default"))); PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, const char **argv) { return google_authenticator(pamh, flags, argc, argv); } #ifdef PAM_STATIC struct pam_module _pam_listfile_modstruct = { MODULE_NAME, pam_sm_authenticate, pam_sm_setcred, NULL, pam_sm_open_session, NULL, NULL }; #endif
001coldblade-authenticator
libpam/pam_google_authenticator.c
C
asf20
48,385
// Unittest for the PAM module. This is part of the Google Authenticator // project. // // Copyright 2010 Google Inc. // Author: Markus Gutschke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <assert.h> #include <dlfcn.h> #include <fcntl.h> #include <security/pam_appl.h> #include <security/pam_modules.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "base32.h" #include "hmac.h" #if !defined(PAM_BAD_ITEM) // FreeBSD does not know about PAM_BAD_ITEM. And PAM_SYMBOL_ERR is an "enum", // we can't test for it at compile-time. #define PAM_BAD_ITEM PAM_SYMBOL_ERR #endif static const char pw[] = "0123456789"; static char *response = ""; static void *pam_module; static enum { TWO_PROMPTS, COMBINED_PASSWORD, COMBINED_PROMPT } conv_mode; static int num_prompts_shown = 0; static int conversation(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata_ptr) { // Keep track of how often the conversation callback is executed. ++num_prompts_shown; if (conv_mode == COMBINED_PASSWORD) { return PAM_CONV_ERR; } if (num_msg == 1 && msg[0]->msg_style == PAM_PROMPT_ECHO_OFF) { *resp = malloc(sizeof(struct pam_response)); assert(*resp); (*resp)->resp = conv_mode == TWO_PROMPTS ? strdup(response) : strcat(strcpy(malloc(sizeof(pw) + strlen(response)), pw), response); (*resp)->resp_retcode = 0; return PAM_SUCCESS; } return PAM_CONV_ERR; } #ifdef sun #define PAM_CONST #else #define PAM_CONST const #endif int pam_get_item(const pam_handle_t *pamh, int item_type, PAM_CONST void **item) __attribute__((visibility("default"))); int pam_get_item(const pam_handle_t *pamh, int item_type, PAM_CONST void **item) { switch (item_type) { case PAM_SERVICE: { static const char *service = "google_authenticator_unittest"; memcpy(item, &service, sizeof(&service)); return PAM_SUCCESS; } case PAM_USER: { char *user = getenv("USER"); memcpy(item, &user, sizeof(&user)); return PAM_SUCCESS; } case PAM_CONV: { static struct pam_conv conv = { .conv = conversation }, *p_conv = &conv; memcpy(item, &p_conv, sizeof(p_conv)); return PAM_SUCCESS; } case PAM_AUTHTOK: { static char *authtok = NULL; if (conv_mode == COMBINED_PASSWORD) { authtok = realloc(authtok, sizeof(pw) + strlen(response)); *item = strcat(strcpy(authtok, pw), response); } else { *item = pw; } return PAM_SUCCESS; } default: return PAM_BAD_ITEM; } } int pam_set_item(pam_handle_t *pamh, int item_type, PAM_CONST void *item) __attribute__((visibility("default"))); int pam_set_item(pam_handle_t *pamh, int item_type, PAM_CONST void *item) { switch (item_type) { case PAM_AUTHTOK: if (strcmp((char *)item, pw)) { return PAM_BAD_ITEM; } return PAM_SUCCESS; default: return PAM_BAD_ITEM; } } static const char *get_error_msg(void) { const char *(*get_error_msg)(void) = (const char *(*)(void))dlsym(pam_module, "get_error_msg"); return get_error_msg ? get_error_msg() : ""; } static void print_diagnostics(int signo) { if (*get_error_msg()) { fprintf(stderr, "%s\n", get_error_msg()); } _exit(1); } static void verify_prompts_shown(int expected_prompts_shown) { assert(num_prompts_shown == expected_prompts_shown); // Reset for the next count. num_prompts_shown = 0; } int main(int argc, char *argv[]) { // Testing Base32 encoding puts("Testing base32 encoding"); static const uint8_t dat[] = "Hello world..."; uint8_t enc[((sizeof(dat) + 4)/5)*8 + 1]; assert(base32_encode(dat, sizeof(dat), enc, sizeof(enc)) == sizeof(enc)-1); assert(!strcmp((char *)enc, "JBSWY3DPEB3W64TMMQXC4LQA")); puts("Testing base32 decoding"); uint8_t dec[sizeof(dat)]; assert(base32_decode(enc, dec, sizeof(dec)) == sizeof(dec)); assert(!memcmp(dat, dec, sizeof(dat))); // Testing HMAC_SHA1 puts("Testing HMAC_SHA1"); uint8_t hmac[20]; hmac_sha1((uint8_t *)"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C" "\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19" "\x1A\x1B\x1C\x1D\x1E\x1F !\"#$%&'()*+,-./0123456789:" ";<=>?", 64, (uint8_t *)"Sample #1", 9, hmac, sizeof(hmac)); assert(!memcmp(hmac, (uint8_t []) { 0x4F, 0x4C, 0xA3, 0xD5, 0xD6, 0x8B, 0xA7, 0xCC, 0x0A, 0x12, 0x08, 0xC9, 0xC6, 0x1E, 0x9C, 0x5D, 0xA0, 0x40, 0x3C, 0x0A }, sizeof(hmac))); hmac_sha1((uint8_t *)"0123456789:;<=>?@ABC", 20, (uint8_t *)"Sample #2", 9, hmac, sizeof(hmac)); assert(!memcmp(hmac, (uint8_t []) { 0x09, 0x22, 0xD3, 0x40, 0x5F, 0xAA, 0x3D, 0x19, 0x4F, 0x82, 0xA4, 0x58, 0x30, 0x73, 0x7D, 0x5C, 0xC6, 0xC7, 0x5D, 0x24 }, sizeof(hmac))); hmac_sha1((uint8_t *)"PQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" "\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A" "\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96" "\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2" "\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE" "\xAF\xB0\xB1\xB2\xB3", 100, (uint8_t *)"Sample #3", 9, hmac, sizeof(hmac)); assert(!memcmp(hmac, (uint8_t []) { 0xBC, 0xF4, 0x1E, 0xAB, 0x8B, 0xB2, 0xD8, 0x02, 0xF3, 0xD0, 0x5C, 0xAF, 0x7C, 0xB0, 0x92, 0xEC, 0xF8, 0xD1, 0xA3, 0xAA }, sizeof(hmac))); hmac_sha1((uint8_t *)"pqrstuvwxyz{|}~\x7F\x80\x81\x82\x83\x84\x85\x86\x87" "\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94" "\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0", 49, (uint8_t *)"Sample #4", 9, hmac, sizeof(hmac)); assert(!memcmp(hmac, (uint8_t []) { 0x9E, 0xA8, 0x86, 0xEF, 0xE2, 0x68, 0xDB, 0xEC, 0xCE, 0x42, 0x0C, 0x75, 0x24, 0xDF, 0x32, 0xE0, 0x75, 0x1A, 0x2A, 0x26 }, sizeof(hmac))); // Load the PAM module puts("Loading PAM module"); pam_module = dlopen("./pam_google_authenticator_testing.so", RTLD_LAZY | RTLD_GLOBAL); assert(pam_module != NULL); signal(SIGABRT, print_diagnostics); // Look up public symbols int (*pam_sm_open_session)(pam_handle_t *, int, int, const char **) = (int (*)(pam_handle_t *, int, int, const char **)) dlsym(pam_module, "pam_sm_open_session"); assert(pam_sm_open_session != NULL); // Look up private test-only API void (*set_time)(time_t t) = (void (*)(time_t))dlsym(pam_module, "set_time"); assert(set_time); int (*compute_code)(uint8_t *, int, unsigned long) = (int (*)(uint8_t*, int, unsigned long))dlsym(pam_module, "compute_code"); assert(compute_code); for (int otp_mode = 0; otp_mode < 8; ++otp_mode) { // Create a secret file with a well-known test vector char fn[] = "/tmp/.google_authenticator_XXXXXX"; int fd = mkstemp(fn); assert(fd >= 0); static const uint8_t secret[] = "2SH3V3GDW7ZNMGYE"; assert(write(fd, secret, sizeof(secret)-1) == sizeof(secret)-1); assert(write(fd, "\n\" TOTP_AUTH", 12) == 12); close(fd); uint8_t binary_secret[sizeof(secret)]; size_t binary_secret_len = base32_decode(secret, binary_secret, sizeof(binary_secret)); // Set up test argc/argv parameters to let the PAM module know where to // find our secret file const char *targv[] = { malloc(strlen(fn) + 8), NULL, NULL, NULL, NULL }; strcat(strcpy((char *)targv[0], "secret="), fn); int targc; int expected_good_prompts_shown; int expected_bad_prompts_shown; switch (otp_mode) { case 0: puts("\nRunning tests, querying for verification code"); conv_mode = TWO_PROMPTS; targc = 1; expected_good_prompts_shown = expected_bad_prompts_shown = 1; break; case 1: puts("\nRunning tests, querying for verification code, " "forwarding system pass"); conv_mode = COMBINED_PROMPT; targv[1] = strdup("forward_pass"); targc = 2; expected_good_prompts_shown = expected_bad_prompts_shown = 1; break; case 2: puts("\nRunning tests with use_first_pass"); conv_mode = COMBINED_PASSWORD; targv[1] = strdup("use_first_pass"); targc = 2; expected_good_prompts_shown = expected_bad_prompts_shown = 0; break; case 3: puts("\nRunning tests with use_first_pass, forwarding system pass"); conv_mode = COMBINED_PASSWORD; targv[1] = strdup("use_first_pass"); targv[2] = strdup("forward_pass"); targc = 3; expected_good_prompts_shown = expected_bad_prompts_shown = 0; break; case 4: puts("\nRunning tests with try_first_pass, combining codes"); conv_mode = COMBINED_PASSWORD; targv[1] = strdup("try_first_pass"); targc = 2; expected_good_prompts_shown = 0; expected_bad_prompts_shown = 2; break; case 5: puts("\nRunning tests with try_first_pass, combining codes, " "forwarding system pass"); conv_mode = COMBINED_PASSWORD; targv[1] = strdup("try_first_pass"); targv[2] = strdup("forward_pass"); targc = 3; expected_good_prompts_shown = 0; expected_bad_prompts_shown = 2; break; case 6: puts("\nRunning tests with try_first_pass, querying for codes"); conv_mode = TWO_PROMPTS; targv[1] = strdup("try_first_pass"); targc = 2; expected_good_prompts_shown = expected_bad_prompts_shown = 1; break; default: assert(otp_mode == 7); puts("\nRunning tests with try_first_pass, querying for codes, " "forwarding system pass"); conv_mode = COMBINED_PROMPT; targv[1] = strdup("try_first_pass"); targv[2] = strdup("forward_pass"); targc = 3; expected_good_prompts_shown = expected_bad_prompts_shown = 1; break; } // Make sure num_prompts_shown is still 0. verify_prompts_shown(0); // Set the timestamp that this test vector needs set_time(10000*30); response = "123456"; // Check if we can log in when using an invalid verification code puts("Testing failed login attempt"); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(expected_bad_prompts_shown); // Check required number of digits if (conv_mode == TWO_PROMPTS) { puts("Testing required number of digits"); response = "50548"; assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(expected_bad_prompts_shown); response = "0050548"; assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(expected_bad_prompts_shown); response = "00050548"; assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(expected_bad_prompts_shown); } // Test a blank response puts("Testing a blank response"); response = ""; assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(expected_bad_prompts_shown); // Set the response that we should send back to the authentication module response = "050548"; // Test handling of missing state files puts("Test handling of missing state files"); const char *old_secret = targv[0]; targv[0] = "secret=/NOSUCHFILE"; assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(0); targv[targc++] = "nullok"; targv[targc] = NULL; assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS); verify_prompts_shown(0); targv[--targc] = NULL; targv[0] = old_secret; // Check if we can log in when using a valid verification code puts("Testing successful login"); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS); verify_prompts_shown(expected_good_prompts_shown); // Test the WINDOW_SIZE option puts("Testing WINDOW_SIZE option"); for (int *tm = (int []){ 9998, 9999, 10001, 10002, 10000, -1 }, *res = (int []){ PAM_SESSION_ERR, PAM_SUCCESS, PAM_SUCCESS, PAM_SESSION_ERR, PAM_SUCCESS }; *tm >= 0;) { set_time(*tm++ * 30); assert(pam_sm_open_session(NULL, 0, targc, targv) == *res++); verify_prompts_shown(expected_good_prompts_shown); } assert(!chmod(fn, 0600)); assert((fd = open(fn, O_APPEND | O_WRONLY)) >= 0); assert(write(fd, "\n\" WINDOW_SIZE 6\n", 17) == 17); close(fd); for (int *tm = (int []){ 9996, 9997, 10002, 10003, 10000, -1 }, *res = (int []){ PAM_SESSION_ERR, PAM_SUCCESS, PAM_SUCCESS, PAM_SESSION_ERR, PAM_SUCCESS }; *tm >= 0;) { set_time(*tm++ * 30); assert(pam_sm_open_session(NULL, 0, targc, targv) == *res++); verify_prompts_shown(expected_good_prompts_shown); } // Test the DISALLOW_REUSE option puts("Testing DISALLOW_REUSE option"); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS); verify_prompts_shown(expected_good_prompts_shown); assert(!chmod(fn, 0600)); assert((fd = open(fn, O_APPEND | O_WRONLY)) >= 0); assert(write(fd, "\" DISALLOW_REUSE\n", 17) == 17); close(fd); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS); verify_prompts_shown(expected_good_prompts_shown); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(expected_good_prompts_shown); // Test that DISALLOW_REUSE expires old entries from the re-use list char *old_response = response; for (int i = 10001; i < 10008; ++i) { set_time(i * 30); char buf[7]; response = buf; sprintf(response, "%06d", compute_code(binary_secret, binary_secret_len, i)); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS); verify_prompts_shown(expected_good_prompts_shown); } set_time(10000 * 30); response = old_response; assert((fd = open(fn, O_RDONLY)) >= 0); char state_file_buf[4096] = { 0 }; assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0); close(fd); const char *disallow = strstr(state_file_buf, "\" DISALLOW_REUSE "); assert(disallow); assert(!memcmp(disallow + 17, "10002 10003 10004 10005 10006 10007\n", 36)); // Test the RATE_LIMIT option puts("Testing RATE_LIMIT option"); assert(!chmod(fn, 0600)); assert((fd = open(fn, O_APPEND | O_WRONLY)) >= 0); assert(write(fd, "\" RATE_LIMIT 4 120\n", 19) == 19); close(fd); for (int *tm = (int []){ 20000, 20001, 20002, 20003, 20004, 20006, -1 }, *res = (int []){ PAM_SUCCESS, PAM_SUCCESS, PAM_SUCCESS, PAM_SUCCESS, PAM_SESSION_ERR, PAM_SUCCESS, -1 }; *tm >= 0;) { set_time(*tm * 30); char buf[7]; response = buf; sprintf(response, "%06d", compute_code(binary_secret, binary_secret_len, *tm++)); assert(pam_sm_open_session(NULL, 0, targc, targv) == *res); verify_prompts_shown( *res != PAM_SUCCESS ? 0 : expected_good_prompts_shown); ++res; } set_time(10000 * 30); response = old_response; assert(!chmod(fn, 0600)); assert((fd = open(fn, O_RDWR)) >= 0); memset(state_file_buf, 0, sizeof(state_file_buf)); assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0); const char *rate_limit = strstr(state_file_buf, "\" RATE_LIMIT "); assert(rate_limit); assert(!memcmp(rate_limit + 13, "4 120 600060 600090 600120 600180\n", 35)); // Test trailing space in RATE_LIMIT. This is considered a file format // error. char *eol = strchr(rate_limit, '\n'); *eol = ' '; assert(!lseek(fd, 0, SEEK_SET)); assert(write(fd, state_file_buf, strlen(state_file_buf)) == strlen(state_file_buf)); close(fd); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(0); assert(!strncmp(get_error_msg(), "Invalid list of timestamps in RATE_LIMIT", 40)); *eol = '\n'; assert(!chmod(fn, 0600)); assert((fd = open(fn, O_WRONLY)) >= 0); assert(write(fd, state_file_buf, strlen(state_file_buf)) == strlen(state_file_buf)); close(fd); // Test TIME_SKEW option puts("Testing TIME_SKEW"); for (int i = 0; i < 4; ++i) { set_time((12000 + i)*30); char buf[7]; response = buf; sprintf(response, "%06d", compute_code(binary_secret, binary_secret_len, 11000 + i)); assert(pam_sm_open_session(NULL, 0, targc, targv) == (i >= 2 ? PAM_SUCCESS : PAM_SESSION_ERR)); verify_prompts_shown(expected_good_prompts_shown); } set_time(12010 * 30); char buf[7]; response = buf; sprintf(response, "%06d", compute_code(binary_secret, binary_secret_len, 11010)); assert(pam_sm_open_session(NULL, 0, 1, (const char *[]){ "noskewadj", 0 }) == PAM_SESSION_ERR); verify_prompts_shown(0); set_time(10000*30); // Test scratch codes puts("Testing scratch codes"); response = "12345678"; assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(expected_bad_prompts_shown); assert(!chmod(fn, 0600)); assert((fd = open(fn, O_APPEND | O_WRONLY)) >= 0); assert(write(fd, "12345678\n", 9) == 9); close(fd); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS); verify_prompts_shown(expected_good_prompts_shown); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(expected_bad_prompts_shown); // Set up secret file for counter-based codes. assert(!chmod(fn, 0600)); assert((fd = open(fn, O_TRUNC | O_WRONLY)) >= 0); assert(write(fd, secret, sizeof(secret)-1) == sizeof(secret)-1); assert(write(fd, "\n\" HOTP_COUNTER 1\n", 18) == 18); close(fd); response = "293240"; // Check if we can log in when using a valid verification code puts("Testing successful counter-based login"); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS); verify_prompts_shown(expected_good_prompts_shown); // Verify that the hotp counter incremented assert((fd = open(fn, O_RDONLY)) >= 0); memset(state_file_buf, 0, sizeof(state_file_buf)); assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0); close(fd); const char *hotp_counter = strstr(state_file_buf, "\" HOTP_COUNTER "); assert(hotp_counter); assert(!memcmp(hotp_counter + 15, "2\n", 2)); // Check if we can log in when using an invalid verification code // (including the same code a second time) puts("Testing failed counter-based login attempt"); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SESSION_ERR); verify_prompts_shown(expected_bad_prompts_shown); // Verify that the hotp counter incremented assert((fd = open(fn, O_RDONLY)) >= 0); memset(state_file_buf, 0, sizeof(state_file_buf)); assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0); close(fd); hotp_counter = strstr(state_file_buf, "\" HOTP_COUNTER "); assert(hotp_counter); assert(!memcmp(hotp_counter + 15, "3\n", 2)); response = "932068"; // Check if we can log in using a future valid verification code (using // default window_size of 3) puts("Testing successful future counter-based login"); assert(pam_sm_open_session(NULL, 0, targc, targv) == PAM_SUCCESS); verify_prompts_shown(expected_good_prompts_shown); // Verify that the hotp counter incremented assert((fd = open(fn, O_RDONLY)) >= 0); memset(state_file_buf, 0, sizeof(state_file_buf)); assert(read(fd, state_file_buf, sizeof(state_file_buf)-1) > 0); close(fd); hotp_counter = strstr(state_file_buf, "\" HOTP_COUNTER "); assert(hotp_counter); assert(!memcmp(hotp_counter + 15, "6\n", 2)); // Remove the temporarily created secret file unlink(fn); // Release memory for the test arguments for (int i = 0; i < targc; ++i) { free((void *)targv[i]); } } // Unload the PAM module dlclose(pam_module); puts("DONE"); return 0; }
001coldblade-authenticator
libpam/pam_google_authenticator_unittest.c
C
asf20
21,734
// HMAC_SHA1 implementation // // Copyright 2010 Google Inc. // Author: Markus Gutschke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef _HMAC_H_ #define _HMAC_H_ #include <stdint.h> void hmac_sha1(const uint8_t *key, int keyLength, const uint8_t *data, int dataLength, uint8_t *result, int resultLength) __attribute__((visibility("hidden"))); #endif /* _HMAC_H_ */
001coldblade-authenticator
libpam/hmac.h
C
asf20
919
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * all parameter classes implement this. */ public interface CipherParameters { }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/CipherParameters.java
Java
asf20
1,289
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.macs; import java.util.Hashtable; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.ExtendedDigest; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.params.KeyParameter; /** * HMAC implementation based on RFC2104 * * H(K XOR opad, H(K XOR ipad, text)) */ public class HMac implements Mac { private final static byte IPAD = (byte)0x36; private final static byte OPAD = (byte)0x5C; private Digest digest; private int digestSize; private int blockLength; private byte[] inputPad; private byte[] outputPad; private static Hashtable blockLengths; static { blockLengths = new Hashtable(); blockLengths.put("GOST3411", new Integer(32)); blockLengths.put("MD2", new Integer(16)); blockLengths.put("MD4", new Integer(64)); blockLengths.put("MD5", new Integer(64)); blockLengths.put("RIPEMD128", new Integer(64)); blockLengths.put("RIPEMD160", new Integer(64)); blockLengths.put("SHA-1", new Integer(64)); blockLengths.put("SHA-224", new Integer(64)); blockLengths.put("SHA-256", new Integer(64)); blockLengths.put("SHA-384", new Integer(128)); blockLengths.put("SHA-512", new Integer(128)); blockLengths.put("Tiger", new Integer(64)); blockLengths.put("Whirlpool", new Integer(64)); } private static int getByteLength( Digest digest) { if (digest instanceof ExtendedDigest) { return ((ExtendedDigest)digest).getByteLength(); } Integer b = (Integer)blockLengths.get(digest.getAlgorithmName()); if (b == null) { throw new IllegalArgumentException("unknown digest passed: " + digest.getAlgorithmName()); } return b.intValue(); } /** * Base constructor for one of the standard digest algorithms that the * byteLength of the algorithm is know for. * * @param digest the digest. */ public HMac( Digest digest) { this(digest, getByteLength(digest)); } private HMac( Digest digest, int byteLength) { this.digest = digest; digestSize = digest.getDigestSize(); this.blockLength = byteLength; inputPad = new byte[blockLength]; outputPad = new byte[blockLength]; } public String getAlgorithmName() { return digest.getAlgorithmName() + "/HMAC"; } public Digest getUnderlyingDigest() { return digest; } public void init( CipherParameters params) { digest.reset(); byte[] key = ((KeyParameter)params).getKey(); if (key.length > blockLength) { digest.update(key, 0, key.length); digest.doFinal(inputPad, 0); for (int i = digestSize; i < inputPad.length; i++) { inputPad[i] = 0; } } else { System.arraycopy(key, 0, inputPad, 0, key.length); for (int i = key.length; i < inputPad.length; i++) { inputPad[i] = 0; } } outputPad = new byte[inputPad.length]; System.arraycopy(inputPad, 0, outputPad, 0, inputPad.length); for (int i = 0; i < inputPad.length; i++) { inputPad[i] ^= IPAD; } for (int i = 0; i < outputPad.length; i++) { outputPad[i] ^= OPAD; } digest.update(inputPad, 0, inputPad.length); } public int getMacSize() { return digestSize; } public void update( byte in) { digest.update(in); } public void update( byte[] in, int inOff, int len) { digest.update(in, inOff, len); } public int doFinal( byte[] out, int outOff) { byte[] tmp = new byte[digestSize]; digest.doFinal(tmp, 0); digest.update(outputPad, 0, outputPad.length); digest.update(tmp, 0, tmp.length); int len = digest.doFinal(out, outOff); reset(); return len; } /** * Reset the mac generator. */ public void reset() { /* * reset the underlying digest. */ digest.reset(); /* * reinitialize the digest. */ digest.update(inputPad, 0, inputPad.length); } }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/macs/HMac.java
Java
asf20
5,852
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * the foundation class for the exceptions thrown by the crypto packages. */ public class RuntimeCryptoException extends RuntimeException { /** * base constructor. */ public RuntimeCryptoException() { } /** * create a RuntimeCryptoException with the given message. * * @param message the message to be carried with the exception. */ public RuntimeCryptoException( String message) { super(message); } }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/RuntimeCryptoException.java
Java
asf20
1,694
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * The base interface for implementations of message authentication codes (MACs). */ public interface Mac { /** * Initialise the MAC. * * @param params the key and other data required by the MAC. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init(CipherParameters params) throws IllegalArgumentException; /** * Return the name of the algorithm the MAC implements. * * @return the name of the algorithm the MAC implements. */ public String getAlgorithmName(); /** * Return the block size for this MAC (in bytes). * * @return the block size for this MAC in bytes. */ public int getMacSize(); /** * add a single byte to the mac for processing. * * @param in the byte to be processed. * @exception IllegalStateException if the MAC is not initialised. */ public void update(byte in) throws IllegalStateException; /** * @param in the array containing the input. * @param inOff the index in the array the data begins at. * @param len the length of the input starting at inOff. * @exception IllegalStateException if the MAC is not initialised. * @exception DataLengthException if there isn't enough data in in. */ public void update(byte[] in, int inOff, int len) throws DataLengthException, IllegalStateException; /** * Compute the final stage of the MAC writing the output to the out * parameter. * <p> * doFinal leaves the MAC in the same state it was after the last init. * * @param out the array the MAC is to be output to. * @param outOff the offset into the out buffer the output is to start at. * @exception DataLengthException if there isn't enough space in out. * @exception IllegalStateException if the MAC is not initialised. */ public int doFinal(byte[] out, int outOff) throws DataLengthException, IllegalStateException; /** * Reset the MAC. At the end of resetting the MAC should be in the * in the same state it was after the last init (if there was one). */ public void reset(); }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/Mac.java
Java
asf20
3,432
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * this exception is thrown if a buffer that is meant to have output * copied into it turns out to be too short, or if we've been given * insufficient input. In general this exception will get thrown rather * than an ArrayOutOfBounds exception. */ public class DataLengthException extends RuntimeCryptoException { /** * base constructor. */ public DataLengthException() { } /** * create a DataLengthException with the given message. * * @param message the message to be carried with the exception. */ public DataLengthException( String message) { super(message); } }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/DataLengthException.java
Java
asf20
1,863
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.params; import org.bouncycastle.crypto.CipherParameters; public class KeyParameter implements CipherParameters { private byte[] key; public KeyParameter( byte[] key) { this(key, 0, key.length); } public KeyParameter( byte[] key, int keyOff, int keyLen) { this.key = new byte[keyLen]; System.arraycopy(key, keyOff, this.key, 0, keyLen); } public byte[] getKey() { return key; } }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/params/KeyParameter.java
Java
asf20
1,704
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; public interface ExtendedDigest extends Digest { /** * Return the size in bytes of the internal buffer the digest applies it's compression * function to. * * @return byte length of the digests internal buffer. */ public int getByteLength(); }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/ExtendedDigest.java
Java
asf20
1,484
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.digests; import org.bouncycastle.crypto.ExtendedDigest; /** * base implementation of MD4 family style digest as outlined in * "Handbook of Applied Cryptography", pages 344 - 347. */ public abstract class GeneralDigest implements ExtendedDigest { private static final int BYTE_LENGTH = 64; private byte[] xBuf; private int xBufOff; private long byteCount; /** * Standard constructor */ protected GeneralDigest() { xBuf = new byte[4]; xBufOff = 0; } /** * Copy constructor. We are using copy constructors in place * of the Object.clone() interface as this interface is not * supported by J2ME. */ protected GeneralDigest(GeneralDigest t) { xBuf = new byte[t.xBuf.length]; System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length); xBufOff = t.xBufOff; byteCount = t.byteCount; } public void update( byte in) { xBuf[xBufOff++] = in; if (xBufOff == xBuf.length) { processWord(xBuf, 0); xBufOff = 0; } byteCount++; } public void update( byte[] in, int inOff, int len) { // // fill the current word // while ((xBufOff != 0) && (len > 0)) { update(in[inOff]); inOff++; len--; } // // process whole words. // while (len > xBuf.length) { processWord(in, inOff); inOff += xBuf.length; len -= xBuf.length; byteCount += xBuf.length; } // // load in the remainder. // while (len > 0) { update(in[inOff]); inOff++; len--; } } public void finish() { long bitLength = (byteCount << 3); // // add the pad bytes. // update((byte)128); while (xBufOff != 0) { update((byte)0); } processLength(bitLength); processBlock(); } public void reset() { byteCount = 0; xBufOff = 0; for (int i = 0; i < xBuf.length; i++) { xBuf[i] = 0; } } public int getByteLength() { return BYTE_LENGTH; } protected abstract void processWord(byte[] in, int inOff); protected abstract void processLength(long bitLength); protected abstract void processBlock(); }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/digests/GeneralDigest.java
Java
asf20
3,779
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.digests; import org.bouncycastle.crypto.util.Pack; /** * implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349. * * It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5 * is the "endienness" of the word processing! */ public class SHA1Digest extends GeneralDigest { private static final int DIGEST_LENGTH = 20; private int H1, H2, H3, H4, H5; private int[] X = new int[80]; private int xOff; /** * Standard constructor */ public SHA1Digest() { reset(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public SHA1Digest(SHA1Digest t) { super(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; System.arraycopy(t.X, 0, X, 0, t.X.length); xOff = t.xOff; } public String getAlgorithmName() { return "SHA-1"; } public int getDigestSize() { return DIGEST_LENGTH; } protected void processWord( byte[] in, int inOff) { // Note: Inlined for performance // X[xOff] = Pack.bigEndianToInt(in, inOff); int n = in[ inOff] << 24; n |= (in[++inOff] & 0xff) << 16; n |= (in[++inOff] & 0xff) << 8; n |= (in[++inOff] & 0xff); X[xOff] = n; if (++xOff == 16) { processBlock(); } } protected void processLength( long bitLength) { if (xOff > 14) { processBlock(); } X[14] = (int)(bitLength >>> 32); X[15] = (int)(bitLength & 0xffffffff); } public int doFinal( byte[] out, int outOff) { finish(); Pack.intToBigEndian(H1, out, outOff); Pack.intToBigEndian(H2, out, outOff + 4); Pack.intToBigEndian(H3, out, outOff + 8); Pack.intToBigEndian(H4, out, outOff + 12); Pack.intToBigEndian(H5, out, outOff + 16); reset(); return DIGEST_LENGTH; } /** * reset the chaining variables */ public void reset() { super.reset(); H1 = 0x67452301; H2 = 0xefcdab89; H3 = 0x98badcfe; H4 = 0x10325476; H5 = 0xc3d2e1f0; xOff = 0; for (int i = 0; i != X.length; i++) { X[i] = 0; } } // // Additive constants // private static final int Y1 = 0x5a827999; private static final int Y2 = 0x6ed9eba1; private static final int Y3 = 0x8f1bbcdc; private static final int Y4 = 0xca62c1d6; private int f( int u, int v, int w) { return ((u & v) | ((~u) & w)); } private int h( int u, int v, int w) { return (u ^ v ^ w); } private int g( int u, int v, int w) { return ((u & v) | (u & w) | (v & w)); } protected void processBlock() { // // expand 16 word block into 80 word block. // for (int i = 16; i < 80; i++) { int t = X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16]; X[i] = t << 1 | t >>> 31; } // // set up working variables. // int A = H1; int B = H2; int C = H3; int D = H4; int E = H5; // // round 1 // int idx = 0; for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + f(B, C, D) + E + X[idx++] + Y1 // B = rotateLeft(B, 30) E += (A << 5 | A >>> 27) + f(B, C, D) + X[idx++] + Y1; B = B << 30 | B >>> 2; D += (E << 5 | E >>> 27) + f(A, B, C) + X[idx++] + Y1; A = A << 30 | A >>> 2; C += (D << 5 | D >>> 27) + f(E, A, B) + X[idx++] + Y1; E = E << 30 | E >>> 2; B += (C << 5 | C >>> 27) + f(D, E, A) + X[idx++] + Y1; D = D << 30 | D >>> 2; A += (B << 5 | B >>> 27) + f(C, D, E) + X[idx++] + Y1; C = C << 30 | C >>> 2; } // // round 2 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y2 // B = rotateLeft(B, 30) E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y2; B = B << 30 | B >>> 2; D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y2; A = A << 30 | A >>> 2; C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y2; E = E << 30 | E >>> 2; B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y2; D = D << 30 | D >>> 2; A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y2; C = C << 30 | C >>> 2; } // // round 3 // for (int j = 0; j < 4; j++) { // E = rotateLeft(A, 5) + g(B, C, D) + E + X[idx++] + Y3 // B = rotateLeft(B, 30) E += (A << 5 | A >>> 27) + g(B, C, D) + X[idx++] + Y3; B = B << 30 | B >>> 2; D += (E << 5 | E >>> 27) + g(A, B, C) + X[idx++] + Y3; A = A << 30 | A >>> 2; C += (D << 5 | D >>> 27) + g(E, A, B) + X[idx++] + Y3; E = E << 30 | E >>> 2; B += (C << 5 | C >>> 27) + g(D, E, A) + X[idx++] + Y3; D = D << 30 | D >>> 2; A += (B << 5 | B >>> 27) + g(C, D, E) + X[idx++] + Y3; C = C << 30 | C >>> 2; } // // round 4 // for (int j = 0; j <= 3; j++) { // E = rotateLeft(A, 5) + h(B, C, D) + E + X[idx++] + Y4 // B = rotateLeft(B, 30) E += (A << 5 | A >>> 27) + h(B, C, D) + X[idx++] + Y4; B = B << 30 | B >>> 2; D += (E << 5 | E >>> 27) + h(A, B, C) + X[idx++] + Y4; A = A << 30 | A >>> 2; C += (D << 5 | D >>> 27) + h(E, A, B) + X[idx++] + Y4; E = E << 30 | E >>> 2; B += (C << 5 | C >>> 27) + h(D, E, A) + X[idx++] + Y4; D = D << 30 | D >>> 2; A += (B << 5 | B >>> 27) + h(C, D, E) + X[idx++] + Y4; C = C << 30 | C >>> 2; } H1 += A; H2 += B; H3 += C; H4 += D; H5 += E; // // reset start of the buffer. // xOff = 0; for (int i = 0; i < 16; i++) { X[i] = 0; } } }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/digests/SHA1Digest.java
Java
asf20
8,093
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto.util; public abstract class Pack { public static int bigEndianToInt(byte[] bs, int off) { int n = bs[ off] << 24; n |= (bs[++off] & 0xff) << 16; n |= (bs[++off] & 0xff) << 8; n |= (bs[++off] & 0xff); return n; } public static void intToBigEndian(int n, byte[] bs, int off) { bs[ off] = (byte)(n >>> 24); bs[++off] = (byte)(n >>> 16); bs[++off] = (byte)(n >>> 8); bs[++off] = (byte)(n ); } public static long bigEndianToLong(byte[] bs, int off) { int hi = bigEndianToInt(bs, off); int lo = bigEndianToInt(bs, off + 4); return ((long)(hi & 0xffffffffL) << 32) | (long)(lo & 0xffffffffL); } public static void longToBigEndian(long n, byte[] bs, int off) { intToBigEndian((int)(n >>> 32), bs, off); intToBigEndian((int)(n & 0xffffffffL), bs, off + 4); } }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/util/Pack.java
Java
asf20
2,125
/*- * Copyright (c) 2000 - 2009 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.bouncycastle.crypto; /** * interface that a message digest conforms to. */ public interface Digest { /** * return the algorithm name * * @return the algorithm name */ public String getAlgorithmName(); /** * return the size, in bytes, of the digest produced by this message digest. * * @return the size, in bytes, of the digest produced by this message digest. */ public int getDigestSize(); /** * update the message digest with a single byte. * * @param in the input byte to be entered. */ public void update(byte in); /** * update the message digest with a block of bytes. * * @param in the byte array containing the data. * @param inOff the offset into the byte array where the data starts. * @param len the length of the data. */ public void update(byte[] in, int inOff, int len); /** * close the digest, producing the final digest value. The doFinal * call leaves the digest reset. * * @param out the array the digest is to be copied into. * @param outOff the offset into the out array the digest is to start at. */ public int doFinal(byte[] out, int outOff); /** * reset the digest back to it's initial state. */ public void reset(); }
001coldblade-authenticator
mobile/blackberry/src/org/bouncycastle/crypto/Digest.java
Java
asf20
2,507
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.Clipboard; import net.rim.device.api.ui.ContextMenu; import net.rim.device.api.ui.MenuItem; import net.rim.device.api.ui.Screen; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.Dialog; import net.rim.device.api.ui.component.ListField; import net.rim.device.api.ui.component.ListFieldCallback; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * BlackBerry port of {@code PinListAdapter}. */ public class PinListField extends ListField implements AuthenticatorResource { private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); /** * {@inheritDoc} */ public int moveFocus(int amount, int status, int time) { invalidate(getSelectedIndex()); return super.moveFocus(amount, status, time); } /** * {@inheritDoc} */ public void onUnfocus() { super.onUnfocus(); invalidate(); } /** * {@inheritDoc} */ protected void makeContextMenu(ContextMenu contextMenu) { super.makeContextMenu(contextMenu); ListFieldCallback callback = getCallback(); final int selectedIndex = getSelectedIndex(); final PinInfo item = (PinInfo) callback.get(this, selectedIndex); if (item.mIsHotp) { MenuItem hotpItem = new MenuItem(sResources, COUNTER_PIN, 0, 0) { public void run() { AuthenticatorScreen screen = (AuthenticatorScreen) getScreen(); String user = item.mUser; String pin = screen.computeAndDisplayPin(user, selectedIndex, true); item.mPin = pin; invalidate(selectedIndex); } }; contextMenu.addItem(hotpItem); } MenuItem copyItem = new MenuItem(sResources, COPY_TO_CLIPBOARD, 0, 0) { public void run() { Clipboard clipboard = Clipboard.getClipboard(); clipboard.put(item.mPin); String message = sResources.getString(COPIED); Dialog.inform(message); } }; MenuItem deleteItem = new MenuItem(sResources, DELETE, 0, 0) { public void run() { String message = (sResources.getString(DELETE_MESSAGE) + "\n" + item.mUser); int defaultChoice = Dialog.NO; if (Dialog.ask(Dialog.D_YES_NO, message, defaultChoice) == Dialog.YES) { AccountDb.delete(item.mUser); AuthenticatorScreen screen = (AuthenticatorScreen) getScreen(); screen.refreshUserList(); } } }; contextMenu.addItem(copyItem); if (item.mIsHotp) { MenuItem checkCodeItem = new MenuItem(sResources, CHECK_CODE_MENU_ITEM, 0, 0) { public void run() { pushScreen(new CheckCodeScreen(item.mUser)); } }; contextMenu.addItem(checkCodeItem); } contextMenu.addItem(deleteItem); } void pushScreen(Screen s) { Screen screen = getScreen(); UiApplication app = (UiApplication) screen.getApplication(); app.pushScreen(s); } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/PinListField.java
Java
asf20
3,649
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.device.api.util.AbstractString; import net.rim.device.api.util.StringPattern; /** * Searches for URIs matching one of the following: * * <pre> * https://www.google.com/accounts/KeyProv?user=username#secret * totp://username@domain#secret * otpauth://totp/user@example.com?secret=FFF... * otpauth://hotp/user@example.com?secret=FFF...&amp;counter=123 * </pre> * * <strong>Important Note:</strong> HTTP/HTTPS URIs may be ignored by the * platform because they are already handled by the browser. */ public class UriStringPattern extends StringPattern { /** * A list of URI prefixes that should be matched. */ private static final String[] PREFIXES = { "https://www.google.com/accounts/KeyProv?", "totp://", "otpauth://totp/", "otpauth://hotp/" }; public UriStringPattern() { } /** * {@inheritDoc} */ public boolean findMatch(AbstractString str, int beginIndex, int maxIndex, StringPattern.Match match) { prefixes: for (int i = 0; i < PREFIXES.length; i++) { String prefix = PREFIXES[i]; if (maxIndex - beginIndex < prefix.length()) { continue prefixes; } characters: for (int a = beginIndex; a < maxIndex; a++) { for (int b = 0; b < prefix.length(); b++) { if (str.charAt(a + b) != prefix.charAt(b)) { continue characters; } } int uriStart = a; while (a < maxIndex && !isWhitespace(str.charAt(a))) { a++; } int uriEnd = a; match.id = AuthenticatorApplication.FACTORY_ID; match.beginIndex = uriStart; match.endIndex = uriEnd; match.prefixLength = 0; return true; } } return false; } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/UriStringPattern.java
Java
asf20
2,389
/*- * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications: * -Changed package name * -Removed annotations * -Removed "@since Android 1.0" comments */ package com.google.authenticator.blackberry; import java.io.UnsupportedEncodingException; /** * This class is used to encode a string using the format required by * {@code application/x-www-form-urlencoded} MIME content type. */ public class URLEncoder { static final String digits = "0123456789ABCDEF"; //$NON-NLS-1$ /** * Prevents this class from being instantiated. */ private URLEncoder() { } /** * Encodes a given string {@code s} in a x-www-form-urlencoded string using * the specified encoding scheme {@code enc}. * <p> * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9') * and characters '.', '-', '*', '_' are converted into their hexadecimal * value prepended by '%'. For example: '#' -> %23. In addition, spaces are * substituted by '+' * </p> * * @param s * the string to be encoded. * @return the encoded string. * @deprecated use {@link #encode(String, String)} instead. */ public static String encode(String s) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ".-*_".indexOf(ch) > -1) { //$NON-NLS-1$ buf.append(ch); } else if (ch == ' ') { buf.append('+'); } else { byte[] bytes = new String(new char[] { ch }).getBytes(); for (int j = 0; j < bytes.length; j++) { buf.append('%'); buf.append(digits.charAt((bytes[j] & 0xf0) >> 4)); buf.append(digits.charAt(bytes[j] & 0xf)); } } } return buf.toString(); } /** * Encodes the given string {@code s} in a x-www-form-urlencoded string * using the specified encoding scheme {@code enc}. * <p> * All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9') * and characters '.', '-', '*', '_' are converted into their hexadecimal * value prepended by '%'. For example: '#' -> %23. In addition, spaces are * substituted by '+' * </p> * * @param s * the string to be encoded. * @param enc * the encoding scheme to be used. * @return the encoded string. * @throws UnsupportedEncodingException * if the specified encoding scheme is invalid. */ public static String encode(String s, String enc) throws UnsupportedEncodingException { if (s == null || enc == null) { throw new NullPointerException(); } // check for UnsupportedEncodingException "".getBytes(enc); //$NON-NLS-1$ StringBuffer buf = new StringBuffer(); int start = -1; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || " .-*_".indexOf(ch) > -1) { //$NON-NLS-1$ if (start >= 0) { convert(s.substring(start, i), buf, enc); start = -1; } if (ch != ' ') { buf.append(ch); } else { buf.append('+'); } } else { if (start < 0) { start = i; } } } if (start >= 0) { convert(s.substring(start, s.length()), buf, enc); } return buf.toString(); } private static void convert(String s, StringBuffer buf, String enc) throws UnsupportedEncodingException { byte[] bytes = s.getBytes(enc); for (int j = 0; j < bytes.length; j++) { buf.append('%'); buf.append(digits.charAt((bytes[j] & 0xf0) >> 4)); buf.append(digits.charAt(bytes[j] & 0xf)); } } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/URLEncoder.java
Java
asf20
5,056
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; /** * Encodes arbitrary byte arrays as case-insensitive base-32 strings using * the legacy encoding scheme. */ public class Base32Legacy extends Base32String { // 32 alpha-numeric characters. Excluding 0, 1, O, and I private static final Base32Legacy INSTANCE = new Base32Legacy("23456789ABCDEFGHJKLMNPQRSTUVWXYZ"); static Base32String getInstance() { return INSTANCE; } protected Base32Legacy(String alphabet) { super(alphabet); } public static byte[] decode(String encoded) throws DecodingException { return getInstance().decodeInternal(encoded); } public static String encode(byte[] data) { return getInstance().encodeInternal(data); } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/Base32Legacy.java
Java
asf20
1,332
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; /** * Callback interface for {@link UpdateTask}. */ public interface UpdateCallback { void onUpdate(String version); }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/UpdateCallback.java
Java
asf20
762
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.component.NullField; /** * Utility methods for using BlackBerry {@link Field Fields}. */ public class FieldUtils { public static boolean isVisible(Field field) { return field.getManager() != null; } /** * BlackBerry {@link Field Fields} do not support invisibility, so swap in an * invisible placeholder to simulate invisibility. * <p> * The placeholder field is stored with {@link Field#setCookie(Object)}. * <p> * The non-placeholder field must be added to a {@link Manager} before marking * is as <em>invisible</em> so that the implementation knows where to insert * the placeholder. * * @param field * the field to toggle. * @param visible * the new visibility. */ public static void setVisible(Field field, boolean visible) { NullField peer = (NullField) field.getCookie(); if (visible && !isVisible(field)) { if (peer == null) { throw new IllegalStateException("Placeholder missing"); } Manager manager = peer.getManager(); manager.replace(peer, field); } else if (!visible && isVisible(field)) { if (peer == null) { peer = new NullField(); field.setCookie(peer); } Manager manager = field.getManager(); manager.replace(field, peer); } } FieldUtils() { } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/FieldUtils.java
Java
asf20
2,080
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import org.bouncycastle.crypto.Mac; /** * An implementation of the HOTP generator specified by RFC 4226. Generates * short passcodes that may be used in challenge-response protocols or as * timeout passcodes that are only valid for a short period. * * The default passcode is a 6-digit decimal code and the default timeout * period is 5 minutes. */ public class PasscodeGenerator { /** Default decimal passcode length */ private static final int PASS_CODE_LENGTH = 6; /** Default passcode timeout period (in seconds) */ private static final int INTERVAL = 30; /** The number of previous and future intervals to check */ private static final int ADJACENT_INTERVALS = 1; private static final int PIN_MODULO = pow(10, PASS_CODE_LENGTH); private static final int pow(int a, int b) { int result = 1; for (int i = 0; i < b; i++) { result *= a; } return result; } private final Signer signer; private final int codeLength; private final int intervalPeriod; /* * Using an interface to allow us to inject different signature * implementations. */ interface Signer { byte[] sign(byte[] data); } /** * @param mac A {@link Mac} used to generate passcodes */ public PasscodeGenerator(Mac mac) { this(mac, PASS_CODE_LENGTH, INTERVAL); } /** * @param mac A {@link Mac} used to generate passcodes * @param passCodeLength The length of the decimal passcode * @param interval The interval that a passcode is valid for */ public PasscodeGenerator(final Mac mac, int passCodeLength, int interval) { this(new Signer() { public byte[] sign(byte[] data){ mac.reset(); mac.update(data, 0, data.length); int length = mac.getMacSize(); byte[] out = new byte[length]; mac.doFinal(out, 0); mac.reset(); return out; } }, passCodeLength, interval); } public PasscodeGenerator(Signer signer, int passCodeLength, int interval) { this.signer = signer; this.codeLength = passCodeLength; this.intervalPeriod = interval; } private String padOutput(int value) { String result = Integer.toString(value); for (int i = result.length(); i < codeLength; i++) { result = "0" + result; } return result; } /** * @return A decimal timeout code */ public String generateTimeoutCode() { return generateResponseCode(clock.getCurrentInterval()); } /** * @param challenge A long-valued challenge * @return A decimal response code * @throws GeneralSecurityException If a JCE exception occur */ public String generateResponseCode(long challenge) { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutput dout = new DataOutputStream(out); try { dout.writeLong(challenge); } catch (IOException e) { // This should never happen with a ByteArrayOutputStream throw new RuntimeException("Unexpected IOException"); } byte[] value = out.toByteArray(); return generateResponseCode(value); } /** * @param challenge An arbitrary byte array used as a challenge * @return A decimal response code * @throws GeneralSecurityException If a JCE exception occur */ public String generateResponseCode(byte[] challenge) { byte[] hash = signer.sign(challenge); // Dynamically truncate the hash // OffsetBits are the low order bits of the last byte of the hash int offset = hash[hash.length - 1] & 0xF; // Grab a positive integer value starting at the given offset. int truncatedHash = hashToInt(hash, offset) & 0x7FFFFFFF; int pinValue = truncatedHash % PIN_MODULO; return padOutput(pinValue); } /** * Grabs a positive integer value from the input array starting at * the given offset. * @param bytes the array of bytes * @param start the index into the array to start grabbing bytes * @return the integer constructed from the four bytes in the array */ private int hashToInt(byte[] bytes, int start) { DataInput input = new DataInputStream( new ByteArrayInputStream(bytes, start, bytes.length - start)); int val; try { val = input.readInt(); } catch (IOException e) { throw new IllegalStateException(String.valueOf(e)); } return val; } /** * @param challenge A challenge to check a response against * @param response A response to verify * @return True if the response is valid */ public boolean verifyResponseCode(long challenge, String response) { String expectedResponse = generateResponseCode(challenge); return expectedResponse.equals(response); } /** * Verify a timeout code. The timeout code will be valid for a time * determined by the interval period and the number of adjacent intervals * checked. * * @param timeoutCode The timeout code * @return True if the timeout code is valid */ public boolean verifyTimeoutCode(String timeoutCode) { return verifyTimeoutCode(timeoutCode, ADJACENT_INTERVALS, ADJACENT_INTERVALS); } /** * Verify a timeout code. The timeout code will be valid for a time * determined by the interval period and the number of adjacent intervals * checked. * * @param timeoutCode The timeout code * @param pastIntervals The number of past intervals to check * @param futureIntervals The number of future intervals to check * @return True if the timeout code is valid */ public boolean verifyTimeoutCode(String timeoutCode, int pastIntervals, int futureIntervals) { long currentInterval = clock.getCurrentInterval(); String expectedResponse = generateResponseCode(currentInterval); if (expectedResponse.equals(timeoutCode)) { return true; } for (int i = 1; i <= pastIntervals; i++) { String pastResponse = generateResponseCode(currentInterval - i); if (pastResponse.equals(timeoutCode)) { return true; } } for (int i = 1; i <= futureIntervals; i++) { String futureResponse = generateResponseCode(currentInterval + i); if (futureResponse.equals(timeoutCode)) { return true; } } return false; } private IntervalClock clock = new IntervalClock() { /* * @return The current interval */ public long getCurrentInterval() { long currentTimeSeconds = System.currentTimeMillis() / 1000; return currentTimeSeconds / getIntervalPeriod(); } public int getIntervalPeriod() { return intervalPeriod; } }; // To facilitate injecting a mock clock interface IntervalClock { int getIntervalPeriod(); long getCurrentInterval(); } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/PasscodeGenerator.java
Java
asf20
7,549
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.ApplicationDescriptor; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.component.BitmapField; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.RichTextField; import net.rim.device.api.ui.container.HorizontalFieldManager; import net.rim.device.api.ui.container.MainScreen; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * BlackBerry port of {@code CheckCodeActivity}. */ public class CheckCodeScreen extends MainScreen implements AuthenticatorResource { private static final boolean SHOW_INSTRUCTIONS = false; private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); private RichTextField mCheckCodeTextView; private LabelField mCodeTextView; private LabelField mVersionText; private Manager mCodeArea; private String mUser; static String getCheckCode(String secret) throws Base32String.DecodingException { final byte[] keyBytes = Base32String.decode(secret); Mac mac = new HMac(new SHA1Digest()); mac.init(new KeyParameter(keyBytes)); PasscodeGenerator pcg = new PasscodeGenerator(mac); return pcg.generateResponseCode(0L); } public CheckCodeScreen(String user) { mUser = user; setTitle(sResources.getString(CHECK_CODE_TITLE)); mCheckCodeTextView = new RichTextField(); mCheckCodeTextView.setText(sResources.getString(CHECK_CODE)); mCodeArea = new HorizontalFieldManager(FIELD_HCENTER); Bitmap bitmap = Bitmap.getBitmapResource("ic_lock_lock.png"); BitmapField icon = new BitmapField(bitmap, FIELD_VCENTER); mCodeTextView = new LabelField("", FIELD_VCENTER); mCodeArea.add(icon); mCodeArea.add(mCodeTextView); ApplicationDescriptor applicationDescriptor = ApplicationDescriptor .currentApplicationDescriptor(); String version = applicationDescriptor.getVersion(); mVersionText = new LabelField(version, FIELD_RIGHT | FIELD_BOTTOM); add(mCheckCodeTextView); add(mCodeArea); add(mVersionText); } /** * {@inheritDoc} */ protected void onDisplay() { super.onDisplay(); onResume(); } /** * {@inheritDoc} */ protected void onExposed() { super.onExposed(); onResume(); } private void onResume() { String secret = AuthenticatorScreen.getSecret(mUser); if (secret == null || secret.length() == 0) { // If the user started up this app but there is no secret key yet, // then tell the user to visit a web page to get the secret key. tellUserToGetSecretKey(); return; } String checkCode = null; String errorMessage = null; try { checkCode = getCheckCode(secret); } catch (RuntimeException e) { errorMessage = sResources.getString(GENERAL_SECURITY_EXCEPTION); } catch (Base32String.DecodingException e) { errorMessage = sResources.getString(DECODING_EXCEPTION); } if (errorMessage != null) { mCheckCodeTextView.setText(errorMessage); FieldUtils.setVisible(mCheckCodeTextView, true); FieldUtils.setVisible(mCodeArea, false); } else { mCodeTextView.setText(checkCode); String checkCodeMessage = sResources.getString(CHECK_CODE); mCheckCodeTextView.setText(checkCodeMessage); FieldUtils.setVisible(mCheckCodeTextView, SHOW_INSTRUCTIONS); FieldUtils.setVisible(mCodeArea, true); } } /** * Tells the user to visit a web page to get a secret key. */ private void tellUserToGetSecretKey() { String message = sResources.getString(NOT_INITIALIZED); mCheckCodeTextView.setText(message); FieldUtils.setVisible(mCheckCodeTextView, true); FieldUtils.setVisible(mCodeArea, false); } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/CheckCodeScreen.java
Java
asf20
4,683
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.ApplicationManager; import net.rim.device.api.system.ApplicationManagerException; import net.rim.device.api.system.CodeModuleManager; import net.rim.device.api.ui.MenuItem; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * A context menu item for shared secret URLs found in other applications (such * as the SMS app). */ public class UriMenuItem extends MenuItem implements AuthenticatorResource { private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); private String mUri; public UriMenuItem(String uri) { super(sResources, ENTER_KEY_MENU_ITEM, 5, 5); mUri = uri; } /** * {@inheritDoc} */ public void run() { try { ApplicationManager manager = ApplicationManager.getApplicationManager(); int moduleHandle = CodeModuleManager .getModuleHandleForClass(AuthenticatorApplication.class); String moduleName = CodeModuleManager.getModuleName(moduleHandle); manager.launch(moduleName + "?uri&" + Uri.encode(mUri)); } catch (ApplicationManagerException e) { e.printStackTrace(); } } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/UriMenuItem.java
Java
asf20
1,862
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.device.api.ui.component.ActiveFieldContext; import net.rim.device.api.util.Factory; /** * Factory for {@link UriActiveFieldCookie} instances. */ public class UriActiveFieldCookieFactory implements Factory { /** * {@inheritDoc} */ public Object createInstance(Object initialData) { if (initialData instanceof ActiveFieldContext) { ActiveFieldContext context = (ActiveFieldContext) initialData; String data = (String) context.getData(); return new UriActiveFieldCookie(data); } return null; } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/UriActiveFieldCookieFactory.java
Java
asf20
1,193
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import net.rim.device.api.i18n.Locale; import net.rim.device.api.system.Application; import net.rim.device.api.system.ApplicationDescriptor; import net.rim.device.api.system.ApplicationManager; import net.rim.device.api.system.Branding; import net.rim.device.api.system.DeviceInfo; /** * Checks for software updates and invokes a callback if one is found. */ public class UpdateTask extends Thread { private static String getApplicationVersion() { ApplicationDescriptor app = ApplicationDescriptor .currentApplicationDescriptor(); return app.getVersion(); } private static String getPlatformVersion() { ApplicationManager manager = ApplicationManager.getApplicationManager(); ApplicationDescriptor[] applications = manager.getVisibleApplications(); for (int i = 0; i < applications.length; i++) { ApplicationDescriptor application = applications[i]; String moduleName = application.getModuleName(); if (moduleName.equals("net_rim_bb_ribbon_app")) { return application.getVersion(); } } return null; } private static String getUserAgent() { String deviceName = DeviceInfo.getDeviceName(); String version = getPlatformVersion(); String profile = System.getProperty("microedition.profiles"); String configuration = System.getProperty("microedition.configuration"); String applicationVersion = getApplicationVersion(); int vendorId = Branding.getVendorId(); return "BlackBerry" + deviceName + "/" + version + " Profile/" + profile + " Configuration/" + configuration + " VendorID/" + vendorId + " Application/" + applicationVersion; } private static String getLanguage() { Locale locale = Locale.getDefault(); return locale.getLanguage(); } private static String getEncoding(HttpConnection c) throws IOException { String enc = "ISO-8859-1"; String contentType = c.getHeaderField("Content-Type"); if (contentType != null) { String prefix = "charset="; int beginIndex = contentType.indexOf(prefix); if (beginIndex != -1) { beginIndex += prefix.length(); int endIndex = contentType.indexOf(';', beginIndex); if (endIndex != -1) { enc = contentType.substring(beginIndex, endIndex); } else { enc = contentType.substring(beginIndex); } } } return enc.trim(); } private static HttpConnection connect(String url) throws IOException { if (DeviceInfo.isSimulator()) { url += ";deviceside=true"; } else { url += ";deviceside=false;ConnectionType=mds-public"; } return (HttpConnection) Connector.open(url); } private final UpdateCallback mCallback; public UpdateTask(UpdateCallback callback) { if (callback == null) { throw new NullPointerException(); } mCallback = callback; } private String getMIDletVersion(Reader reader) throws IOException { BufferedReader r = new BufferedReader(reader); String prefix = "MIDlet-Version:"; for (String line = r.readLine(); line != null; line = r.readLine()) { if (line.startsWith(prefix)) { int beginIndex = prefix.length(); String value = line.substring(beginIndex); return value.trim(); } } return null; } /** * {@inheritDoc} */ public void run() { try { // Visit the original download URL and read the JAD; // if the MIDlet-Version has changed, invoke the callback. String url = Build.DOWNLOAD_URL; String applicationVersion = getApplicationVersion(); String userAgent = getUserAgent(); String language = getLanguage(); for (int redirectCount = 0; redirectCount < 10; redirectCount++) { HttpConnection c = null; InputStream s = null; try { c = connect(url); c.setRequestMethod(HttpConnection.GET); c.setRequestProperty("User-Agent", userAgent); c.setRequestProperty("Accept-Language", language); int responseCode = c.getResponseCode(); if (responseCode == HttpConnection.HTTP_MOVED_PERM || responseCode == HttpConnection.HTTP_MOVED_TEMP) { String location = c.getHeaderField("Location"); if (location != null) { url = location; continue; } else { throw new IOException("Location header missing"); } } else if (responseCode != HttpConnection.HTTP_OK) { throw new IOException("Unexpected response code: " + responseCode); } s = c.openInputStream(); String enc = getEncoding(c); Reader reader = new InputStreamReader(s, enc); final String version = getMIDletVersion(reader); if (version == null) { throw new IOException("MIDlet-Version not found"); } else if (!version.equals(applicationVersion)) { Application application = Application.getApplication(); application.invokeLater(new Runnable() { public void run() { mCallback.onUpdate(version); } }); } else { // Already running latest version } } finally { if (s != null) { s.close(); } if (c != null) { c.close(); } } } } catch (Exception e) { System.out.println(e); } } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/UpdateTask.java
Java
asf20
6,326
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.device.api.system.RuntimeStore; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.util.StringPattern; import net.rim.device.api.util.StringPatternRepository; /** * Main entry point. */ public class AuthenticatorApplication extends UiApplication { public static final long FACTORY_ID = 0xdee739761f1b0a72L; private static boolean sInitialized; public static void main(String[] args) { if (args != null && args.length >= 1 && "startup".equals(args[0])) { // This entry-point is invoked when the device is rebooted. registerStringPattern(); } else if (args != null && args.length >= 2 && "uri".equals(args[0])) { // This entry-point is invoked when the user clicks on a URI containing // the shared secret. String uriString = Uri.decode(args[1]); startApplication(Uri.parse(uriString)); } else { // The default entry point starts the user interface. startApplication(null); } } /** * Registers pattern matcher so that this application can handle certain URI * schemes referenced in other applications. */ private static void registerStringPattern() { if (!sInitialized) { RuntimeStore runtimeStore = RuntimeStore.getRuntimeStore(); UriActiveFieldCookieFactory factory = new UriActiveFieldCookieFactory(); runtimeStore.put(FACTORY_ID, factory); StringPattern pattern = new UriStringPattern(); StringPatternRepository.addPattern(pattern); sInitialized = true; } } private static void startApplication(Uri uri) { UiApplication app = new AuthenticatorApplication(); AuthenticatorScreen screen = new AuthenticatorScreen(); app.pushScreen(screen); if (uri != null) { screen.parseSecret(uri); screen.refreshUserList(); } app.enterEventDispatcher(); } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/AuthenticatorApplication.java
Java
asf20
2,498
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import java.util.Hashtable; /** * Encodes arbitrary byte arrays as case-insensitive base-32 strings */ public class Base32String { // singleton private static final Base32String INSTANCE = new Base32String("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"); // RFC 4668/3548 static Base32String getInstance() { return INSTANCE; } // 32 alpha-numeric characters. private String ALPHABET; private char[] DIGITS; private int MASK; private int SHIFT; private Hashtable CHAR_MAP; static final String SEPARATOR = "-"; protected Base32String(String alphabet) { this.ALPHABET = alphabet; DIGITS = ALPHABET.toCharArray(); MASK = DIGITS.length - 1; SHIFT = numberOfTrailingZeros(DIGITS.length); CHAR_MAP = new Hashtable(); for (int i = 0; i < DIGITS.length; i++) { CHAR_MAP.put(new Character(DIGITS[i]), new Integer(i)); } } /** * Counts the number of 1 bits in the specified integer; this is also * referred to as population count. * * @param i * the integer to examine. * @return the number of 1 bits in {@code i}. */ private static int bitCount(int i) { i -= ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); i = (((i >> 4) + i) & 0x0F0F0F0F); i += (i >> 8); i += (i >> 16); return (i & 0x0000003F); } /** * Determines the number of trailing zeros in the specified integer after * the {@link #lowestOneBit(int) lowest one bit}. * * @param i * the integer to examine. * @return the number of trailing zeros in {@code i}. */ private static int numberOfTrailingZeros(int i) { return bitCount((i & -i) - 1); } public static byte[] decode(String encoded) throws DecodingException { return getInstance().decodeInternal(encoded); } private static String canonicalize(String str) { int length = str.length(); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < length; i++) { char c = str.charAt(i); if (SEPARATOR.indexOf(c) == -1 && c != ' ') { buffer.append(Character.toUpperCase(c)); } } return buffer.toString().trim(); } protected byte[] decodeInternal(String encoded) throws DecodingException { // Remove whitespace and separators encoded = canonicalize(encoded); // Canonicalize to all upper case encoded = encoded.toUpperCase(); if (encoded.length() == 0) { return new byte[0]; } int encodedLength = encoded.length(); int outLength = encodedLength * SHIFT / 8; byte[] result = new byte[outLength]; int buffer = 0; int next = 0; int bitsLeft = 0; for (int i = 0, n = encoded.length(); i < n; i++) { Character c = new Character(encoded.charAt(i)); if (!CHAR_MAP.containsKey(c)) { throw new DecodingException("Illegal character: " + c); } buffer <<= SHIFT; buffer |= ((Integer) CHAR_MAP.get(c)).intValue() & MASK; bitsLeft += SHIFT; if (bitsLeft >= 8) { result[next++] = (byte) (buffer >> (bitsLeft - 8)); bitsLeft -= 8; } } // We'll ignore leftover bits for now. // // if (next != outLength || bitsLeft >= SHIFT) { // throw new DecodingException("Bits left: " + bitsLeft); // } return result; } public static String encode(byte[] data) { return getInstance().encodeInternal(data); } protected String encodeInternal(byte[] data) { if (data.length == 0) { return ""; } // SHIFT is the number of bits per output character, so the length of the // output is the length of the input multiplied by 8/SHIFT, rounded up. if (data.length >= (1 << 28)) { // The computation below will fail, so don't do it. throw new IllegalArgumentException(); } int outputLength = (data.length * 8 + SHIFT - 1) / SHIFT; StringBuffer result = new StringBuffer(outputLength); int buffer = data[0]; int next = 1; int bitsLeft = 8; while (bitsLeft > 0 || next < data.length) { if (bitsLeft < SHIFT) { if (next < data.length) { buffer <<= 8; buffer |= (data[next++] & 0xff); bitsLeft += 8; } else { int pad = SHIFT - bitsLeft; buffer <<= pad; bitsLeft += pad; } } int index = MASK & (buffer >> (bitsLeft - SHIFT)); bitsLeft -= SHIFT; result.append(DIGITS[index]); } return result.toString(); } static class DecodingException extends Exception { public DecodingException(String message) { super(message); } } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/Base32String.java
Java
asf20
5,286
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.device.api.system.Bitmap; import net.rim.device.api.ui.Font; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.component.ListField; import net.rim.device.api.ui.component.ListFieldCallback; /** * A tuple of user, OTP value, and type, that represents a particular user. */ class PinInfo { public String mPin; // calculated OTP, or a placeholder if not calculated public String mUser; public boolean mIsHotp = false; // used to see if button needs to be displayed } /** * BlackBerry port of {@code PinListAdapter}. */ public class PinListFieldCallback implements ListFieldCallback { private static final int PADDING = 4; private final Font mUserFont; private final Font mPinFont; private final Bitmap mIcon; private final int mRowHeight; private final PinInfo[] mItems; public PinListFieldCallback(PinInfo[] items) { super(); mItems = items; mUserFont = Font.getDefault().derive(Font.ITALIC); mPinFont = Font.getDefault(); mIcon = Bitmap.getBitmapResource("ic_lock_lock.png"); mRowHeight = computeRowHeight(); } private int computeRowHeight() { int textHeight = mUserFont.getHeight() + mPinFont.getHeight(); int iconHeight = mIcon.getHeight(); return PADDING + Math.max(textHeight, iconHeight) + PADDING; } public int getRowHeight() { return mRowHeight; } /** * {@inheritDoc} */ public void drawListRow(ListField listField, Graphics graphics, int index, int y, int width) { PinInfo item = mItems[index]; int iconWidth = mIcon.getWidth(); int iconHeight = mIcon.getHeight(); int iconX = width - PADDING - iconWidth; int iconY = y + Math.max(0, (mRowHeight - iconHeight) / 2); graphics.drawBitmap(iconX, iconY, iconWidth, iconHeight, mIcon, 0, 0); int textWidth = Math.max(0, width - iconWidth - PADDING * 3); int textX = PADDING; int textY = y + PADDING; int flags = Graphics.ELLIPSIS; Font savedFont = graphics.getFont(); graphics.setFont(mUserFont); graphics.drawText(item.mUser, textX, textY, flags, textWidth); textY += mUserFont.getHeight(); graphics.setFont(mPinFont); graphics.drawText(item.mPin, textX, textY, flags, textWidth); graphics.setFont(savedFont); } /** * {@inheritDoc} */ public Object get(ListField listField, int index) { return mItems[index]; } /** * {@inheritDoc} */ public int getPreferredWidth(ListField listField) { return Integer.MAX_VALUE; } /** * {@inheritDoc} */ public int indexOfList(ListField listField, String prefix, int start) { for (int i = start; i < mItems.length; i++) { PinInfo item = mItems[i]; // Check if username starts with prefix (ignoring case) if (item.mUser.regionMatches(true, 0, prefix, 0, prefix.length())) { return i; } } return -1; } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/PinListFieldCallback.java
Java
asf20
3,531
/*- * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications: * -Changed package name * -Removed "@since Android 1.0" comments * -Removed logging * -Removed special error messages * -Removed annotations * -Replaced StringBuilder with StringBuffer */ package com.google.authenticator.blackberry; import java.io.IOException; import java.io.Reader; /** * Wraps an existing {@link Reader} and <em>buffers</em> the input. Expensive * interaction with the underlying reader is minimized, since most (smaller) * requests can be satisfied by accessing the buffer alone. The drawback is that * some extra space is required to hold the buffer and that copying takes place * when filling that buffer, but this is usually outweighed by the performance * benefits. * * <p/>A typical application pattern for the class looks like this:<p/> * * <pre> * BufferedReader buf = new BufferedReader(new FileReader(&quot;file.java&quot;)); * </pre> * * @see BufferedWriter */ public class BufferedReader extends Reader { private Reader in; private char[] buf; private int marklimit = -1; private int count; private int markpos = -1; private int pos; /** * Constructs a new BufferedReader on the Reader {@code in}. The * buffer gets the default size (8 KB). * * @param in * the Reader that is buffered. */ public BufferedReader(Reader in) { super(in); this.in = in; buf = new char[8192]; } /** * Constructs a new BufferedReader on the Reader {@code in}. The buffer * size is specified by the parameter {@code size}. * * @param in * the Reader that is buffered. * @param size * the size of the buffer to allocate. * @throws IllegalArgumentException * if {@code size <= 0}. */ public BufferedReader(Reader in, int size) { super(in); if (size <= 0) { throw new IllegalArgumentException(); } this.in = in; buf = new char[size]; } /** * Closes this reader. This implementation closes the buffered source reader * and releases the buffer. Nothing is done if this reader has already been * closed. * * @throws IOException * if an error occurs while closing this reader. */ public void close() throws IOException { synchronized (lock) { if (!isClosed()) { in.close(); buf = null; } } } private int fillbuf() throws IOException { if (markpos == -1 || (pos - markpos >= marklimit)) { /* Mark position not set or exceeded readlimit */ int result = in.read(buf, 0, buf.length); if (result > 0) { markpos = -1; pos = 0; count = result == -1 ? 0 : result; } return result; } if (markpos == 0 && marklimit > buf.length) { /* Increase buffer size to accommodate the readlimit */ int newLength = buf.length * 2; if (newLength > marklimit) { newLength = marklimit; } char[] newbuf = new char[newLength]; System.arraycopy(buf, 0, newbuf, 0, buf.length); buf = newbuf; } else if (markpos > 0) { System.arraycopy(buf, markpos, buf, 0, buf.length - markpos); } /* Set the new position and mark position */ pos -= markpos; count = markpos = 0; int charsread = in.read(buf, pos, buf.length - pos); count = charsread == -1 ? pos : pos + charsread; return charsread; } /** * Indicates whether or not this reader is closed. * * @return {@code true} if this reader is closed, {@code false} * otherwise. */ private boolean isClosed() { return buf == null; } /** * Sets a mark position in this reader. The parameter {@code readlimit} * indicates how many characters can be read before the mark is invalidated. * Calling {@code reset()} will reposition the reader back to the marked * position if {@code readlimit} has not been surpassed. * * @param readlimit * the number of characters that can be read before the mark is * invalidated. * @throws IllegalArgumentException * if {@code readlimit < 0}. * @throws IOException * if an error occurs while setting a mark in this reader. * @see #markSupported() * @see #reset() */ public void mark(int readlimit) throws IOException { if (readlimit < 0) { throw new IllegalArgumentException(); } synchronized (lock) { if (isClosed()) { throw new IOException(); } marklimit = readlimit; markpos = pos; } } /** * Indicates whether this reader supports the {@code mark()} and * {@code reset()} methods. This implementation returns {@code true}. * * @return {@code true} for {@code BufferedReader}. * @see #mark(int) * @see #reset() */ public boolean markSupported() { return true; } /** * Reads a single character from this reader and returns it with the two * higher-order bytes set to 0. If possible, BufferedReader returns a * character from the buffer. If there are no characters available in the * buffer, it fills the buffer and then returns a character. It returns -1 * if there are no more characters in the source reader. * * @return the character read or -1 if the end of the source reader has been * reached. * @throws IOException * if this reader is closed or some other I/O error occurs. */ public int read() throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } /* Are there buffered characters available? */ if (pos < count || fillbuf() != -1) { return buf[pos++]; } return -1; } } /** * Reads at most {@code length} characters from this reader and stores them * at {@code offset} in the character array {@code buffer}. Returns the * number of characters actually read or -1 if the end of the source reader * has been reached. If all the buffered characters have been used, a mark * has not been set and the requested number of characters is larger than * this readers buffer size, BufferedReader bypasses the buffer and simply * places the results directly into {@code buffer}. * * @param buffer * the character array to store the characters read. * @param offset * the initial position in {@code buffer} to store the bytes read * from this reader. * @param length * the maximum number of characters to read, must be * non-negative. * @return number of characters read or -1 if the end of the source reader * has been reached. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code length < 0}, or if * {@code offset + length} is greater than the size of * {@code buffer}. * @throws IOException * if this reader is closed or some other I/O error occurs. */ public int read(char[] buffer, int offset, int length) throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } if (length == 0) { return 0; } int required; if (pos < count) { /* There are bytes available in the buffer. */ int copylength = count - pos >= length ? length : count - pos; System.arraycopy(buf, pos, buffer, offset, copylength); pos += copylength; if (copylength == length || !in.ready()) { return copylength; } offset += copylength; required = length - copylength; } else { required = length; } while (true) { int read; /* * If we're not marked and the required size is greater than the * buffer, simply read the bytes directly bypassing the buffer. */ if (markpos == -1 && required >= buf.length) { read = in.read(buffer, offset, required); if (read == -1) { return required == length ? -1 : length - required; } } else { if (fillbuf() == -1) { return required == length ? -1 : length - required; } read = count - pos >= required ? required : count - pos; System.arraycopy(buf, pos, buffer, offset, read); pos += read; } required -= read; if (required == 0) { return length; } if (!in.ready()) { return length - required; } offset += read; } } } /** * Returns the next line of text available from this reader. A line is * represented by zero or more characters followed by {@code '\n'}, * {@code '\r'}, {@code "\r\n"} or the end of the reader. The string does * not include the newline sequence. * * @return the contents of the line or {@code null} if no characters were * read before the end of the reader has been reached. * @throws IOException * if this reader is closed or some other I/O error occurs. */ public String readLine() throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } /* Are there buffered characters available? */ if ((pos >= count) && (fillbuf() == -1)) { return null; } for (int charPos = pos; charPos < count; charPos++) { char ch = buf[charPos]; if (ch > '\r') { continue; } if (ch == '\n') { String res = new String(buf, pos, charPos - pos); pos = charPos + 1; return res; } else if (ch == '\r') { String res = new String(buf, pos, charPos - pos); pos = charPos + 1; if (((pos < count) || (fillbuf() != -1)) && (buf[pos] == '\n')) { pos++; } return res; } } char eol = '\0'; StringBuffer result = new StringBuffer(80); /* Typical Line Length */ result.append(buf, pos, count - pos); pos = count; while (true) { /* Are there buffered characters available? */ if (pos >= count) { if (eol == '\n') { return result.toString(); } // attempt to fill buffer if (fillbuf() == -1) { // characters or null. return result.length() > 0 || eol != '\0' ? result .toString() : null; } } for (int charPos = pos; charPos < count; charPos++) { if (eol == '\0') { if ((buf[charPos] == '\n' || buf[charPos] == '\r')) { eol = buf[charPos]; } } else if (eol == '\r' && (buf[charPos] == '\n')) { if (charPos > pos) { result.append(buf, pos, charPos - pos - 1); } pos = charPos + 1; return result.toString(); } else if (eol != '\0') { if (charPos > pos) { result.append(buf, pos, charPos - pos - 1); } pos = charPos; return result.toString(); } } if (eol == '\0') { result.append(buf, pos, count - pos); } else { result.append(buf, pos, count - pos - 1); } pos = count; } } } /** * Indicates whether this reader is ready to be read without blocking. * * @return {@code true} if this reader will not block when {@code read} is * called, {@code false} if unknown or blocking will occur. * @throws IOException * if this reader is closed or some other I/O error occurs. * @see #read() * @see #read(char[], int, int) * @see #readLine() */ public boolean ready() throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } return ((count - pos) > 0) || in.ready(); } } /** * Resets this reader's position to the last {@code mark()} location. * Invocations of {@code read()} and {@code skip()} will occur from this new * location. * * @throws IOException * if this reader is closed or no mark has been set. * @see #mark(int) * @see #markSupported() */ public void reset() throws IOException { synchronized (lock) { if (isClosed()) { throw new IOException(); } if (markpos == -1) { throw new IOException(); } pos = markpos; } } /** * Skips {@code amount} characters in this reader. Subsequent * {@code read()}s will not return these characters unless {@code reset()} * is used. Skipping characters may invalidate a mark if {@code readlimit} * is surpassed. * * @param amount * the maximum number of characters to skip. * @return the number of characters actually skipped. * @throws IllegalArgumentException * if {@code amount < 0}. * @throws IOException * if this reader is closed or some other I/O error occurs. * @see #mark(int) * @see #markSupported() * @see #reset() */ public long skip(long amount) throws IOException { if (amount < 0) { throw new IllegalArgumentException(); } synchronized (lock) { if (isClosed()) { throw new IOException(); } if (amount < 1) { return 0; } if (count - pos >= amount) { pos += amount; return amount; } long read = count - pos; pos = count; while (read < amount) { if (fillbuf() == -1) { return read; } if (count - pos >= amount - read) { pos += amount - read; return amount; } // Couldn't get all the characters, skip what we read read += (count - pos); pos = count; } return amount; } } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/BufferedReader.java
Java
asf20
16,856
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import java.util.Hashtable; import java.util.Vector; import com.google.authenticator.blackberry.resource.AuthenticatorResource; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.CodeModuleManager; import net.rim.device.api.system.CodeSigningKey; import net.rim.device.api.system.ControlledAccess; import net.rim.device.api.system.PersistentObject; import net.rim.device.api.system.PersistentStore; /** * BlackBerry port of {@code AccountDb}. */ public class AccountDb { private static final String TABLE_NAME = "accounts"; static final String ID_COLUMN = "_id"; static final String EMAIL_COLUMN = "email"; static final String SECRET_COLUMN = "secret"; static final String COUNTER_COLUMN = "counter"; static final String TYPE_COLUMN = "type"; static final Integer TYPE_LEGACY_TOTP = new Integer(-1); // TODO: remove April 2010 private static final long PERSISTENT_STORE_KEY = 0x9f1343901e600bf7L; static Hashtable sPreferences; static PersistentObject sPersistentObject; /** * Types of secret keys. */ public static class OtpType { private static ResourceBundle sResources = ResourceBundle.getBundle( AuthenticatorResource.BUNDLE_ID, AuthenticatorResource.BUNDLE_NAME); public static final OtpType TOTP = new OtpType(0); // time based public static final OtpType HOTP = new OtpType(1); // counter based private static final OtpType[] values = { TOTP, HOTP }; public final Integer value; // value as stored in database OtpType(int value) { this.value = new Integer(value); } public static OtpType getEnum(Integer i) { for (int index = 0; index < values.length; index++) { OtpType type = values[index]; if (type.value.intValue() == i.intValue()) { return type; } } return null; } public static OtpType[] values() { return values; } /** * {@inheritDoc} */ public String toString() { if (this == TOTP) { return sResources.getString(AuthenticatorResource.TOTP); } else if (this == HOTP) { return sResources.getString(AuthenticatorResource.HOTP); } else { return super.toString(); } } } private AccountDb() { // Don't new me } static { sPersistentObject = PersistentStore.getPersistentObject(PERSISTENT_STORE_KEY); sPreferences = (Hashtable) sPersistentObject.getContents(); if (sPreferences == null) { sPreferences = new Hashtable(); } // Use an instance of a class owned by this application // to easily get the appropriate CodeSigningKey: Object appObject = new FieldUtils(); // Get the public code signing key CodeSigningKey codeSigningKey = CodeSigningKey.get(appObject); if (codeSigningKey == null) { throw new SecurityException("Code not protected by a signing key"); } // Ensure that the code has been signed with the corresponding private key int moduleHandle = CodeModuleManager.getModuleHandleForObject(appObject); if (!ControlledAccess.verifyCodeModuleSignature(moduleHandle, codeSigningKey)) { String signerId = codeSigningKey.getSignerId(); throw new SecurityException("Code not signed by " + signerId + " key"); } Object contents = sPreferences; // Only allow signed applications to access user data contents = new ControlledAccess(contents, codeSigningKey); sPersistentObject.setContents(contents); sPersistentObject.commit(); } private static Vector getAccounts() { Vector accounts = (Vector) sPreferences.get(TABLE_NAME); if (accounts == null) { accounts = new Vector(10); sPreferences.put(TABLE_NAME, accounts); sPersistentObject.commit(); } return accounts; } private static Hashtable getAccount(String email) { if (email == null) { throw new NullPointerException(); } Vector accounts = getAccounts(); for (int i = 0, n = accounts.size(); i < n; i++) { Hashtable account = (Hashtable) accounts.elementAt(i); if (email.equals(account.get(EMAIL_COLUMN))) { return account; } } return null; } static String[] getNames() { Vector accounts = getAccounts(); int size = accounts.size(); String[] names = new String[size]; for (int i = 0; i < size; i++) { Hashtable account = (Hashtable) accounts.elementAt(i); names[i] = (String) account.get(EMAIL_COLUMN); } return names; } static boolean nameExists(String email) { Hashtable account = getAccount(email); return account != null; } static String getSecret(String email) { Hashtable account = getAccount(email); return account != null ? (String) account.get(SECRET_COLUMN) : null; } static Integer getCounter(String email) { Hashtable account = getAccount(email); return account != null ? (Integer) account.get(COUNTER_COLUMN) : null; } static void incrementCounter(String email) { Hashtable account = getAccount(email); if (account != null) { Integer counter = (Integer) account.get(COUNTER_COLUMN); counter = new Integer(counter.intValue() + 1); account.put(COUNTER_COLUMN, counter); sPersistentObject.commit(); } } static OtpType getType(String user) { Hashtable account = getAccount(user); if (account != null) { Integer value = (Integer) account.get(TYPE_COLUMN); return OtpType.getEnum(value); } else { return null; } } static void delete(String email) { Vector accounts = getAccounts(); boolean modified = false; for (int index = 0; index < accounts.size();) { Hashtable account = (Hashtable) accounts.elementAt(index); if (email.equals(account.get(EMAIL_COLUMN))) { accounts.removeElementAt(index); modified = true; } else { index++; } } if (modified) { sPersistentObject.commit(); } } /** * Save key to database, creating a new user entry if necessary. * @param email the user email address. When editing, the new user email. * @param secret the secret key. * @param oldEmail If editing, the original user email, otherwise null. */ static void update(String email, String secret, String oldEmail, AccountDb.OtpType type) { Hashtable account = oldEmail != null ? getAccount(oldEmail) : null; if (account == null) { account = new Hashtable(10); Vector accounts = getAccounts(); accounts.addElement(account); } account.put(EMAIL_COLUMN, email); account.put(SECRET_COLUMN, secret); account.put(TYPE_COLUMN, type.value); if (!account.containsKey(COUNTER_COLUMN)) { account.put(COUNTER_COLUMN, new Integer(0)); } sPersistentObject.commit(); } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/AccountDb.java
Java
asf20
7,490
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.blackberry.api.browser.Browser; import net.rim.blackberry.api.browser.BrowserSession; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.Alert; import net.rim.device.api.system.Application; import net.rim.device.api.system.ApplicationDescriptor; import net.rim.device.api.ui.MenuItem; import net.rim.device.api.ui.Screen; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.Menu; import net.rim.device.api.ui.component.RichTextField; import net.rim.device.api.ui.container.MainScreen; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import com.google.authenticator.blackberry.AccountDb.OtpType; import com.google.authenticator.blackberry.Base32String.DecodingException; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * BlackBerry port of {@code AuthenticatorActivity}. */ public class AuthenticatorScreen extends MainScreen implements UpdateCallback, AuthenticatorResource, Runnable { private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); private static final int VIBRATE_DURATION = 200; private static final long REFRESH_INTERVAL = 30 * 1000; private static final boolean AUTO_REFRESH = true; private static final String TERMS_URL = "http://www.google.com/accounts/TOS"; private static final String PRIVACY_URL = "http://www.google.com/mobile/privacy.html"; /** * Computes the one-time PIN given the secret key. * * @param secret * the secret key * @return the PIN * @throws GeneralSecurityException * @throws DecodingException * If the key string is improperly encoded. */ public static String computePin(String secret, Long counter) { try { final byte[] keyBytes = Base32String.decode(secret); Mac mac = new HMac(new SHA1Digest()); mac.init(new KeyParameter(keyBytes)); PasscodeGenerator pcg = new PasscodeGenerator(mac); if (counter == null) { // time-based totp return pcg.generateTimeoutCode(); } else { // counter-based hotp return pcg.generateResponseCode(counter.longValue()); } } catch (RuntimeException e) { return "General security exception"; } catch (DecodingException e) { return "Decoding exception"; } } /** * Parses a secret value from a URI. The format will be: * * <pre> * https://www.google.com/accounts/KeyProv?user=username#secret * OR * totp://username@domain#secret * otpauth://totp/user@example.com?secret=FFF... * otpauth://hotp/user@example.com?secret=FFF...&amp;counter=123 * </pre> * * @param uri The URI containing the secret key */ void parseSecret(Uri uri) { String scheme = uri.getScheme().toLowerCase(); String path = uri.getPath(); String authority = uri.getAuthority(); String user = DEFAULT_USER; String secret; AccountDb.OtpType type = AccountDb.OtpType.TOTP; Integer counter = new Integer(0); // only interesting for HOTP if (OTP_SCHEME.equals(scheme)) { if (authority != null && authority.equals(TOTP)) { type = AccountDb.OtpType.TOTP; } else if (authority != null && authority.equals(HOTP)) { type = AccountDb.OtpType.HOTP; String counterParameter = uri.getQueryParameter(COUNTER_PARAM); if (counterParameter != null) { counter = Integer.valueOf(counterParameter); } } if (path != null && path.length() > 1) { user = path.substring(1); // path is "/user", so remove leading / } secret = uri.getQueryParameter(SECRET_PARAM); // TODO: remove TOTP scheme } else if (TOTP.equals(scheme)) { if (authority != null) { user = authority; } secret = uri.getFragment(); } else { // https://www.google.com... URI format String userParam = uri.getQueryParameter(USER_PARAM); if (userParam != null) { user = userParam; } secret = uri.getFragment(); } if (secret == null) { // Secret key not found in URI return; } // TODO: April 2010 - remove version parameter handling. String version = uri.getQueryParameter(VERSION_PARAM); if (version == null) { // version is null for legacy URIs try { secret = Base32String.encode(Base32Legacy.decode(secret)); } catch (DecodingException e) { // Error decoding legacy key from URI e.printStackTrace(); } } if (!secret.equals(getSecret(user)) || counter != AccountDb.getCounter(user) || type != AccountDb.getType(user)) { saveSecret(user, secret, null, type); mStatusText.setText(sResources.getString(SECRET_SAVED)); } } static String getSecret(String user) { return AccountDb.getSecret(user); } static void saveSecret(String user, String secret, String originalUser, AccountDb.OtpType type) { if (originalUser == null) { originalUser = user; } if (secret != null) { AccountDb.update(user, secret, originalUser, type); Alert.startVibrate(VIBRATE_DURATION); } } private LabelField mVersionText; private LabelField mStatusText; private RichTextField mEnterPinTextView; private PinListField mUserList; private PinListFieldCallback mUserAdapter; private PinInfo[] mUsers = {}; private boolean mUpdateAvailable; private int mTimer = -1; static final String DEFAULT_USER = "Default account"; private static final String OTP_SCHEME = "otpauth"; private static final String TOTP = "totp"; // time-based private static final String HOTP = "hotp"; // counter-based private static final String USER_PARAM = "user"; private static final String SECRET_PARAM = "secret"; private static final String VERSION_PARAM = "v"; private static final String COUNTER_PARAM = "counter"; public AuthenticatorScreen() { setTitle(sResources.getString(APP_NAME)); // LabelField cannot scroll content that is bigger than the screen, // so use RichTextField instead. mEnterPinTextView = new RichTextField(sResources.getString(ENTER_PIN)); mUserList = new PinListField(); mUserAdapter = new PinListFieldCallback(mUsers); setAdapter(); ApplicationDescriptor applicationDescriptor = ApplicationDescriptor .currentApplicationDescriptor(); String version = applicationDescriptor.getVersion(); mVersionText = new LabelField(version, FIELD_RIGHT | FIELD_BOTTOM); mStatusText = new LabelField("", FIELD_HCENTER | FIELD_BOTTOM); add(mEnterPinTextView); add(mUserList); add(new LabelField(" ")); // One-line spacer add(mStatusText); add(mVersionText); FieldUtils.setVisible(mEnterPinTextView, false); UpdateCallback callback = this; new UpdateTask(callback).start(); } private void setAdapter() { int lastIndex = mUserList.getSelectedIndex(); mUserList.setCallback(mUserAdapter); mUserList.setSize(mUsers.length); mUserList.setRowHeight(mUserAdapter.getRowHeight()); mUserList.setSelectedIndex(lastIndex); } /** * {@inheritDoc} */ protected void onDisplay() { super.onDisplay(); onResume(); } /** * {@inheritDoc} */ protected void onExposed() { super.onExposed(); onResume(); } /** * {@inheritDoc} */ protected void onObscured() { onPause(); super.onObscured(); } private void onResume() { refreshUserList(); if (AUTO_REFRESH) { startTimer(); } } private void onPause() { if (isTimerSet()) { stopTimer(); } } private boolean isTimerSet() { return mTimer != -1; } private void startTimer() { if (isTimerSet()) { stopTimer(); } Application application = getApplication(); Runnable runnable = this; boolean repeat = true; mTimer = application.invokeLater(runnable, REFRESH_INTERVAL, repeat); } private void stopTimer() { if (isTimerSet()) { Application application = getApplication(); application.cancelInvokeLater(mTimer); mTimer = -1; } } /** * {@inheritDoc} */ public void run() { refreshUserList(); } void refreshUserList() { String[] cursor = AccountDb.getNames(); if (cursor.length > 0) { if (mUsers.length != cursor.length) { mUsers = new PinInfo[cursor.length]; } for (int i = 0; i < cursor.length; i++) { String user = cursor[i]; computeAndDisplayPin(user, i, false); } mUserAdapter = new PinListFieldCallback(mUsers); setAdapter(); // force refresh of display if (!FieldUtils.isVisible(mUserList)) { mEnterPinTextView.setText(sResources.getString(ENTER_PIN)); FieldUtils.setVisible(mEnterPinTextView, true); FieldUtils.setVisible(mUserList, true); } } else { // If the user started up this app but there is no secret key yet, // then tell the user to visit a web page to get the secret key. mUsers = new PinInfo[0]; // clear any existing user PIN state tellUserToGetSecretKey(); } } /** * Tells the user to visit a web page to get a secret key. */ private void tellUserToGetSecretKey() { // TODO: fill this in with code to send our phone number to the server String notInitialized = sResources.getString(NOT_INITIALIZED); mEnterPinTextView.setText(notInitialized); FieldUtils.setVisible(mEnterPinTextView, true); FieldUtils.setVisible(mUserList, false); } /** * Computes the PIN and saves it in mUsers. This currently runs in the UI * thread so it should not take more than a second or so. If necessary, we can * move the computation to a background thread. * * @param user the user email to display with the PIN * @param position the index for the screen of this user and PIN * @param computeHotp true if we should increment counter and display new hotp * * @return the generated PIN */ String computeAndDisplayPin(String user, int position, boolean computeHotp) { OtpType type = AccountDb.getType(user); String secret = getSecret(user); PinInfo currentPin; if (mUsers[position] != null) { currentPin = mUsers[position]; // existing PinInfo, so we'll update it } else { currentPin = new PinInfo(); currentPin.mPin = sResources.getString(EMPTY_PIN); } currentPin.mUser = user; if (type == OtpType.TOTP) { currentPin.mPin = computePin(secret, null); } else if (type == OtpType.HOTP) { currentPin.mIsHotp = true; if (computeHotp) { AccountDb.incrementCounter(user); Integer counter = AccountDb.getCounter(user); currentPin.mPin = computePin(secret, new Long(counter.longValue())); } } mUsers[position] = currentPin; return currentPin.mPin; } private void pushScreen(Screen screen) { UiApplication app = (UiApplication) getApplication(); app.pushScreen(screen); } /** * {@inheritDoc} */ public Menu getMenu(int instance) { if (instance == Menu.INSTANCE_CONTEXT) { // Show the full menu instead of the context menu return super.getMenu(Menu.INSTANCE_DEFAULT); } else { return super.getMenu(instance); } } /** * {@inheritDoc} */ protected void makeMenu(Menu menu, int instance) { super.makeMenu(menu, instance); MenuItem enterKeyItem = new MenuItem(sResources, ENTER_KEY_MENU_ITEM, 0, 0) { public void run() { pushScreen(new EnterKeyScreen()); } }; MenuItem termsItem = new MenuItem(sResources, TERMS_MENU_ITEM, 0, 0) { public void run() { BrowserSession session = Browser.getDefaultSession(); session.displayPage(TERMS_URL); } }; MenuItem privacyItem = new MenuItem(sResources, PRIVACY_MENU_ITEM, 0, 0) { public void run() { BrowserSession session = Browser.getDefaultSession(); session.displayPage(PRIVACY_URL); } }; menu.add(enterKeyItem); if (!isTimerSet()) { MenuItem refreshItem = new MenuItem(sResources, REFRESH_MENU_ITEM, 0, 0) { public void run() { refreshUserList(); } }; menu.add(refreshItem); } if (mUpdateAvailable) { MenuItem updateItem = new MenuItem(sResources, UPDATE_NOW, 0, 0) { public void run() { BrowserSession session = Browser.getDefaultSession(); session.displayPage(Build.DOWNLOAD_URL); mStatusText.setText(""); } }; menu.add(updateItem); } menu.add(termsItem); menu.add(privacyItem); } /** * {@inheritDoc} */ public void onUpdate(String version) { String status = sResources.getString(UPDATE_AVAILABLE) + ": " + version; mStatusText.setText(status); mUpdateAvailable = true; } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/AuthenticatorScreen.java
Java
asf20
13,776
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import java.util.Vector; import net.rim.device.api.ui.MenuItem; import net.rim.device.api.ui.component.ActiveFieldCookie; import net.rim.device.api.ui.component.CookieProvider; /** * Handler for input events and context menus on URLs containing shared secrets. */ public class UriActiveFieldCookie implements ActiveFieldCookie { private String mUrl; public UriActiveFieldCookie(String data) { mUrl = data; } /** * {@inheritDoc} */ public boolean invokeApplicationKeyVerb() { return false; } public MenuItem getFocusVerbs(CookieProvider provider, Object context, Vector items) { items.addElement(new UriMenuItem(mUrl)); return (MenuItem) items.elementAt(0); } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/UriActiveFieldCookie.java
Java
asf20
1,351
/*- * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications: * -Changed package name * -Removed Android dependencies * -Removed/replaced Java SE dependencies * -Removed/replaced annotations */ package com.google.authenticator.blackberry; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.ByteArrayOutputStream; import java.util.Vector; /** * Immutable URI reference. A URI reference includes a URI and a fragment, the * component of the URI following a '#'. Builds and parses URI references * which conform to * <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>. * * <p>In the interest of performance, this class performs little to no * validation. Behavior is undefined for invalid input. This class is very * forgiving--in the face of invalid input, it will return garbage * rather than throw an exception unless otherwise specified. */ public abstract class Uri { /* This class aims to do as little up front work as possible. To accomplish that, we vary the implementation dependending on what the user passes in. For example, we have one implementation if the user passes in a URI string (StringUri) and another if the user passes in the individual components (OpaqueUri). *Concurrency notes*: Like any truly immutable object, this class is safe for concurrent use. This class uses a caching pattern in some places where it doesn't use volatile or synchronized. This is safe to do with ints because getting or setting an int is atomic. It's safe to do with a String because the internal fields are final and the memory model guarantees other threads won't see a partially initialized instance. We are not guaranteed that some threads will immediately see changes from other threads on certain platforms, but we don't mind if those threads reconstruct the cached result. As a result, we get thread safe caching with no concurrency overhead, which means the most common case, access from a single thread, is as fast as possible. From the Java Language spec.: "17.5 Final Field Semantics ... when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are." In that same vein, all non-transient fields within Uri implementations should be final and immutable so as to ensure true immutability for clients even when they don't use proper concurrency control. For reference, from RFC 2396: "4.3. Parsing a URI Reference A URI reference is typically parsed according to the four main components and fragment identifier in order to determine what components are present and whether the reference is relative or absolute. The individual components are then parsed for their subparts and, if not opaque, to verify their validity. Although the BNF defines what is allowed in each component, it is ambiguous in terms of differentiating between an authority component and a path component that begins with two slash characters. The greedy algorithm is used for disambiguation: the left-most matching rule soaks up as much of the URI reference string as it is capable of matching. In other words, the authority component wins." The "four main components" of a hierarchical URI consist of <scheme>://<authority><path>?<query> */ /** * NOTE: EMPTY accesses this field during its own initialization, so this * field *must* be initialized first, or else EMPTY will see a null value! * * Placeholder for strings which haven't been cached. This enables us * to cache null. We intentionally create a new String instance so we can * compare its identity and there is no chance we will confuse it with * user data. */ private static final String NOT_CACHED = new String("NOT CACHED"); /** * The empty URI, equivalent to "". */ public static final Uri EMPTY = new HierarchicalUri(null, Part.NULL, PathPart.EMPTY, Part.NULL, Part.NULL); /** * Prevents external subclassing. */ private Uri() {} /** * Returns true if this URI is hierarchical like "http://google.com". * Absolute URIs are hierarchical if the scheme-specific part starts with * a '/'. Relative URIs are always hierarchical. */ public abstract boolean isHierarchical(); /** * Returns true if this URI is opaque like "mailto:nobody@google.com". The * scheme-specific part of an opaque URI cannot start with a '/'. */ public boolean isOpaque() { return !isHierarchical(); } /** * Returns true if this URI is relative, i.e. if it doesn't contain an * explicit scheme. * * @return true if this URI is relative, false if it's absolute */ public abstract boolean isRelative(); /** * Returns true if this URI is absolute, i.e. if it contains an * explicit scheme. * * @return true if this URI is absolute, false if it's relative */ public boolean isAbsolute() { return !isRelative(); } /** * Gets the scheme of this URI. Example: "http" * * @return the scheme or null if this is a relative URI */ public abstract String getScheme(); /** * Gets the scheme-specific part of this URI, i.e. everything between the * scheme separator ':' and the fragment separator '#'. If this is a * relative URI, this method returns the entire URI. Decodes escaped octets. * * <p>Example: "//www.google.com/search?q=android" * * @return the decoded scheme-specific-part */ public abstract String getSchemeSpecificPart(); /** * Gets the scheme-specific part of this URI, i.e. everything between the * scheme separator ':' and the fragment separator '#'. If this is a * relative URI, this method returns the entire URI. Leaves escaped octets * intact. * * <p>Example: "//www.google.com/search?q=android" * * @return the decoded scheme-specific-part */ public abstract String getEncodedSchemeSpecificPart(); /** * Gets the decoded authority part of this URI. For * server addresses, the authority is structured as follows: * {@code [ userinfo '@' ] host [ ':' port ]} * * <p>Examples: "google.com", "bob@google.com:80" * * @return the authority for this URI or null if not present */ public abstract String getAuthority(); /** * Gets the encoded authority part of this URI. For * server addresses, the authority is structured as follows: * {@code [ userinfo '@' ] host [ ':' port ]} * * <p>Examples: "google.com", "bob@google.com:80" * * @return the authority for this URI or null if not present */ public abstract String getEncodedAuthority(); /** * Gets the decoded user information from the authority. * For example, if the authority is "nobody@google.com", this method will * return "nobody". * * @return the user info for this URI or null if not present */ public abstract String getUserInfo(); /** * Gets the encoded user information from the authority. * For example, if the authority is "nobody@google.com", this method will * return "nobody". * * @return the user info for this URI or null if not present */ public abstract String getEncodedUserInfo(); /** * Gets the encoded host from the authority for this URI. For example, * if the authority is "bob@google.com", this method will return * "google.com". * * @return the host for this URI or null if not present */ public abstract String getHost(); /** * Gets the port from the authority for this URI. For example, * if the authority is "google.com:80", this method will return 80. * * @return the port for this URI or -1 if invalid or not present */ public abstract int getPort(); /** * Gets the decoded path. * * @return the decoded path, or null if this is not a hierarchical URI * (like "mailto:nobody@google.com") or the URI is invalid */ public abstract String getPath(); /** * Gets the encoded path. * * @return the encoded path, or null if this is not a hierarchical URI * (like "mailto:nobody@google.com") or the URI is invalid */ public abstract String getEncodedPath(); /** * Gets the decoded query component from this URI. The query comes after * the query separator ('?') and before the fragment separator ('#'). This * method would return "q=android" for * "http://www.google.com/search?q=android". * * @return the decoded query or null if there isn't one */ public abstract String getQuery(); /** * Gets the encoded query component from this URI. The query comes after * the query separator ('?') and before the fragment separator ('#'). This * method would return "q=android" for * "http://www.google.com/search?q=android". * * @return the encoded query or null if there isn't one */ public abstract String getEncodedQuery(); /** * Gets the decoded fragment part of this URI, everything after the '#'. * * @return the decoded fragment or null if there isn't one */ public abstract String getFragment(); /** * Gets the encoded fragment part of this URI, everything after the '#'. * * @return the encoded fragment or null if there isn't one */ public abstract String getEncodedFragment(); /** * Gets the decoded path segments. * * @return decoded path segments, each without a leading or trailing '/' */ public abstract String[] getPathSegments(); /** * Gets the decoded last segment in the path. * * @return the decoded last segment or null if the path is empty */ public abstract String getLastPathSegment(); /** * Compares this Uri to another object for equality. Returns true if the * encoded string representations of this Uri and the given Uri are * equal. Case counts. Paths are not normalized. If one Uri specifies a * default port explicitly and the other leaves it implicit, they will not * be considered equal. */ public boolean equals(Object o) { if (!(o instanceof Uri)) { return false; } Uri other = (Uri) o; return toString().equals(other.toString()); } /** * Hashes the encoded string represention of this Uri consistently with * {@link #equals(Object)}. */ public int hashCode() { return toString().hashCode(); } /** * Compares the string representation of this Uri with that of * another. */ public int compareTo(Uri other) { return toString().compareTo(other.toString()); } /** * Returns the encoded string representation of this URI. * Example: "http://google.com/" */ public abstract String toString(); /** * Constructs a new builder, copying the attributes from this Uri. */ public abstract Builder buildUpon(); /** Index of a component which was not found. */ private final static int NOT_FOUND = -1; /** Placeholder value for an index which hasn't been calculated yet. */ private final static int NOT_CALCULATED = -2; /** * Error message presented when a user tries to treat an opaque URI as * hierarchical. */ private static final String NOT_HIERARCHICAL = "This isn't a hierarchical URI."; /** Default encoding. */ private static final String DEFAULT_ENCODING = "UTF-8"; /** * Creates a Uri which parses the given encoded URI string. * * @param uriString an RFC 2396-compliant, encoded URI * @throws NullPointerException if uriString is null * @return Uri for this given uri string */ public static Uri parse(String uriString) { return new StringUri(uriString); } /** * An implementation which wraps a String URI. This URI can be opaque or * hierarchical, but we extend AbstractHierarchicalUri in case we need * the hierarchical functionality. */ private static class StringUri extends AbstractHierarchicalUri { /** Used in parcelling. */ static final int TYPE_ID = 1; /** URI string representation. */ private final String uriString; private StringUri(String uriString) { if (uriString == null) { throw new NullPointerException("uriString"); } this.uriString = uriString; } /** Cached scheme separator index. */ private volatile int cachedSsi = NOT_CALCULATED; /** Finds the first ':'. Returns -1 if none found. */ private int findSchemeSeparator() { return cachedSsi == NOT_CALCULATED ? cachedSsi = uriString.indexOf(':') : cachedSsi; } /** Cached fragment separator index. */ private volatile int cachedFsi = NOT_CALCULATED; /** Finds the first '#'. Returns -1 if none found. */ private int findFragmentSeparator() { return cachedFsi == NOT_CALCULATED ? cachedFsi = uriString.indexOf('#', findSchemeSeparator()) : cachedFsi; } public boolean isHierarchical() { int ssi = findSchemeSeparator(); if (ssi == NOT_FOUND) { // All relative URIs are hierarchical. return true; } if (uriString.length() == ssi + 1) { // No ssp. return false; } // If the ssp starts with a '/', this is hierarchical. return uriString.charAt(ssi + 1) == '/'; } public boolean isRelative() { // Note: We return true if the index is 0 return findSchemeSeparator() == NOT_FOUND; } private volatile String scheme = NOT_CACHED; public String getScheme() { boolean cached = (scheme != NOT_CACHED); return cached ? scheme : (scheme = parseScheme()); } private String parseScheme() { int ssi = findSchemeSeparator(); return ssi == NOT_FOUND ? null : uriString.substring(0, ssi); } private Part ssp; private Part getSsp() { return ssp == null ? ssp = Part.fromEncoded(parseSsp()) : ssp; } public String getEncodedSchemeSpecificPart() { return getSsp().getEncoded(); } public String getSchemeSpecificPart() { return getSsp().getDecoded(); } private String parseSsp() { int ssi = findSchemeSeparator(); int fsi = findFragmentSeparator(); // Return everything between ssi and fsi. return fsi == NOT_FOUND ? uriString.substring(ssi + 1) : uriString.substring(ssi + 1, fsi); } private Part authority; private Part getAuthorityPart() { if (authority == null) { String encodedAuthority = parseAuthority(this.uriString, findSchemeSeparator()); return authority = Part.fromEncoded(encodedAuthority); } return authority; } public String getEncodedAuthority() { return getAuthorityPart().getEncoded(); } public String getAuthority() { return getAuthorityPart().getDecoded(); } private PathPart path; private PathPart getPathPart() { return path == null ? path = PathPart.fromEncoded(parsePath()) : path; } public String getPath() { return getPathPart().getDecoded(); } public String getEncodedPath() { return getPathPart().getEncoded(); } public String[] getPathSegments() { return getPathPart().getPathSegments().segments; } private String parsePath() { String uriString = this.uriString; int ssi = findSchemeSeparator(); // If the URI is absolute. if (ssi > -1) { // Is there anything after the ':'? boolean schemeOnly = ssi + 1 == uriString.length(); if (schemeOnly) { // Opaque URI. return null; } // A '/' after the ':' means this is hierarchical. if (uriString.charAt(ssi + 1) != '/') { // Opaque URI. return null; } } else { // All relative URIs are hierarchical. } return parsePath(uriString, ssi); } private Part query; private Part getQueryPart() { return query == null ? query = Part.fromEncoded(parseQuery()) : query; } public String getEncodedQuery() { return getQueryPart().getEncoded(); } private String parseQuery() { // It doesn't make sense to cache this index. We only ever // calculate it once. int qsi = uriString.indexOf('?', findSchemeSeparator()); if (qsi == NOT_FOUND) { return null; } int fsi = findFragmentSeparator(); if (fsi == NOT_FOUND) { return uriString.substring(qsi + 1); } if (fsi < qsi) { // Invalid. return null; } return uriString.substring(qsi + 1, fsi); } public String getQuery() { return getQueryPart().getDecoded(); } private Part fragment; private Part getFragmentPart() { return fragment == null ? fragment = Part.fromEncoded(parseFragment()) : fragment; } public String getEncodedFragment() { return getFragmentPart().getEncoded(); } private String parseFragment() { int fsi = findFragmentSeparator(); return fsi == NOT_FOUND ? null : uriString.substring(fsi + 1); } public String getFragment() { return getFragmentPart().getDecoded(); } public String toString() { return uriString; } /** * Parses an authority out of the given URI string. * * @param uriString URI string * @param ssi scheme separator index, -1 for a relative URI * * @return the authority or null if none is found */ static String parseAuthority(String uriString, int ssi) { int length = uriString.length(); // If "//" follows the scheme separator, we have an authority. if (length > ssi + 2 && uriString.charAt(ssi + 1) == '/' && uriString.charAt(ssi + 2) == '/') { // We have an authority. // Look for the start of the path, query, or fragment, or the // end of the string. int end = ssi + 3; LOOP: while (end < length) { switch (uriString.charAt(end)) { case '/': // Start of path case '?': // Start of query case '#': // Start of fragment break LOOP; } end++; } return uriString.substring(ssi + 3, end); } else { return null; } } /** * Parses a path out of this given URI string. * * @param uriString URI string * @param ssi scheme separator index, -1 for a relative URI * * @return the path */ static String parsePath(String uriString, int ssi) { int length = uriString.length(); // Find start of path. int pathStart; if (length > ssi + 2 && uriString.charAt(ssi + 1) == '/' && uriString.charAt(ssi + 2) == '/') { // Skip over authority to path. pathStart = ssi + 3; LOOP: while (pathStart < length) { switch (uriString.charAt(pathStart)) { case '?': // Start of query case '#': // Start of fragment return ""; // Empty path. case '/': // Start of path! break LOOP; } pathStart++; } } else { // Path starts immediately after scheme separator. pathStart = ssi + 1; } // Find end of path. int pathEnd = pathStart; LOOP: while (pathEnd < length) { switch (uriString.charAt(pathEnd)) { case '?': // Start of query case '#': // Start of fragment break LOOP; } pathEnd++; } return uriString.substring(pathStart, pathEnd); } public Builder buildUpon() { if (isHierarchical()) { return new Builder() .scheme(getScheme()) .authority(getAuthorityPart()) .path(getPathPart()) .query(getQueryPart()) .fragment(getFragmentPart()); } else { return new Builder() .scheme(getScheme()) .opaquePart(getSsp()) .fragment(getFragmentPart()); } } } /** * Creates an opaque Uri from the given components. Encodes the ssp * which means this method cannot be used to create hierarchical URIs. * * @param scheme of the URI * @param ssp scheme-specific-part, everything between the * scheme separator (':') and the fragment separator ('#'), which will * get encoded * @param fragment fragment, everything after the '#', null if undefined, * will get encoded * * @throws NullPointerException if scheme or ssp is null * @return Uri composed of the given scheme, ssp, and fragment * * @see Builder if you don't want the ssp and fragment to be encoded */ public static Uri fromParts(String scheme, String ssp, String fragment) { if (scheme == null) { throw new NullPointerException("scheme"); } if (ssp == null) { throw new NullPointerException("ssp"); } return new OpaqueUri(scheme, Part.fromDecoded(ssp), Part.fromDecoded(fragment)); } /** * Opaque URI. */ private static class OpaqueUri extends Uri { /** Used in parcelling. */ static final int TYPE_ID = 2; private final String scheme; private final Part ssp; private final Part fragment; private OpaqueUri(String scheme, Part ssp, Part fragment) { this.scheme = scheme; this.ssp = ssp; this.fragment = fragment == null ? Part.NULL : fragment; } public boolean isHierarchical() { return false; } public boolean isRelative() { return scheme == null; } public String getScheme() { return this.scheme; } public String getEncodedSchemeSpecificPart() { return ssp.getEncoded(); } public String getSchemeSpecificPart() { return ssp.getDecoded(); } public String getAuthority() { return null; } public String getEncodedAuthority() { return null; } public String getPath() { return null; } public String getEncodedPath() { return null; } public String getQuery() { return null; } public String getEncodedQuery() { return null; } public String getFragment() { return fragment.getDecoded(); } public String getEncodedFragment() { return fragment.getEncoded(); } public String[] getPathSegments() { return new String[0]; } public String getLastPathSegment() { return null; } public String getUserInfo() { return null; } public String getEncodedUserInfo() { return null; } public String getHost() { return null; } public int getPort() { return -1; } private volatile String cachedString = NOT_CACHED; public String toString() { boolean cached = cachedString != NOT_CACHED; if (cached) { return cachedString; } StringBuffer sb = new StringBuffer(); sb.append(scheme).append(':'); sb.append(getEncodedSchemeSpecificPart()); if (!fragment.isEmpty()) { sb.append('#').append(fragment.getEncoded()); } return cachedString = sb.toString(); } public Builder buildUpon() { return new Builder() .scheme(this.scheme) .opaquePart(this.ssp) .fragment(this.fragment); } } /** * Wrapper for path segment array. */ static class PathSegments { static final PathSegments EMPTY = new PathSegments(null, 0); final String[] segments; final int size; PathSegments(String[] segments, int size) { this.segments = segments; this.size = size; } public String get(int index) { if (index >= size) { throw new IndexOutOfBoundsException(); } return segments[index]; } public int size() { return this.size; } } /** * Builds PathSegments. */ static class PathSegmentsBuilder { String[] segments; int size = 0; void add(String segment) { if (segments == null) { segments = new String[4]; } else if (size + 1 == segments.length) { String[] expanded = new String[segments.length * 2]; System.arraycopy(segments, 0, expanded, 0, segments.length); segments = expanded; } segments[size++] = segment; } PathSegments build() { if (segments == null) { return PathSegments.EMPTY; } try { return new PathSegments(segments, size); } finally { // Makes sure this doesn't get reused. segments = null; } } } /** * Support for hierarchical URIs. */ private abstract static class AbstractHierarchicalUri extends Uri { public String getLastPathSegment() { // TODO: If we haven't parsed all of the segments already, just // grab the last one directly so we only allocate one string. String[] segments = getPathSegments(); int size = segments.length; if (size == 0) { return null; } return segments[size - 1]; } private Part userInfo; private Part getUserInfoPart() { return userInfo == null ? userInfo = Part.fromEncoded(parseUserInfo()) : userInfo; } public final String getEncodedUserInfo() { return getUserInfoPart().getEncoded(); } private String parseUserInfo() { String authority = getEncodedAuthority(); if (authority == null) { return null; } int end = authority.indexOf('@'); return end == NOT_FOUND ? null : authority.substring(0, end); } public String getUserInfo() { return getUserInfoPart().getDecoded(); } private volatile String host = NOT_CACHED; public String getHost() { boolean cached = (host != NOT_CACHED); return cached ? host : (host = parseHost()); } private String parseHost() { String authority = getEncodedAuthority(); if (authority == null) { return null; } // Parse out user info and then port. int userInfoSeparator = authority.indexOf('@'); int portSeparator = authority.indexOf(':', userInfoSeparator); String encodedHost = portSeparator == NOT_FOUND ? authority.substring(userInfoSeparator + 1) : authority.substring(userInfoSeparator + 1, portSeparator); return decode(encodedHost); } private volatile int port = NOT_CALCULATED; public int getPort() { return port == NOT_CALCULATED ? port = parsePort() : port; } private int parsePort() { String authority = getEncodedAuthority(); if (authority == null) { return -1; } // Make sure we look for the port separtor *after* the user info // separator. We have URLs with a ':' in the user info. int userInfoSeparator = authority.indexOf('@'); int portSeparator = authority.indexOf(':', userInfoSeparator); if (portSeparator == NOT_FOUND) { return -1; } String portString = decode(authority.substring(portSeparator + 1)); try { return Integer.parseInt(portString); } catch (NumberFormatException e) { return -1; } } } /** * Hierarchical Uri. */ private static class HierarchicalUri extends AbstractHierarchicalUri { /** Used in parcelling. */ static final int TYPE_ID = 3; private final String scheme; // can be null private final Part authority; private final PathPart path; private final Part query; private final Part fragment; private HierarchicalUri(String scheme, Part authority, PathPart path, Part query, Part fragment) { this.scheme = scheme; this.authority = Part.nonNull(authority); this.path = path == null ? PathPart.NULL : path; this.query = Part.nonNull(query); this.fragment = Part.nonNull(fragment); } public boolean isHierarchical() { return true; } public boolean isRelative() { return scheme == null; } public String getScheme() { return scheme; } private Part ssp; private Part getSsp() { return ssp == null ? ssp = Part.fromEncoded(makeSchemeSpecificPart()) : ssp; } public String getEncodedSchemeSpecificPart() { return getSsp().getEncoded(); } public String getSchemeSpecificPart() { return getSsp().getDecoded(); } /** * Creates the encoded scheme-specific part from its sub parts. */ private String makeSchemeSpecificPart() { StringBuffer builder = new StringBuffer(); appendSspTo(builder); return builder.toString(); } private void appendSspTo(StringBuffer builder) { String encodedAuthority = authority.getEncoded(); if (encodedAuthority != null) { // Even if the authority is "", we still want to append "//". builder.append("//").append(encodedAuthority); } String encodedPath = path.getEncoded(); if (encodedPath != null) { builder.append(encodedPath); } if (!query.isEmpty()) { builder.append('?').append(query.getEncoded()); } } public String getAuthority() { return this.authority.getDecoded(); } public String getEncodedAuthority() { return this.authority.getEncoded(); } public String getEncodedPath() { return this.path.getEncoded(); } public String getPath() { return this.path.getDecoded(); } public String getQuery() { return this.query.getDecoded(); } public String getEncodedQuery() { return this.query.getEncoded(); } public String getFragment() { return this.fragment.getDecoded(); } public String getEncodedFragment() { return this.fragment.getEncoded(); } public String[] getPathSegments() { return this.path.getPathSegments().segments; } private volatile String uriString = NOT_CACHED; /** * {@inheritDoc} */ public String toString() { boolean cached = (uriString != NOT_CACHED); return cached ? uriString : (uriString = makeUriString()); } private String makeUriString() { StringBuffer builder = new StringBuffer(); if (scheme != null) { builder.append(scheme).append(':'); } appendSspTo(builder); if (!fragment.isEmpty()) { builder.append('#').append(fragment.getEncoded()); } return builder.toString(); } public Builder buildUpon() { return new Builder() .scheme(scheme) .authority(authority) .path(path) .query(query) .fragment(fragment); } } /** * Helper class for building or manipulating URI references. Not safe for * concurrent use. * * <p>An absolute hierarchical URI reference follows the pattern: * {@code &lt;scheme&gt;://&lt;authority&gt;&lt;absolute path&gt;?&lt;query&gt;#&lt;fragment&gt;} * * <p>Relative URI references (which are always hierarchical) follow one * of two patterns: {@code &lt;relative or absolute path&gt;?&lt;query&gt;#&lt;fragment&gt;} * or {@code //&lt;authority&gt;&lt;absolute path&gt;?&lt;query&gt;#&lt;fragment&gt;} * * <p>An opaque URI follows this pattern: * {@code &lt;scheme&gt;:&lt;opaque part&gt;#&lt;fragment&gt;} */ public static final class Builder { private String scheme; private Part opaquePart; private Part authority; private PathPart path; private Part query; private Part fragment; /** * Constructs a new Builder. */ public Builder() {} /** * Sets the scheme. * * @param scheme name or {@code null} if this is a relative Uri */ public Builder scheme(String scheme) { this.scheme = scheme; return this; } Builder opaquePart(Part opaquePart) { this.opaquePart = opaquePart; return this; } /** * Encodes and sets the given opaque scheme-specific-part. * * @param opaquePart decoded opaque part */ public Builder opaquePart(String opaquePart) { return opaquePart(Part.fromDecoded(opaquePart)); } /** * Sets the previously encoded opaque scheme-specific-part. * * @param opaquePart encoded opaque part */ public Builder encodedOpaquePart(String opaquePart) { return opaquePart(Part.fromEncoded(opaquePart)); } Builder authority(Part authority) { // This URI will be hierarchical. this.opaquePart = null; this.authority = authority; return this; } /** * Encodes and sets the authority. */ public Builder authority(String authority) { return authority(Part.fromDecoded(authority)); } /** * Sets the previously encoded authority. */ public Builder encodedAuthority(String authority) { return authority(Part.fromEncoded(authority)); } Builder path(PathPart path) { // This URI will be hierarchical. this.opaquePart = null; this.path = path; return this; } /** * Sets the path. Leaves '/' characters intact but encodes others as * necessary. * * <p>If the path is not null and doesn't start with a '/', and if * you specify a scheme and/or authority, the builder will prepend the * given path with a '/'. */ public Builder path(String path) { return path(PathPart.fromDecoded(path)); } /** * Sets the previously encoded path. * * <p>If the path is not null and doesn't start with a '/', and if * you specify a scheme and/or authority, the builder will prepend the * given path with a '/'. */ public Builder encodedPath(String path) { return path(PathPart.fromEncoded(path)); } /** * Encodes the given segment and appends it to the path. */ public Builder appendPath(String newSegment) { return path(PathPart.appendDecodedSegment(path, newSegment)); } /** * Appends the given segment to the path. */ public Builder appendEncodedPath(String newSegment) { return path(PathPart.appendEncodedSegment(path, newSegment)); } Builder query(Part query) { // This URI will be hierarchical. this.opaquePart = null; this.query = query; return this; } /** * Encodes and sets the query. */ public Builder query(String query) { return query(Part.fromDecoded(query)); } /** * Sets the previously encoded query. */ public Builder encodedQuery(String query) { return query(Part.fromEncoded(query)); } Builder fragment(Part fragment) { this.fragment = fragment; return this; } /** * Encodes and sets the fragment. */ public Builder fragment(String fragment) { return fragment(Part.fromDecoded(fragment)); } /** * Sets the previously encoded fragment. */ public Builder encodedFragment(String fragment) { return fragment(Part.fromEncoded(fragment)); } /** * Encodes the key and value and then appends the parameter to the * query string. * * @param key which will be encoded * @param value which will be encoded */ public Builder appendQueryParameter(String key, String value) { // This URI will be hierarchical. this.opaquePart = null; String encodedParameter = encode(key, null) + "=" + encode(value, null); if (query == null) { query = Part.fromEncoded(encodedParameter); return this; } String oldQuery = query.getEncoded(); if (oldQuery == null || oldQuery.length() == 0) { query = Part.fromEncoded(encodedParameter); } else { query = Part.fromEncoded(oldQuery + "&" + encodedParameter); } return this; } /** * Constructs a Uri with the current attributes. * * @throws UnsupportedOperationException if the URI is opaque and the * scheme is null */ public Uri build() { if (opaquePart != null) { if (this.scheme == null) { throw new UnsupportedOperationException( "An opaque URI must have a scheme."); } return new OpaqueUri(scheme, opaquePart, fragment); } else { // Hierarchical URIs should not return null for getPath(). PathPart path = this.path; if (path == null || path == PathPart.NULL) { path = PathPart.EMPTY; } else { // If we have a scheme and/or authority, the path must // be absolute. Prepend it with a '/' if necessary. if (hasSchemeOrAuthority()) { path = PathPart.makeAbsolute(path); } } return new HierarchicalUri( scheme, authority, path, query, fragment); } } private boolean hasSchemeOrAuthority() { return scheme != null || (authority != null && authority != Part.NULL); } /** * {@inheritDoc} */ public String toString() { return build().toString(); } } /** * Searches the query string for parameter values with the given key. * * @param key which will be encoded * * @throws UnsupportedOperationException if this isn't a hierarchical URI * @throws NullPointerException if key is null * * @return a list of decoded values */ public String[] getQueryParameters(String key) { if (isOpaque()) { throw new UnsupportedOperationException(NOT_HIERARCHICAL); } String query = getEncodedQuery(); if (query == null) { return new String[0]; } String encodedKey; try { encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException("AssertionError: " + e); } // Prepend query with "&" making the first parameter the same as the // rest. query = "&" + query; // Parameter prefix. String prefix = "&" + encodedKey + "="; Vector values = new Vector(); int start = 0; int length = query.length(); while (start < length) { start = query.indexOf(prefix, start); if (start == -1) { // No more values. break; } // Move start to start of value. start += prefix.length(); // Find end of value. int end = query.indexOf('&', start); if (end == -1) { end = query.length(); } String value = query.substring(start, end); values.addElement(decode(value)); start = end; } int size = values.size(); String[] result = new String[size]; values.copyInto(result); return result; } /** * Searches the query string for the first value with the given key. * * @param key which will be encoded * @throws UnsupportedOperationException if this isn't a hierarchical URI * @throws NullPointerException if key is null * * @return the decoded value or null if no parameter is found */ public String getQueryParameter(String key) { if (isOpaque()) { throw new UnsupportedOperationException(NOT_HIERARCHICAL); } String query = getEncodedQuery(); if (query == null) { return null; } String encodedKey; try { encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException("AssertionError: " + e); } String prefix = encodedKey + "="; if (query.length() < prefix.length()) { return null; } int start; if (query.startsWith(prefix)) { // It's the first parameter. start = prefix.length(); } else { // It must be later in the query string. prefix = "&" + prefix; start = query.indexOf(prefix); if (start == -1) { // Not found. return null; } start += prefix.length(); } // Find end of value. int end = query.indexOf('&', start); if (end == -1) { end = query.length(); } String value = query.substring(start, end); return decode(value); } private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); /** * Encodes characters in the given string as '%'-escaped octets * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes * all other characters. * * @param s string to encode * @return an encoded version of s suitable for use as a URI component, * or null if s is null */ public static String encode(String s) { return encode(s, null); } /** * Encodes characters in the given string as '%'-escaped octets * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes * all other characters with the exception of those specified in the * allow argument. * * @param s string to encode * @param allow set of additional characters to allow in the encoded form, * null if no characters should be skipped * @return an encoded version of s suitable for use as a URI component, * or null if s is null */ public static String encode(String s, String allow) { if (s == null) { return null; } // Lazily-initialized buffers. StringBuffer encoded = null; int oldLength = s.length(); // This loop alternates between copying over allowed characters and // encoding in chunks. This results in fewer method calls and // allocations than encoding one character at a time. int current = 0; while (current < oldLength) { // Start in "copying" mode where we copy over allowed chars. // Find the next character which needs to be encoded. int nextToEncode = current; while (nextToEncode < oldLength && isAllowed(s.charAt(nextToEncode), allow)) { nextToEncode++; } // If there's nothing more to encode... if (nextToEncode == oldLength) { if (current == 0) { // We didn't need to encode anything! return s; } else { // Presumably, we've already done some encoding. encoded.append(s.substring(current, oldLength)); return encoded.toString(); } } if (encoded == null) { encoded = new StringBuffer(); } if (nextToEncode > current) { // Append allowed characters leading up to this point. encoded.append(s.substring(current, nextToEncode)); } else { // assert nextToEncode == current } // Switch to "encoding" mode. // Find the next allowed character. current = nextToEncode; int nextAllowed = current + 1; while (nextAllowed < oldLength && !isAllowed(s.charAt(nextAllowed), allow)) { nextAllowed++; } // Convert the substring to bytes and encode the bytes as // '%'-escaped octets. String toEncode = s.substring(current, nextAllowed); try { byte[] bytes = toEncode.getBytes(DEFAULT_ENCODING); int bytesLength = bytes.length; for (int i = 0; i < bytesLength; i++) { encoded.append('%'); encoded.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]); encoded.append(HEX_DIGITS[bytes[i] & 0xf]); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("AssertionError: " + e); } current = nextAllowed; } // Encoded could still be null at this point if s is empty. return encoded == null ? s : encoded.toString(); } /** * Returns true if the given character is allowed. * * @param c character to check * @param allow characters to allow * @return true if the character is allowed or false if it should be * encoded */ private static boolean isAllowed(char c, String allow) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || "_-!.~'()*".indexOf(c) != NOT_FOUND || (allow != null && allow.indexOf(c) != NOT_FOUND); } /** Unicode replacement character: \\uFFFD. */ private static final byte[] REPLACEMENT = { (byte) 0xFF, (byte) 0xFD }; /** * Decodes '%'-escaped octets in the given string using the UTF-8 scheme. * Replaces invalid octets with the unicode replacement character * ("\\uFFFD"). * * @param s encoded string to decode * @return the given string with escaped octets decoded, or null if * s is null */ public static String decode(String s) { /* Compared to java.net.URLEncoderDecoder.decode(), this method decodes a chunk at a time instead of one character at a time, and it doesn't throw exceptions. It also only allocates memory when necessary--if there's nothing to decode, this method won't do much. */ if (s == null) { return null; } // Lazily-initialized buffers. StringBuffer decoded = null; ByteArrayOutputStream out = null; int oldLength = s.length(); // This loop alternates between copying over normal characters and // escaping in chunks. This results in fewer method calls and // allocations than decoding one character at a time. int current = 0; while (current < oldLength) { // Start in "copying" mode where we copy over normal characters. // Find the next escape sequence. int nextEscape = s.indexOf('%', current); if (nextEscape == NOT_FOUND) { if (decoded == null) { // We didn't actually decode anything. return s; } else { // Append the remainder and return the decoded string. decoded.append(s.substring(current, oldLength)); return decoded.toString(); } } // Prepare buffers. if (decoded == null) { // Looks like we're going to need the buffers... // We know the new string will be shorter. Using the old length // may overshoot a bit, but it will save us from resizing the // buffer. decoded = new StringBuffer(oldLength); out = new ByteArrayOutputStream(4); } else { // Clear decoding buffer. out.reset(); } // Append characters leading up to the escape. if (nextEscape > current) { decoded.append(s.substring(current, nextEscape)); current = nextEscape; } else { // assert current == nextEscape } // Switch to "decoding" mode where we decode a string of escape // sequences. // Decode and append escape sequences. Escape sequences look like // "%ab" where % is literal and a and b are hex digits. try { do { if (current + 2 >= oldLength) { // Truncated escape sequence. out.write(REPLACEMENT); } else { int a = Character.digit(s.charAt(current + 1), 16); int b = Character.digit(s.charAt(current + 2), 16); if (a == -1 || b == -1) { // Non hex digits. out.write(REPLACEMENT); } else { // Combine the hex digits into one byte and write. out.write((a << 4) + b); } } // Move passed the escape sequence. current += 3; } while (current < oldLength && s.charAt(current) == '%'); // Decode UTF-8 bytes into a string and append it. decoded.append(new String(out.toByteArray(), DEFAULT_ENCODING)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("AssertionError: " + e); } catch (IOException e) { throw new RuntimeException("AssertionError: " + e); } } // If we don't have a buffer, we didn't have to decode anything. return decoded == null ? s : decoded.toString(); } /** * Support for part implementations. */ static abstract class AbstractPart { /** * Enum which indicates which representation of a given part we have. */ static class Representation { static final int BOTH = 0; static final int ENCODED = 1; static final int DECODED = 2; } volatile String encoded; volatile String decoded; AbstractPart(String encoded, String decoded) { this.encoded = encoded; this.decoded = decoded; } abstract String getEncoded(); final String getDecoded() { boolean hasDecoded = decoded != NOT_CACHED; return hasDecoded ? decoded : (decoded = decode(encoded)); } } /** * Immutable wrapper of encoded and decoded versions of a URI part. Lazily * creates the encoded or decoded version from the other. */ static class Part extends AbstractPart { /** A part with null values. */ static final Part NULL = new EmptyPart(null); /** A part with empty strings for values. */ static final Part EMPTY = new EmptyPart(""); private Part(String encoded, String decoded) { super(encoded, decoded); } boolean isEmpty() { return false; } String getEncoded() { boolean hasEncoded = encoded != NOT_CACHED; return hasEncoded ? encoded : (encoded = encode(decoded)); } /** * Returns given part or {@link #NULL} if the given part is null. */ static Part nonNull(Part part) { return part == null ? NULL : part; } /** * Creates a part from the encoded string. * * @param encoded part string */ static Part fromEncoded(String encoded) { return from(encoded, NOT_CACHED); } /** * Creates a part from the decoded string. * * @param decoded part string */ static Part fromDecoded(String decoded) { return from(NOT_CACHED, decoded); } /** * Creates a part from the encoded and decoded strings. * * @param encoded part string * @param decoded part string */ static Part from(String encoded, String decoded) { // We have to check both encoded and decoded in case one is // NOT_CACHED. if (encoded == null) { return NULL; } if (encoded.length() == 0) { return EMPTY; } if (decoded == null) { return NULL; } if (decoded .length() == 0) { return EMPTY; } return new Part(encoded, decoded); } private static class EmptyPart extends Part { public EmptyPart(String value) { super(value, value); } /** * {@inheritDoc} */ boolean isEmpty() { return true; } } } /** * Immutable wrapper of encoded and decoded versions of a path part. Lazily * creates the encoded or decoded version from the other. */ static class PathPart extends AbstractPart { /** A part with null values. */ static final PathPart NULL = new PathPart(null, null); /** A part with empty strings for values. */ static final PathPart EMPTY = new PathPart("", ""); private PathPart(String encoded, String decoded) { super(encoded, decoded); } String getEncoded() { boolean hasEncoded = encoded != NOT_CACHED; // Don't encode '/'. return hasEncoded ? encoded : (encoded = encode(decoded, "/")); } /** * Cached path segments. This doesn't need to be volatile--we don't * care if other threads see the result. */ private PathSegments pathSegments; /** * Gets the individual path segments. Parses them if necessary. * * @return parsed path segments or null if this isn't a hierarchical * URI */ PathSegments getPathSegments() { if (pathSegments != null) { return pathSegments; } String path = getEncoded(); if (path == null) { return pathSegments = PathSegments.EMPTY; } PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder(); int previous = 0; int current; while ((current = path.indexOf('/', previous)) > -1) { // This check keeps us from adding a segment if the path starts // '/' and an empty segment for "//". if (previous < current) { String decodedSegment = decode(path.substring(previous, current)); segmentBuilder.add(decodedSegment); } previous = current + 1; } // Add in the final path segment. if (previous < path.length()) { segmentBuilder.add(decode(path.substring(previous))); } return pathSegments = segmentBuilder.build(); } static PathPart appendEncodedSegment(PathPart oldPart, String newSegment) { // If there is no old path, should we make the new path relative // or absolute? I pick absolute. if (oldPart == null) { // No old path. return fromEncoded("/" + newSegment); } String oldPath = oldPart.getEncoded(); if (oldPath == null) { oldPath = ""; } int oldPathLength = oldPath.length(); String newPath; if (oldPathLength == 0) { // No old path. newPath = "/" + newSegment; } else if (oldPath.charAt(oldPathLength - 1) == '/') { newPath = oldPath + newSegment; } else { newPath = oldPath + "/" + newSegment; } return fromEncoded(newPath); } static PathPart appendDecodedSegment(PathPart oldPart, String decoded) { String encoded = encode(decoded); // TODO: Should we reuse old PathSegments? Probably not. return appendEncodedSegment(oldPart, encoded); } /** * Creates a path from the encoded string. * * @param encoded part string */ static PathPart fromEncoded(String encoded) { return from(encoded, NOT_CACHED); } /** * Creates a path from the decoded string. * * @param decoded part string */ static PathPart fromDecoded(String decoded) { return from(NOT_CACHED, decoded); } /** * Creates a path from the encoded and decoded strings. * * @param encoded part string * @param decoded part string */ static PathPart from(String encoded, String decoded) { if (encoded == null) { return NULL; } if (encoded.length() == 0) { return EMPTY; } return new PathPart(encoded, decoded); } /** * Prepends path values with "/" if they're present, not empty, and * they don't already start with "/". */ static PathPart makeAbsolute(PathPart oldPart) { boolean encodedCached = oldPart.encoded != NOT_CACHED; // We don't care which version we use, and we don't want to force // unneccessary encoding/decoding. String oldPath = encodedCached ? oldPart.encoded : oldPart.decoded; if (oldPath == null || oldPath.length() == 0 || oldPath.startsWith("/")) { return oldPart; } // Prepend encoded string if present. String newEncoded = encodedCached ? "/" + oldPart.encoded : NOT_CACHED; // Prepend decoded string if present. boolean decodedCached = oldPart.decoded != NOT_CACHED; String newDecoded = decodedCached ? "/" + oldPart.decoded : NOT_CACHED; return new PathPart(newEncoded, newDecoded); } } /** * Creates a new Uri by appending an already-encoded path segment to a * base Uri. * * @param baseUri Uri to append path segment to * @param pathSegment encoded path segment to append * @return a new Uri based on baseUri with the given segment appended to * the path * @throws NullPointerException if baseUri is null */ public static Uri withAppendedPath(Uri baseUri, String pathSegment) { Builder builder = baseUri.buildUpon(); builder = builder.appendEncodedPath(pathSegment); return builder.build(); } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/Uri.java
Java
asf20
65,026
/*- * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.authenticator.blackberry; import net.rim.device.api.i18n.ResourceBundle; import net.rim.device.api.system.ApplicationDescriptor; import net.rim.device.api.ui.Color; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.FieldChangeListener; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.component.ButtonField; import net.rim.device.api.ui.component.EditField; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.ObjectChoiceField; import net.rim.device.api.ui.container.HorizontalFieldManager; import net.rim.device.api.ui.container.MainScreen; import net.rim.device.api.ui.container.VerticalFieldManager; import com.google.authenticator.blackberry.AccountDb.OtpType; import com.google.authenticator.blackberry.resource.AuthenticatorResource; /** * BlackBerry port of {@code EnterKeyActivity}. */ public class EnterKeyScreen extends MainScreen implements AuthenticatorResource, FieldChangeListener { private static ResourceBundle sResources = ResourceBundle.getBundle( BUNDLE_ID, BUNDLE_NAME); private static final int MIN_KEY_BYTES = 10; private static final boolean INTEGRITY_CHECK_ENABLED = false; private LabelField mDescriptionText; private LabelField mStatusText; private LabelField mVersionText; private EditField mAccountName; private EditField mKeyEntryField; private ObjectChoiceField mType; private ButtonField mClearButton; private ButtonField mSubmitButton; private ButtonField mCancelButton; private int mStatusColor; public EnterKeyScreen() { setTitle(sResources.getString(ENTER_KEY_TITLE)); VerticalFieldManager manager = new VerticalFieldManager(); mDescriptionText = new LabelField(sResources.getString(ENTER_KEY_HELP)); mAccountName = new EditField(EditField.NO_NEWLINE); mAccountName.setLabel(sResources.getString(ENTER_ACCOUNT_LABEL)); mKeyEntryField = new EditField(EditField.NO_NEWLINE); mKeyEntryField.setLabel(sResources.getString(ENTER_KEY_LABEL)); mType = new ObjectChoiceField(sResources.getString(TYPE_PROMPT), OtpType .values()); mStatusText = new LabelField() { protected void paint(Graphics graphics) { int savedColor = graphics.getColor(); graphics.setColor(mStatusColor); super.paint(graphics); graphics.setColor(savedColor); } }; mKeyEntryField.setChangeListener(this); manager.add(mDescriptionText); manager.add(new LabelField()); // Spacer manager.add(mAccountName); manager.add(mKeyEntryField); manager.add(mStatusText); manager.add(mType); HorizontalFieldManager buttons = new HorizontalFieldManager(FIELD_HCENTER); mSubmitButton = new ButtonField(sResources.getString(SUBMIT), ButtonField.CONSUME_CLICK); mClearButton = new ButtonField(sResources.getString(CLEAR), ButtonField.CONSUME_CLICK); mCancelButton = new ButtonField(sResources.getString(CANCEL), ButtonField.CONSUME_CLICK); mSubmitButton.setChangeListener(this); mClearButton.setChangeListener(this); mCancelButton.setChangeListener(this); buttons.add(mSubmitButton); buttons.add(mClearButton); buttons.add(mCancelButton); ApplicationDescriptor applicationDescriptor = ApplicationDescriptor .currentApplicationDescriptor(); String version = applicationDescriptor.getVersion(); mVersionText = new LabelField(version, FIELD_RIGHT | FIELD_BOTTOM); add(manager); add(buttons); add(mVersionText); } /* * Either return a check code or an error message */ private boolean validateKeyAndUpdateStatus(boolean submitting) { String userEnteredKey = mKeyEntryField.getText(); try { byte[] decoded = Base32String.decode(userEnteredKey); if (decoded.length < MIN_KEY_BYTES) { // If the user is trying to submit a key that's too short, then // display a message saying it's too short. mStatusText.setText(submitting ? sResources.getString(ENTER_KEY_VALUE_TOO_SHORT) : ""); mStatusColor = Color.BLACK; return false; } else { if (INTEGRITY_CHECK_ENABLED) { String checkCode = CheckCodeScreen.getCheckCode(mKeyEntryField.getText()); mStatusText.setText(sResources.getString(ENTER_KEY_INTEGRITY_CHECK_VALUE) + checkCode); mStatusColor = Color.GREEN; } else { mStatusText.setText(""); } return true; } } catch (Base32String.DecodingException e) { mStatusText.setText(sResources.getString(ENTER_KEY_INVALID_FORMAT)); mStatusColor = Color.RED; return false; } catch (RuntimeException e) { mStatusText.setText(sResources.getString(ENTER_KEY_UNEXPECTED_PROBLEM)); mStatusColor = Color.RED; return false; } } /** * {@inheritDoc} */ public void fieldChanged(Field field, int context) { if (field == mSubmitButton) { if (validateKeyAndUpdateStatus(true)) { AuthenticatorScreen.saveSecret(mAccountName.getText(), mKeyEntryField .getText(), null, (OtpType) mType.getChoice(mType .getSelectedIndex())); close(); } } else if (field == mClearButton) { mStatusText.setText(""); mAccountName.setText(""); mKeyEntryField.setText(""); } else if (field == mCancelButton) { close(); } else if (field == mKeyEntryField) { validateKeyAndUpdateStatus(false); } } /** * {@inheritDoc} */ protected boolean onSavePrompt() { // Disable prompt when the user hits the back button return false; } }
001coldblade-authenticator
mobile/blackberry/src/com/google/authenticator/blackberry/EnterKeyScreen.java
Java
asf20
6,242
// // main.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool drain]; return retVal; }
001coldblade-authenticator
mobile/ios/main.m
Objective-C
asf20
839
// // OTPTableView.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> @protocol OTPTableViewDelegate @optional - (void)otp_tableViewWillBeginEditing:(UITableView *)tableView; - (void)otp_tableViewDidEndEditing:(UITableView *)tableView; @end // OTPTableViews notify their delegates when editing begins and ends. @interface OTPTableView : UITableView @end
001coldblade-authenticator
mobile/ios/Classes/OTPTableView.h
Objective-C
asf20
936
// // OTPAuthAboutController.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPAuthAboutController.h" #import "UIColor+MobileColors.h" #import "GTMLocalizedString.h" @interface OTPAuthAboutWebViewController : UIViewController <UIWebViewDelegate, UIAlertViewDelegate> { @private NSURL *url_; NSString *label_; UIActivityIndicatorView *spinner_; } - (id)initWithURL:(NSURL *)url accessibilityLabel:(NSString *)label; @end @implementation OTPAuthAboutController - (id)init { return [super initWithNibName:@"OTPAuthAboutController" bundle:nil]; } - (void)viewDidLoad { UITableView *view = (UITableView *)[self view]; [view setAccessibilityLabel:@"LegalOptions"]; [view setBackgroundColor:[UIColor googleBlueBackgroundColor]]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // On an iPad, support both portrait modes and landscape modes. return UIInterfaceOrientationIsLandscape(interfaceOrientation) || UIInterfaceOrientationIsPortrait(interfaceOrientation); } // On a phone/pod, don't support upside-down portrait. return interfaceOrientation == UIInterfaceOrientationPortrait || UIInterfaceOrientationIsLandscape(interfaceOrientation); } #pragma mark - #pragma mark TableView Delegate - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 3; } - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section { NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]; version = [NSString stringWithFormat:@"Version: %@", version]; return version; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"AboutCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (!cell) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease]; [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; } NSString *text = nil; NSString *label = nil; switch([indexPath row]) { case 0: label = @"Terms of Service"; text = GTMLocalizedString(@"Terms of Service", @"Terms of Service Table Item Title"); break; case 1: label = @"Privacy Policy"; text = GTMLocalizedString(@"Privacy Policy", @"Privacy Policy Table Item Title"); break; case 2: label = @"Legal Notices"; text = GTMLocalizedString(@"Legal Notices", @"Legal Notices Table Item Title"); break; default: label = @"Unknown Index"; text = label; break; } [[cell textLabel] setText:text]; [cell setIsAccessibilityElement:YES]; [cell setAccessibilityLabel:label]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSURL *url = nil; NSString *label = nil; switch([indexPath row]) { case 0: { url = [NSURL URLWithString:@"http://m.google.com/tospage"]; label = @"Terms of Service"; break; } case 1: // Privacy appears to do the localization thing correctly. So no hacks // needed (contrast to case 0 above. url = [NSURL URLWithString:@"http://www.google.com/mobile/privacy.html"]; label = @"Privacy Policy"; break; case 2: { NSBundle *bundle = [NSBundle mainBundle]; NSString *legalNotices = [bundle pathForResource:@"LegalNotices" ofType:@"html"]; url = [NSURL fileURLWithPath:legalNotices]; label = @"Legal Notices"; } break; default: break; } if (url) { OTPAuthAboutWebViewController *controller = [[[OTPAuthAboutWebViewController alloc] initWithURL:url accessibilityLabel:label] autorelease]; [[self navigationController] pushViewController:controller animated:YES]; } } @end @implementation OTPAuthAboutWebViewController - (id)initWithURL:(NSURL *)url accessibilityLabel:(NSString *)label { if ((self = [super initWithNibName:nil bundle:nil])) { url_ = [url retain]; label_ = [label copy]; } return self; } - (void)dealloc { [url_ release]; [label_ release]; [super dealloc]; } - (void)loadView { UIWebView *webView = [[[UIWebView alloc] initWithFrame:CGRectZero] autorelease]; [webView setScalesPageToFit:YES]; [webView setDelegate:self]; [webView setAccessibilityLabel:label_]; NSURLRequest *request = [NSURLRequest requestWithURL:url_]; [webView loadRequest:request]; [self setView:webView]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // On an iPad, support both portrait modes and landscape modes. return UIInterfaceOrientationIsLandscape(interfaceOrientation) || UIInterfaceOrientationIsPortrait(interfaceOrientation); } // On a phone/pod, don't support upside-down portrait. return interfaceOrientation == UIInterfaceOrientationPortrait || UIInterfaceOrientationIsLandscape(interfaceOrientation); } #pragma mark - #pragma mark UIWebViewDelegate - (void)webViewDidStartLoad:(UIWebView *)webView { spinner_ = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; CGRect bounds = webView.bounds; CGPoint middle = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)); [spinner_ setCenter:middle]; [webView addSubview:spinner_]; [spinner_ startAnimating]; } - (void)stopSpinner { [spinner_ stopAnimating]; [spinner_ removeFromSuperview]; [spinner_ release]; spinner_ = nil; } - (void)webViewDidFinishLoad:(UIWebView *)webView { [self stopSpinner]; } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { [self stopSpinner]; NSString *errString = GTMLocalizedString(@"Unable to load webpage.", @"Notification that a web page cannot be loaded"); UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:errString message:[error localizedDescription] delegate:nil cancelButtonTitle:GTMLocalizedString(@"OK", @"OK button") otherButtonTitles:nil] autorelease]; [alert setDelegate:self]; [alert show]; } #pragma mark - #pragma mark UIAlertViewDelegate - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { [[self navigationController] popViewControllerAnimated:YES]; } @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthAboutController.m
Objective-C
asf20
7,712
// // RootViewController.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> @class OTPAuthBarClock; @interface RootViewController : UITableViewController @property(nonatomic, readwrite, assign) id<UITableViewDataSource, UITableViewDelegate> delegate; @property(nonatomic, readonly, retain) OTPAuthBarClock *clock; @property(nonatomic, readwrite, retain) IBOutlet UIBarButtonItem *addItem; @property(nonatomic, readwrite, retain) IBOutlet UIBarButtonItem *legalItem; @end
001coldblade-authenticator
mobile/ios/Classes/RootViewController.h
Objective-C
asf20
1,054
// // UIColor+MobileColors.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // // This header defines shared colors for all native iPhone Google // apps. #import <UIKit/UIKit.h> @interface UIColor (GMOMobileColors) + (UIColor *)googleBlueBarColor; + (UIColor *)googleBlueBackgroundColor; + (UIColor *)googleTableViewSeparatorColor; + (UIColor *)googleReadItemBackgroundColor; + (UIColor *)googleBlueTextColor; + (UIColor *)googleGreenURLTextColor; + (UIColor *)googleAdYellowBackgroundColor; @end // Returns a gradient that mimics a navigation bar tinted with // googleBlueBarColor. Client responsible for releasing. CGGradientRef GoogleCreateBlueBarGradient();
001coldblade-authenticator
mobile/ios/Classes/UIColor+MobileColors.h
Objective-C
asf20
1,219
// // OTPAuthApplication.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPAuthApplication.h" #import "OTPAuthAppDelegate.h" @implementation OTPAuthApplication #pragma mark - #pragma mark Actions - (IBAction)addAuthURL:(id)sender { [(OTPAuthAppDelegate *)[self delegate] addAuthURL:sender]; } @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthApplication.m
Objective-C
asf20
872
// // UIColor+MobileColors.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "UIColor+MobileColors.h" @implementation UIColor (GMOMobileColors) // Colors derived from the Cirrus UI spec: // https://sites.google.com/a/google.com/guig/mobilewebapps/cirrus-visual-style + (UIColor *)googleBlueBarColor { return [UIColor colorWithRed:(float)0x5C/0xFF green:(float)0x7D/0xFF blue:(float)0xD2/0xFF alpha:1.0]; } + (UIColor *)googleBlueBackgroundColor { return [UIColor colorWithRed:(float)0xEB/0xFF green:(float)0xEF/0xFF blue:(float)0xF9/0xFF alpha:1.0]; } + (UIColor *)googleReadItemBackgroundColor { return [UIColor colorWithRed:(float)0xF3/0xFF green:(float)0xF5/0xFF blue:(float)0xFC/0xFF alpha:1.0]; } + (UIColor *)googleTableViewSeparatorColor { return [UIColor colorWithWhite:0.95 alpha:1.0]; } + (UIColor *)googleBlueTextColor { return [UIColor colorWithRed:(float)0x33/0xFF green:(float)0x55/0xFF blue:(float)0x99/0xFF alpha:1.0]; } + (UIColor *)googleGreenURLTextColor { return [UIColor colorWithRed:(float)0x7F/0xFF green:(float)0xA8/0xFF blue:(float)0x7F/0xFF alpha:1.0]; } + (UIColor *)googleAdYellowBackgroundColor { return [UIColor colorWithRed:1.0 // 255 green:0.9725 // 248 blue:0.8667 // 221 alpha:1.0]; } @end CGGradientRef GoogleCreateBlueBarGradient(void) { CGGradientRef gradient = NULL; CGColorSpaceRef deviceRGB = CGColorSpaceCreateDeviceRGB(); if (!deviceRGB) goto noDeviceRGB; CGFloat color1Comp[] = { (CGFloat)0x98 / (CGFloat)0xFF, (CGFloat)0xAC / (CGFloat)0xFF, (CGFloat)0xE2 / (CGFloat)0xFF, 1.0}; CGFloat color2Comp[] = { (CGFloat)0x67 / (CGFloat)0xFF, (CGFloat)0x86 / (CGFloat)0xFF, (CGFloat)0xD5 / (CGFloat)0xFF, 1.0 }; CGFloat color3Comp[] = { (CGFloat)0x5C / (CGFloat)0xFF, (CGFloat)0x7D / (CGFloat)0xFF, (CGFloat)0xD2 / (CGFloat)0xFF, 1.0 }; CGFloat color4Comp[] = { (CGFloat)0x4A / (CGFloat)0xFF, (CGFloat)0x6A / (CGFloat)0xFF, (CGFloat)0xCB / (CGFloat)0xFF, 1.0 }; CGColorRef color1 = CGColorCreate(deviceRGB, color1Comp); if (!color1) goto noColor1; CGColorRef color2 = CGColorCreate(deviceRGB, color2Comp); if (!color2) goto noColor2; CGColorRef color3 = CGColorCreate(deviceRGB, color3Comp); if (!color3) goto noColor3; CGColorRef color4 = CGColorCreate(deviceRGB, color4Comp); if (!color4) goto noColor4; CGColorRef colors[] = { color1, color2, color3, color4 }; CGFloat locations[] = {0, 0.5, 0.5, 1.0}; CFArrayRef array = CFArrayCreate(NULL, (const void **)colors, sizeof(colors) / sizeof(colors[0]), &kCFTypeArrayCallBacks); if (!array) goto noArray; gradient = CGGradientCreateWithColors(deviceRGB, array, locations); CFRelease(array); noArray: CFRelease(color4); noColor4: CFRelease(color3); noColor3: CFRelease(color2); noColor2: CFRelease(color1); noColor1: CFRelease(deviceRGB); noDeviceRGB: return gradient; }
001coldblade-authenticator
mobile/ios/Classes/UIColor+MobileColors.m
Objective-C
asf20
4,313
// // RootViewController.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "RootViewController.h" #import "OTPAuthURL.h" #import "HOTPGenerator.h" #import "OTPTableViewCell.h" #import "UIColor+MobileColors.h" #import "OTPAuthBarClock.h" #import "TOTPGenerator.h" #import "GTMLocalizedString.h" @interface RootViewController () @property(nonatomic, readwrite, retain) OTPAuthBarClock *clock; - (void)showCopyMenu:(UIGestureRecognizer *)recognizer; @end @implementation RootViewController @synthesize delegate = delegate_; @synthesize clock = clock_; @synthesize addItem = addItem_; @synthesize legalItem = legalItem_; - (void)dealloc { [self.clock invalidate]; self.clock = nil; self.delegate = nil; self.addItem = nil; self.legalItem = nil; [super dealloc]; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // On an iPad, support both portrait modes and landscape modes. return UIInterfaceOrientationIsLandscape(interfaceOrientation) || UIInterfaceOrientationIsPortrait(interfaceOrientation); } // On a phone/pod, don't support upside-down portrait. return interfaceOrientation == UIInterfaceOrientationPortrait || UIInterfaceOrientationIsLandscape(interfaceOrientation); } - (void)viewDidLoad { UITableView *view = (UITableView *)self.view; view.dataSource = self.delegate; view.delegate = self.delegate; view.backgroundColor = [UIColor googleBlueBackgroundColor]; UIButton *titleButton = [[[UIButton alloc] init] autorelease]; [titleButton setImage:[UIImage imageNamed:@"GoogleNavBarLogo.png"] forState:UIControlStateNormal]; [titleButton setTitle:GTMLocalizedString(@"Authenticator", nil) forState:UIControlStateNormal]; UILabel *titleLabel = [titleButton titleLabel]; titleLabel.font = [UIFont boldSystemFontOfSize:20.0]; titleLabel.shadowOffset = CGSizeMake(0.0, -1.0); [titleButton setTitleShadowColor:[UIColor colorWithWhite:0.0 alpha:0.5] forState:UIControlStateNormal]; titleButton.adjustsImageWhenHighlighted = NO; [titleButton sizeToFit]; UINavigationItem *navigationItem = self.navigationItem; navigationItem.titleView = titleButton; self.clock = [[[OTPAuthBarClock alloc] initWithFrame:CGRectMake(0,0,30,30) period:[TOTPGenerator defaultPeriod]] autorelease]; UIBarButtonItem *clockItem = [[[UIBarButtonItem alloc] initWithCustomView:clock_] autorelease]; [navigationItem setLeftBarButtonItem:clockItem animated:NO]; self.navigationController.toolbar.tintColor = [UIColor googleBlueBarColor]; // UIGestureRecognizers are actually in the iOS 3.1.3 SDK, but are not // publicly exposed (and have slightly different method names). // Check to see it the "public" version is available, otherwise don't use it // at all. numberOfTapsRequired does not exist in 3.1.3. if ([UITapGestureRecognizer instancesRespondToSelector:@selector(numberOfTapsRequired)]) { UILongPressGestureRecognizer *gesture = [[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showCopyMenu:)] autorelease]; [view addGestureRecognizer:gesture]; UITapGestureRecognizer *doubleTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showCopyMenu:)] autorelease]; doubleTap.numberOfTapsRequired = 2; [view addGestureRecognizer:doubleTap]; } } - (void)setEditing:(BOOL)editing animated:(BOOL)animated { [super setEditing:editing animated:animated]; self.addItem.enabled = !editing; self.legalItem.enabled = !editing; } - (void)showCopyMenu:(UIGestureRecognizer *)recognizer { BOOL isLongPress = [recognizer isKindOfClass:[UILongPressGestureRecognizer class]]; if ((isLongPress && recognizer.state == UIGestureRecognizerStateBegan) || (!isLongPress && recognizer.state == UIGestureRecognizerStateRecognized)) { CGPoint location = [recognizer locationInView:self.view]; UITableView *view = (UITableView*)self.view; NSIndexPath *indexPath = [view indexPathForRowAtPoint:location]; UITableViewCell* cell = [view cellForRowAtIndexPath:indexPath]; if ([cell respondsToSelector:@selector(showCopyMenu:)]) { location = [view convertPoint:location toView:cell]; [(OTPTableViewCell*)cell showCopyMenu:location]; } } } @end
001coldblade-authenticator
mobile/ios/Classes/RootViewController.m
Objective-C
asf20
5,147
// // OTPAuthURLTest.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "GTMSenTestCase.h" #import "GTMStringEncoding.h" #import "GTMNSDictionary+URLArguments.h" #import "GTMNSString+URLArguments.h" #import "HOTPGenerator.h" #import "OTPAuthURL.h" #import "TOTPGenerator.h" @interface OTPAuthURL () @property(readonly,retain,nonatomic) id generator; + (OTPAuthURL *)authURLWithKeychainDictionary:(NSDictionary *)dict; - (id)initWithOTPGenerator:(id)generator name:(NSString *)name; @end static NSString *const kOTPAuthScheme = @"otpauth"; // These are keys in the otpauth:// query string. static NSString *const kQueryAlgorithmKey = @"algorithm"; static NSString *const kQuerySecretKey = @"secret"; static NSString *const kQueryCounterKey = @"counter"; static NSString *const kQueryDigitsKey = @"digits"; static NSString *const kQueryPeriodKey = @"period"; static NSString *const kValidType = @"totp"; static NSString *const kValidLabel = @"Léon"; static NSString *const kValidAlgorithm = @"SHA256"; static const unsigned char kValidSecret[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; static NSString *const kValidBase32Secret = @"AAAQEAYEAUDAOCAJBIFQYDIOB4"; static const unsigned long long kValidCounter = 18446744073709551615ULL; static NSString *const kValidCounterString = @"18446744073709551615"; static const NSUInteger kValidDigits = 8; static NSString *const kValidDigitsString = @"8"; static const NSTimeInterval kValidPeriod = 45; static NSString *const kValidPeriodString = @"45"; static NSString *const kValidTOTPURLWithoutSecret = @"otpauth://totp/L%C3%A9on?algorithm=SHA256&digits=8&period=45"; static NSString *const kValidTOTPURL = @"otpauth://totp/L%C3%A9on?algorithm=SHA256&digits=8&period=45" @"&secret=AAAQEAYEAUDAOCAJBIFQYDIOB4"; static NSString *const kValidHOTPURL = @"otpauth://hotp/L%C3%A9on?algorithm=SHA256&digits=8" @"&counter=18446744073709551615" @"&secret=AAAQEAYEAUDAOCAJBIFQYDIOB4"; @interface OTPAuthURLTest : GTMTestCase - (void)testInitWithKeychainDictionary; - (void)testInitWithTOTPURL; - (void)testInitWithHOTPURL; - (void)testInitWithInvalidURLS; - (void)testInitWithOTPGeneratorLabel; - (void)testURL; @end @implementation OTPAuthURLTest - (void)testInitWithKeychainDictionary { NSData *secret = [NSData dataWithBytes:kValidSecret length:sizeof(kValidSecret)]; NSData *urlData = [kValidTOTPURLWithoutSecret dataUsingEncoding:NSUTF8StringEncoding]; OTPAuthURL *url = [OTPAuthURL authURLWithKeychainDictionary: [NSDictionary dictionaryWithObjectsAndKeys: urlData, (id)kSecAttrGeneric, secret, (id)kSecValueData, nil]]; STAssertEqualObjects([url name], kValidLabel, @"Léon"); TOTPGenerator *generator = [url generator]; STAssertEqualObjects([generator secret], secret, @""); STAssertEqualObjects([generator algorithm], kValidAlgorithm, @""); STAssertEquals([generator period], kValidPeriod, @""); STAssertEquals([generator digits], kValidDigits, @""); STAssertFalse([url isInKeychain], @""); } - (void)testInitWithTOTPURL { NSData *secret = [NSData dataWithBytes:kValidSecret length:sizeof(kValidSecret)]; OTPAuthURL *url = [OTPAuthURL authURLWithURL:[NSURL URLWithString:kValidTOTPURL] secret:nil]; STAssertEqualObjects([url name], kValidLabel, @"Léon"); TOTPGenerator *generator = [url generator]; STAssertEqualObjects([generator secret], secret, @""); STAssertEqualObjects([generator algorithm], kValidAlgorithm, @""); STAssertEquals([generator period], kValidPeriod, @""); STAssertEquals([generator digits], kValidDigits, @""); } - (void)testInitWithHOTPURL { NSData *secret = [NSData dataWithBytes:kValidSecret length:sizeof(kValidSecret)]; OTPAuthURL *url = [OTPAuthURL authURLWithURL:[NSURL URLWithString:kValidHOTPURL] secret:nil]; STAssertEqualObjects([url name], kValidLabel, @"Léon"); HOTPGenerator *generator = [url generator]; STAssertEqualObjects([generator secret], secret, @""); STAssertEqualObjects([generator algorithm], kValidAlgorithm, @""); STAssertEquals([generator counter], kValidCounter, @""); STAssertEquals([generator digits], kValidDigits, @""); } - (void)testInitWithInvalidURLS { NSArray *badUrls = [NSArray arrayWithObjects: // invalid scheme @"http://foo", // invalid type @"otpauth://foo", // missing secret @"otpauth://totp/bar", // invalid period @"otpauth://totp/bar?secret=AAAQEAYEAUDAOCAJBIFQYDIOB4&period=0", // missing counter @"otpauth://hotp/bar?secret=AAAQEAYEAUDAOCAJBIFQYDIOB4", // invalid algorithm @"otpauth://totp/bar?secret=AAAQEAYEAUDAOCAJBIFQYDIOB4&algorithm=RC4", // invalid digits @"otpauth://totp/bar?secret=AAAQEAYEAUDAOCAJBIFQYDIOB4&digits=2", nil]; for (NSString *badUrl in badUrls) { OTPAuthURL *url = [OTPAuthURL authURLWithURL:[NSURL URLWithString:badUrl] secret:nil]; STAssertNil(url, @"invalid url (%@) generated %@", badUrl, url); } } - (void)testInitWithOTPGeneratorLabel { TOTPGenerator *generator = [[[TOTPGenerator alloc] initWithSecret:[NSData data] algorithm:[OTPGenerator defaultAlgorithm] digits:[OTPGenerator defaultDigits]] autorelease]; OTPAuthURL *url = [[[OTPAuthURL alloc] initWithOTPGenerator:generator name:kValidLabel] autorelease]; STAssertEquals([url generator], generator, @""); STAssertEqualObjects([url name], kValidLabel, @""); STAssertFalse([url isInKeychain], @""); } - (void)testURL { OTPAuthURL *url = [OTPAuthURL authURLWithURL:[NSURL URLWithString:kValidTOTPURL] secret:nil]; STAssertEqualObjects([[url url] scheme], kOTPAuthScheme, @""); STAssertEqualObjects([[url url] host], kValidType, @""); STAssertEqualObjects([[[url url] path] substringFromIndex:1], kValidLabel, @""); NSDictionary *result = [NSDictionary dictionaryWithObjectsAndKeys: kValidAlgorithm, kQueryAlgorithmKey, kValidDigitsString, kQueryDigitsKey, kValidPeriodString, kQueryPeriodKey, nil]; STAssertEqualObjects([NSDictionary gtm_dictionaryWithHttpArgumentsString: [[url url] query]], result, @""); OTPAuthURL *url2 = [OTPAuthURL authURLWithURL:[NSURL URLWithString:kValidHOTPURL] secret:nil]; NSDictionary *resultForHOTP = [NSDictionary dictionaryWithObjectsAndKeys: kValidAlgorithm, kQueryAlgorithmKey, kValidDigitsString, kQueryDigitsKey, kValidCounterString, kQueryCounterKey, nil]; STAssertEqualObjects([NSDictionary gtm_dictionaryWithHttpArgumentsString: [[url2 url] query]], resultForHOTP, @""); } - (void)testDuplicateURLs { NSURL *url = [NSURL URLWithString:kValidTOTPURL]; OTPAuthURL *authURL1 = [OTPAuthURL authURLWithURL:url secret:nil]; OTPAuthURL *authURL2 = [OTPAuthURL authURLWithURL:url secret:nil]; STAssertTrue([authURL1 saveToKeychain], nil); STAssertTrue([authURL2 saveToKeychain], nil); STAssertTrue([authURL1 removeFromKeychain], @"Your keychain may now have an invalid entry %@", authURL1); STAssertTrue([authURL2 removeFromKeychain], @"Your keychain may now have an invalid entry %@", authURL2); } @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthURLTest.m
Objective-C
asf20
8,408
// // TOTPGenerator.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Foundation/Foundation.h> #import "OTPGenerator.h" // The TOTPGenerator class generates a one-time password (OTP) using // the Time-based One-time Password Algorithm described in: // http://tools.ietf.org/html/draft-mraihi-totp-timebased // // Basically, we define TOTP as TOTP = HOTP(K, T) where T is an integer // and represents the number of time steps between the initial counter // time T0 and the current Unix time (i.e. the number of seconds elapsed // since midnight UTC of January 1, 1970). // // More specifically T = (Current Unix time - T0) / X where: // // - X represents the time step in seconds (default value X = 30 // seconds) and is a system parameter; // // - T0 is the Unix time to start counting time steps (default value is // 0, Unix epoch) and is also a system parameter. // @interface TOTPGenerator : OTPGenerator // The period to use when calculating the counter. @property(assign, nonatomic, readonly) NSTimeInterval period; + (NSTimeInterval)defaultPeriod; // Designated initializer. - (id)initWithSecret:(NSData *)secret algorithm:(NSString *)algorithm digits:(NSUInteger)digits period:(NSTimeInterval)period; // Instance method to generate an OTP using the |algorithm|, |secret|, // |digits|, |period| and |now| values configured on the object. // The return value is an NSString of |digits| length, with leading // zero-padding as required. - (NSString *)generateOTPForDate:(NSDate *)date; @end
001coldblade-authenticator
mobile/ios/Classes/TOTPGenerator.h
Objective-C
asf20
2,109
// // OTPAuthBarClock.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPAuthBarClock.h" #import "GTMDefines.h" #import "UIColor+MobileColors.h" @interface OTPAuthBarClock () @property (nonatomic, retain, readwrite) NSTimer *timer; @property (nonatomic, assign, readwrite) NSTimeInterval period; - (void)startUpTimer; @end @implementation OTPAuthBarClock @synthesize timer = timer_; @synthesize period = period_; - (id)initWithFrame:(CGRect)frame period:(NSTimeInterval)period { if ((self = [super initWithFrame:frame])) { [self startUpTimer]; self.opaque = NO; self.period = period; UIApplication *app = [UIApplication sharedApplication]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:app]; [nc addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app]; } return self; } - (void)dealloc { _GTMDevAssert(!self.timer, @"Need to call invalidate on clock!"); [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; } - (void)redrawTimer:(NSTimer *)timer { [self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970]; CGFloat mod = fmod(seconds, self.period); CGFloat percent = mod / self.period; CGContextRef context = UIGraphicsGetCurrentContext(); CGRect bounds = self.bounds; [[UIColor clearColor] setFill]; CGContextFillRect(context, rect); CGFloat midX = CGRectGetMidX(bounds); CGFloat midY = CGRectGetMidY(bounds); CGFloat radius = midY - 4; CGContextMoveToPoint(context, midX, midY); CGFloat start = -M_PI_2; CGFloat end = 2 * M_PI; CGFloat sweep = end * percent + start; CGContextAddArc(context, midX, midY, radius, start, sweep, 1); [[[UIColor googleBlueBackgroundColor] colorWithAlphaComponent:0.7] setFill]; CGContextFillPath(context); if (percent > .875) { CGContextMoveToPoint(context, midX, midY); CGContextAddArc(context, midX, midY, radius, start, sweep, 1); CGFloat alpha = (percent - .875) / .125; [[[UIColor redColor] colorWithAlphaComponent:alpha * 0.5] setFill]; CGContextFillPath(context); } // Draw top shadow CGFloat offset = 0.25; CGFloat x = midX + (radius - offset) * cos(0 - M_PI_4); CGFloat y = midY + (radius - offset) * sin(0 - M_PI_4); [[UIColor blackColor] setStroke]; CGContextMoveToPoint(context, x , y); CGContextAddArc(context, midX, midY, radius - offset, 0 - M_PI_4, 5.0 * M_PI_4, 1); CGContextStrokePath(context); // Draw bottom highlight x = midX + (radius + offset) * cos(0 + M_PI_4); y = midY + (radius + offset) * sin(0 + M_PI_4); [[UIColor whiteColor] setStroke]; CGContextMoveToPoint(context, x , y); CGContextAddArc(context, midX, midY, radius + offset, 0 + M_PI_4, 3.0 * M_PI_4, 0); CGContextStrokePath(context); // Draw face [[UIColor googleBlueTextColor] setStroke]; CGContextMoveToPoint(context, midX + radius , midY); CGContextAddArc(context, midX, midY, radius, 0, 2.0 * M_PI, 1); CGContextStrokePath(context); if (percent > .875) { CGFloat alpha = (percent - .875) / .125; [[[UIColor redColor] colorWithAlphaComponent:alpha] setStroke]; CGContextStrokePath(context); } // Hand x = midX + radius * cos(sweep); y = midY + radius * sin(sweep); CGContextMoveToPoint(context, midX, midY); CGContextAddLineToPoint(context, x, y); CGContextStrokePath(context); } - (void)invalidate { [self.timer invalidate]; self.timer = nil; } - (void)startUpTimer { self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(redrawTimer:) userInfo:nil repeats:YES]; } - (void)applicationDidBecomeActive:(UIApplication *)application { [self startUpTimer]; [self redrawTimer:nil]; } - (void)applicationWillResignActive:(UIApplication *)application { [self invalidate]; } @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthBarClock.m
Objective-C
asf20
4,887
// // OTPScannerOverlayView.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> @interface OTPScannerOverlayView : UIView @end
001coldblade-authenticator
mobile/ios/Classes/OTPScannerOverlayView.h
Objective-C
asf20
707
// // OTPAuthURL.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <Foundation/Foundation.h> @class OTPGenerator; // This class encapsulates the parsing of otpauth:// urls, the creation of // either HOTPGenerator or TOTPGenerator objects, and the persistence of the // objects state to the iPhone keychain in a secure fashion. // // The secret key is stored as the "password" in the keychain item, and the // re-constructed URL is stored in an attribute. @interface OTPAuthURL : NSObject // |name| is an arbitrary UTF8 text string extracted from the url path. @property(readwrite, copy, nonatomic) NSString *name; @property(readonly, nonatomic) NSString *otpCode; @property(readonly, nonatomic) NSString *checkCode; @property(readonly, retain, nonatomic) NSData *keychainItemRef; // Standard base32 alphabet. // Input is case insensitive. // No padding is used. // Ignore space and hyphen (-). // For details on use, see android app: // http://google3/security/strongauth/mobile/android/StrongAuth/src/org/strongauth/Base32String.java + (NSData *)base32Decode:(NSString *)string; + (NSString *)encodeBase32:(NSData *)data; + (OTPAuthURL *)authURLWithURL:(NSURL *)url secret:(NSData *)secret; + (OTPAuthURL *)authURLWithKeychainItemRef:(NSData *)keychainItemRef; // Returns a reconstructed NSURL object representing the current state of the // |generator|. - (NSURL *)url; // Saves the current object state to the keychain. - (BOOL)saveToKeychain; // Removes the current object state from the keychain. - (BOOL)removeFromKeychain; // Returns true if the object was loaded from or subsequently added to the // iPhone keychain. // It does not assert that the keychain is up to date with the latest // |generator| state. - (BOOL)isInKeychain; - (NSString*)checkCode; @end @interface TOTPAuthURL : OTPAuthURL { @private NSTimeInterval generationAdvanceWarning_; NSTimeInterval lastProgress_; BOOL warningSent_; } @property(readwrite, assign, nonatomic) NSTimeInterval generationAdvanceWarning; - (id)initWithSecret:(NSData *)secret name:(NSString *)name; @end @interface HOTPAuthURL : OTPAuthURL { @private NSString *otpCode_; } - (id)initWithSecret:(NSData *)secret name:(NSString *)name; - (void)generateNextOTPCode; @end // Notification sent out |otpGenerationAdvanceWarning_| before a new OTP is // generated. Only applies to TOTP Generators. Has a // |OTPAuthURLSecondsBeforeNewOTPKey| key which is a NSNumber with the // number of seconds remaining before the new OTP is generated. extern NSString *const OTPAuthURLWillGenerateNewOTPWarningNotification; extern NSString *const OTPAuthURLSecondsBeforeNewOTPKey; extern NSString *const OTPAuthURLDidGenerateNewOTPNotification;
001coldblade-authenticator
mobile/ios/Classes/OTPAuthURL.h
Objective-C
asf20
3,292
// // OTPScannerOverlayView.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPScannerOverlayView.h" @implementation OTPScannerOverlayView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.opaque = NO; self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; } return self; } - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGRect bounds = self.bounds; CGFloat rectHeight = 200; CGFloat oneSixthRectHeight = rectHeight * 0.165; CGFloat midX = CGRectGetMidX(bounds); CGFloat midY = CGRectGetMidY(bounds); CGFloat minY = CGRectGetMinY(bounds); CGFloat minX = CGRectGetMinX(bounds); CGFloat maxY = CGRectGetMaxY(bounds); CGFloat maxX = CGRectGetMaxX(bounds); // Blackout boxes CGRect scanRect = CGRectMake(midX - rectHeight * .5, midY - rectHeight * .5, rectHeight, rectHeight); CGRect leftRect = CGRectMake(minX, minY, CGRectGetMinX(scanRect), maxY); CGRect rightRect = CGRectMake(CGRectGetMaxX(scanRect), minY, maxX - CGRectGetMaxX(scanRect), maxY); CGRect bottomRect = CGRectMake(minX, minY, maxX, CGRectGetMinY(scanRect)); CGRect topRect = CGRectMake(CGRectGetMinX(scanRect), CGRectGetMaxY(scanRect), maxX, maxY - CGRectGetMaxY(scanRect)); CGContextBeginPath(context); CGContextAddRect(context, leftRect); CGContextAddRect(context, rightRect); CGContextAddRect(context, bottomRect); CGContextAddRect(context, topRect); [[[UIColor blackColor] colorWithAlphaComponent:0.3] set]; CGContextFillPath(context); // Frame Box [[UIColor greenColor] set]; midX = CGRectGetMidX(scanRect); midY = CGRectGetMidY(scanRect); minY = CGRectGetMinY(scanRect); minX = CGRectGetMinX(scanRect); maxY = CGRectGetMaxY(scanRect); maxX = CGRectGetMaxX(scanRect); CGContextSetLineWidth(context, 2); CGContextMoveToPoint(context, midX - oneSixthRectHeight, minY); CGContextAddLineToPoint(context, minX, minY); CGContextAddLineToPoint(context, minX, midY - oneSixthRectHeight); CGContextStrokePath(context); CGContextMoveToPoint(context, minX, midY + oneSixthRectHeight); CGContextAddLineToPoint(context, minX, maxY); CGContextAddLineToPoint(context, midX - oneSixthRectHeight, maxY); CGContextStrokePath(context); CGContextMoveToPoint(context, midX + oneSixthRectHeight, maxY); CGContextAddLineToPoint(context, maxX, maxY); CGContextAddLineToPoint(context, maxX, midY + oneSixthRectHeight); CGContextStrokePath(context); CGContextMoveToPoint(context, maxX, midY - oneSixthRectHeight); CGContextAddLineToPoint(context, maxX, minY); CGContextAddLineToPoint(context, midX + oneSixthRectHeight, minY); CGContextStrokePath(context); // Cross hairs CGContextSetLineWidth(context, 1); CGContextMoveToPoint(context, midX, minY - oneSixthRectHeight); CGContextAddLineToPoint(context, midX, minY + oneSixthRectHeight); CGContextStrokePath(context); CGContextMoveToPoint(context, midX, maxY - oneSixthRectHeight); CGContextAddLineToPoint(context, midX, maxY + oneSixthRectHeight); CGContextStrokePath(context); CGContextMoveToPoint(context, minX - oneSixthRectHeight, midY); CGContextAddLineToPoint(context, minX + oneSixthRectHeight, midY); CGContextStrokePath(context); CGContextMoveToPoint(context, maxX - oneSixthRectHeight, midY); CGContextAddLineToPoint(context, maxX + oneSixthRectHeight, midY); CGContextStrokePath(context); } @end
001coldblade-authenticator
mobile/ios/Classes/OTPScannerOverlayView.m
Objective-C
asf20
4,248
// // OTPAuthURLEntryController.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import "DecoderDelegate.h" @class OTPAuthURL; @class Decoder; @protocol OTPAuthURLEntryControllerDelegate; @interface OTPAuthURLEntryController : UIViewController <UITextFieldDelegate, UINavigationControllerDelegate, DecoderDelegate, UIAlertViewDelegate, AVCaptureVideoDataOutputSampleBufferDelegate> { @private dispatch_queue_t queue_; } @property(nonatomic, readwrite, assign) id<OTPAuthURLEntryControllerDelegate> delegate; @property(nonatomic, readwrite, retain) IBOutlet UITextField *accountName; @property(nonatomic, readwrite, retain) IBOutlet UITextField *accountKey; @property(nonatomic, readwrite, retain) IBOutlet UILabel *accountNameLabel; @property(nonatomic, readwrite, retain) IBOutlet UILabel *accountKeyLabel; @property(nonatomic, readwrite, retain) IBOutlet UISegmentedControl *accountType; @property(nonatomic, readwrite, retain) IBOutlet UIButton *scanBarcodeButton; @property(nonatomic, readwrite, retain) IBOutlet UIScrollView *scrollView; - (IBAction)accountNameDidEndOnExit:(id)sender; - (IBAction)accountKeyDidEndOnExit:(id)sender; - (IBAction)cancel:(id)sender; - (IBAction)done:(id)sender; - (IBAction)scanBarcode:(id)sender; @end @protocol OTPAuthURLEntryControllerDelegate - (void)authURLEntryController:(OTPAuthURLEntryController*)controller didCreateAuthURL:(OTPAuthURL *)authURL; @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthURLEntryController.h
Objective-C
asf20
2,068
// // OTPAuthAboutController.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> // The about screen accessed through the settings button. @interface OTPAuthAboutController : UITableViewController @end
001coldblade-authenticator
mobile/ios/Classes/OTPAuthAboutController.h
Objective-C
asf20
781
// // OTPTableViewCell.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "OTPTableViewCell.h" #import "HOTPGenerator.h" #import "OTPAuthURL.h" #import "UIColor+MobileColors.h" #import "GTMLocalizedString.h" #import "GTMRoundedRectPath.h" #import "GTMSystemVersion.h" @interface OTPTableViewCell () @property (readwrite, retain, nonatomic) OTPAuthURL *authURL; @property (readwrite, assign, nonatomic) BOOL showingInfo; @property (readonly, nonatomic) BOOL shouldHideInfoButton; - (void)updateUIForAuthURL:(OTPAuthURL *)authURL; @end @interface HOTPTableViewCell () - (void)otpAuthURLDidGenerateNewOTP:(NSNotification *)notification; @end @interface TOTPTableViewCell () - (void)otpAuthURLWillGenerateNewOTP:(NSNotification *)notification; - (void)otpAuthURLDidGenerateNewOTP:(NSNotification *)notification; @end @implementation OTPTableViewCell @synthesize frontCodeLabel = frontCodeLabel_; @synthesize frontWarningLabel = frontWarningLabel_; @synthesize backCheckLabel = backCheckLabel_; @synthesize backIntegrityCheckLabel = backIntegrityCheckLabel_; @synthesize frontNameTextField = frontNameTextField_; @synthesize frontRefreshButton = frontRefreshButton_; @synthesize frontInfoButton = frontInfoButton_; @synthesize frontView = frontView_; @synthesize backView = backView_; @synthesize authURL = authURL_; @synthesize showingInfo = showingInfo_; - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { self.selectionStyle = UITableViewCellSelectionStyleNone; } return self; } - (void)dealloc { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self]; self.frontCodeLabel = nil; self.frontWarningLabel = nil; self.backCheckLabel = nil; self.backIntegrityCheckLabel = nil; self.frontNameTextField = nil; self.frontRefreshButton = nil; self.frontInfoButton = nil; self.frontView = nil; self.backView = nil; self.authURL = nil; [super dealloc]; } - (void)layoutSubviews { [super layoutSubviews]; if (!self.frontView) { [[NSBundle mainBundle] loadNibNamed:@"OTPTableViewCell" owner:self options:nil]; CGRect bounds = self.contentView.bounds; self.frontView.frame = bounds; [self.contentView addSubview:self.frontView]; [self updateUIForAuthURL:self.authURL]; self.backIntegrityCheckLabel.text = GTMLocalizedString(@"Integrity Check Value", @"Integerity Check Value label"); } } - (void)updateUIForAuthURL:(OTPAuthURL *)authURL { self.frontNameTextField.text = authURL.name; NSString *otpCode = authURL.otpCode; self.frontCodeLabel.text = otpCode; self.frontWarningLabel.text = otpCode; self.backCheckLabel.text = authURL.checkCode; self.frontInfoButton.hidden = self.shouldHideInfoButton; } - (void)setAuthURL:(OTPAuthURL *)authURL { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self name:OTPAuthURLDidGenerateNewOTPNotification object:authURL_]; [authURL_ autorelease]; authURL_ = [authURL retain]; [self updateUIForAuthURL:authURL_]; [nc addObserver:self selector:@selector(otpAuthURLDidGenerateNewOTP:) name:OTPAuthURLDidGenerateNewOTPNotification object:authURL_]; } - (void)willBeginEditing { [self.frontNameTextField becomeFirstResponder]; } - (void)didEndEditing { [self.frontNameTextField resignFirstResponder]; } - (void)otpChangeDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { // We retain ourself whenever we start an animation that calls // setAnimationStopSelector, so we must release ourself when we are actually // called. This is so that we don't disappear out from underneath the // animation while it is running. if ([animationID isEqual:@"otpFadeOut"]) { self.frontWarningLabel.alpha = 0; self.frontCodeLabel.alpha = 0; NSString *otpCode = self.authURL.otpCode; self.frontCodeLabel.text = otpCode; self.frontWarningLabel.text = otpCode; [UIView beginAnimations:@"otpFadeIn" context:nil]; [UIView setAnimationDelegate:self]; [self retain]; [UIView setAnimationDidStopSelector:@selector(otpChangeDidStop:finished:context:)]; self.frontCodeLabel.alpha = 1; [UIView commitAnimations]; } else { self.frontCodeLabel.alpha = 1; self.frontWarningLabel.alpha = 0; self.frontWarningLabel.hidden = YES; } [self release]; } - (BOOL)canBecomeFirstResponder { return YES; } - (void)showCopyMenu:(CGPoint)location { if (self.showingInfo) return; UIView *view = self.frontCodeLabel; CGRect selectionRect = [view frame]; if (CGRectContainsPoint(selectionRect, location) && [self becomeFirstResponder]) { UIMenuController *theMenu = [UIMenuController sharedMenuController]; [theMenu setTargetRect:selectionRect inView:[view superview]]; [theMenu setMenuVisible:YES animated:YES]; } } - (BOOL)canPerformAction:(SEL)action withSender:(id)sender { BOOL canPerform = NO; if (action == @selector(copy:)) { canPerform = YES; } else { canPerform = [super canPerformAction:action withSender:sender]; } return canPerform; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } - (void)setEditing:(BOOL)editing animated:(BOOL)animated { [super setEditing:editing animated:animated]; if (!editing) { if (![self.authURL.name isEqual:self.frontNameTextField.text]) { self.authURL.name = self.frontNameTextField.text; // Write out the changes. [self.authURL saveToKeychain]; } [self.frontNameTextField resignFirstResponder]; self.frontNameTextField.userInteractionEnabled = NO; self.frontNameTextField.borderStyle = UITextBorderStyleNone; if (!self.shouldHideInfoButton) { self.frontInfoButton.hidden = NO; } } else { self.frontNameTextField.userInteractionEnabled = YES; self.frontNameTextField.borderStyle = UITextBorderStyleRoundedRect; self.frontInfoButton.hidden = YES; [self hideInfo:self]; } } - (BOOL)shouldHideInfoButton { return [self.authURL isKindOfClass:[TOTPAuthURL class]]; } #pragma mark - #pragma mark Actions - (IBAction)copy:(id)sender { UIPasteboard *pb = [UIPasteboard generalPasteboard]; [pb setValue:self.frontCodeLabel.text forPasteboardType:@"public.utf8-plain-text"]; } - (IBAction)showInfo:(id)sender { if (!self.showingInfo) { self.backView.frame = self.contentView.bounds; [UIView beginAnimations:@"showInfo" context:NULL]; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self.contentView cache:YES]; [self.frontView removeFromSuperview]; [self.contentView addSubview:self.backView]; [UIView commitAnimations]; self.showingInfo = YES; } } - (IBAction)hideInfo:(id)sender { if (self.showingInfo) { self.frontView.frame = self.contentView.bounds; [UIView beginAnimations:@"hideInfo" context:NULL]; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.contentView cache:YES]; [backView_ removeFromSuperview]; [self.contentView addSubview:self.frontView]; [UIView commitAnimations]; self.showingInfo = NO; } } - (IBAction)refreshAuthURL:(id)sender { // For subclasses to override. } @end #pragma mark - @implementation HOTPTableViewCell - (void)layoutSubviews { [super layoutSubviews]; self.frontRefreshButton.hidden = self.isEditing; } - (void)setEditing:(BOOL)editing animated:(BOOL)animated { [super setEditing:editing animated:animated]; if (!editing) { self.frontRefreshButton.hidden = NO; } else { self.frontRefreshButton.hidden = YES; } } - (IBAction)refreshAuthURL:(id)sender { [(HOTPAuthURL *)self.authURL generateNextOTPCode]; } - (void)otpAuthURLDidGenerateNewOTP:(NSNotification *)notification { self.frontCodeLabel.alpha = 1; self.frontWarningLabel.alpha = 0; [UIView beginAnimations:@"otpFadeOut" context:nil]; [UIView setAnimationDelegate:self]; [self retain]; [UIView setAnimationDidStopSelector:@selector(otpChangeDidStop:finished:context:)]; self.frontCodeLabel.alpha = 0; [UIView commitAnimations]; } @end #pragma mark - @implementation TOTPTableViewCell - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { // Only support backgrounding in iOS 4+. if (&UIApplicationWillEnterForegroundNotification != NULL) { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; } } return self; } - (void)dealloc { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self]; [super dealloc]; } // On iOS4+ we need to make sure our timer based codes are up to date // if we have been hidden in the background. - (void)applicationWillEnterForeground:(UIApplication *)application { NSString *code = self.authURL.otpCode; NSString *frontText = self.frontCodeLabel.text; if (![code isEqual:frontText]) { [self otpAuthURLDidGenerateNewOTP:nil]; } } - (void)setAuthURL:(OTPAuthURL *)authURL { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self name:OTPAuthURLWillGenerateNewOTPWarningNotification object:self.authURL]; super.authURL = authURL; [nc addObserver:self selector:@selector(otpAuthURLWillGenerateNewOTP:) name:OTPAuthURLWillGenerateNewOTPWarningNotification object:self.authURL]; } - (void)otpAuthURLWillGenerateNewOTP:(NSNotification *)notification { NSDictionary *userInfo = [notification userInfo]; NSNumber *nsSeconds = [userInfo objectForKey:OTPAuthURLSecondsBeforeNewOTPKey]; NSUInteger seconds = [nsSeconds unsignedIntegerValue]; self.frontWarningLabel.alpha = 0; self.frontWarningLabel.hidden = NO; [UIView beginAnimations:@"Warning" context:nil]; [UIView setAnimationDuration:seconds]; self.frontCodeLabel.alpha = 0; self.frontWarningLabel.alpha = 1; [UIView commitAnimations]; } - (void)otpAuthURLDidGenerateNewOTP:(NSNotification *)notification { self.frontCodeLabel.alpha = 0; self.frontWarningLabel.alpha = 1; [UIView beginAnimations:@"otpFadeOut" context:nil]; [UIView setAnimationDelegate:self]; [self retain]; [UIView setAnimationDidStopSelector:@selector(otpChangeDidStop:finished:context:)]; self.frontWarningLabel.alpha = 0; [UIView commitAnimations]; } @end #pragma mark - @implementation OTPTableViewCellBackView - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { self.opaque = NO; self.clearsContextBeforeDrawing = YES; } return self; } - (void)drawRect:(CGRect)rect { CGGradientRef gradient = GoogleCreateBlueBarGradient(); if (gradient) { CGContextRef context = UIGraphicsGetCurrentContext(); GTMCGContextAddRoundRect(context, self.bounds, 8); CGContextClip(context); CGPoint midTop = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect)); CGPoint midBottom = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect)); CGContextDrawLinearGradient(context, gradient, midTop, midBottom, 0); CFRelease(gradient); } } @end
001coldblade-authenticator
mobile/ios/Classes/OTPTableViewCell.m
Objective-C
asf20
12,344
// // HOTPGeneratorTest.m // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import "HOTPGenerator.h" #import <SenTestingKit/SenTestingKit.h> @interface HOTPGeneratorTest : SenTestCase - (void)testHOTP; @end @implementation HOTPGeneratorTest // http://www.ietf.org/rfc/rfc4226.txt // Appendix D - HOTP Algorithm: Test Values - (void)testHOTP { NSString *secret = @"12345678901234567890"; NSData *secretData = [secret dataUsingEncoding:NSASCIIStringEncoding]; HOTPGenerator *generator = [[[HOTPGenerator alloc] initWithSecret:secretData algorithm:kOTPGeneratorSHA1Algorithm digits:6 counter:0] autorelease]; STAssertNotNil(generator, nil); STAssertEqualObjects(@"755224", [generator generateOTPForCounter:0], nil); // Make sure generating another OTP with generateOTPForCounter: // doesn't change our generator. STAssertEqualObjects(@"755224", [generator generateOTPForCounter:0], nil); NSArray *results = [NSArray arrayWithObjects: @"287082", @"359152", @"969429", @"338314", @"254676", @"287922", @"162583", @"399871", @"520489", @"403154", nil]; for (NSString *result in results) { STAssertEqualObjects(result, [generator generateOTP], @"Invalid result"); } } @end
001coldblade-authenticator
mobile/ios/Classes/HOTPGeneratorTest.m
Objective-C
asf20
1,937
// // OTPTableViewCell.h // // Copyright 2011 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // #import <UIKit/UIKit.h> @class OTPAuthURL; @class OTPTableViewCellBackView; @interface OTPTableViewCell : UITableViewCell<UITextFieldDelegate> @property (retain, nonatomic, readwrite) IBOutlet UILabel *frontCodeLabel; @property (retain, nonatomic, readwrite) IBOutlet UILabel *frontWarningLabel; @property (retain, nonatomic, readwrite) IBOutlet UILabel *backCheckLabel; @property (retain, nonatomic, readwrite) IBOutlet UILabel *backIntegrityCheckLabel; @property (retain, nonatomic, readwrite) IBOutlet UITextField *frontNameTextField; @property (retain, nonatomic, readwrite) IBOutlet UIButton *frontRefreshButton; @property (retain, nonatomic, readwrite) IBOutlet UIButton *frontInfoButton; @property (retain, nonatomic, readwrite) IBOutlet UIView *frontView; @property (retain, nonatomic, readwrite) IBOutlet OTPTableViewCellBackView *backView; - (void)setAuthURL:(OTPAuthURL *)authURL; - (void)willBeginEditing; - (void)didEndEditing; - (IBAction)showInfo:(id)sender; - (IBAction)hideInfo:(id)sender; - (IBAction)refreshAuthURL:(id)sender; - (void)showCopyMenu:(CGPoint)location; @end @interface HOTPTableViewCell : OTPTableViewCell @end @interface TOTPTableViewCell : OTPTableViewCell @end @interface OTPTableViewCellBackView : UIView @end
001coldblade-authenticator
mobile/ios/Classes/OTPTableViewCell.h
Objective-C
asf20
1,884