Merge branch 'master' into improve-file-more

Conflicts:
	.gitmodules
	OpenKeychain/build.gradle
	OpenKeychain/src/main/AndroidManifest.xml
	OpenKeychain/src/main/java/org/sufficientlysecure/keychain/provider/CachedPublicKeyRing.java
	OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptFileFragment.java
	OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/DecryptMessageFragment.java
	OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptAsymmetricFragment.java
	OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptFileFragment.java
	OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/EncryptMessageFragment.java
This commit is contained in:
mar-v-in
2014-07-31 23:19:01 +02:00
439 changed files with 8241 additions and 3217 deletions

View File

@@ -31,11 +31,15 @@ import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.helper.FileHelper;
import org.sufficientlysecure.keychain.helper.OtherHelper;
import org.sufficientlysecure.keychain.helper.Preferences;
import org.sufficientlysecure.keychain.keyimport.FileImportCache;
import org.sufficientlysecure.keychain.keyimport.HkpKeyserver;
import org.sufficientlysecure.keychain.keyimport.Keyserver;
import org.sufficientlysecure.keychain.keyimport.ImportKeysListEntry;
import org.sufficientlysecure.keychain.keyimport.KeybaseKeyserver;
import org.sufficientlysecure.keychain.keyimport.Keyserver;
import org.sufficientlysecure.keychain.keyimport.ParcelableKeyRing;
import org.sufficientlysecure.keychain.pgp.CanonicalizedPublicKeyRing;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKey;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing;
import org.sufficientlysecure.keychain.pgp.PgpDecryptVerify;
import org.sufficientlysecure.keychain.pgp.PgpDecryptVerifyResult;
import org.sufficientlysecure.keychain.pgp.PgpHelper;
@@ -44,15 +48,13 @@ import org.sufficientlysecure.keychain.pgp.PgpKeyOperation;
import org.sufficientlysecure.keychain.pgp.PgpSignEncrypt;
import org.sufficientlysecure.keychain.pgp.Progressable;
import org.sufficientlysecure.keychain.pgp.UncachedKeyRing;
import org.sufficientlysecure.keychain.pgp.WrappedPublicKeyRing;
import org.sufficientlysecure.keychain.pgp.WrappedSecretKey;
import org.sufficientlysecure.keychain.pgp.WrappedSecretKeyRing;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralMsgIdException;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.KeychainDatabase;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.service.OperationResultParcel.OperationLog;
import org.sufficientlysecure.keychain.service.OperationResults.EditKeyResult;
import org.sufficientlysecure.keychain.service.OperationResults.ImportKeyResult;
import org.sufficientlysecure.keychain.util.InputData;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.ProgressScaler;
@@ -138,9 +140,6 @@ public class KeychainIntentService extends IntentService
// delete file securely
public static final String DELETE_FILE = "deleteFile";
// import key
public static final String IMPORT_KEY_LIST = "import_key_list";
// export key
public static final String EXPORT_OUTPUT_STREAM = "export_output_stream";
public static final String EXPORT_FILENAME = "export_filename";
@@ -175,7 +174,7 @@ public class KeychainIntentService extends IntentService
// export
public static final String RESULT_EXPORT = "exported";
public static final String RESULT = "result";
public static final String RESULT_IMPORT = "result";
Messenger mMessenger;
@@ -342,39 +341,37 @@ public class KeychainIntentService extends IntentService
/* Operation */
ProviderHelper providerHelper = new ProviderHelper(this);
PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 10, 50, 100));
try {
OperationLog log = new OperationLog();
UncachedKeyRing ring;
if (saveParcel.mMasterKeyId != null) {
String passphrase = data.getString(SAVE_KEYRING_PASSPHRASE);
WrappedSecretKeyRing secRing =
providerHelper.getWrappedSecretKeyRing(saveParcel.mMasterKeyId);
PgpKeyOperation keyOperations = new PgpKeyOperation(new ProgressScaler(this, 10, 60, 100));
EditKeyResult result;
ring = keyOperations.modifySecretKeyRing(secRing, saveParcel,
passphrase, log, 0);
} else {
ring = keyOperations.createSecretKeyRing(saveParcel, log, 0);
}
if (saveParcel.mMasterKeyId != null) {
String passphrase = data.getString(SAVE_KEYRING_PASSPHRASE);
CanonicalizedSecretKeyRing secRing =
providerHelper.getCanonicalizedSecretKeyRing(saveParcel.mMasterKeyId);
providerHelper.saveSecretKeyRing(ring, new ProgressScaler(this, 10, 95, 100));
result = keyOperations.modifySecretKeyRing(secRing, saveParcel, passphrase);
} else {
result = keyOperations.createSecretKeyRing(saveParcel);
}
// cache new passphrase
if (saveParcel.newPassphrase != null) {
PassphraseCacheService.addCachedPassphrase(this, ring.getMasterKeyId(),
saveParcel.newPassphrase);
}
} catch (ProviderHelper.NotFoundException e) {
sendErrorToHandler(e);
UncachedKeyRing ring = result.getRing();
providerHelper.saveSecretKeyRing(ring, new ProgressScaler(this, 60, 95, 100));
// cache new passphrase
if (saveParcel.mNewPassphrase != null) {
PassphraseCacheService.addCachedPassphrase(this, ring.getMasterKeyId(),
saveParcel.mNewPassphrase, ring.getPublicKey().getPrimaryUserIdWithFallback());
}
setProgress(R.string.progress_done, 100, 100);
/* Output */
sendMessageToHandler(KeychainIntentServiceHandler.MESSAGE_OKAY);
sendMessageToHandler(KeychainIntentServiceHandler.MESSAGE_OKAY, result);
} catch (Exception e) {
sendErrorToHandler(e);
}
} else if (ACTION_DELETE_FILE_SECURELY.equals(action)) {
try {
/* Input */
@@ -398,13 +395,15 @@ public class KeychainIntentService extends IntentService
}
} else if (ACTION_IMPORT_KEYRING.equals(action)) {
try {
List<ParcelableKeyRing> entries = data.getParcelableArrayList(IMPORT_KEY_LIST);
// get entries from cached file
FileImportCache cache = new FileImportCache(this);
List<ParcelableKeyRing> entries = cache.readCache();
PgpImportExport pgpImportExport = new PgpImportExport(this, this);
OperationResults.ImportResult result = pgpImportExport.importKeyRings(entries);
ImportKeyResult result = pgpImportExport.importKeyRings(entries);
Bundle resultData = new Bundle();
resultData.putParcelable(RESULT, result);
resultData.putParcelable(RESULT_IMPORT, result);
sendMessageToHandler(KeychainIntentServiceHandler.MESSAGE_OKAY, resultData);
} catch (Exception e) {
@@ -488,7 +487,7 @@ public class KeychainIntentService extends IntentService
HkpKeyserver server = new HkpKeyserver(keyServer);
ProviderHelper providerHelper = new ProviderHelper(this);
WrappedPublicKeyRing keyring = providerHelper.getWrappedPublicKeyRing(dataUri);
CanonicalizedPublicKeyRing keyring = providerHelper.getCanonicalizedPublicKeyRing(dataUri);
PgpImportExport pgpImportExport = new PgpImportExport(this, null);
boolean uploaded = pgpImportExport.uploadKeyRingToServer(server, keyring);
@@ -537,7 +536,6 @@ public class KeychainIntentService extends IntentService
Intent importIntent = new Intent(this, KeychainIntentService.class);
importIntent.setAction(ACTION_IMPORT_KEYRING);
Bundle importData = new Bundle();
importData.putParcelableArrayList(IMPORT_KEY_LIST, keyRings);
importIntent.putExtra(EXTRA_DATA, importData);
importIntent.putExtra(EXTRA_MESSENGER, mMessenger);
@@ -564,9 +562,9 @@ public class KeychainIntentService extends IntentService
}
ProviderHelper providerHelper = new ProviderHelper(this);
WrappedPublicKeyRing publicRing = providerHelper.getWrappedPublicKeyRing(pubKeyId);
WrappedSecretKeyRing secretKeyRing = providerHelper.getWrappedSecretKeyRing(masterKeyId);
WrappedSecretKey certificationKey = secretKeyRing.getSubKey();
CanonicalizedPublicKeyRing publicRing = providerHelper.getCanonicalizedPublicKeyRing(pubKeyId);
CanonicalizedSecretKeyRing secretKeyRing = providerHelper.getCanonicalizedSecretKeyRing(masterKeyId);
CanonicalizedSecretKey certificationKey = secretKeyRing.getSecretKey();
if(!certificationKey.unlock(signaturePassphrase)) {
throw new PgpGeneralException("Error extracting key (bad passphrase?)");
}
@@ -644,6 +642,12 @@ public class KeychainIntentService extends IntentService
}
}
private void sendMessageToHandler(Integer arg1, OperationResultParcel data) {
Bundle bundle = new Bundle();
bundle.putParcelable(OperationResultParcel.EXTRA_RESULT, data);
sendMessageToHandler(arg1, null, bundle);
}
private void sendMessageToHandler(Integer arg1, Bundle data) {
sendMessageToHandler(arg1, null, data);
}

