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 |
|---|---|---|---|---|---|
// 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_ */
| zy19820306-google-authenticator | libpam/base32.h | C | asf20 | 1,387 |
// 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;
}
| zy19820306-google-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=' ';
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 ±12h window';
}
}
document.getElementById('searchresult').innerHTML=result + ' ';
// 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 secret key in BASE32: </td>
<td><input type="text" id="secret" /></td>
<td> </td>
<td rowspan="8"><a style="text-decoration: none" id="aqr">
<img id="qr" border="0"></a></td><td width="100%"> </td></tr>
<tr><td colspan="3">Account label: </td>
<td><input type="text" id="label" /></td></tr>
<tr><td>Interval: </td><td align="right">30s</td><td> </td></tr>
<tr><td>Time: </td><td align="right">
<span id="epoch"></span></td><td> </td><td>
<input type="text" id="overrideepoch" /></td></tr>
<tr><td>Timestamp: </td><td align="right"><span id="ts"></span></td>
<td> </td><td><input type="text" id="override" /></td></tr>
<tr><td>TOTP: </td><td align="right"><span id="totp"></span></td>
<td> </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>
| zy19820306-google-authenticator | libpam/totp.html | HTML | asf20 | 9,422 |
# 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
| zy19820306-google-authenticator | libpam/Makefile | Makefile | asf20 | 4,915 |
// 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_ */
| zy19820306-google-authenticator | libpam/hmac.h | C | asf20 | 919 |
#!/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) + ';'
| zy19820306-google-authenticator | libpam/utc-time/utc-time.py | Python | asf20 | 300 |
// 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
| zy19820306-google-authenticator | libpam/sha1.h | C | asf20 | 1,189 |
// 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));
}
| zy19820306-google-authenticator | libpam/hmac.c | C | asf20 | 2,495 |
// 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;
}
| zy19820306-google-authenticator | libpam/demo.c | C | asf20 | 4,737 |
// 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, ¶ms) < 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, ¶ms, username, &uid)) &&
!drop_privileges(pamh, username, uid, &old_uid, &old_gid) &&
(fd = open_secret_file(pamh, secret_filename, ¶ms, 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,
¶ms, 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, ¶ms)) {
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
| zy19820306-google-authenticator | libpam/pam_google_authenticator.c | C | asf20 | 48,385 |
//
// OTPAuthAppDelegate.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 "OTPAuthAppDelegate.h"
#import "GTMDefines.h"
#import "OTPAuthURL.h"
#import "HOTPGenerator.h"
#import "TOTPGenerator.h"
#import "OTPTableViewCell.h"
#import "OTPAuthAboutController.h"
#import "OTPWelcomeViewController.h"
#import "OTPAuthBarClock.h"
#import "UIColor+MobileColors.h"
#import "GTMLocalizedString.h"
static NSString *const kOTPKeychainEntriesArray = @"OTPKeychainEntries";
@interface OTPGoodTokenSheet : UIActionSheet
@property(readwrite, nonatomic, retain) OTPAuthURL *authURL;
@end
@interface OTPAuthAppDelegate ()
// The OTPAuthURL objects in this array are loaded from the keychain at
// startup and serialized there on shutdown.
@property (nonatomic, retain) NSMutableArray *authURLs;
@property (nonatomic, assign) RootViewController *rootViewController;
@property (nonatomic, assign) UIBarButtonItem *editButton;
@property (nonatomic, assign) OTPEditingState editingState;
@property (nonatomic, retain) OTPAuthURL *urlBeingAdded;
@property (nonatomic, retain) UIAlertView *urlAddAlert;
- (void)saveKeychainArray;
- (void)updateUI;
- (void)updateEditing:(UITableView *)tableview;
@end
@implementation OTPAuthAppDelegate
@synthesize window = window_;
@synthesize authURLEntryController = authURLEntryController_;
@synthesize navigationController = navigationController_;
@synthesize authURLs = authURLs_;
@synthesize rootViewController = rootViewController_;
@synthesize editButton = editButton_;
@synthesize editingState = editingState_;
@synthesize urlAddAlert = urlAddAlert_;
@synthesize authURLEntryNavigationItem = authURLEntryNavigationItem_;
@synthesize legalButton = legalButton_;
@synthesize navigationItem = navigationItem_;
@synthesize urlBeingAdded = urlBeingAdded_;
- (void)dealloc {
self.window = nil;
self.authURLEntryController = nil;
self.navigationController = nil;
self.rootViewController = nil;
self.authURLs = nil;
self.editButton = nil;
self.urlBeingAdded = nil;
self.legalButton = nil;
self.navigationItem = nil;
self.urlAddAlert = nil;
self.authURLEntryNavigationItem = nil;
[super dealloc];
}
- (void)awakeFromNib {
self.legalButton.title
= GTMLocalizedString(@"Legal Information",
@"Legal Information Button Title");
self.navigationItem.title
= GTMLocalizedString(@"Google Authenticator",
@"Product Name");
self.authURLEntryNavigationItem.title
= GTMLocalizedString(@"Add Token",
@"Add Token Navigation Screen Title");
}
- (void)updateEditing:(UITableView *)tableView {
if ([self.authURLs count] == 0 && [tableView isEditing]) {
[tableView setEditing:NO animated:YES];
}
}
- (void)updateUI {
BOOL hidden = YES;
for (OTPAuthURL *url in self.authURLs) {
if ([url isMemberOfClass:[TOTPAuthURL class]]) {
hidden = NO;
break;
}
}
self.rootViewController.clock.hidden = hidden;
self.editButton.enabled = [self.authURLs count] > 0;
}
- (void)saveKeychainArray {
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSArray *keychainReferences = [self valueForKeyPath:@"authURLs.keychainItemRef"];
[ud setObject:keychainReferences forKey:kOTPKeychainEntriesArray];
[ud synchronize];
}
#pragma mark -
#pragma mark Application Delegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSArray *savedKeychainReferences = [ud arrayForKey:kOTPKeychainEntriesArray];
self.authURLs
= [NSMutableArray arrayWithCapacity:[savedKeychainReferences count]];
for (NSData *keychainRef in savedKeychainReferences) {
OTPAuthURL *authURL = [OTPAuthURL authURLWithKeychainItemRef:keychainRef];
if (authURL) {
[self.authURLs addObject:authURL];
}
}
self.rootViewController
= (RootViewController*)[self.navigationController topViewController];
[self.window addSubview:self.navigationController.view];
if ([self.authURLs count] == 0) {
OTPWelcomeViewController *controller
= [[[OTPWelcomeViewController alloc] init] autorelease];
[self.navigationController pushViewController:controller animated:NO];
}
[self.window makeKeyAndVisible];
return YES;
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
OTPAuthURL *authURL = [OTPAuthURL authURLWithURL:url secret:nil];
if (authURL) {
NSString *title = GTMLocalizedString(@"Add Token",
@"Add Token Alert Title");
NSString *message
= [NSString stringWithFormat:
GTMLocalizedString(@"Do you want to add the token named “%@”?",
@"Add Token Message"), [authURL name]];
NSString *noButton = GTMLocalizedString(@"No", @"No");
NSString *yesButton = GTMLocalizedString(@"Yes", @"Yes");
self.urlAddAlert = [[[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:noButton
otherButtonTitles:yesButton, nil]
autorelease];
self.urlBeingAdded = authURL;
[self.urlAddAlert show];
}
return authURL != nil;
}
#pragma mark -
#pragma mark OTPManualAuthURLEntryControllerDelegate
- (void)authURLEntryController:(OTPAuthURLEntryController*)controller
didCreateAuthURL:(OTPAuthURL *)authURL {
[self.navigationController dismissModalViewControllerAnimated:YES];
[self.navigationController popToRootViewControllerAnimated:NO];
[authURL saveToKeychain];
[self.authURLs addObject:authURL];
[self saveKeychainArray];
[self updateUI];
UITableView *tableView = (UITableView*)self.rootViewController.view;
[tableView reloadData];
}
#pragma mark -
#pragma mark UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController
animated:(BOOL)animated {
[self.rootViewController setEditing:NO animated:animated];
// Only display the toolbar for the rootViewController.
BOOL hidden = viewController != self.rootViewController;
[navigationController setToolbarHidden:hidden animated:YES];
}
- (void)navigationController:(UINavigationController *)navigationController
didShowViewController:(UIViewController *)viewController
animated:(BOOL)animated {
if (viewController == self.rootViewController) {
self.editButton = viewController.editButtonItem;
UIToolbar *toolbar = self.navigationController.toolbar;
NSMutableArray *items = [NSMutableArray arrayWithArray:toolbar.items];
// We are replacing our "proxy edit button" with a real one.
[items replaceObjectAtIndex:0 withObject:self.editButton];
toolbar.items = items;
[self updateUI];
}
}
#pragma mark -
#pragma mark UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellIdentifier = nil;
Class cellClass = Nil;
// See otp_tableViewWillBeginEditing for comments on why this is being done.
NSUInteger idx = self.editingState == kOTPEditingTable ? [indexPath row] : [indexPath section];
OTPAuthURL *url = [self.authURLs objectAtIndex:idx];
if ([url isMemberOfClass:[HOTPAuthURL class]]) {
cellIdentifier = @"HOTPCell";
cellClass = [HOTPTableViewCell class];
} else if ([url isMemberOfClass:[TOTPAuthURL class]]) {
cellIdentifier = @"TOTPCell";
cellClass = [TOTPTableViewCell class];
}
UITableViewCell *cell
= [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[[cellClass alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier] autorelease];
}
[(OTPTableViewCell *)cell setAuthURL:url];
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// See otp_tableViewWillBeginEditing for comments on why this is being done.
return self.editingState == kOTPEditingTable ? 1 : [self.authURLs count];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
// See otp_tableViewWillBeginEditing for comments on why this is being done.
return self.editingState == kOTPEditingTable ? [self.authURLs count] : 1;
}
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath {
NSUInteger oldIndex = [fromIndexPath row];
NSUInteger newIndex = [toIndexPath row];
[self.authURLs exchangeObjectAtIndex:oldIndex withObjectAtIndex:newIndex];
[self saveKeychainArray];
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
OTPTableViewCell *cell
= (OTPTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[cell didEndEditing];
[tableView beginUpdates];
NSUInteger idx = self.editingState == kOTPEditingTable ? [indexPath row] : [indexPath section];
OTPAuthURL *authURL = [self.authURLs objectAtIndex:idx];
// See otp_tableViewWillBeginEditing for comments on why this is being done.
if (self.editingState == kOTPEditingTable) {
NSIndexPath *path = [NSIndexPath indexPathForRow:idx inSection:0];
NSArray *rows = [NSArray arrayWithObject:path];
[tableView deleteRowsAtIndexPaths:rows
withRowAnimation:UITableViewRowAnimationFade];
} else {
NSIndexSet *set = [NSIndexSet indexSetWithIndex:idx];
[tableView deleteSections:set
withRowAnimation:UITableViewRowAnimationFade];
}
[authURL removeFromKeychain];
[self.authURLs removeObjectAtIndex:idx];
[self saveKeychainArray];
[tableView endUpdates];
[self updateUI];
if ([self.authURLs count] == 0 && self.editingState != kOTPEditingSingleRow) {
[self.editButton.target performSelector:self.editButton.action withObject:self];
}
}
}
#pragma mark -
#pragma mark UITableViewDelegate
- (void)tableView:(UITableView*)tableView
willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath {
_GTMDevAssert(self.editingState == kOTPNotEditing, @"Should not be editing");
OTPTableViewCell *cell
= (OTPTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[cell willBeginEditing];
self.editingState = kOTPEditingSingleRow;
}
- (void)tableView:(UITableView*)tableView
didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
_GTMDevAssert(self.editingState == kOTPEditingSingleRow, @"Must be editing single row");
OTPTableViewCell *cell
= (OTPTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
[cell didEndEditing];
self.editingState = kOTPNotEditing;
}
#pragma mark -
#pragma mark OTPTableViewDelegate
// With iOS <= 4 there doesn't appear to be a way to move rows around safely
// in a multisectional table where you want to maintain a single row per
// section. You have control over where a row would go into a section with
// tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:
// but it doesn't allow you to enforce only one row per section.
// By doing this we collapse the table into a single section with multiple rows
// when editing, and then expand back to the "spaced" out view when editing is
// done. We only want this to be done when editing the entire table (by hitting
// the edit button) as when you swipe a row to edit it doesn't allow you
// to move the row.
// When a row is swiped, tableView:willBeginEditingRowAtIndexPath: is called
// first, which means that self.editingState will be set to kOTPEditingSingleRow
// This means that in all code that deals with indexes of items that we need
// to check to see if self.editingState == kOTPEditingTable to know whether to
// check for the index of rows in section 0, or the indexes of the sections
// themselves.
- (void)otp_tableViewWillBeginEditing:(UITableView *)tableView {
if (self.editingState == kOTPNotEditing) {
self.editingState = kOTPEditingTable;
[tableView reloadData];
}
}
- (void)otp_tableViewDidEndEditing:(UITableView *)tableView {
if (self.editingState == kOTPEditingTable) {
self.editingState = kOTPNotEditing;
[tableView reloadData];
}
}
#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
_GTMDevAssert(alertView == self.urlAddAlert, @"Unexpected Alert");
if (buttonIndex == 1) {
[self authURLEntryController:nil
didCreateAuthURL:self.urlBeingAdded];
}
self.urlBeingAdded = nil;
self.urlAddAlert = nil;
}
#pragma mark -
#pragma mark Actions
-(IBAction)addAuthURL:(id)sender {
[self.navigationController popToRootViewControllerAnimated:NO];
[self.rootViewController setEditing:NO animated:NO];
[self.navigationController presentModalViewController:self.authURLEntryController
animated:YES];
}
- (IBAction)showLegalInformation:(id)sender {
OTPAuthAboutController *controller
= [[[OTPAuthAboutController alloc] init] autorelease];
[self.navigationController pushViewController:controller animated:YES];
}
@end
#pragma mark -
@implementation OTPGoodTokenSheet
@synthesize authURL = authURL_;
- (void)dealloc {
self.authURL = nil;
[super dealloc];
}
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthAppDelegate.m | Objective-C | asf20 | 14,280 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPScannerOverlayView.m | Objective-C | asf20 | 4,248 |
//
// OTPWelcomeViewController.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 OTPWelcomeViewController : UIViewController
@property (retain, nonatomic, readwrite) IBOutlet UITextView *welcomeText;
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPWelcomeViewController.h | Objective-C | asf20 | 801 |
//
// 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;
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthURL.h | Objective-C | asf20 | 3,292 |
//
// OTPTableView.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 "OTPTableView.h"
@implementation OTPTableView
- (void)setEditing:(BOOL)editing animated:(BOOL)animate {
if (editing) {
if ([self.delegate
respondsToSelector:@selector(otp_tableViewWillBeginEditing:)]) {
[self.delegate performSelector:@selector(otp_tableViewWillBeginEditing:)
withObject:self];
}
}
[super setEditing:editing animated:animate];
if (!editing) {
if ([self.delegate
respondsToSelector:@selector(otp_tableViewDidEndEditing:)]) {
[self.delegate performSelector:@selector(otp_tableViewDidEndEditing:)
withObject:self];
}
}
}
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPTableView.m | Objective-C | asf20 | 1,283 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/RootViewController.m | Objective-C | asf20 | 5,147 |
//
// HOTPGenerator.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"
@implementation HOTPGenerator
@synthesize counter = counter_;
+ (uint64_t)defaultInitialCounter {
return 1;
}
- (id)initWithSecret:(NSData *)secret
algorithm:(NSString *)algorithm
digits:(NSUInteger)digits
counter:(uint64_t)counter {
if ((self = [super initWithSecret:secret
algorithm:algorithm
digits:digits])) {
counter_ = counter;
}
return self;
}
- (NSString *)generateOTP {
NSUInteger counter = [self counter];
counter += 1;
NSString *otp = [super generateOTPForCounter:counter];
[self setCounter:counter];
return otp;
}
@end
| zy19820306-google-authenticator | mobile/ios/Classes/HOTPGenerator.m | Objective-C | asf20 | 1,304 |
//
// OTPAuthBarClock.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 OTPAuthBarClock : UIView
- (id)initWithFrame:(CGRect)frame period:(NSTimeInterval)period;
- (void)invalidate;
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthBarClock.h | Objective-C | asf20 | 780 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthApplication.m | Objective-C | asf20 | 872 |
//
// 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
| zy19820306-google-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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthAboutController.h | Objective-C | asf20 | 781 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/TOTPGenerator.h | Objective-C | asf20 | 2,109 |
//
// TOTPGenerator.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 "TOTPGenerator.h"
#import "GTMDefines.h"
@interface TOTPGenerator ()
@property(assign, nonatomic, readwrite) NSTimeInterval period;
@end
@implementation TOTPGenerator
@synthesize period = period_;
+ (NSTimeInterval)defaultPeriod {
return 30;
}
- (id)initWithSecret:(NSData *)secret
algorithm:(NSString *)algorithm
digits:(NSUInteger)digits
period:(NSTimeInterval)period {
if ((self = [super initWithSecret:secret
algorithm:algorithm
digits:digits])) {
if (period <= 0 || period > 300) {
_GTMDevLog(@"Bad Period: %f", period);
[self release];
self = nil;
} else {
self.period = period;
}
}
return self;
}
- (NSString *)generateOTP {
return [self generateOTPForDate:[NSDate date]];
}
- (NSString *)generateOTPForDate:(NSDate *)date {
if (!date) {
// If no now date specified, use the current date.
date = [NSDate date];
}
NSTimeInterval seconds = [date timeIntervalSince1970];
uint64_t counter = (uint64_t)(seconds / self.period);
return [super generateOTPForCounter:counter];
}
@end
| zy19820306-google-authenticator | mobile/ios/Classes/TOTPGenerator.m | Objective-C | asf20 | 1,783 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPTableViewCell.m | Objective-C | asf20 | 12,344 |
//
// HOTPGenerator.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 "OTPGenerator.h"
@interface HOTPGenerator : OTPGenerator
// The counter, incremented on each generated OTP.
@property(assign, nonatomic) uint64_t counter;
+ (uint64_t)defaultInitialCounter;
- (id)initWithSecret:(NSData *)secret
algorithm:(NSString *)algorithm
digits:(NSUInteger)digits
counter:(uint64_t)counter;
@end
| zy19820306-google-authenticator | mobile/ios/Classes/HOTPGenerator.h | Objective-C | asf20 | 994 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPScannerOverlayView.h | Objective-C | asf20 | 707 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthBarClock.m | Objective-C | asf20 | 4,887 |
//
// OTPAuthURLEntryController.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 "OTPAuthURLEntryController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "OTPAuthURL.h"
#import "GTMNSString+URLArguments.h"
#import "HOTPGenerator.h"
#import "TOTPGenerator.h"
#import "Decoder.h"
#import "TwoDDecoderResult.h"
#import "OTPScannerOverlayView.h"
#import "GTMLocalizedString.h"
#import "UIColor+MobileColors.h"
@interface OTPAuthURLEntryController ()
@property(nonatomic, readwrite, assign) UITextField *activeTextField;
@property(nonatomic, readwrite, assign) UIBarButtonItem *doneButtonItem;
@property(nonatomic, readwrite, retain) Decoder *decoder;
// queue is retained using dispatch_queue retain semantics.
@property (nonatomic, retain) __attribute__((NSObject)) dispatch_queue_t queue;
@property (nonatomic, retain) AVCaptureSession *avSession;
@property BOOL handleCapture;
- (void)keyboardWasShown:(NSNotification*)aNotification;
- (void)keyboardWillBeHidden:(NSNotification*)aNotification;
@end
@implementation OTPAuthURLEntryController
@synthesize delegate = delegate_;
@synthesize doneButtonItem = doneButtonItem_;
@synthesize accountName = accountName_;
@synthesize accountKey = accountKey_;
@synthesize accountNameLabel = accountNameLabel_;
@synthesize accountKeyLabel = accountKeyLabel_;
@synthesize accountType = accountType_;
@synthesize scanBarcodeButton = scanBarcodeButton_;
@synthesize scrollView = scrollView_;
@synthesize activeTextField = activeTextField_;
@synthesize decoder = decoder_;
@dynamic queue;
@synthesize avSession = avSession_;
@synthesize handleCapture = handleCapture_;
- (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)dealloc {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc removeObserver:self];
self.delegate = nil;
self.doneButtonItem = nil;
self.accountName = nil;
self.accountKey = nil;
self.accountNameLabel = nil;
self.accountKeyLabel = nil;
self.accountType = nil;
self.scanBarcodeButton = nil;
self.scrollView = nil;
self.decoder = nil;
self.queue = nil;
self.avSession = nil;
self.queue = nil;
[super dealloc];
}
- (void)viewDidLoad {
self.accountName.placeholder
= GTMLocalizedString(@"user@example.com",
@"Placeholder string for used acccount");
self.accountNameLabel.text
= GTMLocalizedString(@"Account:",
@"Label for Account field");
self.accountKey.placeholder
= GTMLocalizedString(@"Enter your key",
@"Placeholder string for key field");
self.accountKeyLabel.text
= GTMLocalizedString(@"Key:",
@"Label for Key field");
[self.scanBarcodeButton setTitle:GTMLocalizedString(@"Scan Barcode",
@"Scan Barcode button title")
forState:UIControlStateNormal];
[self.accountType setTitle:GTMLocalizedString(@"Time Based",
@"Time Based Account Type")
forSegmentAtIndex:0];
[self.accountType setTitle:GTMLocalizedString(@"Counter Based",
@"Counter Based Account Type")
forSegmentAtIndex:1];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[nc addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillAppear:(BOOL)animated {
self.accountName.text = @"";
self.accountKey.text = @"";
self.doneButtonItem
= self.navigationController.navigationBar.topItem.rightBarButtonItem;
self.doneButtonItem.enabled = NO;
self.decoder = [[[Decoder alloc] init] autorelease];
self.decoder.delegate = self;
self.scrollView.backgroundColor = [UIColor googleBlueBackgroundColor];
// Hide the Scan button if we don't have a camera that will support video.
AVCaptureDevice *device = nil;
if ([AVCaptureDevice class]) {
// AVCaptureDevice is not supported on iOS 3.1.3
device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
}
if (!device) {
[self.scanBarcodeButton setHidden:YES];
}
}
- (void)viewWillDisappear:(BOOL)animated {
self.doneButtonItem = nil;
self.handleCapture = NO;
[self.avSession stopRunning];
}
- (dispatch_queue_t)queue {
return queue_;
}
- (void)setQueue:(dispatch_queue_t)aQueue {
if (queue_ != aQueue) {
if (queue_) {
dispatch_release(queue_);
}
queue_ = aQueue;
if (queue_) {
dispatch_retain(queue_);
}
}
}
// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification {
NSDictionary* info = [aNotification userInfo];
CGFloat offset = 0;
// UIKeyboardFrameBeginUserInfoKey does not exist on iOS 3.1.3
if (&UIKeyboardFrameBeginUserInfoKey != NULL) {
NSValue *sizeValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [sizeValue CGRectValue].size;
BOOL isLandscape
= UIInterfaceOrientationIsLandscape(self.interfaceOrientation);
offset = isLandscape ? keyboardSize.width : keyboardSize.height;
} else {
NSValue *sizeValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [sizeValue CGRectValue].size;
// The keyboard size value appears to rotate correctly on iOS 3.1.3.
offset = keyboardSize.height;
}
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, offset, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
// If active text field is hidden by keyboard, scroll it so it's visible.
CGRect aRect = self.view.frame;
aRect.size.height -= offset;
if (self.activeTextField) {
CGPoint origin = self.activeTextField.frame.origin;
origin.y += CGRectGetHeight(self.activeTextField.frame);
if (!CGRectContainsPoint(aRect, origin) ) {
CGPoint scrollPoint =
CGPointMake(0.0, - (self.activeTextField.frame.origin.y - offset));
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
}
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)orientation {
// Scrolling is only enabled when in landscape.
if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
self.scrollView.contentSize = self.view.bounds.size;
} else {
self.scrollView.contentSize = CGSizeZero;
}
}
#pragma mark -
#pragma mark Actions
- (IBAction)accountNameDidEndOnExit:(id)sender {
[self.accountKey becomeFirstResponder];
}
- (IBAction)accountKeyDidEndOnExit:(id)sender {
[self done:sender];
}
- (IBAction)done:(id)sender {
// Force the keyboard away.
[self.activeTextField resignFirstResponder];
NSString *encodedSecret = self.accountKey.text;
NSData *secret = [OTPAuthURL base32Decode:encodedSecret];
if ([secret length]) {
Class authURLClass = Nil;
if ([accountType_ selectedSegmentIndex] == 0) {
authURLClass = [TOTPAuthURL class];
} else {
authURLClass = [HOTPAuthURL class];
}
NSString *name = self.accountName.text;
OTPAuthURL *authURL
= [[[authURLClass alloc] initWithSecret:secret
name:name] autorelease];
NSString *checkCode = authURL.checkCode;
if (checkCode) {
[self.delegate authURLEntryController:self didCreateAuthURL:authURL];
}
} else {
NSString *title = GTMLocalizedString(@"Invalid Key",
@"Alert title describing a bad key");
NSString *message = nil;
if ([encodedSecret length]) {
message = [NSString stringWithFormat:
GTMLocalizedString(@"The key '%@' is invalid.",
@"Alert describing invalid key"),
encodedSecret];
} else {
message = GTMLocalizedString(@"You must enter a key.",
@"Alert describing missing key");
}
NSString *button
= GTMLocalizedString(@"Try Again",
@"Button title to try again");
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:button
otherButtonTitles:nil]
autorelease];
[alert show];
}
}
- (IBAction)cancel:(id)sender {
self.handleCapture = NO;
[self.avSession stopRunning];
[self dismissModalViewControllerAnimated:NO];
}
- (IBAction)scanBarcode:(id)sender {
if (!self.avSession) {
self.avSession = [[[AVCaptureSession alloc] init] autorelease];
AVCaptureDevice *device =
[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *captureInput =
[AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
[self.avSession addInput:captureInput];
dispatch_queue_t queue = dispatch_queue_create("OTPAuthURLEntryController",
0);
self.queue = queue;
dispatch_release(queue);
AVCaptureVideoDataOutput *captureOutput =
[[[AVCaptureVideoDataOutput alloc] init] autorelease];
[captureOutput setAlwaysDiscardsLateVideoFrames:YES];
[captureOutput setMinFrameDuration:CMTimeMake(5,1)]; // At most 5 frames/sec.
[captureOutput setSampleBufferDelegate:self
queue:self.queue];
NSNumber *bgra = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
bgra, kCVPixelBufferPixelFormatTypeKey,
nil];
[captureOutput setVideoSettings:videoSettings];
[self.avSession addOutput:captureOutput];
}
AVCaptureVideoPreviewLayer *previewLayer
= [AVCaptureVideoPreviewLayer layerWithSession:self.avSession];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
UIButton *cancelButton =
[UIButton buttonWithType:UIButtonTypeRoundedRect];
NSString *cancelString
= GTMLocalizedString(@"Cancel", @"Cancel button for taking pictures");
cancelButton.accessibilityLabel = @"Cancel";
CGFloat height = [UIFont systemFontSize];
CGSize size
= [cancelString sizeWithFont:[UIFont systemFontOfSize:height]];
[cancelButton setTitle:cancelString forState:UIControlStateNormal];
UIViewController *previewController
= [[[UIViewController alloc] init] autorelease];
[previewController.view.layer addSublayer:previewLayer];
CGRect frame = previewController.view.bounds;
previewLayer.frame = frame;
OTPScannerOverlayView *overlayView
= [[[OTPScannerOverlayView alloc] initWithFrame:frame] autorelease];
[previewController.view addSubview:overlayView];
// Center the cancel button horizontally, and put it
// kBottomPadding from the bottom of the view.
static const int kBottomPadding = 10;
static const int kInternalXMargin = 10;
static const int kInternalYMargin = 10;
frame = CGRectMake(CGRectGetMidX(frame)
- ((size.width / 2) + kInternalXMargin),
CGRectGetHeight(frame)
- (height + (2 * kInternalYMargin) + kBottomPadding),
(2 * kInternalXMargin) + size.width,
height + (2 * kInternalYMargin));
[cancelButton setFrame:frame];
// Set it up so that if the view should resize, the cancel button stays
// h-centered and v-bottom-fixed in the view.
cancelButton.autoresizingMask = (UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin);
[cancelButton addTarget:self
action:@selector(cancel:)
forControlEvents:UIControlEventTouchUpInside];
[overlayView addSubview:cancelButton];
[self presentModalViewController:previewController animated:NO];
self.handleCapture = YES;
[self.avSession startRunning];
}
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
fromConnection:(AVCaptureConnection *)connection {
if (!self.handleCapture) return;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
if (imageBuffer) {
CVReturn ret = CVPixelBufferLockBaseAddress(imageBuffer, 0);
if (ret == kCVReturnSuccess) {
uint8_t *base = (uint8_t *)CVPixelBufferGetBaseAddress(imageBuffer);
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context
= CGBitmapContextCreate(base, width, height, 8, bytesPerRow, colorSpace,
kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
CGImageRef cgImage = CGBitmapContextCreateImage(context);
CGContextRelease(context);
UIImage *image = [UIImage imageWithCGImage:cgImage];
CFRelease(cgImage);
CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
[self.decoder performSelectorOnMainThread:@selector(decodeImage:)
withObject:image
waitUntilDone:NO];
} else {
NSLog(@"Unable to lock buffer %d", ret);
}
} else {
NSLog(@"Unable to get imageBuffer from %@", sampleBuffer);
}
[pool release];
}
#pragma mark -
#pragma mark UITextField Delegate Methods
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
if (textField == self.accountKey) {
NSMutableString *key
= [NSMutableString stringWithString:self.accountKey.text];
[key replaceCharactersInRange:range withString:string];
self.doneButtonItem.enabled = [key length] > 0;
}
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
self.activeTextField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
self.activeTextField = nil;
}
#pragma mark -
#pragma mark DecoderDelegate
- (void)decoder:(Decoder *)decoder
didDecodeImage:(UIImage *)image
usingSubset:(UIImage *)subset
withResult:(TwoDDecoderResult *)twoDResult {
if (self.handleCapture) {
self.handleCapture = NO;
NSString *urlString = twoDResult.text;
NSURL *url = [NSURL URLWithString:urlString];
OTPAuthURL *authURL = [OTPAuthURL authURLWithURL:url
secret:nil];
[self.avSession stopRunning];
if (authURL) {
[self.delegate authURLEntryController:self didCreateAuthURL:authURL];
[self dismissModalViewControllerAnimated:NO];
} else {
NSString *title = GTMLocalizedString(@"Invalid Barcode",
@"Alert title describing a bad barcode");
NSString *message = [NSString stringWithFormat:
GTMLocalizedString(@"The barcode '%@' is not a valid "
@"authentication token barcode.",
@"Alert describing invalid barcode type."),
urlString];
NSString *button = GTMLocalizedString(@"Try Again",
@"Button title to try again");
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:button
otherButtonTitles:nil]
autorelease];
[alert show];
}
}
}
- (void)decoder:(Decoder *)decoder failedToDecodeImage:(UIImage *)image
usingSubset:(UIImage *)subset
reason:(NSString *)reason {
}
#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex {
self.handleCapture = YES;
[self.avSession startRunning];
}
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthURLEntryController.m | Objective-C | asf20 | 17,957 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPTableViewCell.h | Objective-C | asf20 | 1,884 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPTableView.h | Objective-C | asf20 | 936 |
//
// OTPAuthApplication.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 OTPAuthApplication : UIApplication
- (IBAction)addAuthURL:(id)sender;
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthApplication.h | Objective-C | asf20 | 744 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/RootViewController.h | Objective-C | asf20 | 1,054 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/HOTPGeneratorTest.m | Objective-C | asf20 | 1,937 |
//
// OTPAuthURL.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 "OTPAuthURL.h"
#import <Security/Security.h>
#import "GTMNSDictionary+URLArguments.h"
#import "GTMNSString+URLArguments.h"
#import "GTMNSScanner+Unsigned.h"
#import "GTMStringEncoding.h"
#import "HOTPGenerator.h"
#import "TOTPGenerator.h"
static NSString *const kOTPAuthScheme = @"otpauth";
static NSString *const kTOTPAuthScheme = @"totp";
static NSString *const kOTPService = @"com.google.otp.authentication";
// 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 kBase32Charset = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
static NSString *const kBase32Synonyms =
@"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
static NSString *const kBase32Sep = @" -";
static const NSTimeInterval kTOTPDefaultSecondsBeforeChange = 5;
NSString *const OTPAuthURLWillGenerateNewOTPWarningNotification
= @"OTPAuthURLWillGenerateNewOTPWarningNotification";
NSString *const OTPAuthURLDidGenerateNewOTPNotification
= @"OTPAuthURLDidGenerateNewOTPNotification";
NSString *const OTPAuthURLSecondsBeforeNewOTPKey
= @"OTPAuthURLSecondsBeforeNewOTP";
@interface OTPAuthURL ()
// re-declare readwrite
@property(readwrite, retain, nonatomic) NSData *keychainItemRef;
@property(readwrite, retain, nonatomic) OTPGenerator *generator;
// Initialize an OTPAuthURL with a dictionary of attributes from a keychain.
+ (OTPAuthURL *)authURLWithKeychainDictionary:(NSDictionary *)dict;
// Initialize an OTPAuthURL object with an otpauth:// NSURL object.
- (id)initWithOTPGenerator:(OTPGenerator *)generator
name:(NSString *)name;
@end
@interface TOTPAuthURL ()
@property (nonatomic, readwrite, assign) NSTimeInterval lastProgress;
@property (nonatomic, readwrite, assign) BOOL warningSent;
+ (void)totpTimer:(NSTimer *)timer;
- (id)initWithTOTPURL:(NSURL *)url;
- (id)initWithName:(NSString *)name
secret:(NSData *)secret
algorithm:(NSString *)algorithm
digits:(NSUInteger)digits
query:(NSDictionary *)query;
@end
@interface HOTPAuthURL ()
+ (BOOL)isValidCounter:(NSString *)counter;
- (id)initWithName:(NSString *)name
secret:(NSData *)secret
algorithm:(NSString *)algorithm
digits:(NSUInteger)digits
query:(NSDictionary *)query;
@property(readwrite, copy, nonatomic) NSString *otpCode;
@end
@implementation OTPAuthURL
@synthesize name = name_;
@synthesize keychainItemRef = keychainItemRef_;
@synthesize generator = generator_;
@dynamic checkCode;
@dynamic otpCode;
+ (OTPAuthURL *)authURLWithURL:(NSURL *)url
secret:(NSData *)secret {
OTPAuthURL *authURL = nil;
NSString *urlScheme = [url scheme];
if ([urlScheme isEqualToString:kTOTPAuthScheme]) {
// Convert totp:// into otpauth://
authURL = [[[TOTPAuthURL alloc] initWithTOTPURL:url] autorelease];
} else if (![urlScheme isEqualToString:kOTPAuthScheme]) {
// Required (otpauth://)
_GTMDevLog(@"invalid scheme: %@", [url scheme]);
} else {
NSString *path = [url path];
if ([path length] > 1) {
// Optional UTF-8 encoded human readable description (skip leading "/")
NSString *name = [[url path] substringFromIndex:1];
NSDictionary *query =
[NSDictionary gtm_dictionaryWithHttpArgumentsString:[url query]];
// Optional algorithm=(SHA1|SHA256|SHA512|MD5) defaults to SHA1
NSString *algorithm = [query objectForKey:kQueryAlgorithmKey];
if (!algorithm) {
algorithm = [OTPGenerator defaultAlgorithm];
}
if (!secret) {
// Required secret=Base32EncodedKey
NSString *secretString = [query objectForKey:kQuerySecretKey];
secret = [OTPAuthURL base32Decode:secretString];
}
// Optional digits=[68] defaults to 8
NSString *digitString = [query objectForKey:kQueryDigitsKey];
NSUInteger digits = 0;
if (!digitString) {
digits = [OTPGenerator defaultDigits];
} else {
digits = [digitString intValue];
}
NSString *type = [url host];
if ([type isEqualToString:@"hotp"]) {
authURL = [[[HOTPAuthURL alloc] initWithName:name
secret:secret
algorithm:algorithm
digits:digits
query:query] autorelease];
} else if ([type isEqualToString:@"totp"]) {
authURL = [[[TOTPAuthURL alloc] initWithName:name
secret:secret
algorithm:algorithm
digits:digits
query:query] autorelease];
}
}
}
return authURL;
}
+ (OTPAuthURL *)authURLWithKeychainItemRef:(NSData *)data {
OTPAuthURL *authURL = nil;
NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassGenericPassword, kSecClass,
data, (id)kSecValuePersistentRef,
(id)kCFBooleanTrue, kSecReturnAttributes,
(id)kCFBooleanTrue, kSecReturnData,
nil];
NSDictionary *result = nil;
OSStatus status = SecItemCopyMatching((CFDictionaryRef)query,
(CFTypeRef*)&result);
if (status == noErr) {
authURL = [self authURLWithKeychainDictionary:result];
[authURL setKeychainItemRef:data];
}
return authURL;
}
+ (OTPAuthURL *)authURLWithKeychainDictionary:(NSDictionary *)dict {
NSData *urlData = [dict objectForKey:(id)kSecAttrGeneric];
NSData *secretData = [dict objectForKey:(id)kSecValueData];
NSString *urlString = [[[NSString alloc] initWithData:urlData
encoding:NSUTF8StringEncoding]
autorelease];
NSURL *url = [NSURL URLWithString:urlString];
return [self authURLWithURL:url secret:secretData];
}
+ (NSData *)base32Decode:(NSString *)string {
GTMStringEncoding *coder =
[GTMStringEncoding stringEncodingWithString:kBase32Charset];
[coder addDecodeSynonyms:kBase32Synonyms];
[coder ignoreCharacters:kBase32Sep];
return [coder decode:string];
}
+ (NSString *)encodeBase32:(NSData *)data {
GTMStringEncoding *coder =
[GTMStringEncoding stringEncodingWithString:kBase32Charset];
[coder addDecodeSynonyms:kBase32Synonyms];
[coder ignoreCharacters:kBase32Sep];
return [coder encode:data];
}
- (id)initWithOTPGenerator:(OTPGenerator *)generator
name:(NSString *)name {
if ((self = [super init])) {
if (!generator || !name) {
_GTMDevLog(@"Bad Args Generator:%@ Name:%@", generator, name);
[self release];
self = nil;
} else {
self.generator = generator;
self.name = name;
}
}
return self;
}
- (id)init {
[self doesNotRecognizeSelector:_cmd];
return nil;
}
- (void)dealloc {
self.generator = nil;
self.name = nil;
self.keychainItemRef = nil;
[super dealloc];
}
- (NSURL *)url {
[self doesNotRecognizeSelector:_cmd];
return nil;
}
- (BOOL)saveToKeychain {
NSString *urlString = [[self url] absoluteString];
NSData *urlData = [urlString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *attributes =
[NSMutableDictionary dictionaryWithObject:urlData
forKey:(id)kSecAttrGeneric];
OSStatus status;
if ([self isInKeychain]) {
NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassGenericPassword, (id)kSecClass,
self.keychainItemRef, (id)kSecValuePersistentRef,
nil];
status = SecItemUpdate((CFDictionaryRef)query, (CFDictionaryRef)attributes);
_GTMDevLog(@"SecItemUpdate(%@, %@) = %ld", query, attributes, status);
} else {
[attributes setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass];
[attributes setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnPersistentRef];
[attributes setObject:self.generator.secret forKey:(id)kSecValueData];
[attributes setObject:kOTPService forKey:(id)kSecAttrService];
NSData *ref = nil;
// The name here has to be unique or else we will get a errSecDuplicateItem
// so if we have two items with the same name, we will just append a
// random number on the end until we get success. We will try at max of
// 1000 times so as to not hang in shut down.
// We do not display this name to the user, so anything will do.
NSString *name = self.name;
for (int i = 0; i < 1000; i++) {
[attributes setObject:name forKey:(id)kSecAttrAccount];
status = SecItemAdd((CFDictionaryRef)attributes, (CFTypeRef *)&ref);
if (status == errSecDuplicateItem) {
name = [NSString stringWithFormat:@"%@.%ld", self.name, random()];
} else {
break;
}
}
_GTMDevLog(@"SecItemAdd(%@, %@) = %ld", attributes, ref, status);
if (status == noErr) {
self.keychainItemRef = ref;
}
}
return status == noErr;
}
- (BOOL)removeFromKeychain {
if (![self isInKeychain]) {
return NO;
}
NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassGenericPassword, (id)kSecClass,
[self keychainItemRef], (id)kSecValuePersistentRef,
nil];
OSStatus status = SecItemDelete((CFDictionaryRef)query);
_GTMDevLog(@"SecItemDelete(%@) = %ld", query, status);
if (status == noErr) {
[self setKeychainItemRef:nil];
}
return status == noErr;
}
- (BOOL)isInKeychain {
return self.keychainItemRef != nil;
}
- (void)generateNextOTPCode {
_GTMDevLog(@"Called generateNextOTPCode on a non-HOTP generator");
}
- (NSString*)checkCode {
return [self.generator generateOTPForCounter:0];
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@ %p> Name: %@ ref: %p checkCode: %@",
[self class], self, self.name, self.keychainItemRef, self.checkCode];
}
#pragma mark -
#pragma mark URL Validation
@end
@implementation TOTPAuthURL
static NSString *const TOTPAuthURLTimerNotification
= @"TOTPAuthURLTimerNotification";
@synthesize generationAdvanceWarning = generationAdvanceWarning_;
@synthesize lastProgress = lastProgress_;
@synthesize warningSent = warningSent_;
+ (void)initialize {
static NSTimer *sTOTPTimer = nil;
if (!sTOTPTimer) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
sTOTPTimer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:@selector(totpTimer:)
userInfo:nil
repeats:YES];
[pool drain];
}
}
+ (void)totpTimer:(NSTimer *)timer {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:TOTPAuthURLTimerNotification object:self];
}
- (id)initWithOTPGenerator:(OTPGenerator *)generator
name:(NSString *)name {
if ((self = [super initWithOTPGenerator:generator
name:name])) {
[self setGenerationAdvanceWarning:kTOTPDefaultSecondsBeforeChange];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(totpTimer:)
name:TOTPAuthURLTimerNotification
object:nil];
}
return self;
}
- (id)initWithSecret:(NSData *)secret name:(NSString *)name {
TOTPGenerator *generator
= [[[TOTPGenerator alloc] initWithSecret:secret
algorithm:[TOTPGenerator defaultAlgorithm]
digits:[TOTPGenerator defaultDigits]
period:[TOTPGenerator defaultPeriod]]
autorelease];
return [self initWithOTPGenerator:generator
name:name];
}
// totp:// urls are generated by the GAIA smsauthconfig page and implement
// a subset of the functionality available in otpauth:// urls, so we just
// translate to that internally.
- (id)initWithTOTPURL:(NSURL *)url {
NSMutableString *name = nil;
if ([[url user] length]) {
name = [NSMutableString stringWithString:[url user]];
}
if ([url host]) {
[name appendFormat:@"@%@", [url host]];
}
NSData *secret = [OTPAuthURL base32Decode:[url fragment]];
return [self initWithSecret:secret name:name];
}
- (id)initWithName:(NSString *)name
secret:(NSData *)secret
algorithm:(NSString *)algorithm
digits:(NSUInteger)digits
query:(NSDictionary *)query {
NSString *periodString = [query objectForKey:kQueryPeriodKey];
NSTimeInterval period = 0;
if (periodString) {
period = [periodString doubleValue];
} else {
period = [TOTPGenerator defaultPeriod];
}
TOTPGenerator *generator
= [[[TOTPGenerator alloc] initWithSecret:secret
algorithm:algorithm
digits:digits
period:period] autorelease];
if ((self = [self initWithOTPGenerator:generator
name:name])) {
self.lastProgress = period;
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (NSString *)otpCode {
return [self.generator generateOTP];
}
- (void)totpTimer:(NSTimer *)timer {
TOTPGenerator *generator = (TOTPGenerator *)[self generator];
NSTimeInterval delta = [[NSDate date] timeIntervalSince1970];
NSTimeInterval period = [generator period];
uint64_t progress = (uint64_t)delta % (uint64_t)period;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
if (progress == 0 || progress > self.lastProgress) {
[nc postNotificationName:OTPAuthURLDidGenerateNewOTPNotification object:self];
self.lastProgress = period;
self.warningSent = NO;
} else if (progress > period - self.generationAdvanceWarning
&& !self.warningSent) {
NSNumber *warning = [NSNumber numberWithInt:ceil(period - progress)];
NSDictionary *userInfo
= [NSDictionary dictionaryWithObject:warning
forKey:OTPAuthURLSecondsBeforeNewOTPKey];
[nc postNotificationName:OTPAuthURLWillGenerateNewOTPWarningNotification
object:self
userInfo:userInfo];
self.warningSent = YES;
}
}
- (NSURL *)url {
NSMutableDictionary *query = [NSMutableDictionary dictionary];
TOTPGenerator *generator = (TOTPGenerator *)[self generator];
Class generatorClass = [generator class];
NSString *algorithm = [generator algorithm];
if (![algorithm isEqualToString:[generatorClass defaultAlgorithm]]) {
[query setObject:algorithm forKey:kQueryAlgorithmKey];
}
NSUInteger digits = [generator digits];
if (digits != [generatorClass defaultDigits]) {
id val = [NSNumber numberWithUnsignedInteger:digits];
[query setObject:val forKey:kQueryDigitsKey];
}
NSTimeInterval period = [generator period];
if (fpclassify(period - [generatorClass defaultPeriod]) != FP_ZERO) {
id val = [NSNumber numberWithUnsignedInteger:period];
[query setObject:val forKey:kQueryPeriodKey];
}
return [NSURL URLWithString:[NSString stringWithFormat:@"%@://totp/%@?%@",
kOTPAuthScheme,
[self.name gtm_stringByEscapingForURLArgument],
[query gtm_httpArgumentsString]]];
}
@end
@implementation HOTPAuthURL
@synthesize otpCode = otpCode_;
- (id)initWithOTPGenerator:(OTPGenerator *)generator
name:(NSString *)name {
if ((self = [super initWithOTPGenerator:generator name:name])) {
uint64_t counter = [(HOTPGenerator *)generator counter];
self.otpCode = [generator generateOTPForCounter:counter];
}
return self;
}
- (id)initWithSecret:(NSData *)secret name:(NSString *)name {
HOTPGenerator *generator
= [[[HOTPGenerator alloc] initWithSecret:secret
algorithm:[HOTPGenerator defaultAlgorithm]
digits:[HOTPGenerator defaultDigits]
counter:[HOTPGenerator defaultInitialCounter]]
autorelease];
return [self initWithOTPGenerator:generator name:name];
}
- (id)initWithName:(NSString *)name
secret:(NSData *)secret
algorithm:(NSString *)algorithm
digits:(NSUInteger)digits
query:(NSDictionary *)query {
NSString *counterString = [query objectForKey:kQueryCounterKey];
if ([[self class] isValidCounter:counterString]) {
NSScanner *scanner = [NSScanner scannerWithString:counterString];
uint64_t counter;
BOOL goodScan = [scanner gtm_scanUnsignedLongLong:&counter];
// Good scan should always be good based on the isValidCounter check above.
_GTMDevAssert(goodScan, @"goodscan should be true: %c", goodScan);
HOTPGenerator *generator
= [[[HOTPGenerator alloc] initWithSecret:secret
algorithm:algorithm
digits:digits
counter:counter] autorelease];
self = [self initWithOTPGenerator:generator
name:name];
} else {
_GTMDevLog(@"invalid counter: %@", counterString);
self = [super initWithOTPGenerator:nil name:nil];
[self release];
self = nil;
}
return self;
}
- (void)dealloc {
self.otpCode = nil;
[super dealloc];
}
- (void)generateNextOTPCode {
self.otpCode = [[self generator] generateOTP];
[self saveToKeychain];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:OTPAuthURLDidGenerateNewOTPNotification object:self];
}
- (NSURL *)url {
NSMutableDictionary *query = [NSMutableDictionary dictionary];
HOTPGenerator *generator = (HOTPGenerator *)[self generator];
Class generatorClass = [generator class];
NSString *algorithm = [generator algorithm];
if (![algorithm isEqualToString:[generatorClass defaultAlgorithm]]) {
[query setObject:algorithm forKey:kQueryAlgorithmKey];
}
NSUInteger digits = [generator digits];
if (digits != [generatorClass defaultDigits]) {
id val = [NSNumber numberWithUnsignedInteger:digits];
[query setObject:val forKey:kQueryDigitsKey];
}
uint64_t counter = [generator counter];
id val = [NSNumber numberWithUnsignedLongLong:counter];
[query setObject:val forKey:kQueryCounterKey];
return [NSURL URLWithString:[NSString stringWithFormat:@"%@://hotp/%@?%@",
kOTPAuthScheme,
[[self name] gtm_stringByEscapingForURLArgument],
[query gtm_httpArgumentsString]]];
}
+ (BOOL)isValidCounter:(NSString *)counter {
NSCharacterSet *nonDigits =
[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
NSRange pos = [counter rangeOfCharacterFromSet:nonDigits];
return pos.location == NSNotFound;
}
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthURL.m | Objective-C | asf20 | 20,247 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthAboutController.m | Objective-C | asf20 | 7,712 |
//
// 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
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthURLTest.m | Objective-C | asf20 | 8,408 |
//
// OTPGenerator.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>
// The OTPGenerator class generates a one-time password (OTP) using
// the HMAC-Based One-Time Password Algorithm described in RFC4226:
// http://tools.ietf.org/html/rfc4226
//
// The HOTP algorithm is based on an increasing counter value and a
// static symmetric key known only to the token and the validation
// service. In order to create the HOTP value, we will use the HMAC-
// SHA-1 algorithm, as defined in RFC 2104.
//
// As the output of the HMAC-SHA-1 calculation is 160 bits, we must
// truncate this value to something that can be easily entered by a
// user.
//
// HOTP(K,C) = Truncate(HMAC-SHA-1(K,C))
//
// Where:
//
// - Truncate represents the function that converts an HMAC-SHA-1
// value into an HOTP value as defined in Section 5.3 of RFC4226.
//
// The Key (K), the Counter (C), and Data values are hashed high-order
// byte first.
//
// The HOTP values generated by the HOTP generator are treated as big
// endian.
@interface OTPGenerator : NSObject
@property (readonly, nonatomic, copy) NSString *algorithm;
@property (readonly, nonatomic, copy) NSData *secret;
@property (readonly, nonatomic) NSUInteger digits;
// Some default values.
+ (NSString *)defaultAlgorithm;
+ (NSUInteger)defaultDigits;
// Designated initializer.
- (id)initWithSecret:(NSData *)secret
algorithm:(NSString *)algorithm
digits:(NSUInteger)digits;
// Instance method to generate an OTP using the |algorithm|, |secret|,
// |counter| and |digits| values configured on the object.
// The return value is an NSString of |digits| length, with leading
// zero-padding as required.
- (NSString *)generateOTPForCounter:(uint64_t)counter;
// Instance method to generate an OTP using the |algorithm|, |secret|,
// |counter| and |digits| values configured on the object.
// The return value is an NSString of |digits| length, with leading
// zero-padding as required.
- (NSString *)generateOTP;
@end
extern NSString *const kOTPGeneratorSHA1Algorithm;
extern NSString *const kOTPGeneratorSHA256Algorithm;
extern NSString *const kOTPGeneratorSHA512Algorithm;
extern NSString *const kOTPGeneratorSHAMD5Algorithm;
| zy19820306-google-authenticator | mobile/ios/Classes/OTPGenerator.h | Objective-C | asf20 | 2,794 |
//
// HOTPGenerator.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 "OTPGenerator.h"
#import <CommonCrypto/CommonHMAC.h>
#import <CommonCrypto/CommonDigest.h>
#import "GTMDefines.h"
static NSUInteger kPinModTable[] = {
0,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
};
NSString *const kOTPGeneratorSHA1Algorithm = @"SHA1";
NSString *const kOTPGeneratorSHA256Algorithm = @"SHA256";
NSString *const kOTPGeneratorSHA512Algorithm = @"SHA512";
NSString *const kOTPGeneratorSHAMD5Algorithm = @"MD5";
@interface OTPGenerator ()
@property (readwrite, nonatomic, copy) NSString *algorithm;
@property (readwrite, nonatomic, copy) NSData *secret;
@end
@implementation OTPGenerator
+ (NSString *)defaultAlgorithm {
return kOTPGeneratorSHA1Algorithm;
}
+ (NSUInteger)defaultDigits {
return 6;
}
@synthesize algorithm = algorithm_;
@synthesize secret = secret_;
@synthesize digits = digits_;
- (id)init {
[self doesNotRecognizeSelector:_cmd];
return nil;
}
- (id)initWithSecret:(NSData *)secret
algorithm:(NSString *)algorithm
digits:(NSUInteger)digits {
if ((self = [super init])) {
algorithm_ = [algorithm copy];
secret_ = [secret copy];
digits_ = digits;
BOOL goodAlgorithm
= ([algorithm isEqualToString:kOTPGeneratorSHA1Algorithm] ||
[algorithm isEqualToString:kOTPGeneratorSHA256Algorithm] ||
[algorithm isEqualToString:kOTPGeneratorSHA512Algorithm] ||
[algorithm isEqualToString:kOTPGeneratorSHAMD5Algorithm]);
if (!goodAlgorithm || digits_ > 8 || digits_ < 6 || !secret_) {
_GTMDevLog(@"Bad args digits(min 6, max 8): %d secret: %@ algorithm: %@",
digits_, secret_, algorithm_);
[self release];
self = nil;
}
}
return self;
}
- (void)dealloc {
self.algorithm = nil;
self.secret = nil;
[super dealloc];
}
// Must be overriden by subclass.
- (NSString *)generateOTP {
[self doesNotRecognizeSelector:_cmd];
return nil;
}
- (NSString *)generateOTPForCounter:(uint64_t)counter {
CCHmacAlgorithm alg;
NSUInteger hashLength = 0;
if ([algorithm_ isEqualToString:kOTPGeneratorSHA1Algorithm]) {
alg = kCCHmacAlgSHA1;
hashLength = CC_SHA1_DIGEST_LENGTH;
} else if ([algorithm_ isEqualToString:kOTPGeneratorSHA256Algorithm]) {
alg = kCCHmacAlgSHA256;
hashLength = CC_SHA256_DIGEST_LENGTH;
} else if ([algorithm_ isEqualToString:kOTPGeneratorSHA512Algorithm]) {
alg = kCCHmacAlgSHA512;
hashLength = CC_SHA512_DIGEST_LENGTH;
} else if ([algorithm_ isEqualToString:kOTPGeneratorSHAMD5Algorithm]) {
alg = kCCHmacAlgMD5;
hashLength = CC_MD5_DIGEST_LENGTH;
} else {
_GTMDevAssert(NO, @"Unknown algorithm");
return nil;
}
NSMutableData *hash = [NSMutableData dataWithLength:hashLength];
counter = NSSwapHostLongLongToBig(counter);
NSData *counterData = [NSData dataWithBytes:&counter
length:sizeof(counter)];
CCHmacContext ctx;
CCHmacInit(&ctx, alg, [secret_ bytes], [secret_ length]);
CCHmacUpdate(&ctx, [counterData bytes], [counterData length]);
CCHmacFinal(&ctx, [hash mutableBytes]);
const char *ptr = [hash bytes];
unsigned char offset = ptr[hashLength-1] & 0x0f;
unsigned long truncatedHash =
NSSwapBigLongToHost(*((unsigned long *)&ptr[offset])) & 0x7fffffff;
unsigned long pinValue = truncatedHash % kPinModTable[digits_];
_GTMDevLog(@"secret: %@", secret_);
_GTMDevLog(@"counter: %llu", counter);
_GTMDevLog(@"hash: %@", hash);
_GTMDevLog(@"offset: %d", offset);
_GTMDevLog(@"truncatedHash: %d", truncatedHash);
_GTMDevLog(@"pinValue: %d", pinValue);
return [NSString stringWithFormat:@"%0*d", digits_, pinValue];
}
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPGenerator.m | Objective-C | asf20 | 4,302 |
//
// OTPWelcomeViewController.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 "OTPWelcomeViewController.h"
#import "GTMLocalizedString.h"
#import "OTPAuthAppDelegate.h"
@implementation OTPWelcomeViewController
@synthesize welcomeText = welcomeText_;
- (id)init {
if ((self = [super initWithNibName:@"OTPWelcomeViewController" bundle:nil])) {
self.hidesBottomBarWhenPushed = YES;
}
return self;
}
- (void)dealloc {
self.welcomeText = nil;
[super dealloc];
}
- (void)viewWillAppear:(BOOL)animated {
UINavigationItem *navItem = [self navigationItem];
NSString *title = GTMLocalizedString(@"Welcome", @"Title for welcome screen");
navItem.title = title;
navItem.hidesBackButton = YES;
UIBarButtonItem *button
= [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:nil
action:@selector(addAuthURL:)]
autorelease];
[navItem setRightBarButtonItem:button animated:NO];
NSString *label = GTMLocalizedString(@"Welcome_label", @"Welcome text");
welcomeText_.text = label;
}
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPWelcomeViewController.m | Objective-C | asf20 | 1,722 |
//
// 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();
| zy19820306-google-authenticator | mobile/ios/Classes/UIColor+MobileColors.h | Objective-C | asf20 | 1,219 |
//
// OTPAuthAppDelegate.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 "RootViewController.h"
#import "OTPAuthURLEntryController.h"
typedef enum {
kOTPNotEditing,
kOTPEditingSingleRow,
kOTPEditingTable
} OTPEditingState;
@interface OTPAuthAppDelegate : NSObject
<UIApplicationDelegate,
OTPAuthURLEntryControllerDelegate,
UITableViewDataSource,
UITableViewDelegate,
UIActionSheetDelegate,
UIAlertViewDelegate>
@property(nonatomic, retain) IBOutlet UINavigationController *navigationController;
@property(nonatomic, retain) IBOutlet UIWindow *window;
@property(nonatomic, retain) IBOutlet UINavigationController *authURLEntryController;
@property(nonatomic, retain) IBOutlet UIBarButtonItem *legalButton;
@property(nonatomic, retain) IBOutlet UINavigationItem *navigationItem;
@property(nonatomic, retain) IBOutlet UINavigationItem *authURLEntryNavigationItem;
- (IBAction)addAuthURL:(id)sender;
- (IBAction)showLegalInformation:(id)sender;
@end
| zy19820306-google-authenticator | mobile/ios/Classes/OTPAuthAppDelegate.h | Objective-C | asf20 | 1,546 |
//
// TOTPGeneratorTest.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 "TOTPGenerator.h"
#import <SenTestingKit/SenTestingKit.h>
@interface TOTPGeneratorTest : SenTestCase
- (void)testTOTP;
@end
@implementation TOTPGeneratorTest
// http://www.ietf.org/rfc/rfc4226.txt
// Appendix B. Test Vectors
// Only SHA1 defined in test vectors.
- (void)testTOTP {
NSString *secret = @"12345678901234567890";
NSData *secretData = [secret dataUsingEncoding:NSASCIIStringEncoding];
NSTimeInterval intervals[] = { 1111111111, 1234567890, 2000000000 };
NSArray *algorithms = [NSArray arrayWithObjects:
kOTPGeneratorSHA1Algorithm,
kOTPGeneratorSHA256Algorithm,
kOTPGeneratorSHA512Algorithm,
kOTPGeneratorSHAMD5Algorithm,
nil];
NSArray *results = [NSArray arrayWithObjects:
// SHA1 SHA256 SHA512 MD5
@"050471", @"584430", @"380122", @"275841", // date1
@"005924", @"829826", @"671578", @"280616", // date2
@"279037", @"428693", @"464532", @"090484", // date3
nil];
for (size_t i = 0, j = 0; i < sizeof(intervals)/sizeof(*intervals); i++) {
for (NSString *algorithm in algorithms) {
TOTPGenerator *generator
= [[[TOTPGenerator alloc] initWithSecret:secretData
algorithm:algorithm
digits:6
period:30] autorelease];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:intervals[i]];
STAssertEqualObjects([results objectAtIndex:j],
[generator generateOTPForDate:date],
@"Invalid result %d, %@, %@", i, algorithm, date);
j = j + 1;
}
}
}
@end
| zy19820306-google-authenticator | mobile/ios/Classes/TOTPGeneratorTest.m | Objective-C | asf20 | 2,480 |
//
// 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;
}
| zy19820306-google-authenticator | mobile/ios/Classes/UIColor+MobileColors.m | Objective-C | asf20 | 4,313 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta content="text/html; charset=UTF-8" http-equiv="content-type"><title>Barcode Hints</title>
<style type="text/css">
</style>
<meta name="viewport" content="width=device-width; initial-scale=1.0">
</head>
<body style="background-color: #EBEFF9; color: #335599; font-family: sans-serif;">
<p>The iPhone camera has a fixed focus depth which is not ideal for scanning
barcodes. Anything that is too close to the camera will look fuzzy and may be
difficult to decode. For best results:
</p>
<ul>
<li>Take the picture from a distance of at least 2 feet / 60 cm.</li>
<li>Use the
<span style="font-style: italic;">Scale and Move</span>
features to make the barcode as large and clear as possible.</li>
</ul>
</body>
</html>
| zy19820306-google-authenticator | mobile/ios/Resources/Hints.html | HTML | asf20 | 845 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Legal Notices</title>
</head>
<body>
<p>Authenticator © 2010 Google Inc.</p>
<hr />
<p><a href="http://code.google.com/p/zxing/">ZXing</a> Copyright ZXing authors</p>
<p></p>
<p>Licensed under the Apache License, Version 2.0 (the "License").
You may obtain a copy of the License at</p>
<p></p>
<p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p>
<p></p>
<p>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.</p>
<hr />
<p><a href="http://code.google.com/p/google-toolbox-for-mac/">Google Toolbox For Mac</a> Copyright Google Inc.</p>
<p></p>
<p>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</p>
<p></p>
<p><a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a></p>
<p></p>
<p>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.</p>
</body>
</html>
| zy19820306-google-authenticator | mobile/ios/Resources/English.lproj/LegalNotices.html | HTML | asf20 | 1,663 |
//
// 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;
}
| zy19820306-google-authenticator | mobile/ios/main.m | Objective-C | asf20 | 839 |
/*-
* 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;
}
}
| zy19820306-google-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.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);
}
}
| zy19820306-google-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.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;
}
}
}
| zy19820306-google-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.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();
}
| zy19820306-google-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.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);
}
}
| zy19820306-google-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;
/**
* all parameter classes implement this.
*/
public interface CipherParameters
{
}
| zy19820306-google-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;
/**
* 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);
}
}
| zy19820306-google-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;
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();
}
| zy19820306-google-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;
/**
* 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();
}
| zy19820306-google-authenticator | mobile/blackberry/src/org/bouncycastle/crypto/Digest.java | Java | asf20 | 2,507 |
/*-
* 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();
}
| zy19820306-google-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;
/**
* 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);
}
}
| zy19820306-google-authenticator | mobile/blackberry/src/org/bouncycastle/crypto/RuntimeCryptoException.java | Java | asf20 | 1,694 |
/*-
* 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 <scheme>://<authority><absolute path>?<query>#<fragment>}
*
* <p>Relative URI references (which are always hierarchical) follow one
* of two patterns: {@code <relative or absolute path>?<query>#<fragment>}
* or {@code //<authority><absolute path>?<query>#<fragment>}
*
* <p>An opaque URI follows this pattern:
* {@code <scheme>:<opaque part>#<fragment>}
*/
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();
}
}
| zy19820306-google-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;
}
}
| zy19820306-google-authenticator | mobile/blackberry/src/com/google/authenticator/blackberry/EnterKeyScreen.java | Java | asf20 | 6,242 |
/*-
* 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);
}
}
}
| zy19820306-google-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;
}
}
| zy19820306-google-authenticator | mobile/blackberry/src/com/google/authenticator/blackberry/PinListFieldCallback.java | Java | asf20 | 3,531 |
/*-
* 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();
}
}
}
| zy19820306-google-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.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);
}
}
| zy19820306-google-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 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);
}
}
}
| zy19820306-google-authenticator | mobile/blackberry/src/com/google/authenticator/blackberry/UpdateTask.java | Java | asf20 | 6,326 |
/*-
* 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("file.java"));
* </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;
}
}
}
| zy19820306-google-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 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() {
}
}
| zy19820306-google-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;
/**
* 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);
}
} | zy19820306-google-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;
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);
}
}
| zy19820306-google-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;
/**
* Callback interface for {@link UpdateTask}.
*/
public interface UpdateCallback {
void onUpdate(String version);
}
| zy19820306-google-authenticator | mobile/blackberry/src/com/google/authenticator/blackberry/UpdateCallback.java | Java | asf20 | 762 |
/*-
* 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));
}
}
}
| zy19820306-google-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;
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...&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;
}
}
| zy19820306-google-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 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...&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;
}
} | zy19820306-google-authenticator | mobile/blackberry/src/com/google/authenticator/blackberry/UriStringPattern.java | Java | asf20 | 2,389 |
/*-
* 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;
}
}
| zy19820306-google-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 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();
}
}
| zy19820306-google-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;
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();
}
}
| zy19820306-google-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 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();
}
}
| zy19820306-google-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 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);
}
}
| zy19820306-google-authenticator | mobile/blackberry/src/com/google/authenticator/blackberry/UriActiveFieldCookie.java | Java | asf20 | 1,351 |
using namespace System;
enum class NType
{
GATE,
PI,
FB,
PO,
PPI,
PPO
};
enum class GType
{
IPT, BRCH,
INVX1, INVX2, INVX4, INVX8,
AND2X1, AND2X2,
NAND2X1, NAND3X1,
OR2X1, OR2X2,
NOR2X1, NOR3X1,
XOR2X1, XNOR2X1,
AOI21X1, AOI22X1,
OAI21X1, OAI22X1,
DFFNEGX1, DFFPOSX1, DFFSR
};
| zzspring2012logicsim | trunk/type.h | C++ | gpl3 | 322 |
#include "Node.h"
using namespace System;
using namespace System::Collections;
ref class Global
{
public:
static array<Node^>^ nodeAll;
static array<Node^>^ nodeInput;
static array<Node^>^ nodeOutput;
static Hashtable^ nodeFF;
};
| zzspring2012logicsim | trunk/global.h | C++ | gpl3 | 249 |
#include "global.h"
using namespace std;
Node** nodeAll;
Node** nodeInput;
Node** nodeOutput;
int allCount;
int inputCount;
int outputCount;
int wireCount;
int maxLevel;
map<GType, string> gMap;
map<NType, string> nMap;
map<LType, string> lMap;
map<KWord, string> kMap;
thrust::host_vector<devNode>* gMatrix;
thrust::host_vector<devNode>* test;
thrust::host_vector<devNode*> stem_host;
thrust::device_vector<devNode*> stem_device;
vector<module*> moduleAll;
int* matrix;
| zzspring2012logicsim | trunk/native/global.cpp | C++ | gpl3 | 477 |
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>
cudaError_t addWithCuda(int *c, const int *a, const int *b, size_t size);
__global__ void addKernel(int *c, const int *a, const int *b)
{
int i = threadIdx.x;
c[i] = a[i] + b[i];
}
int main()
{
const int arraySize = 5;
const int a[arraySize] = { 1, 2, 3, 4, 5 };
const int b[arraySize] = { 10, 20, 30, 40, 50 };
int c[arraySize] = { 0 };
// Add vectors in parallel.
cudaError_t cudaStatus = addWithCuda(c, a, b, arraySize);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "addWithCuda failed!");
return 1;
}
printf("{1,2,3,4,5} + {10,20,30,40,50} = {%d,%d,%d,%d,%d}\n",
c[0], c[1], c[2], c[3], c[4]);
// cudaDeviceReset must be called before exiting in order for profiling and
// tracing tools such as Parallel Nsight and Visual Profiler to show complete traces.
cudaStatus = cudaDeviceReset();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceReset failed!");
return 1;
}
return 0;
}
// Helper function for using CUDA to add vectors in parallel.
cudaError_t addWithCuda(int *c, const int *a, const int *b, size_t size)
{
int *dev_a = 0;
int *dev_b = 0;
int *dev_c = 0;
cudaError_t cudaStatus;
// Choose which GPU to run on, change this on a multi-GPU system.
cudaStatus = cudaSetDevice(0);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaSetDevice failed! Do you have a CUDA-capable GPU installed?");
goto Error;
}
// Allocate GPU buffers for three vectors (two input, one output) .
cudaStatus = cudaMalloc((void**)&dev_c, size * sizeof(int));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!");
goto Error;
}
cudaStatus = cudaMalloc((void**)&dev_a, size * sizeof(int));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!");
goto Error;
}
cudaStatus = cudaMalloc((void**)&dev_b, size * sizeof(int));
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMalloc failed!");
goto Error;
}
// Copy input vectors from host memory to GPU buffers.
cudaStatus = cudaMemcpy(dev_a, a, size * sizeof(int), cudaMemcpyHostToDevice);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!");
goto Error;
}
cudaStatus = cudaMemcpy(dev_b, b, size * sizeof(int), cudaMemcpyHostToDevice);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!");
goto Error;
}
// Launch a kernel on the GPU with one thread for each element.
addKernel<<<1, size>>>(dev_c, dev_a, dev_b);
// cudaDeviceSynchronize waits for the kernel to finish, and returns
// any errors encountered during the launch.
cudaStatus = cudaDeviceSynchronize();
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaDeviceSynchronize returned error code %d after launching addKernel!\n", cudaStatus);
goto Error;
}
// Copy output vector from GPU buffer to host memory.
cudaStatus = cudaMemcpy(c, dev_c, size * sizeof(int), cudaMemcpyDeviceToHost);
if (cudaStatus != cudaSuccess) {
fprintf(stderr, "cudaMemcpy failed!");
goto Error;
}
Error:
cudaFree(dev_c);
cudaFree(dev_a);
cudaFree(dev_b);
return cudaStatus;
}
| zzspring2012logicsim | trunk/native/kernel.cu | Cuda | gpl3 | 3,553 |
/*
* File: devNode.cpp
* Author: zhouzhao
*
* Created on December 25, 2011, 1:25 PM
*/
#include "devNode.h"
| zzspring2012logicsim | trunk/native/devNode.cpp | C++ | gpl3 | 119 |
#include "cuda.h"
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <queue>
#include <assert.h>
#include <stdlib.h>
using namespace std;
__global__ void initKernel(devNode** dev_ptr, int* matrix_d, int cycle, int depth){
int tid = blockIdx.x * 512 + threadIdx.x;
if(tid < depth){
if(matrix_d[cycle*depth+tid] == 0){
dev_ptr[0][tid].setLogic(ZERO);
}else{
dev_ptr[0][tid].setLogic(ONE);
}
}
}
__global__ void simKernel(devNode** dev_ptr, int level, int depth){
int tid = blockIdx.x * 512 + threadIdx.x;
int logic = X;
int gate;
int fLevelA, fLevelB, fLevelC, fLevelD;
int faninA, faninB, faninC, faninD;
if(tid < depth){
gate = dev_ptr[level][tid].getGate();
if(gate == INVX1 || gate == INVX2 || gate == INVX4 || gate == INVX8){
fLevelA = dev_ptr[level][tid].getLevel(0);
faninA = dev_ptr[level][tid].getFanin(0);
logic = ~(dev_ptr[fLevelA][faninA].getLogic());
}else if(gate == AND2X1 || gate == AND2X2 || gate == HAC){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic();
}else if(gate == NAND2X1){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic());
}else if(gate == NAND3X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic() &
dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == OR2X1 || gate == OR2X2){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic();
}else if(gate == NOR2X1){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic());
}else if(gate == NOR3X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic() |
dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == XOR2X1 || gate == HAS){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = dev_ptr[fLevelA][faninA].getLogic() ^ dev_ptr[fLevelB][faninB].getLogic();
}else if(gate == XNOR2X1){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() ^ dev_ptr[fLevelB][faninB].getLogic());
}else if(gate == AOI21X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ~((dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic()) |
dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == AOI22X1){
fLevelD = dev_ptr[level][tid].getLevel(0);
faninD = dev_ptr[level][tid].getFanin(0);
fLevelC = dev_ptr[level][tid].getLevel(1);
faninC = dev_ptr[level][tid].getFanin(1);
fLevelB = dev_ptr[level][tid].getLevel(2);
faninB = dev_ptr[level][tid].getFanin(2);
fLevelA = dev_ptr[level][tid].getLevel(3);
faninA = dev_ptr[level][tid].getFanin(3);
logic = ~((dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic()) |
(dev_ptr[fLevelC][faninC].getLogic() & dev_ptr[fLevelD][faninD].getLogic()));
}else if(gate == OAI21X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ~((dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic()) &
dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == OAI22X1){
fLevelD = dev_ptr[level][tid].getLevel(0);
faninD = dev_ptr[level][tid].getFanin(0);
fLevelC = dev_ptr[level][tid].getLevel(1);
faninC = dev_ptr[level][tid].getFanin(1);
fLevelB = dev_ptr[level][tid].getLevel(2);
faninB = dev_ptr[level][tid].getFanin(2);
fLevelA = dev_ptr[level][tid].getLevel(3);
faninA = dev_ptr[level][tid].getFanin(3);
logic = ~((dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic()) &
(dev_ptr[fLevelC][faninC].getLogic() | dev_ptr[fLevelD][faninD].getLogic()));
}else if(gate == BUFX2 || gate == BUFX4){
fLevelA = dev_ptr[level][tid].getLevel(0);
faninA = dev_ptr[level][tid].getFanin(0);
logic = dev_ptr[fLevelA][faninA].getLogic();
}else if(gate == FAS){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = (dev_ptr[fLevelA][faninA].getLogic()) ^ (dev_ptr[fLevelB][faninB].getLogic()) ^
(dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == FAC){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ((dev_ptr[fLevelA][faninA].getLogic()) & (dev_ptr[fLevelB][faninB].getLogic())) |
((dev_ptr[fLevelA][faninA].getLogic()) & (dev_ptr[fLevelC][faninC].getLogic())) |
((dev_ptr[fLevelB][faninB].getLogic()) & (dev_ptr[fLevelC][faninC].getLogic()));
}else if(gate == MUX2X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
if(dev_ptr[fLevelC][faninC].getLogic() == ZERO){
logic = dev_ptr[fLevelB][faninB].getLogic();
}else{
logic = dev_ptr[fLevelA][faninA].getLogic();
}
}
dev_ptr[level][tid].setLogic((LType)(logic & 3));
}
}
__global__ void ffKernel(devNode** dev_ptr, int depth){
int tid = blockIdx.x * 512 + threadIdx.x;
int level, offset;
if(tid < depth){
if(dev_ptr[0][tid].getType() == PPI){
level = dev_ptr[0][tid].getLevel(0);
offset = dev_ptr[0][tid].getFanin(0);
dev_ptr[0][tid].setLogic(dev_ptr[level][offset].getLogic());
}
}
}
//check if node is ready to compute its offset
int nodeOffsetReady(Node* np){
int flag = 1;
vector<Node*>::iterator it;
for(it = np->upperNodes.begin(); it < np->upperNodes.end(); it++){
if((*it)->offset == -1){
flag = 0;
break;
}
}
return flag;
}
void transform(){
queue<Node*> nodeQ;
vector<Node*>::iterator it, itf;
map<Node*, Node*>::iterator itt;
Node* np;
devNode* dp;
module* mp = moduleAll.back();
Node** npp = mp->nInput;
gMatrix = new thrust::host_vector<devNode> [maxLevel + 1];
ptrMatrix = new vector<Node*> [maxLevel + 1];
//process all input nodes of top module
for(int i = 0; i < mp->inputNum; i++){
ptrMatrix[0].push_back(npp[i]);
npp[i]->offset = gMatrix[0].size();
gMatrix[0].push_back(devNode(npp[i]->modIndex, npp[i]->index, npp[i]->type, npp[i]->gate, npp[i]->fanin));
for(it = npp[i]->downNodes.begin(); it < npp[i]->downNodes.end(); it++){
if(nodeOffsetReady((*it))){
nodeQ.push((*it));
}
}
}
//process flip flop of all modules
for(int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itt = mp->ffMap.begin(); itt != mp->ffMap.end(); itt++){
np = (*itt).second;
ptrMatrix[0].push_back(np);
np->offset = gMatrix[0].size();
dp = new devNode(np->modIndex, np->index, np->type, np->gate, np->fanin);
gMatrix[0].push_back(*dp);
for(it = np->downNodes.begin(); it < np->downNodes.end(); it++){
if(nodeOffsetReady((*it))){
nodeQ.push((*it));
}
}
}
}
//process dummy nodes of all modules
for(int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itf = mp->nFloat.begin(); itf < mp->nFloat.end(); itf++){
ptrMatrix[0].push_back((*itf));
(*itf)->offset = gMatrix[0].size();
gMatrix[0].push_back(devNode((*itf)->modIndex, (*itf)->index, (*itf)->type, (*itf)->gate, (*itf)->fanin, (*itf)->logic));
for(it = (*itf)->downNodes.begin(); it < (*itf)->downNodes.end(); it++){
if(nodeOffsetReady((*it))){
nodeQ.push((*it));
}
}
}
}
//process the queue
while (nodeQ.size() != 0) {
np = nodeQ.front();
nodeQ.pop();
np->offset = gMatrix[np->level].size();
dp = new devNode(np->modIndex, np->index, np->type, np->gate, np->fanin);
for(int i = 0; i < np->fanin; i++){
dp->setLevel(i, np->upperNodes[i]->level);
dp->setFanin(i, np->upperNodes[i]->offset);
}
gMatrix[np->level].push_back(*dp);
ptrMatrix[np->level].push_back(np);
for(it = np->downNodes.begin(); it < np->downNodes.end(); it++){
if(nodeOffsetReady((*it))){
nodeQ.push((*it));
}
}
}
//process flip flop's fanin of all modules
for(int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itt = mp->ffMap.begin(); itt != mp->ffMap.end(); itt++){
np = (*itt).second;
gMatrix[np->level][np->offset].setLevel(0, (*itt).first->level);
gMatrix[np->level][np->offset].setFanin(0, (*itt).first->offset);
}
}
}
int findBias(int level, int index){
int bias = -1;
for(int i = 0; i < gMatrix[level].size(); i++){
if(gMatrix[level][i].getIndex() == index){
bias = i;
break;
}
}
return bias;
}
//sequential update fanin
void updateFanin(){
Node* np;
int bias = -1;
int level;
for(int i = 1; i <= maxLevel; i++){
for(int j = 0; j < gMatrix[i].size(); j++){
np = nodeAll[gMatrix[i][j].getIndex()];
for(int k = 0; k < np->fanin; k++){
level = i - 1;
while((bias = findBias(level, np->upperNodes[k]->index)) == -1
&& level >= 0){
level--;
}
gMatrix[i][j].setFanin(k, bias);
gMatrix[i][j].setLevel(k, level);
}
}
}
}
void cudaLogicSim(){
ofstream result;
int depth, grid;
devNode** temp;
int* matrix_dev;
module* mp = moduleAll.back();
test = new thrust::host_vector<devNode> [maxLevel+1];
cudaMalloc((void**)&matrix_dev, (mp->inputNum)*MAXCYCLE*sizeof(int));
cudaMemcpy(matrix_dev, matrix, (mp->inputNum)*MAXCYCLE*sizeof(int), cudaMemcpyHostToDevice);
for(int i = 0; i < gMatrix[0].size(); i++){
if(gMatrix[0][i].getType() == PPI){
gMatrix[0][i].setLogic(ZERO);
}
}
//copy all vectors in gMatrix from main memory into device memory
stem_host.resize(maxLevel + 1);
for(int i = 0; i <= maxLevel; i++){
cudaMalloc((void**)&stem_host[i], gMatrix[i].size() * sizeof(devNode));
thrust::device_ptr<devNode> dev_ptr(stem_host[i]); //change raw pointer into thrust pointer
thrust::copy(gMatrix[i].begin(), gMatrix[i].end(), dev_ptr); //thrust copy is used
}
//copy reference of all vectors from main memory into device memory
cudaMalloc(&temp, stem_host.size()*sizeof(devNode*));
devNode** raw_ptr = thrust::raw_pointer_cast(&stem_host[0]); //change thrust pointer into raw pointer
cudaMemcpy(temp, raw_ptr, stem_host.size()*sizeof(devNode*), cudaMemcpyHostToDevice);
//issue series of kernel calls
for(int i = 0; i < MAXCYCLE; i++){
// cout<<"cuda simulate cycle "<<i<<endl;
depth = mp->inputNum;
grid = depth/512 + 1;
initKernel<<<grid, 512>>>(temp, matrix_dev, i, depth);
for(int j = 1; j <= maxLevel; j++){
depth = gMatrix[j].size();
grid = depth/512 + 1;
simKernel<<<grid, 512>>>(temp, j, depth);
}
depth = gMatrix[0].size();
grid = depth/512 + 1;
if(i != MAXCYCLE-1){
ffKernel<<<grid, 512>>>(temp, depth);
}
}
//copy all results from device memory back to main memory and then print
result.open("cuda.txt");
for(int i = 0; i <= maxLevel; i++){
thrust::device_ptr<devNode> dev_ptr_new(stem_host[i]);
test[i].resize(gMatrix[i].size());
// thrust::copy_n(dev_ptr_new, gMatrix[i].size(), test[i].begin()); //thrust copy is used
}
for(int i = 0; i <= maxLevel; i++){
for(int j = 0; j < gMatrix[i].size(); j++){
result<<test[i][j].getIndex()<<"->"<<lMap[test[i][j].getLogic()]<<" ";
}
result<<endl;
}
result.close();
//free all memory allocated on device memory
for(int i = 0; i <= maxLevel; i++){
cudaFree(stem_host[i]);
}
cudaFree(temp);
cudaFree(matrix_dev);
}
void cudaVerify(){
Node* np;
int flag = 1;
cout<<"cuda verify is starting ..."<<endl;
for(int i = 0; i < moduleAll.size(); i++){
for(int j = 0; j < moduleAll[i]->allNum; j++){
np = moduleAll[i]->nAll[j];
// cout<<np->name<<endl;
if(np->level != -1) np->cudaLogic = test[np->level][np->offset].getLogic();
if(np->cudaLogic != np->logic) flag = 0;
}
}
if(flag){
cout<<"Pass!"<<endl;
}else{
cout<<"Fail!"<<endl;
}
}
void cudaSimTest(int a, int b){
long long result = 0;
int temp;
int tempa = a;
int tempb = b;
time_t start, end;
double diff;
for(int i = 0; i < 24; i++){
temp = a & 1;
if(temp == 0){
gMatrix[0][i].setLogic(ZERO);
}else{
gMatrix[0][i].setLogic(ONE);
}
a = a >> 1;
}
for(int i = 24; i < 48; i++){
temp = b & 1;
if(temp == 0){
gMatrix[0][i].setLogic(ZERO);
}else{
gMatrix[0][i].setLogic(ONE);
}
b = b >> 1;
}
time(&start);
cudaLogicSim();
time(&end);
diff = difftime(end, start);
for(int i = 47; i >= 0; i--){
if(nodeOutput[i]->cudaLogic == ZERO){
result = result & 0xfffffffffffffffeLL;
}else if(nodeOutput[i]->cudaLogic == ONE){
result = result | 1;
}
result = result << 1;
}
cout<<tempa<<" * "<<tempb<<" = "<<result<<endl;
printf("GPU took %.5f seconds to do logic simulation\n", diff);
}
| zzspring2012logicsim | trunk/native/cuda.cu | Cuda | gpl3 | 17,857 |
#include <string>
#include "node.h"
Node::Node(int modIndex, int index, string name, NType type, int busIndex){
this->modIndex = modIndex;
this->index = index;
this->busIndex = busIndex;
this->name = name;
this->type = type;
this->gate = NA;
this->fanin = 0;
this->fanout = 0;
this->level = -1;
this->offset = -1;
this->logic = X;
this->cudaLogic = X;
this->touch = false;
}
| zzspring2012logicsim | trunk/native/node.cpp | C++ | gpl3 | 439 |
#include "vertex.h"
vertex::vertex(void)
{
this->topLevel = -1;
this->bottomLevel = -1;
this->subckt = NULL;
this->subptr = NULL;
this->vptr = NULL;
}
vertex::~vertex(void)
{
}
| zzspring2012logicsim | trunk/native/vertex.cpp | C++ | gpl3 | 198 |
/*
* File: type.h
* Author: zhouzhao
*
* Created on December 21, 2011, 1:38 PM
*/
#ifndef TYPE_H
#define TYPE_H
enum NType {
GATE, PI, FB, PO, PPI, PPO, DUMMY
};
enum GType
{
IPT, BRCH,
INVX1, INVX2, INVX4, INVX8,
AND2X1, AND2X2,
NAND2X1, NAND3X1,
OR2X1, OR2X2,
NOR2X1, NOR3X1,
XOR2X1, XNOR2X1,
AOI21X1, AOI22X1,
OAI21X1, OAI22X1,
DFFNEGX1, DFFPOSX1, DFFSR,
BUFX2, BUFX4,
FAX1, FAC, FAS, //FAC = full adder carry; FAS = full adder sum
HAX1, HAC, HAS, //HAC = half adder carry; HAS = half adder sum
MUX2X1, NA
};
//ZERO = 0; DBAR = 1; D = 2; ONE = 3; X = 4;
enum LType
{
ZERO, DBAR, D, ONE, X
};
enum KWord{
MODULE, INPUT, OUTPUT, WIRE, ASSIGN, ENDMODULE
};
#endif /* TYPE_H */
| zzspring2012logicsim | trunk/native/type.h | C | gpl3 | 816 |
#pragma once
#include <thrust/host_vector.h>
#include "node.h"
#include "devNode.h"
class vertex
{
public:
vertex(void);
~vertex(void);
thrust::host_vector<devNode>* subckt;
vector<Node*>* subptr;
int topLevel;
int bottomLevel;
Node* vptr;
};
| zzspring2012logicsim | trunk/native/vertex.h | C++ | gpl3 | 273 |
#include "partition.h"
using namespace std;
//reset touch of nodes in partition
void resetTouch(int topLevel, int bottomLevel){
for(int i = topLevel; i <= bottomLevel; i++){
for(unsigned int j = 0; j < ptrMatrix[i].size(); j++){
ptrMatrix[i][j]->touch = false;
}
}
}
vector<Node*>* ptrTransform(Node* np, int topLevel){
queue<Node*> nodeQ;
Node* nptr;
vector<Node*>::iterator it;
assert(topLevel < np->level);
vector<Node*>* subPtr = new vector<Node*> [np->level - topLevel + 1];
resetTouch(0, np->level);
nodeQ.push(np);
while(nodeQ.size() != 0){
nptr = nodeQ.front();
nodeQ.pop();
if(nptr->level >= topLevel){
subPtr[nptr->level - topLevel].push_back(nptr);
if(nptr->level != topLevel){
for(it = nptr->upperNodes.begin(); it < nptr->upperNodes.end(); it++){
if(!(*it)->touch){
nodeQ.push((*it));
(*it)->touch = true;
}
}
}
}else{
subPtr[0].push_back(nptr);
}
}
return subPtr;
}
thrust::host_vector<devNode>* faninTransform(Node* np, int topLevel){
queue<Node*> nodeQ;
Node* nptr;
devNode* dp;
vector<Node*>::iterator it;
assert(topLevel < np->level);
thrust::host_vector<devNode>* subMatrix = new thrust::host_vector<devNode> [np->level - topLevel + 1];
resetTouch(0, np->level);
//initialize the queue
nodeQ.push(np);
//process the queue
while(nodeQ.size() != 0){
nptr = nodeQ.front();
nodeQ.pop();
if(nptr->level >= topLevel){
nptr->offset = subMatrix[nptr->level - topLevel].size();
dp = new devNode(nptr->modIndex, nptr->index, nptr->type, nptr->gate, nptr->fanin);
subMatrix[nptr->level - topLevel].push_back(*dp);
//only the fanin of node whose level is higher than top level will be pushed into queue
if(nptr->level != topLevel){
for(it = nptr->upperNodes.begin(); it < nptr->upperNodes.end(); it++){
if(!(*it)->touch){
nodeQ.push((*it));
(*it)->touch = true;
}
}
}
}else{
//handle the case when fanin node is above partition level
nptr->offset = subMatrix[0].size();
dp = new devNode(nptr->modIndex, nptr->index, nptr->type, nptr->gate, nptr->fanin);
subMatrix[0].push_back(*dp);
}
}
resetTouch(0, np->level);
//re-process queue to update fanin of each node
nodeQ.push(np);
while(nodeQ.size() != 0){
nptr = nodeQ.front();
nodeQ.pop();
if(nptr->level > topLevel){
for(int i = 0; i < nptr->fanin; i++){
if(nptr->upperNodes[i]->level >= topLevel){
subMatrix[nptr->level - topLevel][nptr->offset].setLevel(i, nptr->upperNodes[i]->level - topLevel);
subMatrix[nptr->level - topLevel][nptr->offset].setFanin(i, nptr->upperNodes[i]->offset);
}else{
subMatrix[nptr->level - topLevel][nptr->offset].setLevel(i, 0);
subMatrix[nptr->level - topLevel][nptr->offset].setFanin(i, nptr->upperNodes[i]->offset);
}
}
for(it = nptr->upperNodes.begin(); it < nptr->upperNodes.end(); it++){
if(!(*it)->touch){
nodeQ.push((*it));
(*it)->touch = true;
}
}
}
}
return subMatrix;
}
void printVertex(vertex* vp){
ofstream vResult;
vResult.open("partition.txt", ofstream::app);
vResult<<"subcircuit at vertex of "<<vp->vptr->index<<endl;
for(int i = 0; i <= vp->bottomLevel - vp->topLevel; i++){
for(unsigned int j = 0; j < vp->subckt[i].size(); j++){
vResult<<vp->subckt[i][j].getIndex()<<" ";
}
vResult<<endl;
}
vResult<<endl;
vResult.close();
}
void printVertexPtr(vertex* vp){
ofstream vResult;
vResult.open("partition_ptr.txt", ofstream::app);
vResult<<"subcircuit at vertex of "<<vp->vptr->index<<endl;
for(int i = 0; i <= vp->bottomLevel - vp->topLevel; i++){
for(unsigned int j = 0; j < vp->subptr[i].size(); j++){
vResult<<vp->subptr[i][j]->index<<" ";
}
vResult<<endl;
}
vResult<<endl;
vResult.close();
}
void printPartition(){
map<int, vector<vertex> >::iterator mit;
vertex* vp;
ofstream pResult;
pResult.open("partition.txt", ofstream::out);
pResult<<endl;
pResult.close();
for(mit = nPartition.begin(); mit != nPartition.end(); mit++){
pResult.open("partition.txt", ofstream::app);
pResult<<"the subcircuit below is partition at level "<<(*mit).first<<endl;
pResult.close();
for(unsigned int i = 0; i < (*mit).second.size(); i++){
vp = &((*mit).second[i]);
printVertex(vp);
}
}
}
void printPartitionPtr(){
map<int, vector<vertex> >::iterator mit;
vertex* vp;
ofstream pResult;
pResult.open("partition_ptr.txt", ofstream::out);
pResult<<endl;
pResult.close();
for(mit = nPartition.begin(); mit != nPartition.end(); mit++){
pResult.open("partition_ptr.txt", ofstream::app);
pResult<<"the subcircuit below is partition at level "<<(*mit).first<<endl;
pResult.close();
for(unsigned int i = 0; i < (*mit).second.size(); i++){
vp = &((*mit).second[i]);
printVertexPtr(vp);
}
}
}
void partitionBuild(int level){
/*
vertex v1399;
Node* np = moduleAll[0]->nAll[1399];
faninTransform(np, 22, v1399.subckt);
*/
vertex* vp;
vector<vertex> temp;
vector<vertex>::iterator it;
Node* np;
/*
for(unsigned int i = 0; i < ptrMatrix[level].size(); i++){
vp = new vertex();
vp->subckt = faninTransform(ptrMatrix[level][i], 0);
vp->subptr = ptrTransform(ptrMatrix[level][i], 0);
vp->topLevel = 0;
vp->bottomLevel = level;
vp->vptr = ptrMatrix[level][i];
temp.push_back(*vp);
}
nPartition.insert(pair<int, vector<vertex> >(level, temp));
*/
for(unsigned int i = 0; i < ptrMatrix[maxLevel].size(); i++){
vp = new vertex();
vp->subckt = faninTransform(ptrMatrix[maxLevel][i], level);
vp->subptr = ptrTransform(ptrMatrix[maxLevel][i], level);
vp->topLevel = level;
vp->bottomLevel = maxLevel;
vp->vptr = ptrMatrix[maxLevel][i];
temp.push_back(*vp);
}
nPartition.insert(pair<int, vector<vertex> >(maxLevel, temp));
temp.clear();
resetTouch(0, level);
for(it = nPartition[maxLevel].begin(); it < nPartition[maxLevel].end(); it++){
for(int i = 0; i < (*it).subptr[0].size(); i++){
np = (*it).subptr[0][i];
if(!np->touch){
vp = new vertex();
vp->subckt = faninTransform(np, 0);
vp->subptr = ptrTransform(np, 0);
vp->topLevel = 0;
vp->bottomLevel = np->level;
vp->vptr = np;
temp.push_back(*vp);
np->touch = true;
}
}
}
nPartition.insert(pair<int, vector<vertex> >(level, temp));
}
| zzspring2012logicsim | trunk/native/partition.cpp | C++ | gpl3 | 6,529 |
/*
* File: global.h
* Author: zhouzhao
*
* Created on December 21, 2011, 3:04 PM
*/
#ifndef GLOBAL_H
#define GLOBAL_H
#include <string>
#include <vector>
#include <map>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include "node.h"
#include "devNode.h"
#include "module.h"
#include "vertex.h"
#define MAXLINE 100
#define MAXCYCLE 100
using namespace std;
extern Node** nodeAll;
extern Node** nodeInput;
extern Node** nodeOutput;
extern int allCount;
extern int inputCount;
extern int outputCount;
extern int wireCount;
extern int maxLevel;
extern map<GType, string> gMap;
extern map<NType, string> nMap;
extern map<LType, string> lMap;
extern map<KWord, string> kMap;
extern thrust::host_vector<devNode>* gMatrix; //matrix used on CPU
extern thrust::host_vector<devNode>* test; //matrix used on CPU for verification
extern vector<Node*>* ptrMatrix; //matrix used on CPU for level access
extern thrust::host_vector<devNode*> stem_host; //vector used to help memory transfer between CPU and GPU
extern thrust::device_vector<devNode*> stem_device; //not used
extern vector<module*> moduleAll;
extern int* matrix; //matrix used to store input vector
extern map<int, vector<vertex> > nPartition; //map data structure for partition result
#endif /* GLOBAL_H */
| zzspring2012logicsim | trunk/native/global.h | C++ | gpl3 | 1,298 |
/*
* File: devNode.cpp
* Author: zhouzhao
*
* Created on December 25, 2011, 1:25 PM
*/
#include "devNode.h"
| zzspring2012logicsim | trunk/native/devNode.cu | Cuda | gpl3 | 118 |
#include "global.h"
using namespace std;
Node** nodeAll;
Node** nodeInput;
Node** nodeOutput;
int allCount;
int inputCount;
int outputCount;
int wireCount;
int maxLevel;
map<GType, string> gMap;
map<NType, string> nMap;
map<LType, string> lMap;
map<KWord, string> kMap;
thrust::host_vector<devNode>* gMatrix;
thrust::host_vector<devNode>* test;
vector<Node*>* ptrMatrix;
thrust::host_vector<devNode*> stem_host;
thrust::device_vector<devNode*> stem_device;
vector<module*> moduleAll;
int* matrix;
map<int, vector<vertex> > nPartition;
| zzspring2012logicsim | trunk/native/global.cu | Cuda | gpl3 | 542 |
/*
* File: module.h
* Author: zhouzhao
*
* Created on December 28, 2011, 8:03 PM
*/
#ifndef MODULE_H
#define MODULE_H
#include <string>
#include <vector>
#include <map>
#include "node.h"
using namespace std;
class module {
public:
module();
module(string name);
module(const module& orig);
virtual ~module();
string name;
map<string, vector<Node*> > inputMap;
map<string, vector<Node*> > outputMap;
map<string, vector<Node*> > wireMap;
Node** nAll; //pointer to reference all nodes in one module
Node** nInput;
Node** nOutput;
int allNum;
int inputNum;
int outputNum;
map<Node*, Node*> ffMap;
vector<Node*> nFloat;
private:
};
#endif /* MODULE_H */
| zzspring2012logicsim | trunk/native/module.h | C++ | gpl3 | 754 |
/*
* File: module.cpp
* Author: zhouzhao
*
* Created on December 28, 2011, 8:03 PM
*/
#include "module.h"
module::module() {
}
module::module(string name){
this->name = name;
}
module::module(const module& orig) {
}
module::~module() {
}
| zzspring2012logicsim | trunk/native/module.cpp | C++ | gpl3 | 257 |
/*
* File: node.h
* Author: zhouzhao
*
* Created on December 21, 2011, 1:26 PM
*/
#ifndef NODE_H
#define NODE_H
#include <string>
#include <vector>
#include "type.h"
using namespace std;
class Node{
public:
int modIndex;
int index;
int busIndex;
NType type;
string name;
GType gate;
int fanin;
int fanout;
vector<Node*> upperNodes;
vector<Node*> downNodes;
int level;
int offset;
LType logic;
LType cudaLogic;
bool touch;
Node(int modIndex, int index, string name, NType type, int busIndex);
};
#endif /* NODE_H */
| zzspring2012logicsim | trunk/native/node.h | C++ | gpl3 | 605 |
/*
* Copyright 1993-2010 NVIDIA Corporation. All rights reserved.
*
* NOTICE TO USER:
*
* This source code is subject to NVIDIA ownership rights under U.S. and
* international Copyright laws. Users and possessors of this source code
* are hereby granted a nonexclusive, royalty-free license to use this code
* in individual and commercial software.
*
* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE
* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR
* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL,
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOURCE CODE.
*
* U.S. Government End Users. This source code is a "commercial item" as
* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of
* "commercial computer software" and "commercial computer software
* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995)
* and is provided to the U.S. Government only as a commercial end item.
* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through
* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the
* source code with only those rights set forth herein.
*
* Any use of this source code in individual and commercial software must
* include, in the user documentation and internal comments to the code,
* the above Disclaimer and U.S. Government End Users Notice.
*/
#pragma once
#ifndef ASSERT_
#if defined(_NEXUS_DEBUG)
#define ASSERT_(cond__) _ASSERT(cond__)
#else
#define ASSERT_(cond__)
#endif
#endif
#define CheckConditionBreak(cond__) \
if (! (cond__)) \
{ \
break; \
}
#define CheckConditionXR(cond__, x__) \
if (! (cond__)) \
{ \
return x__; \
}
#define CheckConditionXR_(cond__, x__) \
if (! (cond__)) \
{ \
cout<<x__<<endl; \
ASSERT_(0); \
}
| zzspring2012logicsim | trunk/native/check.h | C | gpl3 | 2,327 |
#include "global.h"
#include <queue>
#include <vector>
#include <iostream>
#include <fstream>
#include <assert.h>
void partitionBuild(int level);
void printPartition();
void printPartitionPtr();
| zzspring2012logicsim | trunk/native/partition.h | C++ | gpl3 | 208 |
/*
* File: devNode.h
* Author: zhouzhao
*
* Created on December 25, 2011, 1:25 PM
*/
#ifndef DEVNODE_H
#define DEVNODE_H
#include "type.h"
class devNode {
public:
__device__ __host__ devNode(int modIndex, int index, NType type, GType gate, int faninNum){
this->modIndex = modIndex;
this->index = index;
this->type = type;
this->gate = gate;
this->logic = X;
this->faninNum = faninNum;
for(int i = 0; i < 4; i++){
fanin[i] = -1;
level[i] = -1;
}
}
__device__ __host__ devNode(int modIndex, int index, NType type, GType gate, int faninNum, LType dLogic){
this->modIndex = modIndex;
this->index = index;
this->type = type;
this->gate = gate;
this->logic = dLogic;
this->faninNum = faninNum;
for(int i = 0; i < 4; i++){
fanin[i] = -1;
level[i] = -1;
}
}
__device__ __host__ devNode(){
this->modIndex = -1;
this->index = -1;
this->type = DUMMY;
this->gate = NA;
this->logic = X;
this->faninNum = -1;
for(int i = 0; i < 4; i++){
fanin[i] = -1;
level[i] = -1;
}
}
__device__ __host__ ~devNode(){
}
__device__ __host__ int getModule(){
return this->modIndex;
}
__device__ __host__ int getIndex(){
return this->index;
}
__device__ __host__ NType getType(){
return this->type;
}
__device__ __host__ GType getGate(){
return this->gate;
}
__device__ __host__ LType getLogic(){
return this->logic;
}
__device__ __host__ void setLogic(LType logic){
this->logic = logic;
}
__device__ __host__ int getFaninNum(){
return this->faninNum;
}
__device__ __host__ int getFanin(int index){
return fanin[index];
}
__device__ __host__ void setFanin(int index, int num){
fanin[index] = num;
}
__device__ __host__ int getLevel(int index){
return level[index];
}
__device__ __host__ void setLevel(int index, int num){
level[index] = num;
}
private:
int modIndex; //index of module which contains the node
int index; //node index in one module
NType type;
GType gate;
LType logic; //variable
int faninNum;
int fanin[4]; //fanin offset which is variable
int level[4]; //fanin level which is variable
};
#endif /* DEVNODE_H */
| zzspring2012logicsim | trunk/native/devNode.h | C++ | gpl3 | 2,265 |
#include "cuda.h"
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/copy.h>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <queue>
#include <assert.h>
#include <stdlib.h>
using namespace std;
__global__ void initKernel(devNode** dev_ptr, int* matrix_d, int cycle, int depth){
int tid = blockIdx.x * 512 + threadIdx.x;
if(tid < depth){
if(matrix_d[cycle*depth+tid] == 0){
dev_ptr[0][tid].setLogic(ZERO);
}else{
dev_ptr[0][tid].setLogic(ONE);
}
}
}
__global__ void simKernel(devNode** dev_ptr, int level, int depth){
int tid = blockIdx.x * 512 + threadIdx.x;
int logic = X;
int gate;
int fLevelA, fLevelB, fLevelC, fLevelD;
int faninA, faninB, faninC, faninD;
if(tid < depth){
gate = dev_ptr[level][tid].getGate();
if(gate == INVX1 || gate == INVX2 || gate == INVX4 || gate == INVX8){
fLevelA = dev_ptr[level][tid].getLevel(0);
faninA = dev_ptr[level][tid].getFanin(0);
logic = ~(dev_ptr[fLevelA][faninA].getLogic());
}else if(gate == AND2X1 || gate == AND2X2 || gate == HAC){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic();
}else if(gate == NAND2X1){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic());
}else if(gate == NAND3X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic() &
dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == OR2X1 || gate == OR2X2){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic();
}else if(gate == NOR2X1){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic());
}else if(gate == NOR3X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic() |
dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == XOR2X1 || gate == HAS){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = dev_ptr[fLevelA][faninA].getLogic() ^ dev_ptr[fLevelB][faninB].getLogic();
}else if(gate == XNOR2X1){
fLevelB = dev_ptr[level][tid].getLevel(0);
faninB = dev_ptr[level][tid].getFanin(0);
fLevelA = dev_ptr[level][tid].getLevel(1);
faninA = dev_ptr[level][tid].getFanin(1);
logic = ~(dev_ptr[fLevelA][faninA].getLogic() ^ dev_ptr[fLevelB][faninB].getLogic());
}else if(gate == AOI21X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ~((dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic()) |
dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == AOI22X1){
fLevelD = dev_ptr[level][tid].getLevel(0);
faninD = dev_ptr[level][tid].getFanin(0);
fLevelC = dev_ptr[level][tid].getLevel(1);
faninC = dev_ptr[level][tid].getFanin(1);
fLevelB = dev_ptr[level][tid].getLevel(2);
faninB = dev_ptr[level][tid].getFanin(2);
fLevelA = dev_ptr[level][tid].getLevel(3);
faninA = dev_ptr[level][tid].getFanin(3);
logic = ~((dev_ptr[fLevelA][faninA].getLogic() & dev_ptr[fLevelB][faninB].getLogic()) |
(dev_ptr[fLevelC][faninC].getLogic() & dev_ptr[fLevelD][faninD].getLogic()));
}else if(gate == OAI21X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ~((dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic()) &
dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == OAI22X1){
fLevelD = dev_ptr[level][tid].getLevel(0);
faninD = dev_ptr[level][tid].getFanin(0);
fLevelC = dev_ptr[level][tid].getLevel(1);
faninC = dev_ptr[level][tid].getFanin(1);
fLevelB = dev_ptr[level][tid].getLevel(2);
faninB = dev_ptr[level][tid].getFanin(2);
fLevelA = dev_ptr[level][tid].getLevel(3);
faninA = dev_ptr[level][tid].getFanin(3);
logic = ~((dev_ptr[fLevelA][faninA].getLogic() | dev_ptr[fLevelB][faninB].getLogic()) &
(dev_ptr[fLevelC][faninC].getLogic() | dev_ptr[fLevelD][faninD].getLogic()));
}else if(gate == BUFX2 || gate == BUFX4){
fLevelA = dev_ptr[level][tid].getLevel(0);
faninA = dev_ptr[level][tid].getFanin(0);
logic = dev_ptr[fLevelA][faninA].getLogic();
}else if(gate == FAS){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = (dev_ptr[fLevelA][faninA].getLogic()) ^ (dev_ptr[fLevelB][faninB].getLogic()) ^
(dev_ptr[fLevelC][faninC].getLogic());
}else if(gate == FAC){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
logic = ((dev_ptr[fLevelA][faninA].getLogic()) & (dev_ptr[fLevelB][faninB].getLogic())) |
((dev_ptr[fLevelA][faninA].getLogic()) & (dev_ptr[fLevelC][faninC].getLogic())) |
((dev_ptr[fLevelB][faninB].getLogic()) & (dev_ptr[fLevelC][faninC].getLogic()));
}else if(gate == MUX2X1){
fLevelC = dev_ptr[level][tid].getLevel(0);
faninC = dev_ptr[level][tid].getFanin(0);
fLevelB = dev_ptr[level][tid].getLevel(1);
faninB = dev_ptr[level][tid].getFanin(1);
fLevelA = dev_ptr[level][tid].getLevel(2);
faninA = dev_ptr[level][tid].getFanin(2);
if(dev_ptr[fLevelC][faninC].getLogic() == ZERO){
logic = dev_ptr[fLevelB][faninB].getLogic();
}else{
logic = dev_ptr[fLevelA][faninA].getLogic();
}
}
dev_ptr[level][tid].setLogic((LType)(logic & 3));
}
}
__global__ void ffKernel(devNode** dev_ptr, int depth){
int tid = blockIdx.x * 512 + threadIdx.x;
int level, offset;
if(tid < depth){
if(dev_ptr[0][tid].getType() == PPI){
level = dev_ptr[0][tid].getLevel(0);
offset = dev_ptr[0][tid].getFanin(0);
dev_ptr[0][tid].setLogic(dev_ptr[level][offset].getLogic());
}
}
}
//check if node is ready to compute its offset
int nodeOffsetReady(Node* np){
int flag = 1;
vector<Node*>::iterator it;
for(it = np->upperNodes.begin(); it < np->upperNodes.end(); it++){
if((*it)->offset == -1){
flag = 0;
break;
}
}
return flag;
}
void transform(){
queue<Node*> nodeQ;
vector<Node*>::iterator it, itf;
map<Node*, Node*>::iterator itt;
Node* np;
devNode* dp;
module* mp = moduleAll.back();
Node** npp = mp->nInput;
gMatrix = new thrust::host_vector<devNode> [maxLevel+1];
//process all input nodes of top module
for(int i = 0; i < mp->inputNum; i++){
npp[i]->offset = gMatrix[0].size();
gMatrix[0].push_back(devNode(npp[i]->index, npp[i]->type, npp[i]->gate, npp[i]->fanin));
for(it = npp[i]->downNodes.begin(); it < npp[i]->downNodes.end(); it++){
if(nodeOffsetReady((*it))){
nodeQ.push((*it));
}
}
}
//process flip flop of all modules
for(int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itt = mp->ffMap.begin(); itt != mp->ffMap.end(); itt++){
np = (*itt).second;
np->offset = gMatrix[0].size();
dp = new devNode(np->index, np->type, np->gate, np->fanin);
gMatrix[0].push_back(*dp);
for(it = np->downNodes.begin(); it < np->downNodes.end(); it++){
if(nodeOffsetReady((*it))){
nodeQ.push((*it));
}
}
}
}
//process dummy nodes of all modules
for(int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itf = mp->nFloat.begin(); itf < mp->nFloat.end(); itf++){
(*itf)->offset = gMatrix[0].size();
gMatrix[0].push_back(devNode((*itf)->index, (*itf)->type, (*itf)->gate, (*itf)->fanin, (*itf)->logic));
for(it = (*itf)->downNodes.begin(); it < (*itf)->downNodes.end(); it++){
if(nodeOffsetReady((*it))){
nodeQ.push((*it));
}
}
}
}
//process the queue
while (nodeQ.size() != 0) {
np = nodeQ.front();
nodeQ.pop();
np->offset = gMatrix[np->level].size();
dp = new devNode(np->index, np->type, np->gate, np->fanin);
for(int i = 0; i < np->fanin; i++){
dp->setLevel(i, np->upperNodes[i]->level);
dp->setFanin(i, np->upperNodes[i]->offset);
}
gMatrix[np->level].push_back(*dp);
for(it = np->downNodes.begin(); it < np->downNodes.end(); it++){
if(nodeOffsetReady((*it))){
nodeQ.push((*it));
}
}
}
//process flip flop's fanin of all modules
for(int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itt = mp->ffMap.begin(); itt != mp->ffMap.end(); itt++){
np = (*itt).second;
gMatrix[np->level][np->offset].setLevel(0, (*itt).first->level);
gMatrix[np->level][np->offset].setFanin(0, (*itt).first->offset);
}
}
}
int findBias(int level, int index){
int bias = -1;
for(int i = 0; i < gMatrix[level].size(); i++){
if(gMatrix[level][i].getIndex() == index){
bias = i;
break;
}
}
return bias;
}
//sequential update fanin
void updateFanin(){
Node* np;
int bias = -1;
int level;
for(int i = 1; i <= maxLevel; i++){
for(int j = 0; j < gMatrix[i].size(); j++){
np = nodeAll[gMatrix[i][j].getIndex()];
for(int k = 0; k < np->fanin; k++){
level = i - 1;
while((bias = findBias(level, np->upperNodes[k]->index)) == -1
&& level >= 0){
level--;
}
gMatrix[i][j].setFanin(k, bias);
gMatrix[i][j].setLevel(k, level);
}
}
}
}
void cudaLogicSim(){
ofstream result;
int depth, grid;
devNode** temp;
int* matrix_dev;
module* mp = moduleAll.back();
test = new thrust::host_vector<devNode> [maxLevel+1];
cudaMalloc((void**)&matrix_dev, (mp->inputNum)*MAXCYCLE*sizeof(int));
cudaMemcpy(matrix_dev, matrix, (mp->inputNum)*MAXCYCLE*sizeof(int), cudaMemcpyHostToDevice);
for(int i = 0; i < gMatrix[0].size(); i++){
if(gMatrix[0][i].getType() == PPI){
gMatrix[0][i].setLogic(ZERO);
}
}
//copy all vectors in gMatrix from main memory into device memory
stem_host.resize(maxLevel + 1);
for(int i = 0; i <= maxLevel; i++){
cudaMalloc((void**)&stem_host[i], gMatrix[i].size() * sizeof(devNode));
thrust::device_ptr<devNode> dev_ptr(stem_host[i]); //change raw pointer into thrust pointer
thrust::copy(gMatrix[i].begin(), gMatrix[i].end(), dev_ptr); //thrust copy is used
}
//copy reference of all vectors from main memory into device memory
cudaMalloc(&temp, stem_host.size()*sizeof(devNode*));
devNode** raw_ptr = thrust::raw_pointer_cast(&stem_host[0]); //change thrust pointer into raw pointer
cudaMemcpy(temp, raw_ptr, stem_host.size()*sizeof(devNode*), cudaMemcpyHostToDevice);
//issue series of kernel calls
for(int i = 0; i < MAXCYCLE; i++){
// cout<<"cuda simulate cycle "<<i<<endl;
depth = mp->inputNum;
grid = depth/512 + 1;
initKernel<<<grid, 512>>>(temp, matrix_dev, i, depth);
for(int j = 1; j <= maxLevel; j++){
depth = gMatrix[j].size();
grid = depth/512 + 1;
simKernel<<<grid, 512>>>(temp, j, depth);
}
depth = gMatrix[0].size();
grid = depth/512 + 1;
if(i != MAXCYCLE-1){
ffKernel<<<grid, 512>>>(temp, depth);
}
}
//copy all results from device memory back to main memory and then print
result.open("cuda.txt");
for(int i = 0; i <= maxLevel; i++){
thrust::device_ptr<devNode> dev_ptr_new(stem_host[i]);
test[i].resize(gMatrix[i].size());
// thrust::copy_n(dev_ptr_new, gMatrix[i].size(), test[i].begin()); //thrust copy is used
}
for(int i = 0; i <= maxLevel; i++){
for(int j = 0; j < gMatrix[i].size(); j++){
result<<test[i][j].getIndex()<<"->"<<lMap[test[i][j].getLogic()]<<" ";
}
result<<endl;
}
result.close();
//free all memory allocated on device memory
for(int i = 0; i <= maxLevel; i++){
cudaFree(stem_host[i]);
}
cudaFree(temp);
cudaFree(matrix_dev);
}
void cudaVerify(){
Node* np;
int flag = 1;
cout<<"cuda verify is starting ..."<<endl;
for(int i = 0; i < moduleAll.size(); i++){
for(int j = 0; j < moduleAll[i]->allNum; j++){
np = moduleAll[i]->nAll[j];
// cout<<np->name<<endl;
if(np->level != -1) np->cudaLogic = test[np->level][np->offset].getLogic();
if(np->cudaLogic != np->logic) flag = 0;
}
}
if(flag){
cout<<"Pass!"<<endl;
}else{
cout<<"Fail!"<<endl;
}
}
void cudaSimTest(int a, int b){
long long result = 0;
int temp;
int tempa = a;
int tempb = b;
time_t start, end;
double diff;
for(int i = 0; i < 24; i++){
temp = a & 1;
if(temp == 0){
gMatrix[0][i].setLogic(ZERO);
}else{
gMatrix[0][i].setLogic(ONE);
}
a = a >> 1;
}
for(int i = 24; i < 48; i++){
temp = b & 1;
if(temp == 0){
gMatrix[0][i].setLogic(ZERO);
}else{
gMatrix[0][i].setLogic(ONE);
}
b = b >> 1;
}
time(&start);
cudaLogicSim();
time(&end);
diff = difftime(end, start);
for(int i = 47; i >= 0; i--){
if(nodeOutput[i]->cudaLogic == ZERO){
result = result & 0xfffffffffffffffeLL;
}else if(nodeOutput[i]->cudaLogic == ONE){
result = result | 1;
}
result = result << 1;
}
cout<<tempa<<" * "<<tempb<<" = "<<result<<endl;
printf("GPU took %.5f seconds to do logic simulation\n", diff);
}
| zzspring2012logicsim | trunk/native/cuda.cpp | C++ | gpl3 | 17,646 |
/*
* File: cuda.h
* Author: zhouzhao
*
* Created on December 25, 2011, 4:49 PM
*/
#ifndef CUDA_H
#define CUDA_H
#include "global.h"
void transform();
void updateFanin();
void cudaLogicSim();
void cudaSimTest(int a, int b);
void cudaVerify();
#endif /* CUDA_H */
| zzspring2012logicsim | trunk/native/cuda.h | C | gpl3 | 275 |
/*
* File: main.cpp
* Author: zhouzhao
*
* Created on December 21, 2011, 10:48 AM
*/
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <time.h>
#include <iomanip>
#include <algorithm>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/assign/list_inserter.hpp>
#include <boost/assert.hpp>
#include "global.h"
#include "devNode.h"
#include "cuda.h"
#include "partition.h"
using namespace std;
int findNode(string name){
int index = -1;
for(int i = 0; i < allCount; i++){
if(!name.compare(nodeAll[i]->name)){
index = nodeAll[i]->index;
break;
}
}
return index;
}
int containChar(char c, char* trim){
int flag = 0;
for(unsigned int i = 0; i < string(trim).length(); i++){
if(c == trim[i]){
flag = 1;
break;
}
}
return flag;
}
string trimEnd(string oldStr, char* trim){
string::iterator it = oldStr.end()-1;
while(containChar(*it, trim) && it >= oldStr.begin()){
oldStr.erase(it);
it--;
}
return oldStr;
}
//verify if the gate is defined
int gIsDefined(string gate){
int flag = -1;
map<GType, string>::iterator it;
for(it = gMap.begin(); it != gMap.end(); it++){
if(!gate.compare((*it).second)){
flag = (int)((*it).first);
break;
}
}
return flag;
}
//verify if the keyword is defined
int kIsDefined(string keyword){
int flag = -1;
map<KWord, string>::iterator it;
for(it = kMap.begin(); it != kMap.end(); it++){
if(!keyword.compare((*it).second)){
flag = (int)((*it).first);
break;
}
}
return flag;
}
//verify if the module is defined
int mIsDefined(string module){
int flag = -1;
for(unsigned int i = 0; i < moduleAll.size(); i++){
if(!module.compare(moduleAll[i]->name)){
flag = i;
break;
}
}
return flag;
}
//print fanin and fanout of one node
void printFF(Node* np){
vector<Node*>::iterator it;
cout<<"fanin: ";
for(it = np->upperNodes.begin(); it < np->upperNodes.end(); it++){
cout<<(*it)->name<<" ";
}
cout<<"fanout: ";
for(it = np->downNodes.begin(); it < np->downNodes.end(); it++){
cout<<(*it)->name<<" ";
}
}
void printNodeToFile(void){
ofstream result;
module* mp;
Node** npp;
unsigned int nodeSum = 0;
unsigned int gateSum = 0;
unsigned int ffSum = 0;
result.open("result.txt");
for(unsigned int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
nodeSum = nodeSum + mp->allNum;
gateSum = gateSum + mp->allNum - mp->inputNum - mp->ffMap.size();
ffSum = ffSum + mp->ffMap.size();
npp = mp->nAll;
result<<"module "<<mp->name;
for(unsigned int i = 0; i < 80 - mp->name.length() - 7; i++) result<<"-";
result<<endl;
result<<"index\ttype\tname\tgate\tfanin\tfanout\tlevel\tlogic"<<endl;
for(int i = 0; i < 80; i++) result<<"-";
result<<endl;
for(int i = 0; i < mp->allNum; i++){
result<<npp[i]->modIndex<<","<<npp[i]->index<<"\t"<<nMap[npp[i]->type]<<setw(20)
<<npp[i]->name<<setw(20)<<gMap[npp[i]->gate]<<"\t"
<<npp[i]->fanin<<"\t"<<npp[i]->fanout<<"\t"
<<npp[i]->level<<"\t"<<lMap[npp[i]->logic]<<endl;
}
result<<"node number: "<<mp->allNum<<endl;
result<<"input number: "<<mp->inputNum<<endl;
result<<"output number: "<<mp->outputNum<<endl;
result<<"flip flop: "<<mp->ffMap.size()<<endl;
result<<"input node are: ";
for(int i = 0; i < mp->inputNum; i++){
result<<mp->nInput[i]->name<<" ";
}
result<<endl;
result<<"output node are: ";
for(int i = 0; i < mp->outputNum; i++){
result<<mp->nOutput[i]->name<<" ";
}
result<<endl;
result<<endl;
/*
for(int i = 0; i < allCount; i++){
cout<<nodeAll[i]->name<<" ";
printFF(nodeAll[i]);
cout<<endl;
}
*/
}
result<<"summary: "<<endl;
result<<"total number of node is "<<nodeSum<<endl;
result<<"max level is "<<maxLevel<<endl;
result<<"total number of gate is "<<gateSum<<endl;
result<<"total number of flip-flop is "<<ffSum<<endl;
result.close();
}
void printModule(){
map<string, vector<Node*> >::iterator it;
for(unsigned int i = 0; i < moduleAll.size(); i++){
cout<<"module "<<moduleAll[i]->name<<endl;
cout<<moduleAll[i]->allNum<<" "<<moduleAll[i]->inputNum<<" "<<moduleAll[i]->outputNum<<endl;
for(it = moduleAll[i]->inputMap.begin(); it != moduleAll[i]->inputMap.end(); it++){
cout<<(*it).first<<": ";
for(unsigned int i = 0; i < (*it).second.size(); i++){
if((*it).second[i]->upperNodes.size() > 0)
cout<<(*it).second[i]->name<<"->"<<(*it).second[i]->upperNodes[0]->name<<" ";
}
cout<<endl;
}
for(it = moduleAll[i]->outputMap.begin(); it != moduleAll[i]->outputMap.end(); it++){
cout<<(*it).first<<": ";
for(unsigned int i = 0; i < (*it).second.size(); i++){
if((*it).second[i]->downNodes.size() > 0)
cout<<(*it).second[i]->name<<"->"<<(*it).second[i]->downNodes[0]->name<<" ";
}
cout<<endl;
}
}
}
void initGlobal(void){
nodeAll = NULL;
nodeInput = NULL;
nodeOutput = NULL;
allCount = 0;
inputCount = 0;
outputCount = 0;
wireCount = 0;
maxLevel = 0;
boost::assign::insert(gMap)
(IPT, "IPT")(BRCH, "BRCH")
(INVX1, "INVX1")(INVX2, "INVX2")
(INVX4, "INVX4")(INVX8, "INVX8")
(AND2X1, "AND2X1")(AND2X2, "AND2X2")
(NAND2X1, "NAND2X1")(NAND3X1, "NAND3X1")
(OR2X1, "OR2X1")(OR2X2, "OR2X2")
(NOR2X1, "NOR2X1")(NOR3X1, "NOR3X1")
(XOR2X1, "XOR2X1")(XNOR2X1, "XNOR2X1")
(AOI21X1, "AOI21X1")(AOI22X1, "AOI22X1")
(OAI21X1, "OAI21X1")(OAI22X1, "OAI22X1")
(DFFNEGX1, "DFFNEGX1")(DFFPOSX1, "DFFPOSX1")(DFFSR, "DFFSR")
(BUFX2, "BUFX2")(BUFX4, "BUFX4")
(FAX1, "FAX1")(FAC, "FAC")(FAS, "FAS")
(HAX1, "HAX1")(HAC, "HAC")(HAS, "HAS")
(MUX2X1, "MUX2X1")(NA, "NA");
BOOST_ASSERT(gMap.size() == 33);
boost::assign::insert(nMap)
(GATE, "GATE")(PI, "PI")
(FB, "FB")(PO, "PO")
(PPI, "PPI")(PPO, "PPO")
(DUMMY, "DUMMY");
BOOST_ASSERT(nMap.size() == 7);
boost::assign::insert(lMap)
(ZERO, "0")(DBAR, "~D")
(D, "D")(ONE, "1")
(X, "X");
BOOST_ASSERT(lMap.size() == 5);
boost::assign::insert(kMap)
(MODULE, "module")(INPUT, "input")
(OUTPUT, "output")(WIRE, "wire")
(ASSIGN, "assign")(ENDMODULE, "endmodule");
BOOST_ASSERT(kMap.size() == 6);
}
//check if node is ready to compute its level
int nodeReady(Node* np){
int flag = 1;
vector<Node*>::iterator it;
for(it = np->upperNodes.begin(); it < np->upperNodes.end(); it++){
if((*it)->level == -1){
flag = 0;
break;
}
}
return flag;
}
//check if node is ready to compute its logic
int nodeLogicReady(Node* np){
int flag = 1;
vector<Node*>::iterator it;
for(it = np->upperNodes.begin(); it < np->upperNodes.end(); it++){
if((*it)->logic == X){
flag = 0;
break;
}
}
return flag;
}
//compute level of one node
int nodeCompute(Node* np){
int level = -1;
vector<Node*>::iterator it;
for(it = np->upperNodes.begin(); it < np->upperNodes.end(); it++){
if((*it)->level > level){
level = (*it)->level;
}
}
return level + 1;
}
int nodeLogic(Node* np){
int logic = X;
if(np->gate == INVX1 || np->gate == INVX2 || np->gate == INVX4 || np->gate == INVX8){
logic = ~(np->upperNodes[0]->logic);
}else if(np->gate == AND2X1 || np->gate == AND2X2 || np->gate == HAC){
logic = (np->upperNodes[0]->logic) & (np->upperNodes[1]->logic);
}else if(np->gate == NAND2X1){
logic = ~((np->upperNodes[0]->logic) & (np->upperNodes[1]->logic));
}else if(np->gate == NAND3X1){
logic = ~((np->upperNodes[0]->logic) & (np->upperNodes[1]->logic) &
(np->upperNodes[2]->logic));
}else if(np->gate == OR2X1 || np->gate == OR2X2){
logic = (np->upperNodes[0]->logic) | (np->upperNodes[1]->logic);
}else if(np->gate == NOR2X1){
logic = ~((np->upperNodes[0]->logic) | (np->upperNodes[1]->logic));
}else if(np->gate == NOR3X1){
logic = ~((np->upperNodes[0]->logic) | (np->upperNodes[1]->logic) |
(np->upperNodes[2]->logic));
}else if(np->gate == XOR2X1 || np->gate == HAS){
logic = (np->upperNodes[0]->logic) ^ (np->upperNodes[1]->logic);
}else if(np->gate == XNOR2X1){
logic = ~((np->upperNodes[0]->logic) ^ (np->upperNodes[1]->logic));
}else if(np->gate == AOI21X1){
logic = ~((np->upperNodes[0]->logic) | ((np->upperNodes[1]->logic) & (np->upperNodes[2]->logic)));
}else if(np->gate == AOI22X1){
logic = ~(((np->upperNodes[0]->logic) & (np->upperNodes[1]->logic)) |
((np->upperNodes[2]->logic) & (np->upperNodes[3]->logic)));
}else if(np->gate == OAI21X1){
logic = ~((np->upperNodes[0]->logic) & ((np->upperNodes[1]->logic) | (np->upperNodes[2]->logic)));
}else if(np->gate == OAI22X1){
logic = ~(((np->upperNodes[0]->logic) | (np->upperNodes[1]->logic)) &
((np->upperNodes[2]->logic) | (np->upperNodes[3]->logic)));
}else if(np->gate == BUFX2 || np->gate == BUFX4){
logic = np->upperNodes[0]->logic;
}else if(np->gate == FAS){
logic = (np->upperNodes[0]->logic) ^ (np->upperNodes[1]->logic)
^ (np->upperNodes[2]->logic);
}else if(np->gate == FAC){
logic = ((np->upperNodes[0]->logic) & (np->upperNodes[1]->logic)) |
((np->upperNodes[1]->logic) & (np->upperNodes[2]->logic)) |
((np->upperNodes[0]->logic) & (np->upperNodes[2]->logic));
}else if(np->gate == MUX2X1){
if(np->upperNodes[0]->logic == ZERO){
logic = np->upperNodes[1]->logic;
}else{
logic = np->upperNodes[2]->logic;
}
}
return logic & 3;
}
int nodeLevelize(){
queue<Node*> nodeQ;
vector<Node*>::iterator it, itf;
map<Node*, Node*>::iterator itt;
Node* np;
int level = 0;
module* mp = moduleAll.back();
Node** npp = mp->nInput;
//initialize the input node in top module
for(int i = 0; i < mp->inputNum; i++){
npp[i]->level = 0;
for(it = npp[i]->downNodes.begin(); it < npp[i]->downNodes.end(); it++){
if(nodeReady((*it))){
nodeQ.push((*it));
}
}
}
//initialize the flip-flop node in all module
for(unsigned int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itt = mp->ffMap.begin(); itt != mp->ffMap.end(); itt++){
np = (*itt).second;
np->level = 0;
for(it = np->downNodes.begin(); it < np->downNodes.end(); it++){
if(nodeReady((*it))){
nodeQ.push((*it));
}
}
}
}
//initialize the dummy node in all module
for(unsigned int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itf = mp->nFloat.begin(); itf < mp->nFloat.end(); itf++){
(*itf)->level = 0;
for(it = (*itf)->downNodes.begin(); it < (*itf)->downNodes.end(); it++){
if(nodeReady((*it))){
nodeQ.push((*it));
}
}
}
}
//process the queue
while(nodeQ.size() != 0){
np = nodeQ.front();
nodeQ.pop();
np->level = nodeCompute(np);
if(np->level > level) level = np->level;
for(it = np->downNodes.begin(); it < np->downNodes.end(); it++){
if(nodeReady((*it))){
nodeQ.push((*it));
}
}
}
maxLevel = level;
return 0;
}
//perform the logic simulation of one cone
void vertexLogicSim(vertex* vp){
for(int i = 1; i <= vp->bottomLevel - vp->topLevel; i++){
for(int j = 0; j < vp->subptr[i].size(); j++){
vp->subptr[i][j]->logic = (LType)nodeLogic(vp->subptr[i][j]);
}
}
}
int elabLogicSim(int cycle){
queue<Node*> nodeQ;
vector<Node*>::iterator it, itf;
map<Node*, Node*>::iterator itt;
Node* np;
module* mp = moduleAll.back();
Node** npp = mp->nInput;
//clearup node in all module
for(unsigned int i = 0; i < moduleAll.size(); i++){
for(int j = 0; j < moduleAll[i]->allNum; j++){
np = moduleAll[i]->nAll[j];
if(np->type != PPO) np->logic = X;
}
}
//initialize the queue with all inputs of top module
for(int i = 0; i < mp->inputNum; i++){
if(matrix[cycle*(mp->inputNum)+i] == 0){
npp[i]->logic = ZERO;
}else{
npp[i]->logic = ONE;
}
for(it = npp[i]->downNodes.begin(); it < npp[i]->downNodes.end(); it++){
if(nodeLogicReady((*it))){
nodeQ.push((*it));
}
}
}
//initialize the queue with flip flop of all module
for(unsigned int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itt = mp->ffMap.begin(); itt != mp->ffMap.end(); itt++){
np = (*itt).second;
if(cycle == 0){
np->logic = ZERO;
}else{
np->logic = (*itt).first->logic;
}
for(it = np->downNodes.begin(); it < np->downNodes.end(); it++){
if(nodeLogicReady((*it))){
nodeQ.push((*it));
}
}
}
}
//initialize the queue with dummy nodes of all module
for(unsigned int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(itf = mp->nFloat.begin(); itf < mp->nFloat.end(); itf++){
//logic value of dummy node is constant
for(it = (*itf)->downNodes.begin(); it < (*itf)->downNodes.end(); it++){
if(nodeLogicReady((*it))){
nodeQ.push((*it));
}
}
}
}
//process the queue
while(nodeQ.size() != 0){
np = nodeQ.front();
nodeQ.pop();
np->logic = (LType)nodeLogic(np);
for(it = np->downNodes.begin(); it < np->downNodes.end(); it++){
if(nodeLogicReady((*it))){
nodeQ.push((*it));
}
}
}
return 0;
}
void partitionLogicSim(int cycle){
map<int, vector<vertex> >::iterator mit;
map<Node*, Node*>::iterator it;
module* mp = moduleAll.back();
Node** npp = mp->nInput;
vertex* vp;
Node* np;
//initialize the PI node
for(int i = 0; i < mp->inputNum; i++){
if(matrix[cycle*(mp->inputNum)+i] == 0){
npp[i]->logic = ZERO;
}else{
npp[i]->logic = ONE;
}
}
//initialize the PPI node
for(int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(it = mp->ffMap.begin(); it != mp->ffMap.end(); it++){
np = (*it).second;
if(cycle == 0){
np->logic = ZERO;
}else{
np->logic = (*it).first->logic;
}
}
}
for(mit = nPartition.begin(); mit != nPartition.end(); mit++){
for(int i = 0; i < (*mit).second.size(); i++){
vp = &((*mit).second[i]);
vertexLogicSim(vp);
}
}
}
int cpuLogicSim(string vector, int option){
module* mp = moduleAll.back();
matrix = new int[(mp->inputNum)*MAXCYCLE];
ifstream fileHandle;
fileHandle.open(vector.c_str(), ifstream::in);
if(!fileHandle.is_open()){
perror("there is no vector file for logic simulation");
exit(1);
}
for(int i = 0; i < MAXCYCLE; i++){
for(int j = 0; j < mp->inputNum; j++){
fileHandle>>matrix[i*(mp->inputNum)+j];
}
}
fileHandle.close();
for(int i = 0; i < MAXCYCLE; i++){
switch(option){
case 0: elabLogicSim(i); break;
case 1: partitionLogicSim(i); break;
// cout<<"cycle "<<i<<" is complete"<<endl;
}
}
return 0;
}
int simpleLogicSim(){
map<Node*, Node*>::iterator it;
module* mp;
/*
for(int i = 0; i < inputCount; i++){
nodeInput[i]->logic = ZERO;
}
**/
for(unsigned int i = 0; i < moduleAll.size(); i++){
mp = moduleAll[i];
for(it = mp->ffMap.begin(); it != mp->ffMap.end(); it++){
(*it).second->logic = ZERO;
}
}
for(int i = 1; i <= maxLevel; i++){
for(int j = 0; j < allCount; j++){
if(nodeAll[j]->level == i){
nodeAll[j]->logic = (LType)nodeLogic(nodeAll[j]);
}
}
}
return 0;
}
//unit testing for 24-bit multiplier netlist
int logicSimTest(int a, int b){
long long result = 0;
int temp;
int tempa = a;
int tempb = b;
time_t start, end;
double diff;
for(int i = 0; i < 24; i++){
temp = a & 1;
if(temp == 0){
nodeInput[i]->logic = ZERO;
}else{
nodeInput[i]->logic = ONE;
}
a = a >> 1;
}
for(int i = 24; i < 48; i++){
temp = b & 1;
if(temp == 0){
nodeInput[i]->logic = ZERO;
}else{
nodeInput[i]->logic = ONE;
}
b = b >> 1;
}
time(&start);
simpleLogicSim();
time(&end);
diff = difftime(end, start);
for(int i = 47; i >= 0; i--){
if(nodeOutput[i]->logic == ZERO){
result = result & 0xfffffffffffffffeLL;
}else if(nodeOutput[i]->logic == ONE){
result = result | 1;
}
result = result << 1;
}
cout<<tempa<<" * "<<tempb<<" = "<<result<<endl;
printf("CPU took %.5f seconds to do logic simulation\n", diff);
return 0;
}
void modInsertInput(module* modPtr, string name, Node* np){
map<string, vector<Node*> >::iterator it = modPtr->inputMap.find(name);
if(it != modPtr->inputMap.end()){
(*it).second.push_back(np);
}else{
vector<Node*> temp;
temp.push_back(np);
modPtr->inputMap.insert(pair<string, vector<Node*> >(name, temp));
}
}
void modInsertOutput(module* modPtr, string name, Node* np){
map<string, vector<Node*> >::iterator it = modPtr->outputMap.find(name);
if(it != modPtr->outputMap.end()){
(*it).second.push_back(np);
}else{
vector<Node*> temp;
temp.push_back(np);
modPtr->outputMap.insert(pair<string, vector<Node*> >(name, temp));
}
}
void modInsertWire(module* modPtr, string name, Node* np){
map<string, vector<Node*> >::iterator it = modPtr->wireMap.find(name);
if(it != modPtr->wireMap.end()){
(*it).second.push_back(np);
}else{
vector<Node*> temp;
temp.push_back(np);
modPtr->wireMap.insert(pair<string, vector<Node*> >(name, temp));
}
}
//process 1'b1 or 5'b11110
int constNode(string value, Node* np){
vector<string> splitResult;
int wid;
// cout<<value<<endl;
boost::split(splitResult, value, boost::is_any_of("'"));
if((wid = atoi(splitResult[0].c_str())) == 1){
switch (splitResult[1].at(wid)){
case '1': np->logic = ONE; break;
case '0': np->logic = ZERO; break;
}
}
return 0;
}
void prepareVector(){
module* mp = moduleAll.back();
ofstream fileHandle;
fileHandle.open("vector.txt", ofstream::out);
//initialize the random seed
srand(time(NULL));
for(int i = 0; i < MAXCYCLE; i++){
for(int j = 0; j < mp->inputNum; j++){
fileHandle<<rand()%2<<" ";
}
fileHandle<<endl;
}
fileHandle.close();
}
/*
*
*/
int processModule(string netlist) {
ifstream fileHandle;
ofstream fileTemp;
int filePos;
char buffer[MAXLINE*200];
char keyword[MAXLINE/2];
char modName[MAXLINE/2];
char nodeNameL[MAXLINE/2];
char nodeNameR[MAXLINE/2];
string pattern;
boost::sregex_iterator end;
int min, max, mIndex, width;
Node* nodePtr, *np;
string name, line, subname;
vector<string> splitResult;
Node* nodeA, *nodeB, *nodeC, *nodeD;
Node* nodeY, *nodeYC, *nodeYS;
Node* nodeQ, *nodeS;
int inputNum = 0;
KWord state;
module* modPtr, *mMatchPtr;
bool flag;
map<string, vector<Node*> >::iterator mit;
map<string, vector<Node*> >::iterator mjt;
int modIndex;
//initialize the global variables
initGlobal();
//open verilog file
fileHandle.open(netlist.c_str(), ifstream::in);
if(!fileHandle.is_open()) exit(1);
netlist.replace(netlist.find('.')+1, 3, "mod");
fileTemp.open(netlist.c_str(), ofstream::out);
while(!fileHandle.eof()){
fileHandle.getline(buffer, MAXLINE*10);
line = string(buffer);
if(!line.compare("endmodule")){
line.append(";");
}
line.append("\n");
fileTemp.write(line.c_str(), line.length());
}
fileHandle.close();
fileTemp.close();
fileHandle.open(netlist.c_str(), fstream::in);
while(!fileHandle.eof()){
allCount = 0;
inputCount = 0;
outputCount = 0;
wireCount = 0;
//read verilog file for the first time
cout<<"readin the verilog for the first time"<<endl;
flag = true;
filePos = fileHandle.tellg();
while(flag && !fileHandle.getline(buffer, MAXLINE*200, ';').eof()){
line = string(buffer) + string(";");
if(sscanf(buffer, "%s", keyword) == 1){
string key(keyword);
// cout<<key<<endl;
if(kIsDefined(key) != -1){
if(!key.compare("module")){
BOOST_ASSERT(sscanf(buffer, "%s %s", keyword, modName) == 2);
modPtr = new module(string(modName));
modIndex = moduleAll.size();
moduleAll.push_back(modPtr);
cout<<"module "<<modName<<" is parsed"<<endl;
}else if(!key.compare("endmodule")){
flag = false;
}else if(!key.compare("wire")){ //scan wire line
cout<<"scan wire variable:"<<endl;
state = WIRE;
pattern = string("\\[[0-9]+:[0-9]+\\]");
boost::regex regex(pattern.c_str());
if(boost::regex_search(line.begin(), line.end(), regex)){
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
name = it->str();
cout<<name<<endl;
if(sscanf(name.c_str(), "[%d:%d]", &max, &min) == 2){ //wire is bus
wireCount = (max > min)?(wireCount + max - min + 1) : (wireCount + min - max + 1);
}
break;
}
}else{
pattern = string("\\b[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
// cout<<it->str()<<" ";
wireCount++;
}
// cout<<endl;
}
}else if(!key.compare("output")){ //scan output line
cout<<"scan output variable:"<<endl;
state = OUTPUT;
pattern = string("\\[[0-9]+:[0-9]+\\]");
boost::regex regex(pattern.c_str());
if(boost::regex_search(line.begin(), line.end(), regex)){
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
cout<<it->str()<<endl;
name = it->str();
if(sscanf(name.c_str(), "[%d:%d]", &max, &min) == 2){ //output is bus
outputCount = (max > min)?(outputCount + max - min + 1):(outputCount + min - max + 1);
}
break;
}
}else{
pattern = string("\\b[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
cout<<it->str()<<" ";
outputCount++;
}
cout<<endl;
}
}else if(!key.compare("input")){ //scan input line
cout<<"scan input variable:"<<endl;
state = INPUT;
pattern = string("\\[[0-9]+:[0-9]+\\]");
boost::regex regex(pattern.c_str());
if(boost::regex_search(line.begin(), line.end(), regex)){
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
cout<<it->str()<<endl;
name = it->str();
if(sscanf(name.c_str(), "[%d:%d]", &max, &min) == 2){ //input is bus
inputCount = (max > min)?(inputCount + max - min + 1):(inputCount + min - max + 1);
}
break;
}
}else{
pattern = string("\\b[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
cout<<it->str()<<" ";
inputCount++;
}
cout<<endl;
}
}
}else if(gIsDefined(key) == -1 && mIsDefined(key) == -1){
pattern = string("\\b[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
cout<<it->str()<<" ";
switch (state){
case INPUT: inputCount++; break;
case OUTPUT: outputCount++; break;
case WIRE: wireCount++; break;
}
}
cout<<endl;
}
}
}
if(!fileHandle.eof()){
cout<<"number of wire: "<<wireCount<<endl;
cout<<"number of output: "<<outputCount<<endl;
cout<<"number of input: "<<inputCount<<endl;
nodeAll = new Node* [inputCount + wireCount + outputCount];
nodeInput = new Node* [inputCount];
nodeOutput = new Node* [outputCount];
modPtr->nAll = nodeAll;
modPtr->nInput = nodeInput;
modPtr->nOutput = nodeOutput;
modPtr->allNum = inputCount + wireCount + outputCount;
modPtr->inputNum = inputCount;
modPtr->outputNum = outputCount;
inputCount = 0;
outputCount = 0;
}
flag = true;
//read the verilog for the second time
cout<<"readin the verilog for the second time"<<endl;
fileHandle.seekg(filePos);
while(flag && !fileHandle.getline(buffer, MAXLINE*200, ';').eof()){
line = string(buffer) + string(";");
if(sscanf(buffer, "%s", keyword) == 1){
string key(keyword);
if(kIsDefined(key) != -1){
if(!key.compare("endmodule")){
flag = false;
}else if(!key.compare("wire")){ //scan wire line
state = WIRE;
pattern = string("\\[[0-9]+:[0-9]+\\]\\s[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
if(boost::regex_search(line.begin(), line.end(), regex)){
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
cout<<it->str()<<endl;
name = it->str();
boost::split(splitResult, name, boost::is_any_of(" "));
boost::trim_right_if(splitResult[1], boost::is_any_of(",;"));
if(sscanf(splitResult[0].c_str(), "[%d:%d]", &max, &min) == 2){ //wire is bus
int tempMax = (max > min)?max:min;
for(int i = (max > min)?min:max; i <= tempMax; i++){
string newName = splitResult[1] + "[" +
boost::lexical_cast<string>(i) + "]";
nodePtr = new Node(modIndex, allCount, newName, GATE, i);
nodeAll[allCount++] = nodePtr;
modInsertWire(modPtr, splitResult[1], nodePtr);
}
}
break;
}
}else{
pattern = string("\\b[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
// cout<<it->str()<<" ";
name = it->str();
boost::trim_right_if(name, boost::is_any_of(",;"));
nodePtr = new Node(modIndex, allCount, name, GATE, 0);
nodeAll[allCount++] = nodePtr;
modInsertWire(modPtr, name, nodePtr);
}
// cout<<endl;
}
}else if(!key.compare("output")){ //scan output line
state = OUTPUT;
pattern = string("\\[[0-9]+:[0-9]+\\]\\s[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
if(boost::regex_search(line.begin(), line.end(), regex)){
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
cout<<it->str()<<endl;
name = it->str();
boost::split(splitResult, name, boost::is_any_of(" "));
boost::trim_right_if(splitResult[1], boost::is_any_of(",;"));
if(sscanf(splitResult[0].c_str(), "[%d:%d]", &max, &min) == 2){ //output is bus
int tempMax = (max > min)?max:min;
for(int i = (max > min)?min:max; i <= tempMax; i++){
string newName = splitResult[1] + "[" +
boost::lexical_cast<string>(i) + "]";
nodePtr = new Node(modIndex, allCount, newName, PO, i);
nodeAll[allCount++] = nodePtr;
nodeOutput[outputCount++] = nodePtr;
modInsertOutput(modPtr, splitResult[1], nodePtr);
}
}
break;
}
}else{
pattern = string("\\b[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
name = it->str();
cout<<name<<" ";
boost::trim_right_if(name, boost::is_any_of(",;"));
nodePtr = new Node(modIndex, allCount, name, PO, 0);
nodeAll[allCount++] = nodePtr;
nodeOutput[outputCount++] = nodePtr;
modInsertOutput(modPtr, name, nodePtr);
}
cout<<endl;
}
}else if(!key.compare("input")){ //scan input line
state = INPUT;
pattern = string("\\[[0-9]+:[0-9]+\\]\\s[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
if(boost::regex_search(line.begin(), line.end(), regex)){
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
cout<<it->str()<<endl;
name = it->str();
boost::split(splitResult, name, boost::is_any_of(" "));
boost::trim_right_if(splitResult[1], boost::is_any_of(",;"));
if(sscanf(splitResult[0].c_str(), "[%d:%d]", &max, &min) == 2){
int tempMax = (max > min)?max:min;
for(int i = (max > min)?min:max; i <= tempMax; i++){
string newName = splitResult[1] + "[" +
boost::lexical_cast<string>(i) + "]";
nodePtr = new Node(modIndex, allCount, newName, PI, i);
nodePtr->gate = IPT;
nodeAll[allCount++] = nodePtr;
nodeInput[inputCount++] = nodePtr;
modInsertInput(modPtr, splitResult[1], nodePtr);
}
}
break;
}
}else{
pattern = string("\\b[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
name = it->str();
cout<<name<<" ";
boost::trim_right_if(name, boost::is_any_of(",;"));
nodePtr = new Node(modIndex, allCount, name, PI, 0);
nodePtr->gate = IPT;
nodeAll[allCount++] = nodePtr;
nodeInput[inputCount++] = nodePtr;
modInsertInput(modPtr, name, nodePtr);
}
cout<<endl;
}
}
}else if(gIsDefined(key) == -1 && mIsDefined(key) == -1){
pattern = string("\\b[a-zA-Z0-9_]+[,;]");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
name = it->str();
boost::trim_right_if(name, boost::is_any_of(",;"));
switch (state){
case INPUT: nodePtr = new Node(modIndex, allCount, name, PI, 0); break;
case OUTPUT: nodePtr = new Node(modIndex, allCount, name, PO, 0); break;
case WIRE: nodePtr = new Node(modIndex, allCount, name, GATE, 0); break;
}
nodeAll[allCount++] = nodePtr;
}
}
}
}
//read the verilog for the third time
cout<<"readin the verilog for the third time"<<endl;
flag = true;
fileHandle.seekg(filePos);
while(flag && !fileHandle.getline(buffer, MAXLINE*200, ';').eof()){
line = string(buffer) + string(";");
if(sscanf(buffer, "%s", keyword) == 1){
string key(keyword);
// cout<<key<<endl;
if(!key.compare("endmodule")){
flag = false;
}else if(!key.compare("assign")){
BOOST_ASSERT(sscanf(buffer, "%s %s = %s", keyword, nodeNameL, nodeNameR) == 3);
nodeY = nodeAll[findNode(string(nodeNameL))];
name = string(nodeNameR);
boost::trim_right_if(name, boost::is_any_of(",;)"));
int nIndex = findNode(name);
if(nIndex != -1){
nodeA = nodeAll[findNode(name)];
}else{
nodeA = new Node(modIndex, -1, string("dummy"), DUMMY, 0);
constNode(name, nodeA);
modPtr->nFloat.push_back(nodeA);
}
(nodeA->fanout)++;
nodeA->downNodes.push_back(nodeY);
nodeY->fanin = 1;
nodeY->upperNodes.push_back(nodeA);
nodeY->gate = BUFX2;
}else if(gIsDefined(key) != -1){
if(!key.compare("INVX1") || !key.compare("INVX2")
|| !key.compare("INVX4") || !key.compare("INVX8")
|| !key.compare("BUFX2") || !key.compare("BUFX4")){
pattern = string("\\.A\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexA(pattern.c_str());
boost::sregex_iterator itA(line.begin(), line.end(), regexA);
for(; itA != end; itA++){
name = itA->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeA = nodeAll[findNode(name)];
break;
}
pattern = string("\\.Y\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexY(pattern.c_str());
boost::sregex_iterator itY(line.begin(), line.end(), regexY);
for(; itY != end; itY++){
name = itY->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeY = nodeAll[findNode(name)];
break;
}
(nodeA->fanout)++;
nodeA->downNodes.push_back(nodeY);
nodeY->fanin = 1;
nodeY->upperNodes.push_back(nodeA);
if(!key.compare("INVX1")){
nodeY->gate = INVX1;
}else if(!key.compare("INVX2")){
nodeY->gate = INVX2;
}else if(!key.compare("INVX4")){
nodeY->gate = INVX4;
}else if(!key.compare("INVX8")){
nodeY->gate = INVX8;
}else if(!key.compare("BUFX2")){
nodeY->gate = BUFX2;
}else if(key.compare("BUFX4")){
nodeY->gate = BUFX4;
}
}else if(!key.compare("DFFPOSX1") || !key.compare("DFFNEGX1") || !key.compare("DFFSR")){
pattern = string("\\.D\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexD(pattern.c_str());
boost::sregex_iterator itD(line.begin(), line.end(), regexD);
for(; itD != end; itD++){
name = itD->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeD = nodeAll[findNode(name)];
break;
}
pattern = string("\\.Q\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexQ(pattern.c_str());
boost::sregex_iterator itQ(line.begin(), line.end(), regexQ);
for(; itQ != end; itQ++){
name = itQ->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeQ = nodeAll[findNode(name)];
break;
}
nodeD->fanout = 0;
nodeD->type = PPO;
nodeQ->fanin = 0;
nodeQ->type = PPI;
nodeQ->gate = IPT;
modPtr->ffMap.insert(pair<Node*, Node*>(nodeD, nodeQ)); //map for flip flop
}else if(!key.compare("HAX1") || !key.compare("FAX1")){
pattern = string("\\.A\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexA(pattern.c_str());
boost::sregex_iterator itA(line.begin(), line.end(), regexA);
for(; itA != end; itA++){
name = itA->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeA = nodeAll[findNode(name)];
break;
}
pattern = string("\\.B\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexB(pattern.c_str());
boost::sregex_iterator itB(line.begin(), line.end(), regexB);
for(; itB != end; itB++){
name = itB->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeB = nodeAll[findNode(name)];
break;
}
if(!key.compare("FAX1")){
pattern = string("\\.C\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexC(pattern.c_str());
boost::sregex_iterator itC(line.begin(), line.end(), regexC);
for(; itC != end; itC++){
name = itC->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeC = nodeAll[findNode(name)];
break;
}
}
pattern = string("\\.YC\\([a-zA-Z0-9_\\[\\]\\s]*\\)");
boost::regex regexYC(pattern.c_str());
boost::sregex_iterator itYC(line.begin(), line.end(), regexYC);
for(; itYC != end; itYC++){
name = itYC->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 4);
boost::trim_left_if(name, boost::is_any_of(" \n"));
if(name.length() > 0){
nodeYC = nodeAll[findNode(name)];
}else{
nodeYC = new Node(modIndex, -1, string("dummy"), DUMMY, 0); //output dummy node
}
break;
}
pattern = string("\\.YS\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexYS(pattern.c_str());
boost::sregex_iterator itYS(line.begin(), line.end(), regexYS);
for(; itYS != end; itYS++){
name = itYS->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 4);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeYS = nodeAll[findNode(name)];
break;
}
nodeA->fanout = nodeA->fanout + 2;
nodeA->downNodes.push_back(nodeYC);
nodeA->downNodes.push_back(nodeYS);
nodeB->fanout = nodeB->fanout + 2;
nodeB->downNodes.push_back(nodeYC);
nodeB->downNodes.push_back(nodeYS);
if(!key.compare("HAX1")){
nodeYC->fanin = 2;
nodeYC->upperNodes.push_back(nodeB);
nodeYC->upperNodes.push_back(nodeA);
nodeYC->gate = HAC;
nodeYS->fanin = 2;
nodeYS->upperNodes.push_back(nodeB);
nodeYS->upperNodes.push_back(nodeA);
nodeYS->gate = HAS;
}else{
nodeC->fanout = nodeC->fanout + 2;
nodeC->downNodes.push_back(nodeYC);
nodeC->downNodes.push_back(nodeYS);
nodeYC->fanin = 3;
nodeYC->upperNodes.push_back(nodeC);
nodeYC->upperNodes.push_back(nodeB);
nodeYC->upperNodes.push_back(nodeA);
nodeYC->gate = FAC;
nodeYS->fanin = 3;
nodeYS->upperNodes.push_back(nodeC);
nodeYS->upperNodes.push_back(nodeB);
nodeYS->upperNodes.push_back(nodeA);
nodeYS->gate = FAS;
}
}else if(!key.compare("MUX2X1")){
pattern = string("\\.A\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexA(pattern.c_str());
boost::sregex_iterator itA(line.begin(), line.end(), regexA);
for(; itA != end; itA++){
name = itA->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeA = nodeAll[findNode(name)];
break;
}
pattern = string("\\.B\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexB(pattern.c_str());
boost::sregex_iterator itB(line.begin(), line.end(), regexB);
for(; itB != end; itB++){
name = itB->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeB = nodeAll[findNode(name)];
break;
}
pattern = string("\\.S\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexS(pattern.c_str());
boost::sregex_iterator itS(line.begin(), line.end(), regexS);
for(; itS != end; itS++){
name = itS->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeS = nodeAll[findNode(name)];
break;
}
pattern = string("\\.Y\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexY(pattern.c_str());
boost::sregex_iterator itY(line.begin(), line.end(), regexY);
for(; itY != end; itY++){
name = itY->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeY = nodeAll[findNode(name)];
break;
}
(nodeA->fanout)++;
nodeA->downNodes.push_back(nodeY);
(nodeB->fanout)++;
nodeB->downNodes.push_back(nodeY);
(nodeS->fanout)++;
nodeS->downNodes.push_back(nodeY);
nodeY->fanin = 3;
nodeY->upperNodes.push_back(nodeS);
nodeY->upperNodes.push_back(nodeB);
nodeY->upperNodes.push_back(nodeA);
nodeY->gate = MUX2X1;
}else{
pattern = string("[0-9]+X");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
name = it->str();
if(name.length() == 2){
inputNum = atoi(name.substr(0, 1).c_str());
}else if(name.length() == 3){
inputNum = atoi(name.substr(0, 1).c_str()) +
atoi(name.substr(1, 1).c_str());
}else{
cout<<"gate type has error"<<endl;
}
break;
}
for(int i = inputNum; i > 0; i--){
switch (i){
case 1:
{
pattern = string("\\.A\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
name = it->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeA = nodeAll[findNode(name)];
break;
}
break;
}
case 2:
{
pattern = string("\\.B\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
name = it->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeB = nodeAll[findNode(name)];
break;
}
break;
}
case 3:
{
pattern = string("\\.C\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
name = it->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeC = nodeAll[findNode(name)];
break;
}
break;
}
case 4:
{
pattern = string("\\.D\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regex(pattern.c_str());
boost::sregex_iterator it(line.begin(), line.end(), regex);
for(; it != end; it++){
name = it->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeD = nodeAll[findNode(name)];
break;
}
break;
}
}
}
pattern = string("\\.Y\\([a-zA-Z0-9_\\[\\]\\s]+\\)");
boost::regex regexY(pattern.c_str());
boost::sregex_iterator itY(line.begin(), line.end(), regexY);
for(; itY != end; itY++){
name = itY->str();
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, 3);
boost::trim_left_if(name, boost::is_any_of(" \n"));
nodeY = nodeAll[findNode(name)];
break;
}
for(int i = inputNum; i > 0; i--){
switch (i){
case 1:
{
(nodeA->fanout)++;
nodeA->downNodes.push_back(nodeY);
nodeY->upperNodes.push_back(nodeA);
break;
}
case 2:
{
(nodeB->fanout)++;
nodeB->downNodes.push_back(nodeY);
nodeY->upperNodes.push_back(nodeB);
break;
}
case 3:
{
(nodeC->fanout)++;
nodeC->downNodes.push_back(nodeY);
nodeY->upperNodes.push_back(nodeC);
break;
}
case 4:
{
(nodeD->fanout)++;
nodeD->downNodes.push_back(nodeY);
nodeY->upperNodes.push_back(nodeD);
break;
}
}
}
nodeY->fanin = inputNum;
nodeY->gate = (GType)(gIsDefined(key));
}
}else if((mIndex = mIsDefined(key)) != -1){ //mit is lower level while mjt is higher level
mMatchPtr = moduleAll[mIndex];
for(mit = mMatchPtr->inputMap.begin(); mit != mMatchPtr->inputMap.end(); mit++){
pattern = string("\\.") + (*mit).first + string("\\([\\{\\}\\s,'a-zA-Z0-9_\\[\\]:]+\\)");
boost::regex regexM(pattern.c_str());
boost::sregex_iterator itM(line.begin(), line.end(), regexM);
for(; itM != end; itM++){
name = itM->str();
// cout<<name<<endl;
if((*mit).second.size() > 1){ //input of submodule is bus
if(name.find('{', 0) != string::npos){ //if bus is grouped
pattern = string("[\\[\\]:'a-zA-Z0-9_]+[,;}]");
boost::regex regexW(pattern.c_str());
boost::sregex_iterator itW(name.begin(), name.end(), regexW);
width = (*mit).second.size();
for(; itW != end; itW++){
subname = itW->str();
boost::trim_right_if(subname, boost::is_any_of(",;)}"));
boost::split(splitResult, subname, boost::is_any_of("["));
mjt = modPtr->inputMap.find(splitResult[0]);
if(mjt == modPtr->inputMap.end()){
mjt = modPtr->wireMap.find(splitResult[0]);
if(mjt == modPtr->wireMap.end()){
mjt = modPtr->outputMap.find(splitResult[0]);
if(mjt == modPtr->outputMap.end()){
np = new Node(modIndex, -1, string("dummy"), DUMMY, 0);
constNode(splitResult[0], np);
modPtr->nFloat.push_back(np);
(np->fanout)++;
np->downNodes.push_back((*mit).second[width-1]);
(*mit).second[width-1]->fanin = 1;
(*mit).second[width-1]->upperNodes.push_back(np);
(*mit).second[width-1]->gate = BUFX2;
width--;
continue;
}
}
}
if((*mjt).second.size() > 1){ //input of top module is bus
if(splitResult.size() > 1){ //subbus is used
if(sscanf(splitResult[1].c_str(), "%d:%d", &max, &min) == 2){
if(max < min) swap(max, min);
for(int k = min - (*mjt).second[0]->busIndex;
k <= max - (*mjt).second[0]->busIndex; k++){
np = (*mjt).second[k];
(np->fanout)++;
int temp = width-max+min-1+k-min+(*mjt).second[0]->busIndex;
np->downNodes.push_back((*mit).second[temp]);
(*mit).second[temp]->fanin = 1;
(*mit).second[temp]->upperNodes.push_back(np);
(*mit).second[temp]->gate = BUFX2;
}
width = width - (max - min + 1);
}else{ //only one line of bus is used
BOOST_ASSERT(sscanf(splitResult[1].c_str(), "%d", &max) == 1);
np = (*mjt).second[max-(*mjt).second[0]->busIndex];
(np->fanout)++;
np->downNodes.push_back((*mit).second[width-1]);
(*mit).second[width-1]->fanin = 1;
(*mit).second[width-1]->upperNodes.push_back(np);
(*mit).second[width-1]->gate = BUFX2;
width--;
}
}else{ //all line in bus is used
for(int k = 0; k < (*mjt).second.size(); k++){
np = (*mjt).second[k];
(np->fanout)++;
np->downNodes.push_back((*mit).second[width-(*mjt).second.size()+k]);
(*mit).second[width-(*mjt).second.size()+k]->fanin = 1;
(*mit).second[width-(*mjt).second.size()+k]->upperNodes.push_back(np);
(*mit).second[width-(*mjt).second.size()+k]->gate = BUFX2;
}
width = width - (*mjt).second.size();
}
}else{ //input of top module is a line
np = (*mjt).second[0];
(np->fanout)++;
np->downNodes.push_back((*mit).second[width-1]);
(*mit).second[width-1]->fanin = 1;
(*mit).second[width-1]->upperNodes.push_back(np);
(*mit).second[width-1]->gate = BUFX2;
width--;
}
}
}else{ //bus is not grouped
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, (*mit).first.length()+2);
boost::trim_left_if(name, boost::is_any_of(" \n"));
boost::split(splitResult, name, boost::is_any_of("["));
mjt = modPtr->inputMap.find(splitResult[0]);
if(mjt == modPtr->inputMap.end()){
mjt = modPtr->wireMap.find(splitResult[0]);
if(mjt == modPtr->wireMap.end()){
mjt = modPtr->outputMap.find(splitResult[0]);
}
}
if(splitResult.size() > 1){ //sub bus is used
BOOST_ASSERT(sscanf(splitResult[1].c_str(), "%d:%d", &max, &min) == 2);
if(max < min) swap(max, min);
for(int k = min - (*mjt).second[0]->busIndex;
k <= max - (*mjt).second[0]->busIndex; k++){
np = (*mjt).second[k];
(np->fanout)++;
int temp = k - min + (*mjt).second[0]->busIndex;
np->downNodes.push_back((*mit).second[temp]);
(*mit).second[temp]->fanin = 1;
(*mit).second[temp]->upperNodes.push_back(np);
(*mit).second[temp]->gate = BUFX2;
}
}else{ //all line in bus is used
for(int k = 0; k < (*mjt).second.size(); k++){
np = (*mjt).second[k];
(np->fanout)++;
np->downNodes.push_back((*mit).second[k]);
(*mit).second[k]->fanin = 1;
(*mit).second[k]->upperNodes.push_back(np);
(*mit).second[k]->gate = BUFX2;
}
}
}
}else{ //input of submodule is a line
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, (*mit).first.length()+2);
boost::trim_left_if(name, boost::is_any_of(" \n"));
int nIndex = findNode(name);
if(nIndex != -1){
np = nodeAll[nIndex];
}else{
np = new Node(modIndex, -1, string("dummy"), DUMMY, 0);
constNode(name, np);
modPtr->nFloat.push_back(np);
}
(np->fanout)++;
np->downNodes.push_back((*mit).second[0]);
(*mit).second[0]->fanin = 1;
(*mit).second[0]->upperNodes.push_back(np);
(*mit).second[0]->gate = BUFX2;
}
break;
}
}
for(mit = mMatchPtr->outputMap.begin(); mit != mMatchPtr->outputMap.end(); mit++){
pattern = string("\\.") + (*mit).first + string("\\([\\{\\}\\s,a-zA-Z0-9_\\[\\]:]+\\)");
boost::regex regexM(pattern.c_str());
boost::sregex_iterator itM(line.begin(), line.end(), regexM);
for(; itM != end; itM++){
name = itM->str();
// cout<<name<<endl;
if((*mit).second.size() > 1){ //output of submodule is bus
if(name.find('{', 0) != string::npos){
pattern = string("[\\[\\]:a-zA-Z0-9_]+[,;}]");
boost::regex regexW(pattern.c_str());
boost::sregex_iterator itW(name.begin(), name.end(), regexW);
width = (*mit).second.size();
for(; itW != end; itW++){
subname = itW->str();
boost::trim_right_if(subname, boost::is_any_of(",;)}"));
boost::split(splitResult, subname, boost::is_any_of("["));
mjt = modPtr->outputMap.find(splitResult[0]);
if(mjt == modPtr->outputMap.end()){
mjt = modPtr->wireMap.find(splitResult[0]);
}
if((*mjt).second.size() > 1){
if(splitResult.size() > 1){
if(sscanf(splitResult[1].c_str(), "%d:%d", &max, &min) == 2){
if(max < min) swap(max, min);
for(int k = min - (*mjt).second[0]->busIndex;
k <= max - (*mjt).second[0]->busIndex; k++){
np = (*mjt).second[k];
int temp = width-max+min-1+k-min+(*mjt).second[0]->busIndex;
((*mit).second[temp]->fanout)++;
(*mit).second[temp]->downNodes.push_back(np);
np->fanin = 1;
np->upperNodes.push_back((*mit).second[temp]);
np->gate = BUFX2;
}
width = width - (max - min + 1);
}else{
BOOST_ASSERT(sscanf(splitResult[1].c_str(), "%d", &max) == 1);
np = (*mjt).second[max-(*mjt).second[0]->busIndex];
((*mit).second[width-1]->fanout)++;
(*mit).second[width-1]->downNodes.push_back(np);
np->fanin = 1;
np->upperNodes.push_back((*mit).second[width-1]);
np->gate = BUFX2;
width--;
}
}else{
for(unsigned int k = 0; k < (*mjt).second.size(); k++){
np = (*mjt).second[k];
((*mit).second[width-(*mjt).second.size()+k]->fanout)++;
(*mit).second[width-(*mjt).second.size()+k]->downNodes.push_back(np);
np->fanin = 1;
np->upperNodes.push_back((*mit).second[width-(*mjt).second.size()+k]);
np->gate = BUFX2;
}
width = width - (*mjt).second.size();
}
}else{
np = (*mjt).second[0];
((*mit).second[width-1]->fanout)++;
(*mit).second[width-1]->downNodes.push_back(np);
np->fanin = 1;
np->upperNodes.push_back((*mit).second[width-1]);
np->gate = BUFX2;
width--;
}
}
}else{
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, (*mit).first.length()+2);
boost::trim_left_if(name, boost::is_any_of(" \n"));
boost::split(splitResult, name, boost::is_any_of("["));
mjt = modPtr->outputMap.find(splitResult[0]);
if(mjt == modPtr->outputMap.end()){
mjt = modPtr->wireMap.find(name);
}
if(splitResult.size() > 1){
BOOST_ASSERT(sscanf(splitResult[1].c_str(), "%d:%d", &max, &min) == 2);
if(max < min) swap(max, min);
for(int k = min - (*mjt).second[0]->busIndex;
k < max - (*mjt).second[0]->busIndex; k++){
np = (*mjt).second[k];
int temp = k - min + (*mjt).second[0]->busIndex;
((*mit).second[temp]->fanout)++;
(*mit).second[temp]->downNodes.push_back(np);
np->fanin = 1;
np->upperNodes.push_back((*mit).second[temp]);
np->gate = BUFX2;
}
}else{
for(unsigned int k = 0; k < (*mjt).second.size(); k++){
np = (*mjt).second[k];
((*mit).second[k]->fanout)++;
(*mit).second[k]->downNodes.push_back(np);
np->fanin = 1;
np->upperNodes.push_back((*mit).second[k]);
np->gate = BUFX2;
}
}
}
}else{
boost::trim_right_if(name, boost::is_any_of(",;)"));
name.erase(0, (*mit).first.length()+2);
boost::trim_left_if(name, boost::is_any_of(" \n"));
np = nodeAll[findNode(name)];
((*mit).second[0]->fanout)++;
(*mit).second[0]->downNodes.push_back(np);
np->fanin = 1;
np->upperNodes.push_back((*mit).second[0]);
np->gate = BUFX2;
}
break;
}
}
}
}
}
}
fileHandle.close();
return 0;
}
void printTransform(){
ofstream fileHandle;
fileHandle.open("cpu.txt", ofstream::out);
for(int i = 0; i <= maxLevel; i++){
for(unsigned int j = 0; j < ptrMatrix[i].size(); j++){
fileHandle << ptrMatrix[i][j]->name << " ";
}
fileHandle << endl;
}
fileHandle.close();
}
int main(int argc, char** argv) {
time_t start, end;
double diff_cpu, diff_gpu;
if(argc != 3){
perror("input verilog netlist or vector is missing");
exit(1);
}
processModule(string(argv[1])); //parse and elaborate the verilog netlist
// prepareVector(); //generate random input vector
nodeLevelize(); //levelize the netlist
transform(); //prepare data strucutre of gMatrix and ptrMatrix
printTransform();
partitionBuild(24); //partition at level 24
printPartition();
printPartitionPtr();
time(&start);
cpuLogicSim(argv[2], 1); //sequential logic simulation on CPU 0->unpartition 1->partition
time(&end);
diff_cpu = difftime(end, start);
printNodeToFile(); //print parse result to file
//cuda accelerated logic simulation
time(&start);
// cudaLogicSim();
time(&end);
diff_gpu = difftime(end, start);
// cudaVerify();
printf("CPU took %.5f seconds to do logic simulation\n", diff_cpu);
printf("GPU took %.5f seconds to do logic simulation\n", diff_gpu);
return 0;
}
| zzspring2012logicsim | trunk/native/main.cpp | C++ | gpl3 | 81,164 |