Cleanup of code, AIDL-calls renamed!

This commit is contained in:
Markus Doits 2011-06-05 19:05:57 +00:00
parent 6502e58c26
commit 24205b8dbc
3 changed files with 355 additions and 362 deletions

View File

@ -40,7 +40,7 @@ public class ApgService extends Service {
PRIVATE_KEY_PASSPHRASE_WRONG, PRIVATE_KEY_PASSPHRASE_WRONG,
PRIVATE_KEY_PASSPHRASE_MISSING; PRIVATE_KEY_PASSPHRASE_MISSING;
public int shifted_ordinal() { public int shiftedOrdinal() {
return ordinal() + 100; return ordinal() + 100;
} }
} }
@ -90,7 +90,6 @@ public class ApgService extends Service {
args = new HashSet<arg>(); args = new HashSet<arg>();
args.add(arg.KEY_TYPE); args.add(arg.KEY_TYPE);
FUNCTIONS_REQUIRED_ARGS.put("get_keys", args); FUNCTIONS_REQUIRED_ARGS.put("get_keys", args);
} }
/** optional arguments for each AIDL function */ /** optional arguments for each AIDL function */
@ -124,21 +123,7 @@ public class ApgService extends Service {
FUNCTIONS_DEFAULTS.put(arg.COMPRESSION, "getDefaultMessageCompression"); FUNCTIONS_DEFAULTS.put(arg.COMPRESSION, "getDefaultMessageCompression");
} }
/** a map the default functions to their return types */ /** a map of the default function names to their method */
private static final HashMap<String, Class<?>> FUNCTIONS_DEFAULTS_TYPES = new HashMap<String, Class<?>>();
static {
try {
FUNCTIONS_DEFAULTS_TYPES.put("getDefaultEncryptionAlgorithm", Preferences.class.getMethod("getDefaultEncryptionAlgorithm").getReturnType());
FUNCTIONS_DEFAULTS_TYPES.put("getDefaultHashAlgorithm", Preferences.class.getMethod("getDefaultHashAlgorithm").getReturnType());
FUNCTIONS_DEFAULTS_TYPES.put("getDefaultAsciiArmour", Preferences.class.getMethod("getDefaultAsciiArmour").getReturnType());
FUNCTIONS_DEFAULTS_TYPES.put("getForceV3Signatures", Preferences.class.getMethod("getForceV3Signatures").getReturnType());
FUNCTIONS_DEFAULTS_TYPES.put("getDefaultMessageCompression", Preferences.class.getMethod("getDefaultMessageCompression").getReturnType());
} catch (Exception e) {
Log.e(TAG, "Function default exception: " + e.getMessage());
}
}
/** a map the default function names to their method */
private static final HashMap<String, Method> FUNCTIONS_DEFAULTS_METHODS = new HashMap<String, Method>(); private static final HashMap<String, Method> FUNCTIONS_DEFAULTS_METHODS = new HashMap<String, Method>();
static { static {
try { try {
@ -152,44 +137,45 @@ public class ApgService extends Service {
} }
} }
/** private static Cursor getKeyEntries(HashMap<String, Object> pParams) {
* maps a fingerprint or user id of a key to as master key in database
*
* @param search_key
* fingerprint or user id to search for
* @return master key if found, or 0
*/
private static long get_master_key(String search_key, Bundle pReturn) {
if (search_key == null || search_key.length() != 8) {
return 0;
}
ArrayList<String> tmp = new ArrayList<String>();
tmp.add(search_key);
long[] _keys = get_master_key(tmp, pReturn);
if (_keys.length > 0)
return _keys[0];
else
return 0;
}
private static Cursor get_key_entries(HashMap<String, Object> params) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(KeyRings.TABLE_NAME + " INNER JOIN " + Keys.TABLE_NAME + " ON " + "(" + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + Keys.TABLE_NAME qb.setTables(KeyRings.TABLE_NAME + " INNER JOIN " + Keys.TABLE_NAME + " ON " + "(" + KeyRings.TABLE_NAME + "." + KeyRings._ID + " = " + Keys.TABLE_NAME
+ "." + Keys.KEY_RING_ID + " AND " + Keys.TABLE_NAME + "." + Keys.IS_MASTER_KEY + " = '1'" + ") " + " INNER JOIN " + UserIds.TABLE_NAME + "." + Keys.KEY_RING_ID + " AND " + Keys.TABLE_NAME + "." + Keys.IS_MASTER_KEY + " = '1'" + ") " + " INNER JOIN " + UserIds.TABLE_NAME
+ " ON " + "(" + Keys.TABLE_NAME + "." + Keys._ID + " = " + UserIds.TABLE_NAME + "." + UserIds.KEY_ID + " AND " + UserIds.TABLE_NAME + "." + " ON " + "(" + Keys.TABLE_NAME + "." + Keys._ID + " = " + UserIds.TABLE_NAME + "." + UserIds.KEY_ID + " AND " + UserIds.TABLE_NAME + "."
+ UserIds.RANK + " = '0') "); + UserIds.RANK + " = '0') ");
String orderBy = params.containsKey("order_by") ? (String) params.get("order_by") : UserIds.TABLE_NAME + "." + UserIds.USER_ID + " ASC"; String orderBy = pParams.containsKey("order_by") ? (String) pParams.get("order_by") : UserIds.TABLE_NAME + "." + UserIds.USER_ID + " ASC";
String type_val[] = null; String typeVal[] = null;
String type_where = null; String typeWhere = null;
if (params.containsKey("key_type")) { if (pParams.containsKey("key_type")) {
type_where = KeyRings.TABLE_NAME + "." + KeyRings.TYPE + " = ?"; typeWhere = KeyRings.TABLE_NAME + "." + KeyRings.TYPE + " = ?";
type_val = new String[] { typeVal = new String[] {
"" + params.get("key_type") "" + pParams.get("key_type")
}; };
} }
return qb.query(Apg.getDatabase().db(), (String[]) params.get("columns"), type_where, type_val, null, null, orderBy); return qb.query(Apg.getDatabase().db(), (String[]) pParams.get("columns"), typeWhere, typeVal, null, null, orderBy);
}
/**
* maps a fingerprint or user id of a key to a master key in database
*
* @param search_key
* fingerprint or user id to search for
* @return master key if found, or 0
*/
private static long getMasterKey(String pSearchKey, Bundle pReturn) {
if (pSearchKey == null || pSearchKey.length() != 8) {
return 0;
}
ArrayList<String> keyList = new ArrayList<String>();
keyList.add(pSearchKey);
long[] keys = getMasterKey(keyList, pReturn);
if (keys.length > 0) {
return keys[0];
} else {
return 0;
}
} }
/** /**
@ -200,7 +186,7 @@ public class ApgService extends Service {
* database * database
* @return an array of master keys * @return an array of master keys
*/ */
private static long[] get_master_key(ArrayList<String> search_keys, Bundle pReturn) { private static long[] getMasterKey(ArrayList<String> pSearchKeys, Bundle pReturn) {
HashMap<String, Object> qParams = new HashMap<String, Object>(); HashMap<String, Object> qParams = new HashMap<String, Object>();
qParams.put("columns", new String[] { qParams.put("columns", new String[] {
@ -209,30 +195,30 @@ public class ApgService extends Service {
}); });
qParams.put("key_type", Id.database.type_public); qParams.put("key_type", Id.database.type_public);
Cursor mCursor = get_key_entries(qParams); Cursor mCursor = getKeyEntries(qParams);
if( LOCAL_LOGV ) Log.v(TAG, "going through installed user keys"); if( LOCAL_LOGV ) Log.v(TAG, "going through installed user keys");
ArrayList<Long> _master_keys = new ArrayList<Long>(); ArrayList<Long> masterKeys = new ArrayList<Long>();
while (mCursor.moveToNext()) { while (mCursor.moveToNext()) {
long _cur_mkey = mCursor.getLong(0); long curMkey = mCursor.getLong(0);
String _cur_user = mCursor.getString(1); String curUser = mCursor.getString(1);
String _cur_fprint = Apg.getSmallFingerPrint(_cur_mkey); String curFprint = Apg.getSmallFingerPrint(curMkey);
if( LOCAL_LOGV ) Log.v(TAG, "current user: " + _cur_user + " (" + _cur_fprint + ")"); if( LOCAL_LOGV ) Log.v(TAG, "current user: " + curUser + " (" + curFprint + ")");
if (search_keys.contains(_cur_fprint) || search_keys.contains(_cur_user)) { if (pSearchKeys.contains(curFprint) || pSearchKeys.contains(curUser)) {
if( LOCAL_LOGV ) Log.v(TAG, "master key found for: " + _cur_fprint); if( LOCAL_LOGV ) Log.v(TAG, "master key found for: " + curFprint);
_master_keys.add(_cur_mkey); masterKeys.add(curMkey);
search_keys.remove(_cur_fprint); pSearchKeys.remove(curFprint);
} else { } else {
if( LOCAL_LOGV ) Log.v(TAG, "Installed key " + _cur_fprint + " is not in the list of public keys to encrypt with"); if( LOCAL_LOGV ) Log.v(TAG, "Installed key " + curFprint + " is not in the list of public keys to encrypt with");
} }
} }
mCursor.close(); mCursor.close();
long[] _master_longs = new long[_master_keys.size()]; long[] masterKeyLongs = new long[masterKeys.size()];
int i = 0; int i = 0;
for (Long _key : _master_keys) { for (Long key : masterKeys) {
_master_longs[i++] = _key; masterKeyLongs[i++] = key;
} }
if (i == 0) { if (i == 0) {
@ -240,12 +226,12 @@ public class ApgService extends Service {
pReturn.getStringArrayList(ret.WARNINGS.name()).add("Searched for public key(s) but found not one"); pReturn.getStringArrayList(ret.WARNINGS.name()).add("Searched for public key(s) but found not one");
} }
for (String _key : search_keys) { for (String key : pSearchKeys) {
Log.w(TAG, "Searched for key " + _key + " but cannot find it in APG"); Log.w(TAG, "Searched for key " + key + " but cannot find it in APG");
pReturn.getStringArrayList(ret.WARNINGS.name()).add("Searched for key " + _key + " but cannot find it in APG"); pReturn.getStringArrayList(ret.WARNINGS.name()).add("Searched for key " + key + " but cannot find it in APG");
} }
return _master_longs; return masterKeyLongs;
} }
/** /**
@ -254,27 +240,27 @@ public class ApgService extends Service {
* @param args * @param args
* the bundle to add default parameters to if missing * the bundle to add default parameters to if missing
*/ */
private void add_default_arguments(String call, Bundle args) { private void addDefaultArguments(String pCall, Bundle pArgs) {
// check whether there are optional elements defined for that call // check whether there are optional elements defined for that call
if (FUNCTIONS_OPTIONAL_ARGS.containsKey(call)) { if (FUNCTIONS_OPTIONAL_ARGS.containsKey(pCall)) {
Preferences _mPreferences = Preferences.getPreferences(getBaseContext(), true); Preferences preferences = Preferences.getPreferences(getBaseContext(), true);
Iterator<arg> _iter = FUNCTIONS_DEFAULTS.keySet().iterator(); Iterator<arg> iter = FUNCTIONS_DEFAULTS.keySet().iterator();
while (_iter.hasNext()) { while (iter.hasNext()) {
arg _current_arg = _iter.next(); arg currentArg = iter.next();
String _current_key = _current_arg.name(); String currentKey = currentArg.name();
if (!args.containsKey(_current_key) && FUNCTIONS_OPTIONAL_ARGS.get(call).contains(_current_arg)) { if (!pArgs.containsKey(currentKey) && FUNCTIONS_OPTIONAL_ARGS.get(pCall).contains(currentArg)) {
String _current_function_name = FUNCTIONS_DEFAULTS.get(_current_arg); String currentFunctionName = FUNCTIONS_DEFAULTS.get(currentArg);
try { try {
Class<?> _ret_type = FUNCTIONS_DEFAULTS_TYPES.get(_current_function_name); Class<?> returnType = FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName).getReturnType();
if (_ret_type == String.class) { if (returnType == String.class) {
args.putString(_current_key, (String) FUNCTIONS_DEFAULTS_METHODS.get(_current_function_name).invoke(_mPreferences)); pArgs.putString(currentKey, (String) FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName).invoke(preferences));
} else if (_ret_type == boolean.class) { } else if (returnType == boolean.class) {
args.putBoolean(_current_key, (Boolean) FUNCTIONS_DEFAULTS_METHODS.get(_current_function_name).invoke(_mPreferences)); pArgs.putBoolean(currentKey, (Boolean) FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName).invoke(preferences));
} else if (_ret_type == int.class) { } else if (returnType == int.class) {
args.putInt(_current_key, (Integer) FUNCTIONS_DEFAULTS_METHODS.get(_current_function_name).invoke(_mPreferences)); pArgs.putInt(currentKey, (Integer) FUNCTIONS_DEFAULTS_METHODS.get(currentFunctionName).invoke(preferences));
} else { } else {
Log.e(TAG, "Unknown return type " + _ret_type.toString() + " for default option"); Log.e(TAG, "Unknown return type " + returnType.toString() + " for default option");
} }
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "Exception in add_default_arguments " + e.getMessage()); Log.e(TAG, "Exception in add_default_arguments " + e.getMessage());
@ -290,7 +276,7 @@ public class ApgService extends Service {
* @param pReturn * @param pReturn
* the Bundle to update * the Bundle to update
*/ */
private void add_default_returns(Bundle pReturn) { private void addDefaultReturns(Bundle pReturn) {
ArrayList<String> errors = new ArrayList<String>(); ArrayList<String> errors = new ArrayList<String>();
ArrayList<String> warnings = new ArrayList<String>(); ArrayList<String> warnings = new ArrayList<String>();
@ -308,13 +294,13 @@ public class ApgService extends Service {
* @param pReturn * @param pReturn
* the bundle to write errors to * the bundle to write errors to
*/ */
private void check_required_args(String function, Bundle pArgs, Bundle pReturn) { private void checkForRequiredArgs(String pFunction, Bundle pArgs, Bundle pReturn) {
if (FUNCTIONS_REQUIRED_ARGS.containsKey(function)) { if (FUNCTIONS_REQUIRED_ARGS.containsKey(pFunction)) {
Iterator<arg> _iter = FUNCTIONS_REQUIRED_ARGS.get(function).iterator(); Iterator<arg> iter = FUNCTIONS_REQUIRED_ARGS.get(pFunction).iterator();
while (_iter.hasNext()) { while (iter.hasNext()) {
String _cur_arg = _iter.next().name(); String curArg = iter.next().name();
if (!pArgs.containsKey(_cur_arg)) { if (!pArgs.containsKey(curArg)) {
pReturn.getStringArrayList(ret.ERRORS.name()).add("Argument missing: " + _cur_arg); pReturn.getStringArrayList(ret.ERRORS.name()).add("Argument missing: " + curArg);
} }
} }
} }
@ -330,60 +316,60 @@ public class ApgService extends Service {
* @param pReturn * @param pReturn
* the bundle to write warnings to * the bundle to write warnings to
*/ */
private void check_unknown_args(String function, Bundle pArgs, Bundle pReturn) { private void checkForUnknownArgs(String pFunction, Bundle pArgs, Bundle pReturn) {
HashSet<arg> all_args = new HashSet<arg>(); HashSet<arg> allArgs = new HashSet<arg>();
if (FUNCTIONS_REQUIRED_ARGS.containsKey(function)) { if (FUNCTIONS_REQUIRED_ARGS.containsKey(pFunction)) {
all_args.addAll(FUNCTIONS_REQUIRED_ARGS.get(function)); allArgs.addAll(FUNCTIONS_REQUIRED_ARGS.get(pFunction));
} }
if (FUNCTIONS_OPTIONAL_ARGS.containsKey(function)) { if (FUNCTIONS_OPTIONAL_ARGS.containsKey(pFunction)) {
all_args.addAll(FUNCTIONS_OPTIONAL_ARGS.get(function)); allArgs.addAll(FUNCTIONS_OPTIONAL_ARGS.get(pFunction));
} }
ArrayList<String> _unknown_args = new ArrayList<String>(); ArrayList<String> unknownArgs = new ArrayList<String>();
Iterator<String> _iter = pArgs.keySet().iterator(); Iterator<String> iter = pArgs.keySet().iterator();
while (_iter.hasNext()) { while (iter.hasNext()) {
String _cur_key = _iter.next(); String curKey = iter.next();
try { try {
arg _cur_arg = arg.valueOf(_cur_key); arg curArg = arg.valueOf(curKey);
if (!all_args.contains(_cur_arg)) { if (!allArgs.contains(curArg)) {
pReturn.getStringArrayList(ret.WARNINGS.name()).add("Unknown argument: " + _cur_key); pReturn.getStringArrayList(ret.WARNINGS.name()).add("Unknown argument: " + curKey);
_unknown_args.add(_cur_key); unknownArgs.add(curKey);
} }
} catch (Exception e) { } catch (Exception e) {
pReturn.getStringArrayList(ret.WARNINGS.name()).add("Unknown argument: " + _cur_key); pReturn.getStringArrayList(ret.WARNINGS.name()).add("Unknown argument: " + curKey);
_unknown_args.add(_cur_key); unknownArgs.add(curKey);
} }
} }
// remove unknown arguments so our bundle has just what we need // remove unknown arguments so our bundle has just what we need
for (String _arg : _unknown_args) { for (String arg : unknownArgs) {
pArgs.remove(_arg); pArgs.remove(arg);
} }
} }
private boolean prepare_args(String call, Bundle pArgs, Bundle pReturn) { private boolean prepareArgs(String pCall, Bundle pArgs, Bundle pReturn) {
Apg.initialize(getBaseContext()); Apg.initialize(getBaseContext());
/* add default return values for all functions */ /* add default return values for all functions */
add_default_returns(pReturn); addDefaultReturns(pReturn);
/* add default arguments if missing */ /* add default arguments if missing */
add_default_arguments(call, pArgs); addDefaultArguments(pCall, pArgs);
if( LOCAL_LOGV ) Log.v(TAG, "add_default_arguments"); if( LOCAL_LOGV ) Log.v(TAG, "add_default_arguments");
/* check for required arguments */ /* check for required arguments */
check_required_args(call, pArgs, pReturn); checkForRequiredArgs(pCall, pArgs, pReturn);
if( LOCAL_LOGV ) Log.v(TAG, "check_required_args"); if( LOCAL_LOGV ) Log.v(TAG, "check_required_args");
/* check for unknown arguments and add to warning if found */ /* check for unknown arguments and add to warning if found */
check_unknown_args(call, pArgs, pReturn); checkForUnknownArgs(pCall, pArgs, pReturn);
if( LOCAL_LOGV ) Log.v(TAG, "check_unknown_args"); if( LOCAL_LOGV ) Log.v(TAG, "check_unknown_args");
/* return if errors happened */ /* return if errors happened */
if (pReturn.getStringArrayList(ret.ERRORS.name()).size() != 0) { if (pReturn.getStringArrayList(ret.ERRORS.name()).size() != 0) {
if( LOCAL_LOGV ) Log.v(TAG, "Errors after preparing, not executing "+call); if( LOCAL_LOGV ) Log.v(TAG, "Errors after preparing, not executing "+pCall);
pReturn.putInt(ret.ERROR.name(), error.ARGUMENTS_MISSING.shifted_ordinal()); pReturn.putInt(ret.ERROR.name(), error.ARGUMENTS_MISSING.shiftedOrdinal());
return false; return false;
} }
if( LOCAL_LOGV ) Log.v(TAG, "error return"); if( LOCAL_LOGV ) Log.v(TAG, "error return");
@ -393,30 +379,30 @@ public class ApgService extends Service {
private boolean encrypt(Bundle pArgs, Bundle pReturn) { private boolean encrypt(Bundle pArgs, Bundle pReturn) {
long _pub_master_keys[] = {}; long pubMasterKeys[] = {};
if (pArgs.containsKey(arg.PUBLIC_KEYS.name())) { if (pArgs.containsKey(arg.PUBLIC_KEYS.name())) {
ArrayList<String> _list = pArgs.getStringArrayList(arg.PUBLIC_KEYS.name()); ArrayList<String> list = pArgs.getStringArrayList(arg.PUBLIC_KEYS.name());
ArrayList<String> _pub_keys = new ArrayList<String>(); ArrayList<String> pubKeys = new ArrayList<String>();
if( LOCAL_LOGV ) Log.v(TAG, "Long size: " + _list.size()); if( LOCAL_LOGV ) Log.v(TAG, "Long size: " + list.size());
Iterator<String> _iter = _list.iterator(); Iterator<String> iter = list.iterator();
while (_iter.hasNext()) { while (iter.hasNext()) {
_pub_keys.add(_iter.next()); pubKeys.add(iter.next());
} }
_pub_master_keys = get_master_key(_pub_keys, pReturn); pubMasterKeys = getMasterKey(pubKeys, pReturn);
} }
InputStream _inStream = new ByteArrayInputStream(pArgs.getString(arg.MESSAGE.name()).getBytes()); InputStream inStream = new ByteArrayInputStream(pArgs.getString(arg.MESSAGE.name()).getBytes());
InputData _in = new InputData(_inStream, 0); // XXX Size second param? InputData in = new InputData(inStream, 0); // XXX Size second param?
OutputStream _out = new ByteArrayOutputStream(); OutputStream out = new ByteArrayOutputStream();
if( LOCAL_LOGV ) Log.v(TAG, "About to encrypt"); if( LOCAL_LOGV ) Log.v(TAG, "About to encrypt");
try { try {
Apg.encrypt(getBaseContext(), // context Apg.encrypt(getBaseContext(), // context
_in, // input stream in, // input stream
_out, // output stream out, // output stream
pArgs.getBoolean(arg.ARMORED_OUTPUT.name()), // ARMORED_OUTPUT pArgs.getBoolean(arg.ARMORED_OUTPUT.name()), // ARMORED_OUTPUT
_pub_master_keys, // encryption keys pubMasterKeys, // encryption keys
get_master_key(pArgs.getString(arg.SIGNATURE_KEY.name()), pReturn), // signature key getMasterKey(pArgs.getString(arg.SIGNATURE_KEY.name()), pReturn), // signature key
pArgs.getString(arg.PRIVATE_KEY_PASSPHRASE.name()), // signature passphrase pArgs.getString(arg.PRIVATE_KEY_PASSPHRASE.name()), // signature passphrase
null, // progress null, // progress
pArgs.getInt(arg.ENCRYPTION_ALGORYTHM.name()), // encryption pArgs.getInt(arg.ENCRYPTION_ALGORYTHM.name()), // encryption
@ -427,29 +413,29 @@ public class ApgService extends Service {
); );
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "Exception in encrypt"); Log.e(TAG, "Exception in encrypt");
String _msg = e.getMessage(); String msg = e.getMessage();
if (_msg.equals(getBaseContext().getString(R.string.error_noSignaturePassPhrase))) { if (msg.equals(getBaseContext().getString(R.string.error_noSignaturePassPhrase))) {
pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot encrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() + " missing): " + _msg); pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot encrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() + " missing): " + msg);
pReturn.putInt(ret.ERROR.name(), error.PRIVATE_KEY_PASSPHRASE_MISSING.shifted_ordinal()); pReturn.putInt(ret.ERROR.name(), error.PRIVATE_KEY_PASSPHRASE_MISSING.shiftedOrdinal());
} else if (_msg.equals(getBaseContext().getString(R.string.error_couldNotExtractPrivateKey))) { } else if (msg.equals(getBaseContext().getString(R.string.error_couldNotExtractPrivateKey))) {
pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot encrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() + " probably wrong): " + _msg); pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot encrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() + " probably wrong): " + msg);
pReturn.putInt(ret.ERROR.name(), error.PRIVATE_KEY_PASSPHRASE_WRONG.shifted_ordinal()); pReturn.putInt(ret.ERROR.name(), error.PRIVATE_KEY_PASSPHRASE_WRONG.shiftedOrdinal());
} else { } else {
pReturn.getStringArrayList(ret.ERRORS.name()).add("Internal failure (" + e.getClass() + ") in APG when encrypting: " + e.getMessage()); pReturn.getStringArrayList(ret.ERRORS.name()).add("Internal failure (" + e.getClass() + ") in APG when encrypting: " + e.getMessage());
pReturn.putInt(ret.ERROR.name(), error.APG_FAILURE.shifted_ordinal()); pReturn.putInt(ret.ERROR.name(), error.APG_FAILURE.shiftedOrdinal());
} }
return false; return false;
} }
if( LOCAL_LOGV ) Log.v(TAG, "Encrypted"); if( LOCAL_LOGV ) Log.v(TAG, "Encrypted");
pReturn.putString(ret.RESULT.name(), _out.toString()); pReturn.putString(ret.RESULT.name(), out.toString());
return true; return true;
} }
private final IApgService.Stub mBinder = new IApgService.Stub() { private final IApgService.Stub mBinder = new IApgService.Stub() {
public boolean get_keys(Bundle pArgs, Bundle pReturn) { public boolean getKeys(Bundle pArgs, Bundle pReturn) {
prepare_args("get_keys", pArgs, pReturn); prepareArgs("get_keys", pArgs, pReturn);
HashMap<String, Object> qParams = new HashMap<String, Object>(); HashMap<String, Object> qParams = new HashMap<String, Object>();
qParams.put("columns", new String[] { qParams.put("columns", new String[] {
@ -459,31 +445,31 @@ public class ApgService extends Service {
qParams.put("key_type", pArgs.getInt(arg.KEY_TYPE.name())); qParams.put("key_type", pArgs.getInt(arg.KEY_TYPE.name()));
Cursor mCursor = get_key_entries(qParams); Cursor cursor = getKeyEntries(qParams);
ArrayList<String> fprints = new ArrayList<String>(); ArrayList<String> fPrints = new ArrayList<String>();
ArrayList<String> ids = new ArrayList<String>(); ArrayList<String> ids = new ArrayList<String>();
while (mCursor.moveToNext()) { while (cursor.moveToNext()) {
if( LOCAL_LOGV ) Log.v(TAG, "adding key "+Apg.getSmallFingerPrint(mCursor.getLong(0))); if( LOCAL_LOGV ) Log.v(TAG, "adding key "+Apg.getSmallFingerPrint(cursor.getLong(0)));
fprints.add(Apg.getSmallFingerPrint(mCursor.getLong(0))); fPrints.add(Apg.getSmallFingerPrint(cursor.getLong(0)));
ids.add(mCursor.getString(1)); ids.add(cursor.getString(1));
} }
mCursor.close(); cursor.close();
pReturn.putStringArrayList(ret.FINGERPRINTS.name(), fprints); pReturn.putStringArrayList(ret.FINGERPRINTS.name(), fPrints);
pReturn.putStringArrayList(ret.USER_IDS.name(), ids); pReturn.putStringArrayList(ret.USER_IDS.name(), ids);
return true; return true;
} }
public boolean encrypt_with_public_key(Bundle pArgs, Bundle pReturn) { public boolean encryptWithPublicKey(Bundle pArgs, Bundle pReturn) {
if (!prepare_args("encrypt_with_public_key", pArgs, pReturn)) { if (!prepareArgs("encrypt_with_public_key", pArgs, pReturn)) {
return false; return false;
} }
return encrypt(pArgs, pReturn); return encrypt(pArgs, pReturn);
} }
public boolean encrypt_with_passphrase(Bundle pArgs, Bundle pReturn) { public boolean encryptWithPassphrase(Bundle pArgs, Bundle pReturn) {
if (!prepare_args("encrypt_with_passphrase", pArgs, pReturn)) { if (!prepareArgs("encrypt_with_passphrase", pArgs, pReturn)) {
return false; return false;
} }
@ -492,11 +478,11 @@ public class ApgService extends Service {
} }
public boolean decrypt(Bundle pArgs, Bundle pReturn) { public boolean decrypt(Bundle pArgs, Bundle pReturn) {
if (!prepare_args("decrypt", pArgs, pReturn)) { if (!prepareArgs("decrypt", pArgs, pReturn)) {
return false; return false;
} }
String _passphrase = pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) != null ? pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) : pArgs String passphrase = pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) != null ? pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) : pArgs
.getString(arg.PRIVATE_KEY_PASSPHRASE.name()); .getString(arg.PRIVATE_KEY_PASSPHRASE.name());
InputStream inStream = new ByteArrayInputStream(pArgs.getString(arg.MESSAGE.name()).getBytes()); InputStream inStream = new ByteArrayInputStream(pArgs.getString(arg.MESSAGE.name()).getBytes());
@ -504,21 +490,21 @@ public class ApgService extends Service {
OutputStream out = new ByteArrayOutputStream(); OutputStream out = new ByteArrayOutputStream();
if( LOCAL_LOGV ) Log.v(TAG, "About to decrypt"); if( LOCAL_LOGV ) Log.v(TAG, "About to decrypt");
try { try {
Apg.decrypt(getBaseContext(), in, out, _passphrase, null, // progress Apg.decrypt(getBaseContext(), in, out, passphrase, null, // progress
pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) != null // symmetric pArgs.getString(arg.SYMMETRIC_PASSPHRASE.name()) != null // symmetric
); );
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "Exception in decrypt"); Log.e(TAG, "Exception in decrypt");
String _msg = e.getMessage(); String msg = e.getMessage();
if (_msg.equals(getBaseContext().getString(R.string.error_noSecretKeyFound))) { if (msg.equals(getBaseContext().getString(R.string.error_noSecretKeyFound))) {
pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot decrypt: " + _msg); pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot decrypt: " + msg);
pReturn.putInt(ret.ERROR.name(), error.NO_MATCHING_SECRET_KEY.shifted_ordinal()); pReturn.putInt(ret.ERROR.name(), error.NO_MATCHING_SECRET_KEY.shiftedOrdinal());
} else if (_msg.equals(getBaseContext().getString(R.string.error_wrongPassPhrase))) { } else if (msg.equals(getBaseContext().getString(R.string.error_wrongPassPhrase))) {
pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot decrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() + " wrong/missing): " + _msg); pReturn.getStringArrayList(ret.ERRORS.name()).add("Cannot decrypt (" + arg.PRIVATE_KEY_PASSPHRASE.name() + " wrong/missing): " + msg);
pReturn.putInt(ret.ERROR.name(), error.PRIVATE_KEY_PASSPHRASE_WRONG.shifted_ordinal()); pReturn.putInt(ret.ERROR.name(), error.PRIVATE_KEY_PASSPHRASE_WRONG.shiftedOrdinal());
} else { } else {
pReturn.getStringArrayList(ret.ERRORS.name()).add("Internal failure (" + e.getClass() + ") in APG when decrypting: " + _msg); pReturn.getStringArrayList(ret.ERRORS.name()).add("Internal failure (" + e.getClass() + ") in APG when decrypting: " + msg);
pReturn.putInt(ret.ERROR.name(), error.APG_FAILURE.shifted_ordinal()); pReturn.putInt(ret.ERROR.name(), error.APG_FAILURE.shiftedOrdinal());
} }
return false; return false;
} }

View File

@ -2,11 +2,12 @@ package org.thialfihar.android.apg;
interface IApgService { interface IApgService {
/* All functions fill the return_vals Bundle with the following keys: /* All functions fill the returnVals Bundle with the following keys:
* *
* ArrayList<String> "WARNINGS" = Warnings, if any * ArrayList<String> "WARNINGS" = Warnings, if any
* ArrayList<String> "ERRORS" = Human readable error descriptions, if any * ArrayList<String> "ERRORS" = Human readable error descriptions, if any
* int "ERROR" = Numeric representation of error, if any, starting with 100 * int "ERROR" = Numeric representation of error, if any
* starting with 100:
* 100: Required argument missing * 100: Required argument missing
* 101: Generic failure of APG * 101: Generic failure of APG
* 102: No matching private key found * 102: No matching private key found
@ -14,11 +15,10 @@ interface IApgService {
* 104: Private key's passphrase missing * 104: Private key's passphrase missing
*/ */
/* ******************************************************* /* ********************************************************
* Encrypting and decrypting * Encryption
* ********************************************************/ * ********************************************************/
/* All encryption function's arguments /* All encryption function's arguments
* *
* Bundle params' keys: * Bundle params' keys:
@ -54,27 +54,28 @@ interface IApgService {
* (optional) * (optional)
* String "PRIVATE_KEY_PASSPHRASE" = Passphrase for signing key * String "PRIVATE_KEY_PASSPHRASE" = Passphrase for signing key
* *
* Bundle return_vals (in addition to the ERRORS/WARNINGS above): * Bundle returnVals (in addition to the ERRORS/WARNINGS above):
* String "RESULT" = Encrypted message * String "RESULT" = Encrypted message
*/ */
/* Additional argument: /* Additional argument for function below:
* (required) * (required)
* String "SYMMETRIC_PASSPHRASE" = Symmetric passphrase to use * String "SYMMETRIC_PASSPHRASE" = Symmetric passphrase to use
*/ */
boolean encrypt_with_passphrase(in Bundle params, out Bundle return_vals); boolean encryptWithPassphrase(in Bundle params, out Bundle returnVals);
/* Additional argument: /* Additional argument:
* (required) * (required)
* ArrayList<String> "PUBLIC_KEYS" = Public keys (8char fingerprint "123ABC12" OR * ArrayList<String> "PUBLIC_KEYS" = Public keys (8char fingerprint "123ABC12" OR
* complete id "Alice Meyer <ab@email.com>") * complete id "Alice Meyer <ab@email.com>")
*/ */
boolean encrypt_with_public_key(in Bundle params, out Bundle return_vals); boolean encryptWithPublicKey(in Bundle params, out Bundle returnVals);
/* ********************************************************
* Decryption
* ********************************************************/
/* Decrypt something /* Bundle params:
*
* Bundle params:
* (required) * (required)
* String "MESSAGE" = Message to decrypt * String "MESSAGE" = Message to decrypt
* *
@ -87,11 +88,9 @@ interface IApgService {
* Bundle return_vals: * Bundle return_vals:
* String "RESULT" = Decrypted message * String "RESULT" = Decrypted message
*/ */
boolean decrypt(in Bundle params, out Bundle returnVals);
boolean decrypt(in Bundle params, out Bundle return_vals); /* ********************************************************
/* *******************************************************
* Get key information * Get key information
* ********************************************************/ * ********************************************************/
@ -106,8 +105,9 @@ interface IApgService {
* Returns: * Returns:
* StringArrayList "FINGERPRINTS" = Short fingerprints of keys * StringArrayList "FINGERPRINTS" = Short fingerprints of keys
* *
* StringArrayList "USER_IDS" = User ids of corrosponding fingerprints (order is the same) * StringArrayList "USER_IDS" = User ids of corresponding fingerprints
* (order is the same as in FINGERPRINTS)
*/ */
boolean get_keys(in Bundle params, out Bundle return_vals); boolean getKeys(in Bundle params, out Bundle returnVals);
} }

View File

@ -46,14 +46,19 @@ import org.thialfihar.android.apg.utils.ApgConInterface.OnCallFinishListener;
* </p> * </p>
* *
* @author Markus Doits <markus.doits@googlemail.com> * @author Markus Doits <markus.doits@googlemail.com>
* @version 0.9.9 * @version 1.0rc1
* *
*/ */
public class ApgCon { public class ApgCon {
private static final boolean LOCAL_LOGV = true; private static final boolean LOCAL_LOGV = true;
private static final boolean LOCAL_LOGD = true; private static final boolean LOCAL_LOGD = true;
private class call_async extends AsyncTask<String, Void, Void> { private final static String TAG = "ApgCon";
private final static int API_VERSION = 1; // aidl api-version it expects
public int secondsToWaitForConnection = 15;
private class CallAsync extends AsyncTask<String, Void, Void> {
@Override @Override
protected Void doInBackground(String... arg) { protected Void doInBackground(String... arg) {
@ -64,48 +69,46 @@ public class ApgCon {
protected void onPostExecute(Void res) { protected void onPostExecute(Void res) {
if( LOCAL_LOGD ) Log.d(TAG, "Async execution finished"); if( LOCAL_LOGD ) Log.d(TAG, "Async execution finished");
async_running = false; mAsyncRunning = false;
} }
} }
private final static String TAG = "ApgCon";
private final static int api_version = 1; // aidl api-version it expects
private final Context mContext; private final Context mContext;
private final error connection_status; private final error mConnectionStatus;
private boolean async_running = false; private boolean mAsyncRunning = false;
private OnCallFinishListener onCallFinishListener; private OnCallFinishListener mOnCallFinishListener;
private final Bundle result = new Bundle(); private final Bundle mResult = new Bundle();
private final Bundle args = new Bundle(); private final Bundle mArgs = new Bundle();
private final ArrayList<String> error_list = new ArrayList<String>(); private final ArrayList<String> mErrorList = new ArrayList<String>();
private final ArrayList<String> warning_list = new ArrayList<String>(); private final ArrayList<String> mWarningList = new ArrayList<String>();
/** Remote service for decrypting and encrypting data */ /** Remote service for decrypting and encrypting data */
private IApgService apgService = null; private IApgService mApgService = null;
/** Set apgService accordingly to connection status */ /** Set apgService accordingly to connection status */
private ServiceConnection apgConnection = new ServiceConnection() { private ServiceConnection mApgConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) { public void onServiceConnected(ComponentName className, IBinder service) {
if( LOCAL_LOGD ) Log.d(TAG, "IApgService bound to apgService"); if( LOCAL_LOGD ) Log.d(TAG, "IApgService bound to apgService");
apgService = IApgService.Stub.asInterface(service); mApgService = IApgService.Stub.asInterface(service);
} }
public void onServiceDisconnected(ComponentName className) { public void onServiceDisconnected(ComponentName className) {
if( LOCAL_LOGD ) Log.d(TAG, "IApgService disconnected"); if( LOCAL_LOGD ) Log.d(TAG, "IApgService disconnected");
apgService = null; mApgService = null;
} }
}; };
/** /**
* Different types of local errors * Different types of local errors
*
* @author markus
*
*/ */
public static enum error { public static enum error {
/**
* no error
*/
NO_ERROR, NO_ERROR,
/** /**
* generic error * generic error
@ -131,6 +134,9 @@ public class ApgCon {
* found APG but without AIDL interface * found APG but without AIDL interface
*/ */
APG_AIDL_MISSING, APG_AIDL_MISSING,
/**
* found APG but with wrong API
*/
APG_API_MISSMATCH APG_API_MISSMATCH
} }
@ -156,77 +162,78 @@ public class ApgCon {
if( LOCAL_LOGV ) Log.v(TAG, "EncryptionService created"); if( LOCAL_LOGV ) Log.v(TAG, "EncryptionService created");
mContext = ctx; mContext = ctx;
error tmp_connection_status = null; error tmpError = null;
try { try {
if( LOCAL_LOGV ) Log.v(TAG, "Searching for the right APG version"); if( LOCAL_LOGV ) Log.v(TAG, "Searching for the right APG version");
ServiceInfo apg_services[] = ctx.getPackageManager().getPackageInfo("org.thialfihar.android.apg", ServiceInfo apgServices[] = ctx.getPackageManager().getPackageInfo("org.thialfihar.android.apg",
PackageManager.GET_SERVICES | PackageManager.GET_META_DATA).services; PackageManager.GET_SERVICES | PackageManager.GET_META_DATA).services;
if (apg_services == null) { if (apgServices == null) {
Log.e(TAG, "Could not fetch services"); Log.e(TAG, "Could not fetch services");
tmp_connection_status = error.GENERIC; tmpError = error.GENERIC;
} else { } else {
boolean apg_service_found = false; boolean apgServiceFound = false;
for (ServiceInfo inf : apg_services) { for (ServiceInfo inf : apgServices) {
if( LOCAL_LOGV ) Log.v(TAG, "Found service of APG: " + inf.name); if( LOCAL_LOGV ) Log.v(TAG, "Found service of APG: " + inf.name);
if (inf.name.equals("org.thialfihar.android.apg.ApgService")) { if (inf.name.equals("org.thialfihar.android.apg.ApgService")) {
apg_service_found = true; apgServiceFound = true;
if (inf.metaData == null) { if (inf.metaData == null) {
Log.w(TAG, "Could not determine ApgService API"); Log.w(TAG, "Could not determine ApgService API");
Log.w(TAG, "This probably won't work!"); Log.w(TAG, "This probably won't work!");
warning_list.add("(LOCAL) Could not determine ApgService API"); mWarningList.add("(LOCAL) Could not determine ApgService API");
tmp_connection_status = error.APG_API_MISSMATCH; tmpError = error.APG_API_MISSMATCH;
} else if (inf.metaData.getInt("api_version") != api_version) { } else if (inf.metaData.getInt("api_version") != API_VERSION) {
Log.w(TAG, "Found ApgService API version" + inf.metaData.getInt("api_version") + " but exspected " + api_version); Log.w(TAG, "Found ApgService API version" + inf.metaData.getInt("api_version") + " but exspected " + API_VERSION);
Log.w(TAG, "This probably won't work!"); Log.w(TAG, "This probably won't work!");
warning_list.add("(LOCAL) Found ApgService API version" + inf.metaData.getInt("api_version") + " but exspected " + api_version); mWarningList.add("(LOCAL) Found ApgService API version" + inf.metaData.getInt("api_version") + " but exspected " + API_VERSION);
tmp_connection_status = error.APG_API_MISSMATCH; tmpError = error.APG_API_MISSMATCH;
} else { } else {
if( LOCAL_LOGV ) Log.v(TAG, "Found api_version " + api_version + ", everything should work"); if( LOCAL_LOGV ) Log.v(TAG, "Found api_version " + API_VERSION + ", everything should work");
tmp_connection_status = error.NO_ERROR; tmpError = error.NO_ERROR;
} }
} }
} }
if (!apg_service_found) { if (!apgServiceFound) {
Log.e(TAG, "Could not find APG with AIDL interface, this probably won't work"); Log.e(TAG, "Could not find APG with AIDL interface, this probably won't work");
error_list.add("(LOCAL) Could not find APG with AIDL interface, this probably won't work"); mErrorList.add("(LOCAL) Could not find APG with AIDL interface, this probably won't work");
result.putInt(ret.ERROR.name(), error.APG_AIDL_MISSING.ordinal()); mResult.putInt(ret.ERROR.name(), error.APG_AIDL_MISSING.ordinal());
tmp_connection_status = error.APG_NOT_FOUND; tmpError = error.APG_NOT_FOUND;
} }
} }
} catch (PackageManager.NameNotFoundException e) { } catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Could not find APG, is it installed?", e); Log.e(TAG, "Could not find APG, is it installed?", e);
error_list.add("(LOCAL) Could not find APG, is it installed?"); mErrorList.add("(LOCAL) Could not find APG, is it installed?");
result.putInt(ret.ERROR.name(), error.APG_NOT_FOUND.ordinal()); mResult.putInt(ret.ERROR.name(), error.APG_NOT_FOUND.ordinal());
tmp_connection_status = error.APG_NOT_FOUND; tmpError = error.APG_NOT_FOUND;
} }
connection_status = tmp_connection_status; mConnectionStatus = tmpError;
} }
/** try to connect to the apg service */ /** try to connect to the apg service */
private boolean connect() { private boolean connect() {
if( LOCAL_LOGV ) Log.v(TAG, "trying to bind the apgService to context"); if( LOCAL_LOGV ) Log.v(TAG, "trying to bind the apgService to context");
if (apgService != null) { if (mApgService != null) {
if( LOCAL_LOGV ) Log.v(TAG, "allready connected"); if( LOCAL_LOGV ) Log.v(TAG, "allready connected");
return true; return true;
} }
try { try {
mContext.bindService(new Intent(IApgService.class.getName()), apgConnection, Context.BIND_AUTO_CREATE); mContext.bindService(new Intent(IApgService.class.getName()), mApgConnection, Context.BIND_AUTO_CREATE);
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "could not bind APG service", e); Log.e(TAG, "could not bind APG service", e);
return false; return false;
} }
int wait_count = 0; int waitCount = 0;
while (apgService == null && wait_count++ < 15) { while (mApgService == null && waitCount++ < secondsToWaitForConnection) {
if( LOCAL_LOGV ) Log.v(TAG, "sleeping 1 second to wait for apg"); if( LOCAL_LOGV ) Log.v(TAG, "sleeping 1 second to wait for apg");
android.os.SystemClock.sleep(1000); android.os.SystemClock.sleep(1000);
} }
if (wait_count >= 15) { if (waitCount >= secondsToWaitForConnection) {
if( LOCAL_LOGV ) Log.v(TAG, "slept waiting for nothing!"); if( LOCAL_LOGV ) Log.v(TAG, "slept waiting for nothing!");
return false; return false;
} }
@ -250,14 +257,14 @@ public class ApgCon {
*/ */
public void disconnect() { public void disconnect() {
if( LOCAL_LOGV ) Log.v(TAG, "disconnecting apgService"); if( LOCAL_LOGV ) Log.v(TAG, "disconnecting apgService");
if (apgService != null) { if (mApgService != null) {
mContext.unbindService(apgConnection); mContext.unbindService(mApgConnection);
apgService = null; mApgService = null;
} }
} }
private boolean initialize() { private boolean initialize() {
if (apgService == null) { if (mApgService == null) {
if (!connect()) { if (!connect()) {
if( LOCAL_LOGV ) Log.v(TAG, "connection to apg service failed"); if( LOCAL_LOGV ) Log.v(TAG, "connection to apg service failed");
return false; return false;
@ -270,40 +277,40 @@ public class ApgCon {
* Calls a function from APG's AIDL-interface * Calls a function from APG's AIDL-interface
* *
* <p> * <p>
* After you have set up everything with {@link #set_arg(String, String)} * After you have set up everything with {@link #setArg(String, String)}
* (and variants), you can call a function from the AIDL-interface. This * (and variants), you can call a function from the AIDL-interface. This
* will * will
* <ul> * <ul>
* <li>start connection to the remote interface (if not already connected)</li> * <li>start connection to the remote interface (if not already connected)</li>
* <li>call the passed function with all set up parameters synchronously</li> * <li>call the passed function with all set up parameters synchronously</li>
* <li>set up everything to retrieve the result and/or warnings/errors</li> * <li>set up everything to retrieve the mResult and/or warnings/errors</li>
* <li>call the callback if provided * <li>call the callback if provided
* </ul> * </ul>
* </p> * </p>
* *
* <p> * <p>
* Note your thread will be blocked during execution - if you want to call * Note your thread will be blocked during execution - if you want to call
* the function asynchronously, see {@link #call_async(String)}. * the function asynchronously, see {@link #callAsync(String)}.
* </p> * </p>
* *
* @param function * @param function
* a remote function to call * a remote function to call
* @return true, if call successful (= no errors), else false * @return true, if call successful (= no errors), else false
* *
* @see #call_async(String) * @see #callAsync(String)
* @see #set_arg(String, String) * @see #setArg(String, String)
* @see #set_onCallFinishListener(OnCallFinishListener) * @see #setOnCallFinishListener(OnCallFinishListener)
*/ */
public boolean call(String function) { public boolean call(String function) {
boolean success = this.call(function, args, result); boolean success = this.call(function, mArgs, mResult);
if (onCallFinishListener != null) { if (mOnCallFinishListener != null) {
try { try {
if( LOCAL_LOGD ) Log.d(TAG, "About to execute callback"); if( LOCAL_LOGD ) Log.d(TAG, "About to execute callback");
onCallFinishListener.onCallFinish(result); mOnCallFinishListener.onCallFinish(mResult);
if( LOCAL_LOGD ) Log.d(TAG, "Callback executed"); if( LOCAL_LOGD ) Log.d(TAG, "Callback executed");
} catch (Exception e) { } catch (Exception e) {
Log.w(TAG, "Exception on callback: (" + e.getClass() + ") " + e.getMessage(), e); Log.w(TAG, "Exception on callback: (" + e.getClass() + ") " + e.getMessage(), e);
warning_list.add("(LOCAL) Could not execute callback (" + e.getClass() + "): " + e.getMessage()); mWarningList.add("(LOCAL) Could not execute callback (" + e.getClass() + "): " + e.getMessage());
} }
} }
return success; return success;
@ -321,8 +328,8 @@ public class ApgCon {
* <p> * <p>
* To see whether the task is finished, you have to possibilities: * To see whether the task is finished, you have to possibilities:
* <ul> * <ul>
* <li>In your thread, poll {@link #is_running()}</li> * <li>In your thread, poll {@link #isRunning()}</li>
* <li>Supply a callback with {@link #set_onCallFinishListener(OnCallFinishListener)}</li> * <li>Supply a callback with {@link #setOnCallFinishListener(OnCallFinishListener)}</li>
* </ul> * </ul>
* </p> * </p>
* *
@ -330,47 +337,47 @@ public class ApgCon {
* a remote function to call * a remote function to call
* *
* @see #call(String) * @see #call(String)
* @see #is_running() * @see #isRunning()
* @see #set_onCallFinishListener(OnCallFinishListener) * @see #setOnCallFinishListener(OnCallFinishListener)
*/ */
public void call_async(String function) { public void callAsync(String function) {
async_running = true; mAsyncRunning = true;
new call_async().execute(function); new CallAsync().execute(function);
} }
private boolean call(String function, Bundle pArgs, Bundle pReturn) { private boolean call(String function, Bundle pArgs, Bundle pReturn) {
if (!initialize()) { if (!initialize()) {
error_list.add("(LOCAL) Cannot bind to ApgService"); mErrorList.add("(LOCAL) Cannot bind to ApgService");
result.putInt(ret.ERROR.name(), error.CANNOT_BIND_TO_APG.ordinal()); mResult.putInt(ret.ERROR.name(), error.CANNOT_BIND_TO_APG.ordinal());
return false; return false;
} }
if (function == null || function.length() == 0) { if (function == null || function.length() == 0) {
error_list.add("(LOCAL) Function to call missing"); mErrorList.add("(LOCAL) Function to call missing");
result.putInt(ret.ERROR.name(), error.CALL_MISSING.ordinal()); mResult.putInt(ret.ERROR.name(), error.CALL_MISSING.ordinal());
return false; return false;
} }
try { try {
Boolean success = (Boolean) IApgService.class.getMethod(function, Bundle.class, Bundle.class).invoke(apgService, pArgs, pReturn); Boolean success = (Boolean) IApgService.class.getMethod(function, Bundle.class, Bundle.class).invoke(mApgService, pArgs, pReturn);
error_list.addAll(pReturn.getStringArrayList(ret.ERRORS.name())); mErrorList.addAll(pReturn.getStringArrayList(ret.ERRORS.name()));
warning_list.addAll(pReturn.getStringArrayList(ret.WARNINGS.name())); mWarningList.addAll(pReturn.getStringArrayList(ret.WARNINGS.name()));
return success; return success;
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
Log.e(TAG, "Remote call not known (" + function + "): " + e.getMessage(), e); Log.e(TAG, "Remote call not known (" + function + "): " + e.getMessage(), e);
error_list.add("(LOCAL) Remote call not known (" + function + "): " + e.getMessage()); mErrorList.add("(LOCAL) Remote call not known (" + function + "): " + e.getMessage());
result.putInt(ret.ERROR.name(), error.CALL_NOT_KNOWN.ordinal()); mResult.putInt(ret.ERROR.name(), error.CALL_NOT_KNOWN.ordinal());
return false; return false;
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
Throwable orig = e.getTargetException(); Throwable orig = e.getTargetException();
Log.w(TAG, "Exception of type '" + orig.getClass() + "' on AIDL call '" + function + "': " + orig.getMessage(), orig); Log.w(TAG, "Exception of type '" + orig.getClass() + "' on AIDL call '" + function + "': " + orig.getMessage(), orig);
error_list.add("(LOCAL) Exception of type '" + orig.getClass() + "' on AIDL call '" + function + "': " + orig.getMessage()); mErrorList.add("(LOCAL) Exception of type '" + orig.getClass() + "' on AIDL call '" + function + "': " + orig.getMessage());
return false; return false;
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, "Generic error (" + e.getClass() + "): " + e.getMessage(), e); Log.e(TAG, "Generic error (" + e.getClass() + "): " + e.getMessage(), e);
error_list.add("(LOCAL) Generic error (" + e.getClass() + "): " + e.getMessage()); mErrorList.add("(LOCAL) Generic error (" + e.getClass() + "): " + e.getMessage());
result.putInt(ret.ERROR.name(), error.GENERIC.ordinal()); mResult.putInt(ret.ERROR.name(), error.GENERIC.ordinal());
return false; return false;
} }
@ -390,7 +397,7 @@ public class ApgCon {
* *
* <p> * <p>
* Note, that the parameters are not deleted after a call, so you have to * Note, that the parameters are not deleted after a call, so you have to
* reset ({@link #clear_args()}) them manually if you want to. * reset ({@link #clearArgs()}) them manually if you want to.
* </p> * </p>
* *
* *
@ -399,10 +406,10 @@ public class ApgCon {
* @param val * @param val
* the value * the value
* *
* @see #clear_args() * @see #clearArgs()
*/ */
public void set_arg(String key, String val) { public void setArg(String key, String val) {
args.putString(key, val); mArgs.putString(key, val);
} }
/** /**
@ -415,7 +422,7 @@ public class ApgCon {
* *
* <code> * <code>
* <pre> * <pre>
* set_arg("a key", new String[]{ "entry 1", "entry 2" }); * setArg("a key", new String[]{ "entry 1", "entry 2" });
* </pre> * </pre>
* </code> * </code>
* *
@ -424,14 +431,14 @@ public class ApgCon {
* @param vals * @param vals
* the value * the value
* *
* @see #set_arg(String, String) * @see #setArg(String, String)
*/ */
public void set_arg(String key, String vals[]) { public void setArg(String key, String vals[]) {
ArrayList<String> list = new ArrayList<String>(); ArrayList<String> list = new ArrayList<String>();
for (String val : vals) { for (String val : vals) {
list.add(val); list.add(val);
} }
args.putStringArrayList(key, list); mArgs.putStringArrayList(key, list);
} }
/** /**
@ -442,10 +449,10 @@ public class ApgCon {
* @param vals * @param vals
* the value * the value
* *
* @see #set_arg(String, String) * @see #setArg(String, String)
*/ */
public void set_arg(String key, boolean val) { public void setArg(String key, boolean val) {
args.putBoolean(key, val); mArgs.putBoolean(key, val);
} }
/** /**
@ -456,10 +463,10 @@ public class ApgCon {
* @param vals * @param vals
* the value * the value
* *
* @see #set_arg(String, String) * @see #setArg(String, String)
*/ */
public void set_arg(String key, int val) { public void setArg(String key, int val) {
args.putInt(key, val); mArgs.putInt(key, val);
} }
/** /**
@ -474,14 +481,14 @@ public class ApgCon {
* @param vals * @param vals
* the value * the value
* *
* @see #set_arg(String, String) * @see #setArg(String, String)
*/ */
public void set_arg(String key, int vals[]) { public void setArg(String key, int vals[]) {
ArrayList<Integer> list = new ArrayList<Integer>(); ArrayList<Integer> list = new ArrayList<Integer>();
for (int val : vals) { for (int val : vals) {
list.add(val); list.add(val);
} }
args.putIntegerArrayList(key, list); mArgs.putIntegerArrayList(key, list);
} }
/** /**
@ -489,17 +496,17 @@ public class ApgCon {
* *
* <p> * <p>
* Anything the has been set up with the various * Anything the has been set up with the various
* {@link #set_arg(String, String)} functions, is cleared. * {@link #setArg(String, String)} functions, is cleared.
* </p> * </p>
* <p> * <p>
* Note, that any warning, error, callback, result, etc. is not cleared with * Note, that any warning, error, callback, mResult, etc. is not cleared with
* this. * this.
* </p> * </p>
* *
* @see #reset() * @see #reset()
*/ */
public void clear_args() { public void clearArgs() {
args.clear(); mArgs.clear();
} }
/** /**
@ -509,8 +516,8 @@ public class ApgCon {
* the object's key you want to return * the object's key you want to return
* @return an object at position key, or null if not set * @return an object at position key, or null if not set
*/ */
public Object get_arg(String key) { public Object getArg(String key) {
return args.get(key); return mArgs.get(key);
} }
/** /**
@ -525,12 +532,12 @@ public class ApgCon {
* @return a human readable description of a error that happened, or null if * @return a human readable description of a error that happened, or null if
* no more errors * no more errors
* *
* @see #has_next_error() * @see #hasNextError()
* @see #clear_errors() * @see #clearErrors()
*/ */
public String get_next_error() { public String getNextError() {
if (error_list.size() != 0) if (mErrorList.size() != 0)
return error_list.remove(0); return mErrorList.remove(0);
else else
return null; return null;
} }
@ -540,10 +547,10 @@ public class ApgCon {
* *
* @return true, if there are unreturned errors, false otherwise * @return true, if there are unreturned errors, false otherwise
* *
* @see #get_next_error() * @see #getNextError()
*/ */
public boolean has_next_error() { public boolean hasNextError() {
return error_list.size() != 0; return mErrorList.size() != 0;
} }
/** /**
@ -552,15 +559,15 @@ public class ApgCon {
* <p> * <p>
* Values <100 mean the error happened locally, values >=100 mean the error * Values <100 mean the error happened locally, values >=100 mean the error
* happened at the remote side (APG). See the IApgService.aidl (or get the * happened at the remote side (APG). See the IApgService.aidl (or get the
* human readable description with {@link #get_next_error()}) for what * human readable description with {@link #getNextError()}) for what
* errors >=100 mean. * errors >=100 mean.
* </p> * </p>
* *
* @return the id of the error that happened * @return the id of the error that happened
*/ */
public int get_error() { public int getError() {
if (result.containsKey(ret.ERROR.name())) if (mResult.containsKey(ret.ERROR.name()))
return result.getInt(ret.ERROR.name()); return mResult.getInt(ret.ERROR.name());
else else
return -1; return -1;
} }
@ -577,12 +584,12 @@ public class ApgCon {
* @return a human readable description of a warning that happened, or null * @return a human readable description of a warning that happened, or null
* if no more warnings * if no more warnings
* *
* @see #has_next_warning() * @see #hasNextWarning()
* @see #clear_warnings() * @see #clearWarnings()
*/ */
public String get_next_warning() { public String getNextWarning() {
if (warning_list.size() != 0) if (mWarningList.size() != 0)
return warning_list.remove(0); return mWarningList.remove(0);
else else
return null; return null;
} }
@ -592,94 +599,94 @@ public class ApgCon {
* *
* @return true, if there are unreturned warnings, false otherwise * @return true, if there are unreturned warnings, false otherwise
* *
* @see #get_next_warning() * @see #getNextWarning()
*/ */
public boolean has_next_warning() { public boolean hasNextWarning() {
return warning_list.size() != 0; return mWarningList.size() != 0;
} }
/** /**
* Get the result * Get the result
* *
* <p> * <p>
* This gets your result. After doing an encryption or decryption with APG, * This gets your mResult. After doing an encryption or decryption with APG,
* you get the output with this function. * you get the output with this function.
* </p> * </p>
* <p> * <p>
* Note, that when your last remote call is unsuccessful, the result will * Note, that when your last remote call is unsuccessful, the mResult will
* still have the same value like the last successful call (or null, if no * still have the same value like the last successful call (or null, if no
* call was successful). To ensure you do not work with old call's results, * call was successful). To ensure you do not work with old call's mResults,
* either be sure to {@link #reset()} (or at least {@link #clear_result()}) * either be sure to {@link #reset()} (or at least {@link #clearResult()})
* your instance before each new call or always check that * your instance before each new call or always check that
* {@link #has_next_error()} is false. * {@link #hasNextError()} is false.
* </p> * </p>
* *
* @return the result of the last {@link #call(String)} or * @return the mResult of the last {@link #call(String)} or
* {@link #call_asinc(String)}. * {@link #call_asinc(String)}.
* *
* @see #reset() * @see #reset()
* @see #clear_result() * @see #clearResult()
* @see #get_result_bundle() * @see #getResultBundle()
*/ */
public String get_result() { public String getResult() {
return result.getString(ret.RESULT.name()); return mResult.getString(ret.RESULT.name());
} }
/** /**
* Get the result bundle * Get the mResult bundle
* *
* <p> * <p>
* Unlike {@link #get_result()}, which only returns any en-/decrypted * Unlike {@link #getResult()}, which only returns any en-/decrypted
* message, this function returns the complete information that was returned * message, this function returns the complete information that was returned
* by Apg. This also includes the "RESULT", but additionally the warnings, * by Apg. This also includes the "RESULT", but additionally the warnings,
* errors and any other information. * errors and any other information.
* </p> * </p>
* <p> * <p>
* For warnings and errors it is suggested to use the functions that are * For warnings and errors it is suggested to use the functions that are
* provided here, namely {@link #get_error()}, {@link #get_next_error()}, * provided here, namely {@link #getError()}, {@link #getNextError()},
* {@link #get_next_Warning()} etc.), but if any call returns something non * {@link #get_next_Warning()} etc.), but if any call returns something non
* standard, you have access to the complete result bundle to extract the * standard, you have access to the complete mResult bundle to extract the
* information. * information.
* </p> * </p>
* *
* @return the complete result-bundle of the last call to apg * @return the complete mResult-bundle of the last call to apg
*/ */
public Bundle get_result_bundle() { public Bundle getResultBundle() {
return result; return mResult;
} }
public error get_connection_status() { public error getConnectionStatus() {
return connection_status; return mConnectionStatus;
} }
/** /**
* Clears all unfetched errors * Clears all unfetched errors
* *
* @see #get_next_error() * @see #getNextError()
* @see #has_next_error() * @see #hasNextError()
*/ */
public void clear_errors() { public void clearErrors() {
error_list.clear(); mErrorList.clear();
result.remove(ret.ERROR.name()); mResult.remove(ret.ERROR.name());
} }
/** /**
* Clears all unfetched warnings * Clears all unfetched warnings
* *
* @see #get_next_warning() * @see #getNextWarning()
* @see #has_next_warning() * @see #hasNextWarning()
*/ */
public void clear_warnings() { public void clearWarnings() {
warning_list.clear(); mWarningList.clear();
} }
/** /**
* Clears the last result * Clears the last mResult
* *
* @see #get_result() * @see #getResult()
*/ */
public void clear_result() { public void clearResult() {
result.remove(ret.RESULT.name()); mResult.remove(ret.RESULT.name());
} }
/** /**
@ -689,34 +696,34 @@ public class ApgCon {
* a object to call back after async execution * a object to call back after async execution
* @see ApgConInterface * @see ApgConInterface
*/ */
public void set_onCallFinishListener(OnCallFinishListener lis) { public void setOnCallFinishListener(OnCallFinishListener lis) {
onCallFinishListener = lis; mOnCallFinishListener = lis;
} }
/** /**
* Clears any callback object * Clears any callback object
* *
* @see #set_onCallFinishListener(OnCallFinishListener) * @see #setOnCallFinishListener(OnCallFinishListener)
*/ */
public void clear_onCallFinishListener() { public void clearOnCallFinishListener() {
onCallFinishListener = null; mOnCallFinishListener = null;
} }
/** /**
* Checks, whether an async execution is running * Checks, whether an async execution is running
* *
* <p> * <p>
* If you started something with {@link #call_async(String)}, this will * If you started something with {@link #callAsync(String)}, this will
* return true if the task is still running * return true if the task is still running
* </p> * </p>
* *
* @return true, if an async task is still running, false otherwise * @return true, if an async task is still running, false otherwise
* *
* @see #call_async(String) * @see #callAsync(String)
* *
*/ */
public boolean is_running() { public boolean isRunning() {
return async_running; return mAsyncRunning;
} }
/** /**
@ -724,24 +731,24 @@ public class ApgCon {
* *
* <p> * <p>
* This currently resets everything in this instance. Errors, warnings, * This currently resets everything in this instance. Errors, warnings,
* results, callbacks, ... are removed. Any connection to the remote * mResults, callbacks, ... are removed. Any connection to the remote
* interface is upheld, though. * interface is upheld, though.
* </p> * </p>
* *
* <p> * <p>
* Note, that when an async execution ({@link #call_async(String)}) is * Note, that when an async execution ({@link #callAsync(String)}) is
* running, it's result, warnings etc. will still be evaluated (which might * running, it's mResult, warnings etc. will still be evaluated (which might
* be not what you want). Also mind, that any callback you set is also * be not what you want). Also mind, that any callback you set is also
* reseted, so on finishing the execution any before defined callback will * reseted, so on finishing the execution any before defined callback will
* NOT BE TRIGGERED. * NOT BE TRIGGERED.
* </p> * </p>
*/ */
public void reset() { public void reset() {
clear_errors(); clearErrors();
clear_warnings(); clearWarnings();
clear_args(); clearArgs();
clear_onCallFinishListener(); clearOnCallFinishListener();
result.clear(); mResult.clear();
} }
} }