Merge pull request #1461 from open-keychain/keyserver-sync

Periodic Keyserver Sync
This commit is contained in:
Dominik Schürmann
2015-08-20 17:55:55 +02:00
41 changed files with 955 additions and 77 deletions

View File

@@ -141,9 +141,11 @@ android {
// Reference them in the java files with e.g. BuildConfig.ACCOUNT_TYPE.
buildConfigField "String", "ACCOUNT_TYPE", "\"org.sufficientlysecure.keychain.account\""
buildConfigField "String", "PROVIDER_CONTENT_AUTHORITY", "\"org.sufficientlysecure.keychain.provider\""
// Reference them in .xml files.
resValue "string", "account_type", "org.sufficientlysecure.keychain.account"
resValue "string", "provider_content_authority", "org.sufficientlysecure.keychain.provider"
}
debug {
@@ -151,9 +153,11 @@ android {
// Reference them in the java files with e.g. BuildConfig.ACCOUNT_TYPE.
buildConfigField "String", "ACCOUNT_TYPE", "\"org.sufficientlysecure.keychain.debug.account\""
buildConfigField "String", "PROVIDER_CONTENT_AUTHORITY", "\"org.sufficientlysecure.keychain.debug.provider\""
// Reference them in .xml files.
resValue "string", "account_type", "org.sufficientlysecure.keychain.debug.account"
resValue "string", "provider_content_authority", "org.sufficientlysecure.keychain.debug.provider"
// Enable code coverage (Jacoco)
testCoverageEnabled true

View File

@@ -723,10 +723,13 @@
android:name=".service.KeychainService"
android:exported="false" />
<!-- label is made to be "Keyserver Sync" since that is the only context in which
the user will see it-->
<provider
android:name=".provider.KeychainProvider"
android:authorities="${applicationId}.provider"
android:exported="false" />
android:exported="false"
android:label="@string/keyserver_sync_settings_title"/>
<!-- Internal classes of the remote APIs (not exported) -->
<activity
@@ -800,6 +803,20 @@
android:resource="@xml/custom_pgp_contacts_structure" />
</service>
<service
android:name=".service.KeyserverSyncAdapterService"
android:exported="true"
android:process=":sync"
tools:ignore="ExportedService">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="@xml/keyserver_sync_adapter_desc" />
</service>
<!-- Storage Provider for temporary decrypted files -->
<provider
android:name=".provider.TemporaryStorageProvider"

View File

@@ -19,14 +19,9 @@ package org.sufficientlysecure.keychain;
import android.os.Environment;
import org.spongycastle.bcpg.HashAlgorithmTags;
import org.spongycastle.bcpg.SymmetricKeyAlgorithmTags;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.sufficientlysecure.keychain.BuildConfig;
import java.io.File;
import java.net.InetSocketAddress;
import java.net.Proxy;
public final class Constants {
@@ -34,6 +29,7 @@ public final class Constants {
public static final boolean DEBUG = BuildConfig.DEBUG;
public static final boolean DEBUG_LOG_DB_QUERIES = false;
public static final boolean DEBUG_SYNC_REMOVE_CONTACTS = false;
public static final boolean DEBUG_KEYSERVER_SYNC = false;
public static final String TAG = DEBUG ? "Keychain D" : "Keychain";
@@ -43,7 +39,7 @@ public final class Constants {
public static final String ACCOUNT_TYPE = BuildConfig.ACCOUNT_TYPE;
public static final String CUSTOM_CONTACT_DATA_MIME_TYPE = "vnd.android.cursor.item/vnd.org.sufficientlysecure.keychain.key";
public static final String PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID + ".provider";
public static final String PROVIDER_AUTHORITY = BuildConfig.PROVIDER_CONTENT_AUTHORITY;
public static final String TEMPSTORAGE_AUTHORITY = BuildConfig.APPLICATION_ID + ".tempstorage";
public static final String CLIPBOARD_LABEL = "Keychain";
@@ -81,6 +77,11 @@ public final class Constants {
public static final File APP_DIR_FILE = new File(APP_DIR, "export.asc");
}
public static final class Notification {
public static final int PASSPHRASE_CACHE = 1;
public static final int KEYSERVER_SYNC_FAIL_ORBOT = 2;
}
public static final class Pref {
public static final String PASSPHRASE_CACHE_TTL = "passphraseCacheTtl";
public static final String PASSPHRASE_CACHE_SUBS = "passphraseCacheSubs";
@@ -104,6 +105,9 @@ public final class Constants {
public static final String PROXY_PORT = "proxyPort";
public static final String PROXY_TYPE = "proxyType";
public static final String THEME = "theme";
// keyserver sync settings
public static final String SYNC_CONTACTS = "syncContacts";
public static final String SYNC_KEYSERVER = "syncKeyserver";
public static final class Theme {
public static final String LIGHT = "light";
@@ -123,7 +127,7 @@ public final class Constants {
public static final class Defaults {
public static final String KEY_SERVERS = "hkps://hkps.pool.sks-keyservers.net, hkps://pgp.mit.edu";
public static final int PREF_VERSION = 5;
public static final int PREF_VERSION = 6;
}
public static final class key {

View File

@@ -23,7 +23,6 @@ import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
@@ -35,7 +34,7 @@ import android.widget.Toast;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.sufficientlysecure.keychain.provider.KeychainDatabase;
import org.sufficientlysecure.keychain.provider.TemporaryStorageProvider;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.service.KeyserverSyncAdapterService;
import org.sufficientlysecure.keychain.ui.ConsolidateDialogActivity;
import org.sufficientlysecure.keychain.ui.util.FormattingUtils;
import org.sufficientlysecure.keychain.util.Log;
@@ -97,7 +96,7 @@ public class KeychainApplication extends Application {
setupAccountAsNeeded(this);
// Update keyserver list as needed
Preferences.getPreferences(this).upgradePreferences();
Preferences.getPreferences(this).upgradePreferences(this);
TlsHelper.addStaticCA("pool.sks-keyservers.net", getAssets(), "sks-keyservers.netCA.cer");
@@ -136,17 +135,20 @@ public class KeychainApplication extends Application {
}
/**
* Add OpenKeychain account to Android to link contacts with keys
* Add OpenKeychain account to Android to link contacts with keys and keyserver sync
*/
public static void setupAccountAsNeeded(Context context) {
try {
AccountManager manager = AccountManager.get(context);
Account[] accounts = manager.getAccountsByType(Constants.ACCOUNT_TYPE);
if (accounts == null || accounts.length == 0) {
if (accounts.length == 0) {
Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE);
if (manager.addAccountExplicitly(account, null, null)) {
// for contact sync
ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
KeyserverSyncAdapterService.enableKeyserverSync(context);
} else {
Log.e(Constants.TAG, "Adding account failed!");
}

View File

@@ -196,9 +196,9 @@ public class HkpKeyserver extends Keyserver {
/**
* returns a client with pinned certificate if necessary
*
* @param url
* @param proxy
* @return
* @param url url to be queried by client
* @param proxy proxy to be used by client
* @return client with a pinned certificate if necesary
*/
public static OkHttpClient getClient(URL url, Proxy proxy) throws IOException {
OkHttpClient client = new OkHttpClient();
@@ -360,7 +360,7 @@ public class HkpKeyserver extends Keyserver {
try {
data = query(request, proxy);
} catch (HttpError httpError) {
Log.e(Constants.TAG, "Failed to get key at HkpKeyserver", httpError);
Log.d(Constants.TAG, "Failed to get key at HkpKeyserver", httpError);
throw new QueryFailedException("not found");
}
Matcher matcher = PgpHelper.PGP_PUBLIC_KEY.matcher(data);

View File

@@ -22,6 +22,7 @@ package org.sufficientlysecure.keychain.operations;
import java.io.IOException;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
@@ -231,7 +232,7 @@ public class ImportOperation extends BaseOperation<ImportKeyringParcel> {
log.add(LogType.MSG_IMPORT_FETCH_ERROR_DECODE, 3);
}
} catch (Keyserver.QueryFailedException e) {
Log.e(Constants.TAG, "query failed", e);
Log.d(Constants.TAG, "query failed", e);
log.add(LogType.MSG_IMPORT_FETCH_KEYSERVER_ERROR, 3, e.getMessage());
}
}
@@ -305,15 +306,25 @@ public class ImportOperation extends BaseOperation<ImportKeyringParcel> {
}
if (!result.success()) {
badKeys += 1;
} else if (result.updated()) {
updatedKeys += 1;
importedMasterKeyIds.add(key.getMasterKeyId());
} else {
newKeys += 1;
if (key.isSecret()) {
secret += 1;
if (result.updated()) {
updatedKeys += 1;
importedMasterKeyIds.add(key.getMasterKeyId());
} else {
newKeys += 1;
if (key.isSecret()) {
secret += 1;
}
importedMasterKeyIds.add(key.getMasterKeyId());
}
if (entry.mBytes == null) {
// synonymous to isDownloadFromKeyserver.
// If no byte data was supplied, import from keyserver took place
// this prevents file imports being noted as keyserver imports
mProviderHelper.renewKeyLastUpdatedTime(key.getMasterKeyId(),
GregorianCalendar.getInstance().getTimeInMillis(),
TimeUnit.MILLISECONDS);
}
importedMasterKeyIds.add(key.getMasterKeyId());
}
log.add(result, 2);
@@ -386,7 +397,7 @@ public class ImportOperation extends BaseOperation<ImportKeyringParcel> {
@NonNull
@Override
public OperationResult execute(ImportKeyringParcel importInput, CryptoInputParcel cryptoInput) {
public ImportKeyResult execute(ImportKeyringParcel importInput, CryptoInputParcel cryptoInput) {
ArrayList<ParcelableKeyRing> keyList = importInput.mKeyList;
String keyServer = importInput.mKeyserver;
@@ -492,12 +503,12 @@ public class ImportOperation extends BaseOperation<ImportKeyringParcel> {
/**
* Used to accumulate the results of individual key imports
*/
private class KeyImportAccumulator {
public static class KeyImportAccumulator {
private OperationResult.OperationLog mImportLog = new OperationResult.OperationLog();
Progressable mProgressable;
private int mTotalKeys;
private int mImportedKeys = 0;
ArrayList<Long> mImportedMasterKeyIds = new ArrayList<Long>();
ArrayList<Long> mImportedMasterKeyIds = new ArrayList<>();
private int mBadKeys = 0;
private int mNewKeys = 0;
private int mUpdatedKeys = 0;
@@ -515,21 +526,17 @@ public class ImportOperation extends BaseOperation<ImportKeyringParcel> {
public KeyImportAccumulator(int totalKeys, Progressable externalProgressable) {
mTotalKeys = totalKeys;
mProgressable = externalProgressable;
mProgressable.setProgress(0, totalKeys);
}
public int getTotalKeys() {
return mTotalKeys;
}
public int getImportedKeys() {
return mImportedKeys;
if (mProgressable != null) {
mProgressable.setProgress(0, totalKeys);
}
}
public synchronized void accumulateKeyImport(ImportKeyResult result) {
mImportedKeys++;
mProgressable.setProgress(mImportedKeys, mTotalKeys);
if (mProgressable != null) {
mProgressable.setProgress(mImportedKeys, mTotalKeys);
}
mImportLog.addAll(result.getLog().toList());//accumulates log
mBadKeys += result.mBadKeys;

View File

@@ -93,13 +93,13 @@ public class RevokeOperation extends BaseOperation<RevokeKeyringParcel> {
log.add(OperationResult.LogType.MSG_REVOKE_OK, 1);
return new RevokeResult(RevokeResult.RESULT_OK, log, masterKeyId);
} else {
log.add(OperationResult.LogType.MSG_REVOKE_KEY_FAIL, 1);
log.add(OperationResult.LogType.MSG_REVOKE_ERROR_KEY_FAIL, 1);
return new RevokeResult(RevokeResult.RESULT_ERROR, log, masterKeyId);
}
} catch (PgpKeyNotFoundException | ProviderHelper.NotFoundException e) {
Log.e(Constants.TAG, "could not find key to revoke", e);
log.add(OperationResult.LogType.MSG_REVOKE_KEY_FAIL, 1);
log.add(OperationResult.LogType.MSG_REVOKE_ERROR_KEY_FAIL, 1);
return new RevokeResult(RevokeResult.RESULT_ERROR, log, masterKeyId);
}
}

View File

@@ -763,10 +763,9 @@ public abstract class OperationResult implements Parcelable {
MSG_DEL_FAIL (LogLevel.WARN, R.plurals.msg_del_fail),
MSG_REVOKE_ERROR_EMPTY (LogLevel.ERROR, R.string.msg_revoke_error_empty),
MSG_REVOKE_ERROR_MULTI_SECRET (LogLevel.DEBUG, R.string.msg_revoke_error_multi_secret),
MSG_REVOKE_ERROR_NOT_FOUND (LogLevel.DEBUG, R.string.msg_revoke_error_multi_secret),
MSG_REVOKE_ERROR_NOT_FOUND (LogLevel.ERROR, R.string.msg_revoke_error_not_found),
MSG_REVOKE (LogLevel.DEBUG, R.string.msg_revoke_key),
MSG_REVOKE_KEY_FAIL (LogLevel.ERROR, R.string.msg_revoke_key_fail),
MSG_REVOKE_ERROR_KEY_FAIL (LogLevel.ERROR, R.string.msg_revoke_key_fail),
MSG_REVOKE_OK (LogLevel.OK, R.string.msg_revoke_ok),
// keybase verification

View File

@@ -51,6 +51,11 @@ public class KeychainContract {
String EXPIRY = "expiry";
}
interface UpdatedKeysColumns {
String MASTER_KEY_ID = "master_key_id"; // not a database id
String LAST_UPDATED = "last_updated"; // time since epoch in seconds
}
interface UserPacketsColumns {
String MASTER_KEY_ID = "master_key_id"; // foreign key to key_rings._ID
String TYPE = "type"; // not a database id
@@ -97,6 +102,8 @@ public class KeychainContract {
public static final String BASE_KEY_RINGS = "key_rings";
public static final String BASE_UPDATED_KEYS = "updated_keys";
public static final String PATH_UNIFIED = "unified";
public static final String PATH_FIND = "find";
@@ -234,6 +241,16 @@ public class KeychainContract {
}
public static class UpdatedKeys implements UpdatedKeysColumns, BaseColumns {
public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon()
.appendPath(BASE_UPDATED_KEYS).build();
public static final String CONTENT_TYPE
= "vnd.android.cursor.dir/vnd.org.sufficientlysecure.keychain.provider.updated_keys";
public static final String CONTENT_ITEM_TYPE
= "vnd.android.cursor.item/vnd.org.sufficientlysecure.keychain.provider.updated_keys";
}
public static class UserPackets implements UserPacketsColumns, BaseColumns {
public static final String VERIFIED = "verified";
public static final Uri CONTENT_URI = BASE_CONTENT_URI_INTERNAL.buildUpon()

View File

@@ -34,6 +34,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.ApiAppsColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.CertsColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingsColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeysColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.UpdatedKeysColumns;
import org.sufficientlysecure.keychain.provider.KeychainContract.UserPacketsColumns;
import org.sufficientlysecure.keychain.ui.ConsolidateDialogActivity;
import org.sufficientlysecure.keychain.util.Log;
@@ -53,7 +54,7 @@ import java.io.IOException;
*/
public class KeychainDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "openkeychain.db";
private static final int DATABASE_VERSION = 11;
private static final int DATABASE_VERSION = 12;
static Boolean apgHack = false;
private Context mContext;
@@ -61,6 +62,7 @@ public class KeychainDatabase extends SQLiteOpenHelper {
String KEY_RINGS_PUBLIC = "keyrings_public";
String KEY_RINGS_SECRET = "keyrings_secret";
String KEYS = "keys";
String UPDATED_KEYS = "updated_keys";
String USER_PACKETS = "user_packets";
String CERTS = "certs";
String API_APPS = "api_apps";
@@ -144,6 +146,14 @@ public class KeychainDatabase extends SQLiteOpenHelper {
+ Tables.USER_PACKETS + "(" + UserPacketsColumns.MASTER_KEY_ID + ", " + UserPacketsColumns.RANK + ") ON DELETE CASCADE"
+ ")";
private static final String CREATE_UPDATE_KEYS =
"CREATE TABLE IF NOT EXISTS " + Tables.UPDATED_KEYS + " ("
+ UpdatedKeysColumns.MASTER_KEY_ID + " INTEGER PRIMARY KEY, "
+ UpdatedKeysColumns.LAST_UPDATED + " INTEGER, "
+ "FOREIGN KEY(" + UpdatedKeysColumns.MASTER_KEY_ID + ") REFERENCES "
+ Tables.KEY_RINGS_PUBLIC + "(" + KeyRingsColumns.MASTER_KEY_ID + ") ON DELETE CASCADE"
+ ")";
private static final String CREATE_API_APPS =
"CREATE TABLE IF NOT EXISTS " + Tables.API_APPS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
@@ -206,6 +216,7 @@ public class KeychainDatabase extends SQLiteOpenHelper {
db.execSQL(CREATE_KEYS);
db.execSQL(CREATE_USER_PACKETS);
db.execSQL(CREATE_CERTS);
db.execSQL(CREATE_UPDATE_KEYS);
db.execSQL(CREATE_API_APPS);
db.execSQL(CREATE_API_APPS_ACCOUNTS);
db.execSQL(CREATE_API_APPS_ALLOWED_KEYS);
@@ -278,8 +289,11 @@ public class KeychainDatabase extends SQLiteOpenHelper {
// fix problems in database, see #1402 for details
// https://github.com/open-keychain/open-keychain/issues/1402
db.execSQL("DELETE FROM api_accounts WHERE key_id BETWEEN 0 AND 3");
case 12:
db.execSQL(CREATE_UPDATE_KEYS);
if (oldVersion == 10) {
// no consolidate if we are updating from 10, we're just here for the api_accounts fix
// no consolidate if we are updating from 10, we're just here for
// the api_accounts fix and the new update keys table
return;
}

View File

@@ -38,6 +38,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.Certs;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingData;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.KeychainContract.Keys;
import org.sufficientlysecure.keychain.provider.KeychainContract.UpdatedKeys;
import org.sufficientlysecure.keychain.provider.KeychainContract.UserPackets;
import org.sufficientlysecure.keychain.provider.KeychainContract.UserPacketsColumns;
import org.sufficientlysecure.keychain.provider.KeychainDatabase.Tables;
@@ -72,6 +73,9 @@ public class KeychainProvider extends ContentProvider {
private static final int KEY_RINGS_FIND_BY_EMAIL = 400;
private static final int KEY_RINGS_FIND_BY_SUBKEY = 401;
private static final int UPDATED_KEYS = 500;
private static final int UPDATED_KEYS_SPECIFIC = 501;
protected UriMatcher mUriMatcher;
/**
@@ -179,6 +183,12 @@ public class KeychainProvider extends ContentProvider {
matcher.addURI(authority, KeychainContract.BASE_API_APPS + "/*/"
+ KeychainContract.PATH_ALLOWED_KEYS, API_ALLOWED_KEYS);
/**
* to access table containing last updated dates of keys
*/
matcher.addURI(authority, KeychainContract.BASE_UPDATED_KEYS, UPDATED_KEYS);
matcher.addURI(authority, KeychainContract.BASE_UPDATED_KEYS + "/*", UPDATED_KEYS_SPECIFIC);
return matcher;
}
@@ -218,6 +228,11 @@ public class KeychainProvider extends ContentProvider {
case KEY_RING_SECRET:
return KeyRings.CONTENT_ITEM_TYPE;
case UPDATED_KEYS:
return UpdatedKeys.CONTENT_TYPE;
case UPDATED_KEYS_SPECIFIC:
return UpdatedKeys.CONTENT_ITEM_TYPE;
case API_APPS:
return ApiApps.CONTENT_TYPE;
@@ -606,6 +621,22 @@ public class KeychainProvider extends ContentProvider {
break;
}
case UPDATED_KEYS:
case UPDATED_KEYS_SPECIFIC: {
HashMap<String, String> projectionMap = new HashMap<>();
qb.setTables(Tables.UPDATED_KEYS);
projectionMap.put(UpdatedKeys.MASTER_KEY_ID, Tables.UPDATED_KEYS + "."
+ UpdatedKeys.MASTER_KEY_ID);
projectionMap.put(UpdatedKeys.LAST_UPDATED, Tables.UPDATED_KEYS + "."
+ UpdatedKeys.LAST_UPDATED);
qb.setProjectionMap(projectionMap);
if (match == UPDATED_KEYS_SPECIFIC) {
qb.appendWhere(UpdatedKeys.MASTER_KEY_ID + " = ");
qb.appendWhereEscapeString(uri.getPathSegments().get(1));
}
break;
}
case API_APPS: {
qb.setTables(Tables.API_APPS);
@@ -726,6 +757,12 @@ public class KeychainProvider extends ContentProvider {
keyId = values.getAsLong(Certs.MASTER_KEY_ID);
break;
}
case UPDATED_KEYS: {
long updatedKeyId = db.replace(Tables.UPDATED_KEYS, null, values);
rowUri = UpdatedKeys.CONTENT_URI.buildUpon().appendPath("" + updatedKeyId)
.build();
break;
}
case API_APPS: {
db.insertOrThrow(Tables.API_APPS, null, values);
break;

View File

@@ -59,6 +59,7 @@ import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRingData;
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
import org.sufficientlysecure.keychain.provider.KeychainContract.Keys;
import org.sufficientlysecure.keychain.provider.KeychainContract.UserPackets;
import org.sufficientlysecure.keychain.provider.KeychainContract.UpdatedKeys;
import org.sufficientlysecure.keychain.remote.AccountSettings;
import org.sufficientlysecure.keychain.remote.AppSettings;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
@@ -82,6 +83,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* This class contains high level methods for database access. Despite its
@@ -685,6 +687,36 @@ public class ProviderHelper {
mIndent -= 1;
}
// before deleting key, retrieve it's last updated time
final int INDEX_MASTER_KEY_ID = 0;
final int INDEX_LAST_UPDATED = 1;
Cursor lastUpdatedCursor = mContentResolver.query(
UpdatedKeys.CONTENT_URI,
new String[]{
UpdatedKeys.MASTER_KEY_ID,
UpdatedKeys.LAST_UPDATED
},
UpdatedKeys.MASTER_KEY_ID + " = ?",
new String[]{"" + masterKeyId},
null
);
if (lastUpdatedCursor.moveToNext()) {
// there was an entry to re-insert
// this operation must happen after the new key is inserted
ContentValues lastUpdatedEntry = new ContentValues(2);
lastUpdatedEntry.put(UpdatedKeys.MASTER_KEY_ID,
lastUpdatedCursor.getLong(INDEX_MASTER_KEY_ID));
lastUpdatedEntry.put(UpdatedKeys.LAST_UPDATED,
lastUpdatedCursor.getLong(INDEX_LAST_UPDATED));
operations.add(
ContentProviderOperation
.newInsert(UpdatedKeys.CONTENT_URI)
.withValues(lastUpdatedEntry)
.build()
);
}
lastUpdatedCursor.close();
try {
// delete old version of this keyRing, which also deletes all keys and userIds on cascade
int deleted = mContentResolver.delete(
@@ -1239,6 +1271,28 @@ public class ProviderHelper {
}
// 2. wipe database (IT'S DANGEROUS)
// first, backup our list of updated key times
ArrayList<ContentValues> updatedKeysValues = new ArrayList<>();
final int INDEX_MASTER_KEY_ID = 0;
final int INDEX_LAST_UPDATED = 1;
Cursor lastUpdatedCursor = mContentResolver.query(
UpdatedKeys.CONTENT_URI,
new String[]{
UpdatedKeys.MASTER_KEY_ID,
UpdatedKeys.LAST_UPDATED
},
null, null, null);
while (lastUpdatedCursor.moveToNext()) {
ContentValues values = new ContentValues();
values.put(UpdatedKeys.MASTER_KEY_ID,
lastUpdatedCursor.getLong(INDEX_MASTER_KEY_ID));
values.put(UpdatedKeys.LAST_UPDATED,
lastUpdatedCursor.getLong(INDEX_LAST_UPDATED));
updatedKeysValues.add(values);
}
lastUpdatedCursor.close();
log.add(LogType.MSG_CON_DB_CLEAR, indent);
mContentResolver.delete(KeyRings.buildUnifiedKeyRingsUri(), null, null);
@@ -1288,6 +1342,10 @@ public class ProviderHelper {
new ProgressFixedScaler(progress, 25, 99, 100, R.string.progress_con_reimport))
.serialKeyRingImport(itPublics, numPublics, null, null);
log.add(result, indent);
// re-insert our backed up list of updated key times
// TODO: can this cause issues in case a public key re-import failed?
mContentResolver.bulkInsert(UpdatedKeys.CONTENT_URI,
updatedKeysValues.toArray(new ContentValues[updatedKeysValues.size()]));
} else {
log.add(LogType.MSG_CON_REIMPORT_PUBLIC_SKIP, indent);
}
@@ -1397,6 +1455,14 @@ public class ProviderHelper {
return getKeyRingAsArmoredString(data);
}
public Uri renewKeyLastUpdatedTime(long masterKeyId, long time, TimeUnit timeUnit) {
ContentValues values = new ContentValues();
values.put(UpdatedKeys.MASTER_KEY_ID, masterKeyId);
values.put(UpdatedKeys.LAST_UPDATED, timeUnit.toSeconds(time));
return mContentResolver.insert(UpdatedKeys.CONTENT_URI, values);
}
public ArrayList<String> getRegisteredApiApps() {
Cursor cursor = mContentResolver.query(ApiApps.CONTENT_URI, null, null, null, null);

View File

@@ -45,7 +45,7 @@ public class ContactSyncAdapterService extends Service {
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
final SyncResult syncResult) {
Log.d(Constants.TAG, "Performing a sync!");
Log.d(Constants.TAG, "Performing a contact sync!");
// TODO: Import is currently disabled for 2.8, until we implement proper origin management
// importDone.set(false);
// KeychainApplication.setupAccountAsNeeded(ContactSyncAdapterService.this);

View File

@@ -0,0 +1,516 @@
package org.sufficientlysecure.keychain.service;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SyncResult;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.PowerManager;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.keyimport.ParcelableKeyRing;
import org.sufficientlysecure.keychain.operations.ImportOperation;
import org.sufficientlysecure.keychain.operations.results.ImportKeyResult;
import org.sufficientlysecure.keychain.operations.results.OperationResult;
import org.sufficientlysecure.keychain.provider.KeychainContract;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.ui.OrbotRequiredDialogActivity;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.ParcelableProxy;
import org.sufficientlysecure.keychain.util.Preferences;
import org.sufficientlysecure.keychain.util.orbot.OrbotHelper;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class KeyserverSyncAdapterService extends Service {
// how often a sync should be initiated, in s
public static final long SYNC_INTERVAL =
Constants.DEBUG_KEYSERVER_SYNC
? TimeUnit.MINUTES.toSeconds(2) : TimeUnit.DAYS.toSeconds(3);
// time since last update after which a key should be updated again, in s
public static final long KEY_UPDATE_LIMIT =
Constants.DEBUG_KEYSERVER_SYNC ? 1 : TimeUnit.DAYS.toSeconds(7);
// time by which a sync is postponed in case of a
public static final long SYNC_POSTPONE_TIME =
Constants.DEBUG_KEYSERVER_SYNC ? 30 * 1000 : TimeUnit.MINUTES.toMillis(5);
// Time taken by Orbot before a new circuit is created
public static final int ORBOT_CIRCUIT_TIMEOUT = (int) TimeUnit.MINUTES.toMillis(10);
private static final String ACTION_IGNORE_TOR = "ignore_tor";
private static final String ACTION_UPDATE_ALL = "update_all";
private static final String ACTION_SYNC_NOW = "sync_now";
private static final String ACTION_DISMISS_NOTIFICATION = "cancel_sync";
private static final String ACTION_START_ORBOT = "start_orbot";
private static final String ACTION_CANCEL = "cancel";
private AtomicBoolean mCancelled = new AtomicBoolean(false);
@Override
public int onStartCommand(final Intent intent, int flags, final int startId) {
switch (intent.getAction()) {
case ACTION_CANCEL: {
mCancelled.set(true);
break;
}
// the reason for the separation betweyeen SYNC_NOW and UPDATE_ALL is so that starting
// the sync directly from the notification is possible while the screen is on with
// UPDATE_ALL, but a postponed sync is only started if screen is off
case ACTION_SYNC_NOW: {
// this checks for screen on/off before sync, and postpones the sync if on
ContentResolver.requestSync(
new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE),
Constants.PROVIDER_AUTHORITY,
new Bundle()
);
break;
}
case ACTION_UPDATE_ALL: {
// does not check for screen on/off
asyncKeyUpdate(this, new CryptoInputParcel());
break;
}
case ACTION_IGNORE_TOR: {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(Constants.Notification.KEYSERVER_SYNC_FAIL_ORBOT);
asyncKeyUpdate(this, new CryptoInputParcel(ParcelableProxy.getForNoProxy()));
break;
}
case ACTION_START_ORBOT: {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(Constants.Notification.KEYSERVER_SYNC_FAIL_ORBOT);
Intent startOrbot = new Intent(this, OrbotRequiredDialogActivity.class);
startOrbot.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startOrbot.putExtra(OrbotRequiredDialogActivity.EXTRA_START_ORBOT, true);
Messenger messenger = new Messenger(
new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case OrbotRequiredDialogActivity.MESSAGE_ORBOT_STARTED: {
asyncKeyUpdate(KeyserverSyncAdapterService.this,
new CryptoInputParcel());
break;
}
case OrbotRequiredDialogActivity.MESSAGE_ORBOT_IGNORE: {
asyncKeyUpdate(KeyserverSyncAdapterService.this,
new CryptoInputParcel(
ParcelableProxy.getForNoProxy()));
break;
}
case OrbotRequiredDialogActivity.MESSAGE_DIALOG_CANCEL: {
// just stop service
stopSelf();
break;
}
}
}
}
);
startOrbot.putExtra(OrbotRequiredDialogActivity.EXTRA_MESSENGER, messenger);
startActivity(startOrbot);
break;
}
case ACTION_DISMISS_NOTIFICATION: {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(Constants.Notification.KEYSERVER_SYNC_FAIL_ORBOT);
stopSelf(startId);
break;
}
}
return START_NOT_STICKY;
}
private class KeyserverSyncAdapter extends AbstractThreadedSyncAdapter {
public KeyserverSyncAdapter() {
super(KeyserverSyncAdapterService.this, true);
}
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
Log.d(Constants.TAG, "Performing a keyserver sync!");
PowerManager pm = (PowerManager) KeyserverSyncAdapterService.this
.getSystemService(Context.POWER_SERVICE);
@SuppressWarnings("deprecation") // our min is API 15, deprecated only in 20
boolean isScreenOn = pm.isScreenOn();
if (!isScreenOn) {
Intent serviceIntent = new Intent(KeyserverSyncAdapterService.this,
KeyserverSyncAdapterService.class);
serviceIntent.setAction(ACTION_UPDATE_ALL);
startService(serviceIntent);
} else {
postponeSync();
}
}
@Override
public void onSyncCanceled() {
super.onSyncCanceled();
cancelUpdates(KeyserverSyncAdapterService.this);
}
}
@Override
public IBinder onBind(Intent intent) {
return new KeyserverSyncAdapter().getSyncAdapterBinder();
}
private void handleUpdateResult(ImportKeyResult result) {
if (result.isPending()) {
// result is pending due to Orbot not being started
// try to start it silently, if disabled show notifications
new OrbotHelper.SilentStartManager() {
@Override
protected void onOrbotStarted() {
// retry the update
asyncKeyUpdate(KeyserverSyncAdapterService.this,
new CryptoInputParcel());
}
@Override
protected void onSilentStartDisabled() {
// show notification
NotificationManager manager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(Constants.Notification.KEYSERVER_SYNC_FAIL_ORBOT,
getOrbotNoification(KeyserverSyncAdapterService.this));
}
}.startOrbotAndListen(this, false);
} else if (isUpdateCancelled()) {
Log.d(Constants.TAG, "Keyserver sync cancelled, postponing by" + SYNC_POSTPONE_TIME
+ "ms");
postponeSync();
} else {
Log.d(Constants.TAG, "Keyserver sync completed: Updated: " + result.mUpdatedKeys
+ " Failed: " + result.mBadKeys);
stopSelf();
}
}
private void postponeSync() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent serviceIntent = new Intent(this, KeyserverSyncAdapterService.class);
serviceIntent.setAction(ACTION_SYNC_NOW);
PendingIntent pi = PendingIntent.getService(this, 0, serviceIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(
AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + SYNC_POSTPONE_TIME,
pi
);
}
private void asyncKeyUpdate(final Context context,
final CryptoInputParcel cryptoInputParcel) {
new Thread(new Runnable() {
@Override
public void run() {
ImportKeyResult result = updateKeysFromKeyserver(context, cryptoInputParcel);
handleUpdateResult(result);
}
}).start();
}
private synchronized ImportKeyResult updateKeysFromKeyserver(final Context context,
final CryptoInputParcel cryptoInputParcel) {
mCancelled.set(false);
ArrayList<ParcelableKeyRing> keyList = getKeysToUpdate(context);
if (isUpdateCancelled()) { // if we've already been cancelled
return new ImportKeyResult(OperationResult.RESULT_CANCELLED,
new OperationResult.OperationLog());
}
if (cryptoInputParcel.getParcelableProxy() == null) {
// no explicit proxy, retrieve from preferences. Check if we should do a staggered sync
if (Preferences.getPreferences(context).getProxyPrefs().torEnabled) {
return staggeredUpdate(context, keyList, cryptoInputParcel);
} else {
return directUpdate(context, keyList, cryptoInputParcel);
}
} else {
return directUpdate(context, keyList, cryptoInputParcel);
}
}
private ImportKeyResult directUpdate(Context context, ArrayList<ParcelableKeyRing> keyList,
CryptoInputParcel cryptoInputParcel) {
Log.d(Constants.TAG, "Starting normal update");
ImportOperation importOp = new ImportOperation(context, new ProviderHelper(context), null);
return importOp.execute(
new ImportKeyringParcel(keyList,
Preferences.getPreferences(context).getPreferredKeyserver()),
cryptoInputParcel
);
}
/**
* will perform a staggered update of user's keys using delays to ensure new Tor circuits, as
* performed by parcimonie. Relevant issue and method at:
* https://github.com/open-keychain/open-keychain/issues/1337
*
* @return result of the sync
*/
private ImportKeyResult staggeredUpdate(Context context, ArrayList<ParcelableKeyRing> keyList,
CryptoInputParcel cryptoInputParcel) {
Log.d(Constants.TAG, "Starting staggered update");
// final int WEEK_IN_SECONDS = (int) TimeUnit.DAYS.toSeconds(7);
final int WEEK_IN_SECONDS = 0;
ImportOperation.KeyImportAccumulator accumulator
= new ImportOperation.KeyImportAccumulator(keyList.size(), null);
for (ParcelableKeyRing keyRing : keyList) {
int waitTime;
int staggeredTime = new Random().nextInt(1 + 2 * (WEEK_IN_SECONDS / keyList.size()));
if (staggeredTime >= ORBOT_CIRCUIT_TIMEOUT) {
waitTime = staggeredTime;
} else {
waitTime = ORBOT_CIRCUIT_TIMEOUT + new Random().nextInt(ORBOT_CIRCUIT_TIMEOUT);
}
Log.d(Constants.TAG, "Updating key with fingerprint " + keyRing.mExpectedFingerprint +
" with a wait time of " + waitTime + "s");
try {
Thread.sleep(waitTime * 1000);
} catch (InterruptedException e) {
Log.e(Constants.TAG, "Exception during sleep between key updates", e);
// skip this one
continue;
}
ArrayList<ParcelableKeyRing> keyWrapper = new ArrayList<>();
keyWrapper.add(keyRing);
if (isUpdateCancelled()) {
return new ImportKeyResult(ImportKeyResult.RESULT_CANCELLED,
new OperationResult.OperationLog());
}
ImportKeyResult result =
new ImportOperation(context, new ProviderHelper(context), null, mCancelled)
.execute(
new ImportKeyringParcel(
keyWrapper,
Preferences.getPreferences(context)
.getPreferredKeyserver()
),
cryptoInputParcel
);
if (result.isPending()) {
return result;
}
accumulator.accumulateKeyImport(result);
}
return accumulator.getConsolidatedResult();
}
/**
* 1. Get keys which have been updated recently and therefore do not need to
* be updated now
* 2. Get list of all keys and filter out ones that don't need to be updated
* 3. Return keys to be updated
*
* @return list of keys that require update
*/
private ArrayList<ParcelableKeyRing> getKeysToUpdate(Context context) {
// 1. Get keys which have been updated recently and don't need to updated now
final int INDEX_UPDATED_KEYS_MASTER_KEY_ID = 0;
final int INDEX_LAST_UPDATED = 1;
// all time in seconds not milliseconds
final long CURRENT_TIME = GregorianCalendar.getInstance().getTimeInMillis() / 1000;
Cursor updatedKeysCursor = context.getContentResolver().query(
KeychainContract.UpdatedKeys.CONTENT_URI,
new String[]{
KeychainContract.UpdatedKeys.MASTER_KEY_ID,
KeychainContract.UpdatedKeys.LAST_UPDATED
},
"? - " + KeychainContract.UpdatedKeys.LAST_UPDATED + " < " + KEY_UPDATE_LIMIT,
new String[]{"" + CURRENT_TIME},
null
);
ArrayList<Long> ignoreMasterKeyIds = new ArrayList<>();
while (updatedKeysCursor.moveToNext()) {
long masterKeyId = updatedKeysCursor.getLong(INDEX_UPDATED_KEYS_MASTER_KEY_ID);
Log.d(Constants.TAG, "Keyserver sync: Ignoring {" + masterKeyId + "} last updated at {"
+ updatedKeysCursor.getLong(INDEX_LAST_UPDATED) + "}s");
ignoreMasterKeyIds.add(masterKeyId);
}
updatedKeysCursor.close();
// 2. Make a list of public keys which should be updated
final int INDEX_MASTER_KEY_ID = 0;
final int INDEX_FINGERPRINT = 1;
Cursor keyCursor = context.getContentResolver().query(
KeychainContract.KeyRings.buildUnifiedKeyRingsUri(),
new String[]{
KeychainContract.KeyRings.MASTER_KEY_ID,
KeychainContract.KeyRings.FINGERPRINT
},
null,
null,
null
);
if (keyCursor == null) {
return new ArrayList<>();
}
ArrayList<ParcelableKeyRing> keyList = new ArrayList<>();
while (keyCursor.moveToNext()) {
long keyId = keyCursor.getLong(INDEX_MASTER_KEY_ID);
if (ignoreMasterKeyIds.contains(keyId)) {
continue;
}
Log.d(Constants.TAG, "Keyserver sync: Updating {" + keyId + "}");
String fingerprint = KeyFormattingUtils
.convertFingerprintToHex(keyCursor.getBlob(INDEX_FINGERPRINT));
String hexKeyId = KeyFormattingUtils
.convertKeyIdToHex(keyId);
// we aren't updating from keybase as of now
keyList.add(new ParcelableKeyRing(fingerprint, hexKeyId, null));
}
keyCursor.close();
return keyList;
}
private boolean isUpdateCancelled() {
return mCancelled.get();
}
/**
* will cancel an update already in progress. We send an Intent to cancel it instead of simply
* modifying a static variable sync the service is running in a process that is different from
* the default application process where the UI code runs.
*
* @param context used to send an Intent to the service requesting cancellation.
*/
public static void cancelUpdates(Context context) {
Intent intent = new Intent(context, KeyserverSyncAdapterService.class);
intent.setAction(ACTION_CANCEL);
context.startService(intent);
}
private Notification getOrbotNoification(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.ic_stat_notify_24dp)
.setLargeIcon(getBitmap(R.drawable.ic_launcher, context))
.setContentTitle(context.getString(R.string.keyserver_sync_orbot_notif_title))
.setContentText(context.getString(R.string.keyserver_sync_orbot_notif_msg))
.setAutoCancel(true);
// In case the user decides to not use tor
Intent ignoreTorIntent = new Intent(context, KeyserverSyncAdapterService.class);
ignoreTorIntent.setAction(ACTION_IGNORE_TOR);
PendingIntent ignoreTorPi = PendingIntent.getService(
context,
0, // security not issue since we're giving this pending intent to Notification Manager
ignoreTorIntent,
PendingIntent.FLAG_CANCEL_CURRENT
);
builder.addAction(R.drawable.ic_stat_tor_off,
context.getString(R.string.keyserver_sync_orbot_notif_ignore),
ignoreTorPi);
Intent startOrbotIntent = new Intent(context, KeyserverSyncAdapterService.class);
startOrbotIntent.setAction(ACTION_START_ORBOT);
PendingIntent startOrbotPi = PendingIntent.getService(
context,
0, // security not issue since we're giving this pending intent to Notification Manager
startOrbotIntent,
PendingIntent.FLAG_CANCEL_CURRENT
);
builder.addAction(R.drawable.ic_stat_tor,
context.getString(R.string.keyserver_sync_orbot_notif_start),
startOrbotPi
);
builder.setContentIntent(startOrbotPi);
return builder.build();
}
public static void enableKeyserverSync(Context context) {
try {
AccountManager manager = AccountManager.get(context);
Account[] accounts = manager.getAccountsByType(Constants.ACCOUNT_TYPE);
Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE);
if (accounts.length == 0) {
if (!manager.addAccountExplicitly(account, null, null)) {
Log.e(Constants.TAG, "Adding account failed!");
}
}
// for keyserver sync
ContentResolver.setIsSyncable(account, Constants.PROVIDER_AUTHORITY, 1);
ContentResolver.setSyncAutomatically(account, Constants.PROVIDER_AUTHORITY,
true);
ContentResolver.addPeriodicSync(
account,
Constants.PROVIDER_AUTHORITY,
new Bundle(),
SYNC_INTERVAL
);
} catch (SecurityException e) {
Log.e(Constants.TAG, "SecurityException when adding the account", e);
Toast.makeText(context, R.string.reinstall_openkeychain, Toast.LENGTH_LONG).show();
}
}
// from de.azapps.mirakel.helper.Helpers from https://github.com/MirakelX/mirakel-android
private Bitmap getBitmap(int resId, Context context) {
int mLargeIconWidth = (int) context.getResources().getDimension(
android.R.dimen.notification_large_icon_width);
int mLargeIconHeight = (int) context.getResources().getDimension(
android.R.dimen.notification_large_icon_height);
Drawable d;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
// noinspection deprecation (can't help it at this api level)
d = context.getResources().getDrawable(resId);
} else {
d = context.getDrawable(resId);
}
if (d == null) {
return null;
}
Bitmap b = Bitmap.createBitmap(mLargeIconWidth, mLargeIconHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
d.setBounds(0, 0, mLargeIconWidth, mLargeIconHeight);
d.draw(c);
return b;
}
}

View File

@@ -101,8 +101,6 @@ public class PassphraseCacheService extends Service {
private static final long DEFAULT_TTL = 15;
private static final int NOTIFICATION_ID = 1;
private static final int MSG_PASSPHRASE_CACHE_GET_OKAY = 1;
private static final int MSG_PASSPHRASE_CACHE_GET_KEY_NOT_FOUND = 2;
@@ -477,7 +475,7 @@ public class PassphraseCacheService extends Service {
private void updateService() {
if (mPassphraseCache.size() > 0) {
startForeground(NOTIFICATION_ID, getNotification());
startForeground(Constants.Notification.PASSPHRASE_CACHE, getNotification());
} else {
// stop whole service if no cached passphrases remaining
Log.d(Constants.TAG, "PassphraseCacheService: No passphrases remaining in memory, stopping service!");

View File

@@ -48,7 +48,6 @@ import org.sufficientlysecure.keychain.service.RevokeKeyringParcel;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.ui.base.CryptoOperationHelper;
import org.sufficientlysecure.keychain.ui.dialog.CustomAlertDialogBuilder;
import org.sufficientlysecure.keychain.ui.util.Notify;
import org.sufficientlysecure.keychain.ui.util.ThemeChanger;
import org.sufficientlysecure.keychain.util.Log;

View File

@@ -18,11 +18,6 @@
package org.sufficientlysecure.keychain.ui;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
@@ -68,18 +63,22 @@ import org.sufficientlysecure.keychain.provider.KeychainDatabase;
import org.sufficientlysecure.keychain.provider.ProviderHelper;
import org.sufficientlysecure.keychain.service.ConsolidateInputParcel;
import org.sufficientlysecure.keychain.service.ImportKeyringParcel;
import org.sufficientlysecure.keychain.service.KeyserverSyncAdapterService;
import org.sufficientlysecure.keychain.ui.adapter.KeyAdapter;
import org.sufficientlysecure.keychain.ui.base.CryptoOperationHelper;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
import org.sufficientlysecure.keychain.ui.util.FormattingUtils;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
import org.sufficientlysecure.keychain.ui.util.Notify;
import org.sufficientlysecure.keychain.ui.util.Notify.Style;
import org.sufficientlysecure.keychain.util.FabContainer;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.Preferences;
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Public key list with sticky list headers. It does _not_ extend ListFragment because it uses
* StickyListHeaders library which does not extend upon ListView.
@@ -536,7 +535,7 @@ public class KeyListFragment extends LoaderFragment
);
if (cursor == null) {
Notify.create(activity, R.string.error_loading_keys, Style.ERROR);
Notify.create(activity, R.string.error_loading_keys, Notify.Style.ERROR);
return;
}

View File

@@ -18,12 +18,22 @@
package org.sufficientlysecure.keychain.ui;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.view.ContextThemeWrapper;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.compatibility.DialogFragmentWorkaround;
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
import org.sufficientlysecure.keychain.ui.util.ThemeChanger;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.ParcelableProxy;
import org.sufficientlysecure.keychain.util.orbot.OrbotHelper;
@@ -34,8 +44,14 @@ import org.sufficientlysecure.keychain.util.orbot.OrbotHelper;
public class OrbotRequiredDialogActivity extends FragmentActivity
implements OrbotHelper.DialogActions {
public static final int MESSAGE_ORBOT_STARTED = 1;
public static final int MESSAGE_ORBOT_IGNORE = 2;
public static final int MESSAGE_DIALOG_CANCEL = 3;
// if suppplied and true will start Orbot directly without showing dialog
public static final String EXTRA_START_ORBOT = "start_orbot";
// used for communicating results when triggered from a service
public static final String EXTRA_MESSENGER = "messenger";
// to provide any previous crypto input into which proxy preference is merged
public static final String EXTRA_CRYPTO_INPUT = "extra_crypto_input";
@@ -43,6 +59,9 @@ public class OrbotRequiredDialogActivity extends FragmentActivity
public static final String RESULT_CRYPTO_INPUT = "result_crypto_input";
private CryptoInputParcel mCryptoInputParcel;
private Messenger mMessenger;
private ProgressDialog mShowOrbotProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
@@ -54,9 +73,16 @@ public class OrbotRequiredDialogActivity extends FragmentActivity
mCryptoInputParcel = new CryptoInputParcel();
}
mMessenger = getIntent().getParcelableExtra(EXTRA_MESSENGER);
boolean startOrbotDirect = getIntent().getBooleanExtra(EXTRA_START_ORBOT, false);
if (startOrbotDirect) {
OrbotHelper.bestPossibleOrbotStart(this, this);
ContextThemeWrapper theme = ThemeChanger.getDialogThemeWrapper(this);
mShowOrbotProgressDialog = new ProgressDialog(theme);
mShowOrbotProgressDialog.setTitle(R.string.progress_starting_orbot);
mShowOrbotProgressDialog.setCancelable(false);
mShowOrbotProgressDialog.show();
OrbotHelper.bestPossibleOrbotStart(this, this, false);
} else {
showDialog();
}
@@ -84,13 +110,32 @@ public class OrbotRequiredDialogActivity extends FragmentActivity
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case OrbotHelper.START_TOR_RESULT: {
onOrbotStarted(); // assumption that orbot was started, no way to tell for sure
dismissOrbotProgressDialog();
// unfortunately, this result is returned immediately and not when Orbot is started
// 10s is approximately the longest time Orbot has taken to start
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
onOrbotStarted(); // assumption that orbot was started
}
}, 10000);
}
}
}
/**
* for when Orbot is started without showing the dialog by the EXTRA_START_ORBOT intent extra
*/
private void dismissOrbotProgressDialog() {
if (mShowOrbotProgressDialog != null) {
mShowOrbotProgressDialog.dismiss();
}
}
@Override
public void onOrbotStarted() {
dismissOrbotProgressDialog();
sendMessage(MESSAGE_ORBOT_STARTED);
Intent intent = new Intent();
// send back unmodified CryptoInputParcel for a retry
intent.putExtra(RESULT_CRYPTO_INPUT, mCryptoInputParcel);
@@ -100,6 +145,7 @@ public class OrbotRequiredDialogActivity extends FragmentActivity
@Override
public void onNeutralButton() {
sendMessage(MESSAGE_ORBOT_IGNORE);
Intent intent = new Intent();
mCryptoInputParcel.addParcelableProxy(ParcelableProxy.getForNoProxy());
intent.putExtra(RESULT_CRYPTO_INPUT, mCryptoInputParcel);
@@ -109,6 +155,19 @@ public class OrbotRequiredDialogActivity extends FragmentActivity
@Override
public void onCancel() {
sendMessage(MESSAGE_DIALOG_CANCEL);
finish();
}
private void sendMessage(int what) {
if (mMessenger != null) {
Message msg = Message.obtain();
msg.what = what;
try {
mMessenger.send(msg);
} catch (RemoteException e) {
Log.e(Constants.TAG, "Could not deliver message", e);
}
}
}
}

View File

@@ -18,11 +18,12 @@
package org.sufficientlysecure.keychain.ui;
import android.annotation.TargetApi;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
@@ -31,6 +32,7 @@ import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.provider.ContactsContract;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
@@ -467,11 +469,94 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
}
}
/**
* This fragment shows the keyserver/contacts sync preferences
*/
public static class SyncSettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.sync_preferences);
}
@Override
public void onResume() {
super.onResume();
// this needs to be done in onResume since the user can change sync values from Android
// settings and we need to reflect that change when the user navigates back
AccountManager manager = AccountManager.get(getActivity());
final Account account = manager.getAccountsByType(Constants.ACCOUNT_TYPE)[0];
// for keyserver sync
initializeSyncCheckBox(
(CheckBoxPreference) findPreference(Constants.Pref.SYNC_KEYSERVER),
account,
Constants.PROVIDER_AUTHORITY
);
// for contacts sync
initializeSyncCheckBox(
(CheckBoxPreference) findPreference(Constants.Pref.SYNC_CONTACTS),
account,
ContactsContract.AUTHORITY
);
}
private void initializeSyncCheckBox(final CheckBoxPreference syncCheckBox,
final Account account,
final String authority) {
boolean syncEnabled = ContentResolver.getSyncAutomatically(account, authority);
syncCheckBox.setChecked(syncEnabled);
setSummary(syncCheckBox, authority, syncEnabled);
syncCheckBox.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean syncEnabled = (Boolean) newValue;
if (syncEnabled) {
ContentResolver.setSyncAutomatically(account, authority, true);
} else {
// disable syncs
ContentResolver.setSyncAutomatically(account, authority, false);
// cancel any ongoing/pending syncs
ContentResolver.cancelSync(account, authority);
}
setSummary(syncCheckBox, authority, syncEnabled);
return true;
}
});
}
private void setSummary(CheckBoxPreference syncCheckBox, String authority,
boolean checked) {
switch (authority) {
case Constants.PROVIDER_AUTHORITY: {
if (checked) {
syncCheckBox.setSummary(R.string.label_sync_settings_keyserver_summary_on);
} else {
syncCheckBox.setSummary(R.string.label_sync_settings_keyserver_summary_off);
}
break;
}
case ContactsContract.AUTHORITY: {
if (checked) {
syncCheckBox.setSummary(R.string.label_sync_settings_contacts_summary_on);
} else {
syncCheckBox.setSummary(R.string.label_sync_settings_contacts_summary_off);
}
break;
}
}
}
}
protected boolean isValidFragment(String fragmentName) {
return AdvancedPrefsFragment.class.getName().equals(fragmentName)
|| CloudSearchPrefsFragment.class.getName().equals(fragmentName)
|| ProxyPrefsFragment.class.getName().equals(fragmentName)
|| GuiPrefsFragment.class.getName().equals(fragmentName)
|| SyncSettingsFragment.class.getName().equals(fragmentName)
|| super.isValidFragment(fragmentName);
}

View File

@@ -30,6 +30,7 @@ import android.view.ViewGroup;
import android.widget.TextView;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.service.KeyserverSyncAdapterService;
import org.sufficientlysecure.keychain.ui.util.ThemeChanger;
/**
@@ -51,6 +52,7 @@ public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onResume() {
super.onResume();
KeyserverSyncAdapterService.cancelUpdates(this);
if (mThemeChanger.changeTheme()) {
Intent intent = getIntent();

View File

@@ -26,6 +26,7 @@ import android.preference.PreferenceManager;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.Constants.Pref;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.service.KeyserverSyncAdapterService;
import java.net.Proxy;
import java.util.ArrayList;
@@ -306,7 +307,7 @@ public class Preferences {
return new ProxyPrefs(true, false, Constants.Orbot.PROXY_HOST, Constants.Orbot.PROXY_PORT,
Constants.Orbot.PROXY_TYPE);
} else if (useNormalProxy) {
return new ProxyPrefs(useTor, useNormalProxy, getProxyHost(), getProxyPort(), getProxyType());
return new ProxyPrefs(false, true, getProxyHost(), getProxyPort(), getProxyType());
} else {
return new ProxyPrefs(false, false, null, -1, null);
}
@@ -356,7 +357,7 @@ public class Preferences {
}
}
public void upgradePreferences() {
public void upgradePreferences(Context context) {
if (mSharedPreferences.getInt(Constants.Pref.PREF_DEFAULT_VERSION, 0) !=
Constants.Defaults.PREF_VERSION) {
switch (mSharedPreferences.getInt(Constants.Pref.PREF_DEFAULT_VERSION, 0)) {
@@ -394,6 +395,10 @@ public class Preferences {
}
// fall through
case 5: {
KeyserverSyncAdapterService.enableKeyserverSync(context);
}
// fall through
case 6: {
}
}

View File

@@ -361,7 +361,7 @@ public class OrbotHelper {
.show(fragmentActivity.getSupportFragmentManager(),
"OrbotHelperOrbotStartDialog");
}
}.startOrbotAndListen(fragmentActivity);
}.startOrbotAndListen(fragmentActivity, true);
return false;
} else {
@@ -385,7 +385,8 @@ public class OrbotHelper {
* activities wishing to respond to a change in Orbot state.
*/
public static void bestPossibleOrbotStart(final DialogActions dialogActions,
final Activity activity) {
final Activity activity,
boolean showProgress) {
new SilentStartManager() {
@Override
@@ -397,23 +398,23 @@ public class OrbotHelper {
protected void onSilentStartDisabled() {
requestShowOrbotStart(activity);
}
}.startOrbotAndListen(activity);
}.startOrbotAndListen(activity, showProgress);
}
/**
* base class for listening to silent orbot starts. Also handles display of progress dialog.
*/
private static abstract class SilentStartManager {
public static abstract class SilentStartManager {
private ProgressDialog mProgressDialog;
public void startOrbotAndListen(Context context) {
mProgressDialog = new ProgressDialog(ThemeChanger.getDialogThemeWrapper(context));
mProgressDialog.setMessage(context.getString(R.string.progress_starting_orbot));
mProgressDialog.setCancelable(false);
mProgressDialog.show();
public void startOrbotAndListen(final Context context, final boolean showProgress) {
Log.d(Constants.TAG, "starting orbot listener");
if (showProgress) {
showProgressDialog(context);
}
BroadcastReceiver receiver = new BroadcastReceiver() {
final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getStringExtra(OrbotHelper.EXTRA_STATUS)) {
@@ -423,14 +424,18 @@ public class OrbotHelper {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mProgressDialog.dismiss();
if (showProgress) {
mProgressDialog.dismiss();
}
onOrbotStarted();
}
}, 1000);
break;
case OrbotHelper.STATUS_STARTS_DISABLED:
context.unregisterReceiver(this);
mProgressDialog.dismiss();
if (showProgress) {
mProgressDialog.dismiss();
}
onSilentStartDisabled();
break;
@@ -444,6 +449,13 @@ public class OrbotHelper {
requestStartTor(context);
}
private void showProgressDialog(Context context) {
mProgressDialog = new ProgressDialog(ThemeChanger.getDialogThemeWrapper(context));
mProgressDialog.setMessage(context.getString(R.string.progress_starting_orbot));
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
protected abstract void onOrbotStarted();
protected abstract void onSilentStartDisabled();

Binary file not shown.

After

Width:  |  Height:  |  Size: 920 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 920 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 540 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 540 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 727 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

View File

@@ -51,6 +51,7 @@
<string name="section_passphrase_cache">"Password/PIN Handling"</string>
<string name="section_proxy_settings">"Proxy Settings"</string>
<string name="section_gui">"Interface"</string>
<string name="section_sync_settings">"Sync Settings"</string>
<string name="section_certify">"Confirm"</string>
<string name="section_actions">"Actions"</string>
<string name="section_share_key">"Key"</string>
@@ -175,6 +176,15 @@
<string name="pref_keybase">"keybase.io"</string>
<string name="pref_keybase_summary">"Search keys on keybase.io"</string>
<string name="label_sync_settings_keyserver_title">"Automatically update keys"</string>
<string name="label_sync_settings_keyserver_summary_on">"Keys older than a week are updated from the preferred keyserver"</string>
<string name="label_sync_settings_keyserver_summary_off">"Keys not automatically updated"</string>
<string name="label_sync_settings_contacts_title">"Sync Contacts with Keys"</string>
<string name="label_sync_settings_contacts_summary_on">"Keys linked to contacts with matching emails, happens completely offline"</string>
<string name="label_sync_settings_contacts_summary_off">"New keys will not be linked to contacts"</string>
<!-- label shown in Android settings under the OpenKeychain account -->
<string name="keyserver_sync_settings_title">"Automatically update keys"</string>
<!-- Proxy Preferences -->
<string name="pref_proxy_tor_title">"Enable Tor"</string>
<string name="pref_proxy_tor_summary">"Requires Orbot to be installed"</string>
@@ -1304,7 +1314,6 @@
</plurals>
<string name="msg_revoke_error_empty">"Nothing to revoke!"</string>
<string name="msg_revoke_error_multi_secret">"Secret keys can only be revoked individually!"</string>
<string name="msg_revoke_error_not_found">"Cannot find key to revoke!"</string>
<string name="msg_revoke_key">"Revoking key %s"</string>
<string name="msg_revoke_key_fail">"Failed revoking key"</string>
@@ -1351,6 +1360,12 @@
<string name="passp_cache_notif_clear">"Clear Passwords"</string>
<string name="passp_cache_notif_pwd">"Password"</string>
<!-- Keyserver sync -->
<string name="keyserver_sync_orbot_notif_title">"Sync From Cloud requires Orbot"</string>
<string name="keyserver_sync_orbot_notif_msg">"Tap to start orbot"</string>
<string name="keyserver_sync_orbot_notif_start">"Start Orbot"</string>
<string name="keyserver_sync_orbot_notif_ignore">"Direct"</string>
<!-- First Time -->
<string name="first_time_text1">"Take back your privacy with OpenKeychain!"</string>
<string name="first_time_create_key">"Create my key"</string>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<sync-adapter xmlns:android="http://schemas.android.com/apk/res/android"
android:contentAuthority="@string/provider_content_authority"
android:accountType="@string/account_type"
android:supportsUploading="false"
android:userVisible="true"
android:allowParallelSyncs="false"
android:isAlwaysSyncable="true" />

View File

@@ -11,4 +11,7 @@
<header
android:fragment="org.sufficientlysecure.keychain.ui.SettingsActivity$ProxyPrefsFragment"
android:title="@string/section_proxy_settings" />
<header
android:fragment="org.sufficientlysecure.keychain.ui.SettingsActivity$SyncSettingsFragment"
android:title="@string/section_sync_settings" />
</preference-headers>

View File

@@ -0,0 +1,10 @@
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="syncKeyserver"
android:persistent="false"
android:title="@string/label_sync_settings_keyserver_title"/>
<CheckBoxPreference
android:key="syncContacts"
android:persistent="false"
android:title="@string/label_sync_settings_contacts_title" />
</PreferenceScreen>