View File

@@ -25,12 +25,11 @@ import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import com.devspark.appmsg.AppMsg;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.ui.dialog.ProgressDialogFragment;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.Notify;
public class KeychainIntentServiceHandler extends Handler {
@@ -102,9 +101,9 @@ public class KeychainIntentServiceHandler extends Handler {
// show error from service
if (data.containsKey(DATA_ERROR)) {
AppMsg.makeText(mActivity,
Notify.showNotify(mActivity,
mActivity.getString(R.string.error_message, data.getString(DATA_ERROR)),
AppMsg.STYLE_ALERT).show();
Notify.Style.ERROR);
}
break;

View File

@@ -1,14 +1,27 @@
package org.sufficientlysecure.keychain.service;
import android.app.Activity;
import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import android.view.View;
import com.github.johnpersano.supertoasts.SuperCardToast;
import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.OnClickWrapper;
import com.github.johnpersano.supertoasts.util.Style;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.ui.LogDisplayActivity;
import org.sufficientlysecure.keychain.ui.LogDisplayFragment;
import org.sufficientlysecure.keychain.util.IterableIterator;
import org.sufficientlysecure.keychain.util.Log;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/** Represent the result of an operation.
*
@@ -21,6 +34,9 @@ import java.util.ArrayList;
*
*/
public class OperationResultParcel implements Parcelable {
public static final String EXTRA_RESULT = "operation_result";
/** Holds the overall result, the number specifying varying degrees of success. The first bit
* is 0 on overall success, 1 on overall failure. All other bits may be used for more specific
* conditions. */
@@ -67,9 +83,7 @@ public class OperationResultParcel implements Parcelable {
mType = type;
mParameters = parameters;
mIndent = indent;
}
public LogEntryParcel(LogLevel level, LogType type, Object... parameters) {
this(level, type, 0, parameters);
Log.v(Constants.TAG, "log: " + this.toString());
}
public LogEntryParcel(Parcel source) {
@@ -102,6 +116,77 @@ public class OperationResultParcel implements Parcelable {
}
};
@Override
public String toString() {
return "LogEntryParcel{" +
"mLevel=" + mLevel +
", mType=" + mType +
", mParameters=" + Arrays.toString(mParameters) +
", mIndent=" + mIndent +
'}';
}
}
public SuperCardToast createNotify(final Activity activity) {
int resultType = getResult();
String str;
int duration, color;
// Not an overall failure
if ((resultType & OperationResultParcel.RESULT_ERROR) == 0) {
if (getLog().containsWarnings()) {
duration = 0;
color = Style.ORANGE;
} else {
duration = SuperToast.Duration.LONG;
color = Style.GREEN;
}
str = "operation succeeded!";
// str = activity.getString(R.string.import_error);
} else {
duration = 0;
color = Style.RED;
str = "operation failed";
// str = activity.getString(R.string.import_error);
}
boolean button = getLog() != null && !getLog().isEmpty();
SuperCardToast toast = new SuperCardToast(activity,
button ? SuperToast.Type.BUTTON : SuperToast.Type.STANDARD,
Style.getStyle(color, SuperToast.Animations.POPUP));
toast.setText(str);
toast.setDuration(duration);
toast.setIndeterminate(duration == 0);
toast.setSwipeToDismiss(true);
// If we have a log and it's non-empty, show a View Log button
if (button) {
toast.setButtonIcon(R.drawable.ic_action_view_as_list,
activity.getResources().getString(R.string.view_log));
toast.setButtonTextColor(activity.getResources().getColor(R.color.black));
toast.setTextColor(activity.getResources().getColor(R.color.black));
toast.setOnClickWrapper(new OnClickWrapper("supercardtoast",
new SuperToast.OnClickListener() {
@Override
public void onClick(View view, Parcelable token) {
Intent intent = new Intent(
activity, LogDisplayActivity.class);
intent.putExtra(LogDisplayFragment.EXTRA_RESULT, OperationResultParcel.this);
activity.startActivity(intent);
}
}
));
}
return toast;
}
/** This is an enum of all possible log events.
@@ -123,6 +208,8 @@ public class OperationResultParcel implements Parcelable {
*/
public static enum LogType {
INTERNAL_ERROR (R.string.internal_error),
// import public
MSG_IP(R.string.msg_ip),
MSG_IP_APPLY_BATCH (R.string.msg_ip_apply_batch),
@@ -193,6 +280,7 @@ public class OperationResultParcel implements Parcelable {
MSG_KC_REVOKE_BAD_LOCAL (R.string.msg_kc_revoke_bad_local),
MSG_KC_REVOKE_BAD_TIME (R.string.msg_kc_revoke_bad_time),
MSG_KC_REVOKE_BAD_TYPE (R.string.msg_kc_revoke_bad_type),
MSG_KC_REVOKE_BAD_TYPE_UID (R.string.msg_kc_revoke_bad_type_uid),
MSG_KC_REVOKE_BAD (R.string.msg_kc_revoke_bad),
MSG_KC_REVOKE_DUP (R.string.msg_kc_revoke_dup),
MSG_KC_SUB (R.string.msg_kc_sub),
@@ -224,6 +312,7 @@ public class OperationResultParcel implements Parcelable {
MSG_KC_UID_NO_CERT (R.string.msg_kc_uid_no_cert),
MSG_KC_UID_REVOKE_DUP (R.string.msg_kc_uid_revoke_dup),
MSG_KC_UID_REVOKE_OLD (R.string.msg_kc_uid_revoke_old),
MSG_KC_UID_REMOVE (R.string.msg_kc_uid_remove),
// keyring consolidation
@@ -233,9 +322,17 @@ public class OperationResultParcel implements Parcelable {
MSG_MG_HETEROGENEOUS (R.string.msg_mg_heterogeneous),
MSG_MG_NEW_SUBKEY (R.string.msg_mg_new_subkey),
MSG_MG_FOUND_NEW (R.string.msg_mg_found_new),
MSG_MG_UNCHANGED (R.string.msg_mg_unchanged),
// secret key create
MSG_CR_ERROR_NO_MASTER (R.string.msg_mr),
MSG_CR (R.string.msg_cr),
MSG_CR_ERROR_NO_MASTER (R.string.msg_cr_error_no_master),
MSG_CR_ERROR_NO_USER_ID (R.string.msg_cr_error_no_user_id),
MSG_CR_ERROR_NO_CERTIFY (R.string.msg_cr_error_no_certify),
MSG_CR_ERROR_KEYSIZE_512 (R.string.msg_cr_error_keysize_512),
MSG_CR_ERROR_UNKNOWN_ALGO (R.string.msg_cr_error_unknown_algo),
MSG_CR_ERROR_INTERNAL_PGP (R.string.msg_cr_error_internal_pgp),
MSG_CR_ERROR_MASTER_ELGAMAL (R.string.msg_cr_error_master_elgamal),
// secret key modify
MSG_MF (R.string.msg_mr),
@@ -243,10 +340,13 @@ public class OperationResultParcel implements Parcelable {
MSG_MF_ERROR_FINGERPRINT (R.string.msg_mf_error_fingerprint),
MSG_MF_ERROR_KEYID (R.string.msg_mf_error_keyid),
MSG_MF_ERROR_INTEGRITY (R.string.msg_mf_error_integrity),
MSG_MF_ERROR_NOEXIST_PRIMARY (R.string.msg_mf_error_noexist_primary),
MSG_MF_ERROR_REVOKED_PRIMARY (R.string.msg_mf_error_revoked_primary),
MSG_MF_ERROR_PGP (R.string.msg_mf_error_pgp),
MSG_MF_ERROR_SIG (R.string.msg_mf_error_sig),
MSG_MF_PASSPHRASE (R.string.msg_mf_passphrase),
MSG_MF_PRIMARY_REPLACE_OLD (R.string.msg_mf_primary_replace_old),
MSG_MF_PRIMARY_NEW (R.string.msg_mf_primary_new),
MSG_MF_SUBKEY_CHANGE (R.string.msg_mf_subkey_change),
MSG_MF_SUBKEY_MISSING (R.string.msg_mf_subkey_missing),
MSG_MF_SUBKEY_NEW_ID (R.string.msg_mf_subkey_new_id),
@@ -257,6 +357,7 @@ public class OperationResultParcel implements Parcelable {
MSG_MF_UID_ADD (R.string.msg_mf_uid_add),
MSG_MF_UID_PRIMARY (R.string.msg_mf_uid_primary),
MSG_MF_UID_REVOKE (R.string.msg_mf_uid_revoke),
MSG_MF_UID_ERROR_EMPTY (R.string.msg_mf_uid_error_empty),
MSG_MF_UNLOCK_ERROR (R.string.msg_mf_unlock_error),
MSG_MF_UNLOCK (R.string.msg_mf_unlock),
;
@@ -288,7 +389,7 @@ public class OperationResultParcel implements Parcelable {
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mResult);
dest.writeTypedList(mLog);
dest.writeTypedList(mLog.toList());
}
public static final Creator<OperationResultParcel> CREATOR = new Creator<OperationResultParcel>() {
@@ -301,20 +402,21 @@ public class OperationResultParcel implements Parcelable {
}
};
public static class OperationLog extends ArrayList<LogEntryParcel> {
public static class OperationLog implements Iterable<LogEntryParcel> {
private final List<LogEntryParcel> mParcels = new ArrayList<LogEntryParcel>();
/// Simple convenience method
public void add(LogLevel level, LogType type, int indent, Object... parameters) {
Log.d(Constants.TAG, type.toString());
add(new OperationResultParcel.LogEntryParcel(level, type, indent, parameters));
mParcels.add(new OperationResultParcel.LogEntryParcel(level, type, indent, parameters));
}
public void add(LogLevel level, LogType type, int indent) {
add(new OperationResultParcel.LogEntryParcel(level, type, indent, (Object[]) null));
mParcels.add(new OperationResultParcel.LogEntryParcel(level, type, indent, (Object[]) null));
}
public boolean containsWarnings() {
for(LogEntryParcel entry : new IterableIterator<LogEntryParcel>(iterator())) {
for(LogEntryParcel entry : new IterableIterator<LogEntryParcel>(mParcels.iterator())) {
if (entry.mLevel == LogLevel.WARN || entry.mLevel == LogLevel.ERROR) {
return true;
}
@@ -322,6 +424,22 @@ public class OperationResultParcel implements Parcelable {
return false;
}
public void addAll(List<LogEntryParcel> parcels) {
mParcels.addAll(parcels);
}
public List<LogEntryParcel> toList() {
return mParcels;
}
public boolean isEmpty() {
return mParcels.isEmpty();
}
@Override
public Iterator<LogEntryParcel> iterator() {
return mParcels.iterator();
}
}
}

View File

@@ -12,12 +12,13 @@ import com.github.johnpersano.supertoasts.util.OnClickWrapper;
import com.github.johnpersano.supertoasts.util.Style;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.pgp.UncachedKeyRing;
import org.sufficientlysecure.keychain.ui.LogDisplayActivity;
import org.sufficientlysecure.keychain.ui.LogDisplayFragment;
public abstract class OperationResults {
public static class ImportResult extends OperationResultParcel {
public static class ImportKeyResult extends OperationResultParcel {
public final int mNewKeys, mUpdatedKeys, mBadKeys;
@@ -47,15 +48,15 @@ public abstract class OperationResults {
return (mResult & RESULT_FAIL_NOTHING) == RESULT_FAIL_NOTHING;
}
public ImportResult(Parcel source) {
public ImportKeyResult(Parcel source) {
super(source);
mNewKeys = source.readInt();
mUpdatedKeys = source.readInt();
mBadKeys = source.readInt();
}
public ImportResult(int result, OperationLog log,
int newKeys, int updatedKeys, int badKeys) {
public ImportKeyResult(int result, OperationLog log,
int newKeys, int updatedKeys, int badKeys) {
super(result, log);
mNewKeys = newKeys;
mUpdatedKeys = updatedKeys;
@@ -70,17 +71,17 @@ public abstract class OperationResults {
dest.writeInt(mBadKeys);
}
public static Creator<ImportResult> CREATOR = new Creator<ImportResult>() {
public ImportResult createFromParcel(final Parcel source) {
return new ImportResult(source);
public static Creator<ImportKeyResult> CREATOR = new Creator<ImportKeyResult>() {
public ImportKeyResult createFromParcel(final Parcel source) {
return new ImportKeyResult(source);
}
public ImportResult[] newArray(final int size) {
return new ImportResult[size];
public ImportKeyResult[] newArray(final int size) {
return new ImportKeyResult[size];
}
};
public void displayNotify(final Activity activity) {
public SuperCardToast createNotify(final Activity activity) {
int resultType = getResult();
@@ -88,11 +89,11 @@ public abstract class OperationResults {
int duration, color;
// Not an overall failure
if ((resultType & ImportResult.RESULT_ERROR) == 0) {
if ((resultType & OperationResultParcel.RESULT_ERROR) == 0) {
String withWarnings;
// Any warnings?
if ((resultType & ImportResult.RESULT_WITH_WARNINGS) > 0) {
if ((resultType & ImportKeyResult.RESULT_WITH_WARNINGS) > 0) {
duration = 0;
color = Style.ORANGE;
withWarnings = activity.getResources().getString(R.string.import_with_warnings);
@@ -106,7 +107,7 @@ public abstract class OperationResults {
if (this.isOkBoth()) {
str = activity.getResources().getQuantityString(
R.plurals.import_keys_added_and_updated_1, mNewKeys, mNewKeys);
str += activity.getResources().getQuantityString(
str += " "+ activity.getResources().getQuantityString(
R.plurals.import_keys_added_and_updated_2, mUpdatedKeys, mUpdatedKeys, withWarnings);
} else if (isOkUpdated()) {
str = activity.getResources().getQuantityString(
@@ -142,7 +143,7 @@ public abstract class OperationResults {
// If we have a log and it's non-empty, show a View Log button
if (button) {
toast.setButtonIcon(R.drawable.ic_action_view_as_list,
activity.getResources().getString(R.string.import_view_log));
activity.getResources().getString(R.string.view_log));
toast.setButtonTextColor(activity.getResources().getColor(R.color.black));
toast.setTextColor(activity.getResources().getColor(R.color.black));
toast.setOnClickWrapper(new OnClickWrapper("supercardtoast",
@@ -151,18 +152,59 @@ public abstract class OperationResults {
public void onClick(View view, Parcelable token) {
Intent intent = new Intent(
activity, LogDisplayActivity.class);
intent.putExtra(LogDisplayFragment.EXTRA_RESULT, ImportResult.this);
intent.putExtra(LogDisplayFragment.EXTRA_RESULT, ImportKeyResult.this);
activity.startActivity(intent);
}
}
));
}
toast.show();
return toast;
}
}
public static class EditKeyResult extends OperationResultParcel {
private transient UncachedKeyRing mRing;
public final Long mRingMasterKeyId;
public EditKeyResult(int result, OperationLog log,
UncachedKeyRing ring) {
super(result, log);
mRing = ring;
mRingMasterKeyId = ring != null ? ring.getMasterKeyId() : null;
}
public UncachedKeyRing getRing() {
return mRing;
}
public EditKeyResult(Parcel source) {
super(source);
mRingMasterKeyId = source.readLong();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeLong(mRingMasterKeyId);
}
public static Creator<EditKeyResult> CREATOR = new Creator<EditKeyResult>() {
public EditKeyResult createFromParcel(final Parcel source) {
return new EditKeyResult(source);
}
public EditKeyResult[] newArray(final int size) {
return new EditKeyResult[size];
}
};
}
public static class SaveKeyringResult extends OperationResultParcel {
public SaveKeyringResult(int result, OperationLog log) {

View File

@@ -18,6 +18,7 @@
package org.sufficientlysecure.keychain.service;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
@@ -25,6 +26,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
@@ -32,11 +34,15 @@ import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.util.LongSparseArray;
import android.support.v4.app.NotificationCompat;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.helper.Preferences;
import org.sufficientlysecure.keychain.pgp.WrappedSecretKeyRing;
import org.sufficientlysecure.keychain.pgp.CanonicalizedSecretKeyRing;
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.util.Log;
@@ -54,6 +60,8 @@ public class PassphraseCacheService extends Service {
+ "PASSPHRASE_CACHE_ADD";
public static final String ACTION_PASSPHRASE_CACHE_GET = Constants.INTENT_PREFIX
+ "PASSPHRASE_CACHE_GET";
public static final String ACTION_PASSPHRASE_CACHE_CLEAR = Constants.INTENT_PREFIX
+ "PASSPHRASE_CACHE_CLEAR";
public static final String BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE = Constants.INTENT_PREFIX
+ "PASSPHRASE_CACHE_BROADCAST";
@@ -62,13 +70,16 @@ public class PassphraseCacheService extends Service {
public static final String EXTRA_KEY_ID = "key_id";
public static final String EXTRA_PASSPHRASE = "passphrase";
public static final String EXTRA_MESSENGER = "messenger";
public static final String EXTRA_USER_ID = "user_id";
private static final int REQUEST_ID = 0;
private static final long DEFAULT_TTL = 15;
private static final int NOTIFICATION_ID = 1;
private BroadcastReceiver mIntentReceiver;
private LongSparseArray<String> mPassphraseCache = new LongSparseArray<String>();
private LongSparseArray<CachedPassphrase> mPassphraseCache = new LongSparseArray<CachedPassphrase>();
Context mContext;
@@ -81,14 +92,17 @@ public class PassphraseCacheService extends Service {
* @param keyId
* @param passphrase
*/
public static void addCachedPassphrase(Context context, long keyId, String passphrase) {
public static void addCachedPassphrase(Context context, long keyId, String passphrase,
String primaryUserId) {
Log.d(Constants.TAG, "PassphraseCacheService.cacheNewPassphrase() for " + keyId);
Intent intent = new Intent(context, PassphraseCacheService.class);
intent.setAction(ACTION_PASSPHRASE_CACHE_ADD);
intent.putExtra(EXTRA_TTL, Preferences.getPreferences(context).getPassphraseCacheTtl());
intent.putExtra(EXTRA_PASSPHRASE, passphrase);
intent.putExtra(EXTRA_KEY_ID, keyId);
intent.putExtra(EXTRA_USER_ID, primaryUserId);
context.startService(intent);
}
@@ -159,42 +173,46 @@ public class PassphraseCacheService extends Service {
// passphrase for symmetric encryption?
if (keyId == Constants.key.symmetric) {
Log.d(Constants.TAG, "PassphraseCacheService.getCachedPassphraseImpl() for symmetric encryption");
String cachedPassphrase = mPassphraseCache.get(Constants.key.symmetric);
String cachedPassphrase = mPassphraseCache.get(Constants.key.symmetric).getPassphrase();
if (cachedPassphrase == null) {
return null;
}
addCachedPassphrase(this, Constants.key.symmetric, cachedPassphrase);
addCachedPassphrase(this, Constants.key.symmetric, cachedPassphrase, getString(R.string.passp_cache_notif_pwd));
return cachedPassphrase;
}
// try to get master key id which is used as an identifier for cached passphrases
try {
Log.d(Constants.TAG, "PassphraseCacheService.getCachedPassphraseImpl() for masterKeyId " + keyId);
WrappedSecretKeyRing key = new ProviderHelper(this).getWrappedSecretKeyRing(
CanonicalizedSecretKeyRing key = new ProviderHelper(this).getCanonicalizedSecretKeyRing(
KeychainContract.KeyRings.buildUnifiedKeyRingsFindBySubkeyUri(keyId));
// no passphrase needed? just add empty string and return it, then
if (!key.hasPassphrase()) {
Log.d(Constants.TAG, "Key has no passphrase! Caches and returns empty passphrase!");
addCachedPassphrase(this, keyId, "");
try {
addCachedPassphrase(this, keyId, "", key.getPrimaryUserIdWithFallback());
} catch (PgpGeneralException e) {
Log.d(Constants.TAG, "PgpGeneralException occured");
}
return "";
}
// get cached passphrase
String cachedPassphrase = mPassphraseCache.get(keyId);
CachedPassphrase cachedPassphrase = mPassphraseCache.get(keyId);
if (cachedPassphrase == null) {
Log.d(Constants.TAG, "PassphraseCacheService Passphrase not (yet) cached, returning null");
Log.d(Constants.TAG, "PassphraseCacheService: Passphrase not (yet) cached, returning null");
// not really an error, just means the passphrase is not cached but not empty either
return null;
}
// set it again to reset the cache life cycle
Log.d(Constants.TAG, "PassphraseCacheService Cache passphrase again when getting it!");
addCachedPassphrase(this, keyId, cachedPassphrase);
return cachedPassphrase;
Log.d(Constants.TAG, "PassphraseCacheService: Cache passphrase again when getting it!");
addCachedPassphrase(this, keyId, cachedPassphrase.getPassphrase(), cachedPassphrase.getPrimaryUserID());
return cachedPassphrase.getPassphrase();
} catch (ProviderHelper.NotFoundException e) {
Log.e(Constants.TAG, "PassphraseCacheService Passphrase for unknown key was requested!");
Log.e(Constants.TAG, "PassphraseCacheService: Passphrase for unknown key was requested!");
return null;
}
}
@@ -211,7 +229,7 @@ public class PassphraseCacheService extends Service {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(Constants.TAG, "PassphraseCacheService Received broadcast...");
Log.d(Constants.TAG, "PassphraseCacheService: Received broadcast...");
if (action.equals(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE)) {
long keyId = intent.getLongExtra(EXTRA_KEY_ID, -1);
@@ -236,10 +254,8 @@ public class PassphraseCacheService extends Service {
private static PendingIntent buildIntent(Context context, long keyId) {
Intent intent = new Intent(BROADCAST_ACTION_PASSPHRASE_CACHE_SERVICE);
intent.putExtra(EXTRA_KEY_ID, keyId);
PendingIntent sender = PendingIntent.getBroadcast(context, REQUEST_ID, intent,
return PendingIntent.getBroadcast(context, REQUEST_ID, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
return sender;
}
/**
@@ -256,14 +272,17 @@ public class PassphraseCacheService extends Service {
if (ACTION_PASSPHRASE_CACHE_ADD.equals(intent.getAction())) {
long ttl = intent.getLongExtra(EXTRA_TTL, DEFAULT_TTL);
long keyId = intent.getLongExtra(EXTRA_KEY_ID, -1);
String passphrase = intent.getStringExtra(EXTRA_PASSPHRASE);
String primaryUserID = intent.getStringExtra(EXTRA_USER_ID);
Log.d(Constants.TAG,
"PassphraseCacheService Received ACTION_PASSPHRASE_CACHE_ADD intent in onStartCommand() with keyId: "
+ keyId + ", ttl: " + ttl);
"PassphraseCacheService: Received ACTION_PASSPHRASE_CACHE_ADD intent in onStartCommand() with keyId: "
+ keyId + ", ttl: " + ttl + ", usrId: " + primaryUserID
);
// add keyId and passphrase to memory
mPassphraseCache.put(keyId, passphrase);
// add keyId, passphrase and primary user id to memory
mPassphraseCache.put(keyId, new CachedPassphrase(passphrase, primaryUserID));
if (ttl > 0) {
// register new alarm with keyId for this passphrase
@@ -271,6 +290,8 @@ public class PassphraseCacheService extends Service {
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, triggerTime, buildIntent(this, keyId));
}
updateService();
} else if (ACTION_PASSPHRASE_CACHE_GET.equals(intent.getAction())) {
long keyId = intent.getLongExtra(EXTRA_KEY_ID, -1);
Messenger messenger = intent.getParcelableExtra(EXTRA_MESSENGER);
@@ -284,10 +305,21 @@ public class PassphraseCacheService extends Service {
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.e(Constants.TAG, "PassphraseCacheService Sending message failed", e);
Log.e(Constants.TAG, "PassphraseCacheService: Sending message failed", e);
}
} else if (ACTION_PASSPHRASE_CACHE_CLEAR.equals(intent.getAction())) {
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
// Stop all ttl alarms
for (int i = 0; i < mPassphraseCache.size(); i++) {
am.cancel(buildIntent(this, mPassphraseCache.keyAt(i)));
}
mPassphraseCache.clear();
updateService();
} else {
Log.e(Constants.TAG, "PassphraseCacheService Intent or Intent Action not supported!");
Log.e(Constants.TAG, "PassphraseCacheService: Intent or Intent Action not supported!");
}
}
@@ -306,13 +338,76 @@ public class PassphraseCacheService extends Service {
Log.d(Constants.TAG, "PassphraseCacheService Timeout of keyId " + keyId + ", removed from memory!");
// stop whole service if no cached passphrases remaining
if (mPassphraseCache.size() == 0) {
Log.d(Constants.TAG, "PassphraseCacheServic No passphrases remaining in memory, stopping service!");
stopSelf();
updateService();
}
private void updateService() {
if (mPassphraseCache.size() > 0) {
startForeground(NOTIFICATION_ID, getNotification());
} else {
// stop whole service if no cached passphrases remaining
Log.d(Constants.TAG, "PassphraseCacheService: No passphrases remaining in memory, stopping service!");
stopForeground(true);
}
}
private Notification getNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
builder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText(String.format(getString(R.string.passp_cache_notif_n_keys),
mPassphraseCache.size()));
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
inboxStyle.setBigContentTitle(getString(R.string.passp_cache_notif_keys));
// Moves events into the big view
for (int i = 0; i < mPassphraseCache.size(); i++) {
inboxStyle.addLine(mPassphraseCache.valueAt(i).getPrimaryUserID());
}
// Moves the big view style object into the notification object.
builder.setStyle(inboxStyle);
// Add purging action
Intent intent = new Intent(getApplicationContext(), PassphraseCacheService.class);
intent.setAction(ACTION_PASSPHRASE_CACHE_CLEAR);
builder.addAction(
R.drawable.abc_ic_clear_normal,
getString(R.string.passp_cache_notif_clear),
PendingIntent.getService(
getApplicationContext(),
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
);
} else {
// Fallback, since expandable notifications weren't available back then
builder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(String.format(getString(R.string.passp_cache_notif_n_keys,
mPassphraseCache.size())))
.setContentText(getString(R.string.passp_cache_notif_click_to_clear));
Intent intent = new Intent(getApplicationContext(), PassphraseCacheService.class);
intent.setAction(ACTION_PASSPHRASE_CACHE_CLEAR);
builder.setContentIntent(
PendingIntent.getService(
getApplicationContext(),
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
);
}
return builder.build();
}
@Override
public void onCreate() {
super.onCreate();
@@ -341,4 +436,29 @@ public class PassphraseCacheService extends Service {
private final IBinder mBinder = new PassphraseCacheBinder();
}
public class CachedPassphrase {
private String primaryUserID;
private String passphrase;
public CachedPassphrase(String passphrase, String primaryUserID) {
setPassphrase(passphrase);
setPrimaryUserID(primaryUserID);
}
public String getPrimaryUserID() {
return primaryUserID;
}
public String getPassphrase() {
return passphrase;
}
public void setPrimaryUserID(String primaryUserID) {
this.primaryUserID = primaryUserID;
}
public void setPassphrase(String passphrase) {
this.passphrase = passphrase;
}
}
}

View File

@@ -27,23 +27,19 @@ public class SaveKeyringParcel implements Parcelable {
// the key fingerprint, for safety. MUST be null for a new key.
public byte[] mFingerprint;
public String newPassphrase;
public String mNewPassphrase;
public ArrayList<String> addUserIds;
public ArrayList<SubkeyAdd> addSubKeys;
public ArrayList<String> mAddUserIds;
public ArrayList<SubkeyAdd> mAddSubKeys;
public ArrayList<SubkeyChange> changeSubKeys;
public String changePrimaryUserId;
public ArrayList<SubkeyChange> mChangeSubKeys;
public String mChangePrimaryUserId;
public ArrayList<String> revokeUserIds;
public ArrayList<Long> revokeSubKeys;
public ArrayList<String> mRevokeUserIds;
public ArrayList<Long> mRevokeSubKeys;
public SaveKeyringParcel() {
addUserIds = new ArrayList<String>();
addSubKeys = new ArrayList<SubkeyAdd>();
changeSubKeys = new ArrayList<SubkeyChange>();
revokeUserIds = new ArrayList<String>();
revokeSubKeys = new ArrayList<Long>();
reset();
}
public SaveKeyringParcel(long masterKeyId, byte[] fingerprint) {
@@ -52,6 +48,16 @@ public class SaveKeyringParcel implements Parcelable {
mFingerprint = fingerprint;
}
public void reset() {
mNewPassphrase = null;
mAddUserIds = new ArrayList<String>();
mAddSubKeys = new ArrayList<SubkeyAdd>();
mChangePrimaryUserId = null;
mChangeSubKeys = new ArrayList<SubkeyChange>();
mRevokeUserIds = new ArrayList<String>();
mRevokeSubKeys = new ArrayList<Long>();
}
// performance gain for using Parcelable here would probably be negligible,
// use Serializable instead.
public static class SubkeyAdd implements Serializable {
@@ -70,6 +76,7 @@ public class SaveKeyringParcel implements Parcelable {
public static class SubkeyChange implements Serializable {
public long mKeyId;
public Integer mFlags;
// this is a long unix timestamp, in seconds (NOT MILLISECONDS!)
public Long mExpiry;
public SubkeyChange(long keyId, Integer flags, Long expiry) {
mKeyId = keyId;
@@ -82,16 +89,16 @@ public class SaveKeyringParcel implements Parcelable {
mMasterKeyId = source.readInt() != 0 ? source.readLong() : null;
mFingerprint = source.createByteArray();
newPassphrase = source.readString();
mNewPassphrase = source.readString();
addUserIds = source.createStringArrayList();
addSubKeys = (ArrayList<SubkeyAdd>) source.readSerializable();
mAddUserIds = source.createStringArrayList();
mAddSubKeys = (ArrayList<SubkeyAdd>) source.readSerializable();
changeSubKeys = (ArrayList<SubkeyChange>) source.readSerializable();
changePrimaryUserId = source.readString();
mChangeSubKeys = (ArrayList<SubkeyChange>) source.readSerializable();
mChangePrimaryUserId = source.readString();
revokeUserIds = source.createStringArrayList();
revokeSubKeys = (ArrayList<Long>) source.readSerializable();
mRevokeUserIds = source.createStringArrayList();
mRevokeSubKeys = (ArrayList<Long>) source.readSerializable();
}
@Override
@@ -102,16 +109,16 @@ public class SaveKeyringParcel implements Parcelable {
}
destination.writeByteArray(mFingerprint);
destination.writeString(newPassphrase);
destination.writeString(mNewPassphrase);
destination.writeStringList(addUserIds);
destination.writeSerializable(addSubKeys);
destination.writeStringList(mAddUserIds);
destination.writeSerializable(mAddSubKeys);
destination.writeSerializable(changeSubKeys);
destination.writeString(changePrimaryUserId);
destination.writeSerializable(mChangeSubKeys);
destination.writeString(mChangePrimaryUserId);
destination.writeStringList(revokeUserIds);
destination.writeSerializable(revokeSubKeys);
destination.writeStringList(mRevokeUserIds);
destination.writeSerializable(mRevokeSubKeys);
}
public static final Creator<SaveKeyringParcel> CREATOR = new Creator<SaveKeyringParcel>() {