From fb7359e6a3aaa3ee0b985358c044de2a5594d45b Mon Sep 17 00:00:00 2001 From: Daniel Gultsch Date: Fri, 16 Oct 2015 09:58:31 +0200 Subject: block code when doing unforced disconnect --- .../services/XmppConnectionService.java | 376 ++++++++++----------- .../siacs/conversations/xmpp/XmppConnection.java | 67 ++-- 2 files changed, 220 insertions(+), 223 deletions(-) (limited to 'src/main/java/eu/siacs') diff --git a/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java b/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java index f9f9b71e2..bb4a1ce96 100644 --- a/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java +++ b/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java @@ -26,10 +26,9 @@ import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.ContactsContract; import android.security.KeyChain; -import android.security.KeyChainException; +import android.util.DisplayMetrics; import android.util.Log; import android.util.LruCache; -import android.util.DisplayMetrics; import android.util.Pair; import net.java.otr4j.OtrException; @@ -38,16 +37,11 @@ import net.java.otr4j.session.SessionID; import net.java.otr4j.session.SessionImpl; import net.java.otr4j.session.SessionStatus; -import org.bouncycastle.asn1.x500.X500Name; -import org.bouncycastle.asn1.x500.style.BCStyle; -import org.bouncycastle.asn1.x500.style.IETFUtils; -import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.openintents.openpgp.util.OpenPgpApi; import org.openintents.openpgp.util.OpenPgpServiceConnection; import java.math.BigInteger; import java.security.SecureRandom; -import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; @@ -124,9 +118,16 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public static final String ACTION_CLEAR_NOTIFICATION = "clear_notification"; public static final String ACTION_DISABLE_FOREGROUND = "disable_foreground"; - private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts"; public static final String ACTION_TRY_AGAIN = "try_again"; public static final String ACTION_DISABLE_ACCOUNT = "disable_account"; + private static final String ACTION_MERGE_PHONE_CONTACTS = "merge_phone_contacts"; + private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor(); + private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor(); + private final IBinder mBinder = new XmppConnectionBinder(); + private final List conversations = new CopyOnWriteArrayList<>(); + private final IqGenerator mIqGenerator = new IqGenerator(this); + private final List mInProgressAvatarFetches = new ArrayList<>(); + public DatabaseBackend databaseBackend; private ContentObserver contactObserver = new ContentObserver(null) { @Override public void onChange(boolean selfChange) { @@ -137,63 +138,30 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa startService(intent); } }; - - private final SerialSingleThreadExecutor mFileAddingExecutor = new SerialSingleThreadExecutor(); - private final SerialSingleThreadExecutor mDatabaseExecutor = new SerialSingleThreadExecutor(); - - private final IBinder mBinder = new XmppConnectionBinder(); - private final List conversations = new CopyOnWriteArrayList<>(); - private final FileObserver fileObserver = new FileObserver( - FileBackend.getConversationsImageDirectory()) { - - @Override - public void onEvent(int event, String path) { - if (event == FileObserver.DELETE) { - markFileDeleted(path.split("\\.")[0]); - } - } - }; - private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() { - - @Override - public void onJinglePacketReceived(Account account, JinglePacket packet) { - mJingleConnectionManager.deliverPacket(account, packet); - } - }; - private final OnBindListener mOnBindListener = new OnBindListener() { - - @Override - public void onBind(final Account account) { - account.getRoster().clearPresences(); - fetchRosterFromServer(account); - fetchBookmarks(account); - sendPresence(account); - connectMultiModeConversations(account); - mMessageArchiveService.executePendingQueries(account); - mJingleConnectionManager.cancelInTransmission(); - syncDirtyContacts(account); - account.getAxolotlService().publishBundlesIfNeeded(true, false); - } - }; - private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() { - + private FileBackend fileBackend = new FileBackend(this); + private MemorizingTrustManager mMemorizingTrustManager; + private NotificationService mNotificationService = new NotificationService( + this); + private OnMessagePacketReceived mMessageParser = new MessageParser(this); + private OnPresencePacketReceived mPresenceParser = new PresenceParser(this); + private IqParser mIqParser = new IqParser(this); + private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() { @Override - public void onMessageAcknowledged(Account account, String uuid) { - for (final Conversation conversation : getConversations()) { - if (conversation.getAccount() == account) { - Message message = conversation.findUnsentMessageWithUuid(uuid); - if (message != null) { - markMessage(message, Message.STATUS_SEND); - if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) { - databaseBackend.updateConversation(conversation); - } - } + public void onIqPacketReceived(Account account, IqPacket packet) { + if (packet.getType() != IqPacket.TYPE.RESULT) { + Element error = packet.findChild("error"); + String text = error != null ? error.findChildContent("text") : null; + if (text != null) { + Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": received iq error - " + text); } } } }; - private final IqGenerator mIqGenerator = new IqGenerator(this); - public DatabaseBackend databaseBackend; + private MessageGenerator mMessageGenerator = new MessageGenerator(this); + private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this); + private List accounts; + private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager( + this); public OnContactStatusChanged onContactStatusChanged = new OnContactStatusChanged() { @Override @@ -220,42 +188,77 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } } }; - private FileBackend fileBackend = new FileBackend(this); - private MemorizingTrustManager mMemorizingTrustManager; - private NotificationService mNotificationService = new NotificationService( + private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager( this); - private OnMessagePacketReceived mMessageParser = new MessageParser(this); - private OnPresencePacketReceived mPresenceParser = new PresenceParser(this); - private IqParser mIqParser = new IqParser(this); - private OnIqPacketReceived mDefaultIqHandler = new OnIqPacketReceived() { + private AvatarService mAvatarService = new AvatarService(this); + private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this); + private OnConversationUpdate mOnConversationUpdate = null; + private final FileObserver fileObserver = new FileObserver( + FileBackend.getConversationsImageDirectory()) { + @Override - public void onIqPacketReceived(Account account, IqPacket packet) { - if (packet.getType() != IqPacket.TYPE.RESULT) { - Element error = packet.findChild("error"); - String text = error != null ? error.findChildContent("text") : null; - if (text != null) { - Log.d(Config.LOGTAG,account.getJid().toBareJid()+": received iq error - "+text); + public void onEvent(int event, String path) { + if (event == FileObserver.DELETE) { + markFileDeleted(path.split("\\.")[0]); + } + } + }; + private final OnJinglePacketReceived jingleListener = new OnJinglePacketReceived() { + + @Override + public void onJinglePacketReceived(Account account, JinglePacket packet) { + mJingleConnectionManager.deliverPacket(account, packet); + } + }; + private final OnMessageAcknowledged mOnMessageAcknowledgedListener = new OnMessageAcknowledged() { + + @Override + public void onMessageAcknowledged(Account account, String uuid) { + for (final Conversation conversation : getConversations()) { + if (conversation.getAccount() == account) { + Message message = conversation.findUnsentMessageWithUuid(uuid); + if (message != null) { + markMessage(message, Message.STATUS_SEND); + if (conversation.setLastMessageTransmitted(System.currentTimeMillis())) { + databaseBackend.updateConversation(conversation); + } + } } } } }; - private MessageGenerator mMessageGenerator = new MessageGenerator(this); - private PresenceGenerator mPresenceGenerator = new PresenceGenerator(this); - private List accounts; - private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager( - this); - private HttpConnectionManager mHttpConnectionManager = new HttpConnectionManager( - this); - private AvatarService mAvatarService = new AvatarService(this); - private final List mInProgressAvatarFetches = new ArrayList<>(); - private MessageArchiveService mMessageArchiveService = new MessageArchiveService(this); - private OnConversationUpdate mOnConversationUpdate = null; private int convChangedListenerCount = 0; private OnShowErrorToast mOnShowErrorToast = null; private int showErrorToastListenerCount = 0; private int unreadCount = -1; private OnAccountUpdate mOnAccountUpdate = null; private OnCaptchaRequested mOnCaptchaRequested = null; + private int accountChangedListenerCount = 0; + private int captchaRequestedListenerCount = 0; + private OnRosterUpdate mOnRosterUpdate = null; + private OnUpdateBlocklist mOnUpdateBlocklist = null; + private int updateBlocklistListenerCount = 0; + private int rosterChangedListenerCount = 0; + private OnMucRosterUpdate mOnMucRosterUpdate = null; + private int mucRosterChangedListenerCount = 0; + private OnKeyStatusUpdated mOnKeyStatusUpdated = null; + private int keyStatusUpdatedListenerCount = 0; + private SecureRandom mRandom; + private final OnBindListener mOnBindListener = new OnBindListener() { + + @Override + public void onBind(final Account account) { + account.getRoster().clearPresences(); + fetchRosterFromServer(account); + fetchBookmarks(account); + sendPresence(account); + connectMultiModeConversations(account); + mMessageArchiveService.executePendingQueries(account); + mJingleConnectionManager.cancelInTransmission(); + syncDirtyContacts(account); + account.getAxolotlService().publishBundlesIfNeeded(true, false); + } + }; private OnStatusChanged statusListener = new OnStatusChanged() { @Override @@ -267,10 +270,10 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa if (account.getStatus() == Account.State.ONLINE) { if (connection != null && connection.getFeatures().csi()) { if (checkListeners()) { - Log.d(Config.LOGTAG, account.getJid().toBareJid()+ " sending csi//inactive"); + Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//inactive"); connection.sendInactive(); } else { - Log.d(Config.LOGTAG, account.getJid().toBareJid()+ " sending csi//active"); + Log.d(Config.LOGTAG, account.getJid().toBareJid() + " sending csi//active"); connection.sendActive(); } } @@ -294,7 +297,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa resetSendingToWaiting(account); if (!account.isOptionSet(Account.OPTION_DISABLED)) { int timeToReconnect = mRandom.nextInt(20) + 10; - scheduleWakeUpCall(timeToReconnect,account.getUuid().hashCode()); + scheduleWakeUpCall(timeToReconnect, account.getUuid().hashCode()); } } else if (account.getStatus() == Account.State.REGISTRATION_SUCCESSFUL) { databaseBackend.updateAccount(account); @@ -307,23 +310,12 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa + ": error connecting account. try again in " + next + "s for the " + (connection.getAttempt() + 1) + " time"); - scheduleWakeUpCall(next,account.getUuid().hashCode()); + scheduleWakeUpCall(next, account.getUuid().hashCode()); } - } + } getNotificationService().updateErrorNotification(); } }; - private int accountChangedListenerCount = 0; - private int captchaRequestedListenerCount = 0; - private OnRosterUpdate mOnRosterUpdate = null; - private OnUpdateBlocklist mOnUpdateBlocklist = null; - private int updateBlocklistListenerCount = 0; - private int rosterChangedListenerCount = 0; - private OnMucRosterUpdate mOnMucRosterUpdate = null; - private int mucRosterChangedListenerCount = 0; - private OnKeyStatusUpdated mOnKeyStatusUpdated = null; - private int keyStatusUpdatedListenerCount = 0; - private SecureRandom mRandom; private OpenPgpServiceConnection pgpServiceConnection; private PgpEngine mPgpEngine = null; private WakeLock wakeLock; @@ -333,6 +325,11 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa private EventReceiver mEventReceiver = new EventReceiver(); private boolean mRestoredFromDatabase = false; + + private static String generateFetchKey(Account account, final Avatar avatar) { + return account.getJid().toBareJid() + "_" + avatar.owner + "_" + avatar.sha1sum; + } + public boolean areMessagesInitialized() { return this.mRestoredFromDatabase; } @@ -341,8 +338,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa if (pgpServiceConnection.isBound()) { if (this.mPgpEngine == null) { this.mPgpEngine = new PgpEngine(new OpenPgpApi( - getApplicationContext(), - pgpServiceConnection.getService()), this); + getApplicationContext(), + pgpServiceConnection.getService()), this); } return mPgpEngine; } else { @@ -366,7 +363,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa if (encryption == Message.ENCRYPTION_PGP) { encryption = Message.ENCRYPTION_DECRYPTED; } - Message message = new Message(conversation,uri.toString(),encryption); + Message message = new Message(conversation, uri.toString(), encryption); if (conversation.getNextCounterpart() != null) { message.setCounterpart(conversation.getNextCounterpart()); } @@ -378,8 +375,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } public void attachFileToConversation(final Conversation conversation, - final Uri uri, - final UiCallback callback) { + final Uri uri, + final UiCallback callback) { final Message message; if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) { message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED); @@ -389,7 +386,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa message.setCounterpart(conversation.getNextCounterpart()); message.setType(Message.TYPE_FILE); String path = getFileBackend().getOriginalPath(uri); - if (path!=null) { + if (path != null) { message.setRelativeFilePath(path); getFileBackend().updateFileParams(message); if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) { @@ -419,7 +416,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public void attachImageToConversation(final Conversation conversation, final Uri uri, final UiCallback callback) { if (getFileBackend().useImageAsIs(uri)) { - Log.d(Config.LOGTAG,"using image as is"); + Log.d(Config.LOGTAG, "using image as is"); attachFileToConversation(conversation, uri, callback); return; } @@ -427,7 +424,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa if (conversation.getNextEncryption() == Message.ENCRYPTION_PGP) { message = new Message(conversation, "", Message.ENCRYPTION_DECRYPTED); } else { - message = new Message(conversation, "",conversation.getNextEncryption()); + message = new Message(conversation, "", conversation.getNextEncryption()); } message.setCounterpart(conversation.getNextCounterpart()); message.setType(Message.TYPE_IMAGE); @@ -462,7 +459,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa final String action = intent == null ? null : intent.getAction(); boolean interactive = false; if (action != null) { - Log.d(Config.LOGTAG,"action: "+action); + Log.d(Config.LOGTAG, "action: " + action); switch (action) { case ConnectivityManager.CONNECTIVITY_ACTION: if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) { @@ -483,7 +480,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa mNotificationService.clear(); break; case ACTION_DISABLE_FOREGROUND: - getPreferences().edit().putBoolean("keep_foreground_service",false).commit(); + getPreferences().edit().putBoolean("keep_foreground_service", false).commit(); toggleForegroundService(); break; case ACTION_TRY_AGAIN: @@ -495,7 +492,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa String jid = intent.getStringExtra("account"); Account account = jid == null ? null : findAccountByJid(Jid.fromString(jid)); if (account != null) { - account.setOption(Account.OPTION_DISABLED,true); + account.setOption(Account.OPTION_DISABLED, true); updateAccount(account); } } catch (final InvalidJidException ignored) { @@ -535,7 +532,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa long lastReceived = account.getXmppConnection().getLastPacketReceived(); long lastSent = account.getXmppConnection().getLastPingSent(); long pingInterval = "ui".equals(action) ? Config.PING_MIN_INTERVAL * 1000 : Config.PING_MAX_INTERVAL * 1000; - long msToNextPing = (Math.max(lastReceived,lastSent) + pingInterval) - SystemClock.elapsedRealtime(); + long msToNextPing = (Math.max(lastReceived, lastSent) + pingInterval) - SystemClock.elapsedRealtime(); long pingTimeoutIn = (lastSent + Config.PING_TIMEOUT * 1000) - SystemClock.elapsedRealtime(); if (lastSent > lastReceived) { if (pingTimeoutIn < 0) { @@ -543,24 +540,24 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa this.reconnectAccount(account, true, interactive); } else { int secs = (int) (pingTimeoutIn / 1000); - this.scheduleWakeUpCall(secs,account.getUuid().hashCode()); + this.scheduleWakeUpCall(secs, account.getUuid().hashCode()); } } else if (msToNextPing <= 0) { account.getXmppConnection().sendPing(); - Log.d(Config.LOGTAG, account.getJid().toBareJid()+" send ping"); - this.scheduleWakeUpCall(Config.PING_TIMEOUT,account.getUuid().hashCode()); + Log.d(Config.LOGTAG, account.getJid().toBareJid() + " send ping"); + this.scheduleWakeUpCall(Config.PING_TIMEOUT, account.getUuid().hashCode()); } else { this.scheduleWakeUpCall((int) (msToNextPing / 1000), account.getUuid().hashCode()); } } else if (account.getStatus() == Account.State.OFFLINE) { - reconnectAccount(account,true, interactive); + reconnectAccount(account, true, interactive); } else if (account.getStatus() == Account.State.CONNECTING) { long timeout = Config.CONNECT_TIMEOUT - ((SystemClock.elapsedRealtime() - account.getXmppConnection().getLastConnect()) / 1000); if (timeout < 0) { Log.d(Config.LOGTAG, account.getJid() + ": time out during connect reconnecting"); reconnectAccount(account, true, interactive); } else { - scheduleWakeUpCall((int) timeout,account.getUuid().hashCode()); + scheduleWakeUpCall((int) timeout, account.getUuid().hashCode()); } } else { if (account.getXmppConnection().getTimeToNextAttempt() <= 0) { @@ -621,8 +618,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } private void resetAllAttemptCounts(boolean reallyAll) { - Log.d(Config.LOGTAG,"resetting all attepmt counts"); - for(Account account : accounts) { + Log.d(Config.LOGTAG, "resetting all attepmt counts"); + for (Account account : accounts) { if (account.hasErrorStatus() || reallyAll) { final XmppConnection connection = account.getXmppConnection(); if (connection != null) { @@ -634,7 +631,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public boolean hasInternetConnection() { ConnectivityManager cm = (ConnectivityManager) getApplicationContext() - .getSystemService(Context.CONNECTIVITY_SERVICE); + .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnected(); } @@ -667,7 +664,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa this.pgpServiceConnection.bindToService(); this.pm = (PowerManager) getSystemService(Context.POWER_SERVICE); - this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"XmppConnectionService"); + this.wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "XmppConnectionService"); toggleForegroundService(); updateUnreadCountBadge(); toggleScreenEventReceiver(); @@ -677,7 +674,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public void onTrimMemory(int level) { super.onTrimMemory(level); if (level >= TRIM_MEMORY_COMPLETE) { - Log.d(Config.LOGTAG,"clear cache due to low memory"); + Log.d(Config.LOGTAG, "clear cache due to low memory"); getBitmapCache().evictAll(); } } @@ -717,7 +714,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa @Override public void onTaskRemoved(final Intent rootIntent) { super.onTaskRemoved(rootIntent); - if (!getPreferences().getBoolean("keep_foreground_service",false)) { + if (!getPreferences().getBoolean("keep_foreground_service", false)) { this.logoutAndSave(); } } @@ -800,11 +797,11 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa message.getConversation().endOtrIfNeeded(); message.getConversation().findUnsentMessagesWithEncryption(Message.ENCRYPTION_OTR, new Conversation.OnMessageFound() { - @Override - public void onMessageFound(Message message) { - markMessage(message,Message.STATUS_SEND_FAILED); - } - }); + @Override + public void onMessageFound(Message message) { + markMessage(message, Message.STATUS_SEND_FAILED); + } + }); } if (account.isOnlineAndConnected()) { @@ -812,7 +809,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa case Message.ENCRYPTION_NONE: if (message.needsUploading()) { if (account.httpUploadAvailable() || message.fixCounterpart()) { - this.sendFileMessage(message,delay); + this.sendFileMessage(message, delay); } else { break; } @@ -824,7 +821,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa case Message.ENCRYPTION_DECRYPTED: if (message.needsUploading()) { if (account.httpUploadAvailable() || message.fixCounterpart()) { - this.sendFileMessage(message,delay); + this.sendFileMessage(message, delay); } else { break; } @@ -857,7 +854,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa message.setAxolotlFingerprint(account.getAxolotlService().getOwnFingerprint()); if (message.needsUploading()) { if (account.httpUploadAvailable() || message.fixCounterpart()) { - this.sendFileMessage(message,delay); + this.sendFileMessage(message, delay); } else { break; } @@ -880,7 +877,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } } } else { - switch(message.getEncryption()) { + switch (message.getEncryption()) { case Message.ENCRYPTION_DECRYPTED: if (!message.needsUploading()) { String pgpBody = message.getEncryptedBody(); @@ -907,9 +904,9 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa if (resend) { if (packet != null) { if (account.getXmppConnection().getFeatures().sm() || conversation.getMode() == Conversation.MODE_MULTI) { - markMessage(message,Message.STATUS_UNSEND); + markMessage(message, Message.STATUS_UNSEND); } else { - markMessage(message,Message.STATUS_SEND); + markMessage(message, Message.STATUS_SEND); } } } else { @@ -921,7 +918,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } if (packet != null) { if (delay) { - mMessageGenerator.addDelay(packet,message.getTimeSent()); + mMessageGenerator.addDelay(packet, message.getTimeSent()); } if (conversation.setOutgoingChatState(Config.DEFAULT_CHATSTATE)) { if (this.sendChatStates()) { @@ -989,7 +986,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } account.setBookmarks(bookmarks); } else { - Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not fetch bookmarks"); + Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not fetch bookmarks"); } } }; @@ -1013,12 +1010,12 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa mPhoneContactMergerThread = new Thread(new Runnable() { @Override public void run() { - Log.d(Config.LOGTAG,"start merging phone contacts with roster"); + Log.d(Config.LOGTAG, "start merging phone contacts with roster"); for (Account account : accounts) { List withSystemAccounts = account.getRoster().getWithSystemAccounts(); for (Bundle phoneContact : phoneContacts) { if (Thread.interrupted()) { - Log.d(Config.LOGTAG,"interrupted merging phone contacts"); + Log.d(Config.LOGTAG, "interrupted merging phone contacts"); return; } Jid jid; @@ -1029,8 +1026,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } final Contact contact = account.getRoster().getContact(jid); String systemAccount = phoneContact.getInt("phoneid") - + "#" - + phoneContact.getString("lookup"); + + "#" + + phoneContact.getString("lookup"); contact.setSystemAccount(systemAccount); if (contact.setPhotoUri(phoneContact.getString("photouri"))) { getAvatarService().clear(contact); @@ -1038,7 +1035,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa contact.setSystemName(phoneContact.getString("displayname")); withSystemAccounts.remove(contact); } - for(Contact contact : withSystemAccounts) { + for (Contact contact : withSystemAccounts) { contact.setSystemAccount(null); contact.setSystemName(null); if (contact.setPhotoUri(null)) { @@ -1046,7 +1043,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } } } - Log.d(Config.LOGTAG,"finished merging phone contacts"); + Log.d(Config.LOGTAG, "finished merging phone contacts"); updateAccountUi(); } }); @@ -1064,11 +1061,11 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa Account account = accountLookupTable.get(conversation.getAccountUuid()); conversation.setAccount(account); } - Runnable runnable =new Runnable() { + Runnable runnable = new Runnable() { @Override public void run() { - Log.d(Config.LOGTAG,"restoring roster"); - for(Account account : accounts) { + Log.d(Config.LOGTAG, "restoring roster"); + for (Account account : accounts) { databaseBackend.readRoster(account.getRoster()); account.initAccountServices(XmppConnectionService.this); } @@ -1077,7 +1074,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa PhoneHelper.loadPhoneContacts(getApplicationContext(), new CopyOnWriteArrayList(), XmppConnectionService.this); - Log.d(Config.LOGTAG,"restoring messages"); + Log.d(Config.LOGTAG, "restoring messages"); for (Conversation conversation : conversations) { conversation.addAll(0, databaseBackend.getMessages(conversation, Config.PAGE_SIZE)); checkDeletedFiles(conversation); @@ -1090,7 +1087,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } mNotificationService.finishBacklog(); mRestoredFromDatabase = true; - Log.d(Config.LOGTAG,"restored all messages"); + Log.d(Config.LOGTAG, "restored all messages"); updateConversationUi(); } }; @@ -1110,8 +1107,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa if (!getFileBackend().isFileAvailable(message)) { message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED)); final int s = message.getStatus(); - if(s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) { - markMessage(message,Message.STATUS_SEND_FAILED); + if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) { + markMessage(message, Message.STATUS_SEND_FAILED); } } } @@ -1125,8 +1122,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa if (!getFileBackend().isFileAvailable(message)) { message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED)); final int s = message.getStatus(); - if(s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) { - markMessage(message,Message.STATUS_SEND_FAILED); + if (s == Message.STATUS_WAITING || s == Message.STATUS_OFFERED || s == Message.STATUS_UNSEND) { + markMessage(message, Message.STATUS_SEND_FAILED); } else { updateConversationUi(); } @@ -1169,7 +1166,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } public void loadMoreMessages(final Conversation conversation, final long timestamp, final OnMoreMessagesLoaded callback) { - if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation,callback)) { + if (XmppConnectionService.this.getMessageArchiveService().queryInProgress(conversation, callback)) { return; } Log.d(Config.LOGTAG, "load more messages for " + conversation.getName() + " prior to " + MessageGenerator.getTimestamp(timestamp)); @@ -1177,7 +1174,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa @Override public void run() { final Account account = conversation.getAccount(); - List messages = databaseBackend.getMessages(conversation, 50,timestamp); + List messages = databaseBackend.getMessages(conversation, 50, timestamp); if (messages.size() > 0) { conversation.addAll(0, messages); checkDeletedFiles(conversation); @@ -1186,7 +1183,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa && account.isOnlineAndConnected()) { if ((conversation.getMode() == Conversation.MODE_SINGLE && account.getXmppConnection().getFeatures().mam()) || (conversation.getMode() == Conversation.MODE_MULTI && conversation.getMucOptions().mamSupport())) { - MessageArchiveService.Query query = getMessageArchiveService().query(conversation,0,timestamp - 1); + MessageArchiveService.Query query = getMessageArchiveService().query(conversation, 0, timestamp - 1); if (query != null) { query.setCallback(callback); } @@ -1320,7 +1317,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public void run() { try { X509Certificate[] chain = KeyChain.getCertificateChain(XmppConnectionService.this, alias); - Pair info = CryptoHelper.extractJidAndName(chain[0]); + Pair info = CryptoHelper.extractJidAndName(chain[0]); if (findAccountByJid(info.first) == null) { Account account = new Account(info.first, ""); account.setPrivateKeyAlias(alias); @@ -1338,6 +1335,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa callback.informUser(R.string.account_already_exists); } } catch (Exception e) { + e.printStackTrace(); callback.informUser(R.string.unable_to_parse_certificate); } } @@ -1364,13 +1362,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } else { showErrorToastInUi(R.string.jid_does_not_match_certificate); } - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (KeyChainException e) { - e.printStackTrace(); - } catch (InvalidJidException e) { - e.printStackTrace(); - } catch (CertificateEncodingException e) { + } catch (Exception e) { e.printStackTrace(); } } @@ -1378,7 +1370,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public void updateAccount(final Account account) { this.statusListener.onStatusChanged(account); databaseBackend.updateAccount(account); - reconnectAccount(account, false, true); + reconnectAccountInBackground(account); updateAccountUi(); getNotificationService().updateErrorNotification(); } @@ -1655,7 +1647,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } } } - for(Conversation conversation : getConversations()) { + for (Conversation conversation : getConversations()) { conversation.setIncomingChatState(ChatState.ACTIVE); } this.mNotificationService.setIsInForeground(false); @@ -1666,7 +1658,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa List conversations = getConversations(); for (Conversation conversation : conversations) { if (conversation.getMode() == Conversation.MODE_MULTI && conversation.getAccount() == account) { - joinMuc(conversation,true); + joinMuc(conversation, true); } } } @@ -1791,10 +1783,14 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } public void leaveMuc(Conversation conversation) { + leaveMuc(conversation, false); + } + + private void leaveMuc(Conversation conversation, boolean now) { Account account = conversation.getAccount(); account.pendingConferenceJoins.remove(conversation); account.pendingConferenceLeaves.remove(conversation); - if (account.getStatus() == Account.State.ONLINE) { + if (account.getStatus() == Account.State.ONLINE || now) { PresencePacket packet = new PresencePacket(); packet.setTo(conversation.getJid()); packet.setFrom(conversation.getAccount().getJid()); @@ -2006,7 +2002,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa }); } - public void disconnect(Account account, boolean force) { + private void disconnect(Account account, boolean force) { if ((account.getStatus() == Account.State.ONLINE) || (account.getStatus() == Account.State.DISABLED)) { if (!force) { @@ -2014,7 +2010,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa for (Conversation conversation : conversations) { if (conversation.getAccount() == account) { if (conversation.getMode() == Conversation.MODE_MULTI) { - leaveMuc(conversation); + leaveMuc(conversation, true); } else { if (conversation.endOtrIfNeeded()) { Log.d(Config.LOGTAG, account.getJid().toBareJid() @@ -2204,13 +2200,9 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa fetchAvatar(account, avatar, null); } - private static String generateFetchKey(Account account, final Avatar avatar) { - return account.getJid().toBareJid()+"_"+avatar.owner+"_"+avatar.sha1sum; - } - public void fetchAvatar(Account account, final Avatar avatar, final UiCallback callback) { final String KEY = generateFetchKey(account, avatar); - synchronized(this.mInProgressAvatarFetches) { + synchronized (this.mInProgressAvatarFetches) { if (this.mInProgressAvatarFetches.contains(KEY)) { return; } else { @@ -2375,9 +2367,9 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa if (!account.isOptionSet(Account.OPTION_DISABLED)) { synchronized (this.mInProgressAvatarFetches) { - for(Iterator iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext();) { + for (Iterator iterator = this.mInProgressAvatarFetches.iterator(); iterator.hasNext(); ) { final String KEY = iterator.next(); - if (KEY.startsWith(account.getJid().toBareJid()+"_")) { + if (KEY.startsWith(account.getJid().toBareJid() + "_")) { iterator.remove(); } } @@ -2385,6 +2377,13 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa if (account.getXmppConnection() == null) { account.setXmppConnection(createConnection(account)); + } else if (!force) { + try { + Log.d(Config.LOGTAG, "wait for disconnect"); + Thread.sleep(500); //sleep wait for disconnect + } catch (InterruptedException e) { + //ignored + } } Thread thread = new Thread(account.getXmppConnection()); account.getXmppConnection().setInteractive(interactive); @@ -2401,20 +2400,20 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa new Thread(new Runnable() { @Override public void run() { - reconnectAccount(account,false,true); + reconnectAccount(account, false, true); } }).start(); } public void invite(Conversation conversation, Jid contact) { - Log.d(Config.LOGTAG,conversation.getAccount().getJid().toBareJid()+": inviting "+contact+" to "+conversation.getJid().toBareJid()); + Log.d(Config.LOGTAG, conversation.getAccount().getJid().toBareJid() + ": inviting " + contact + " to " + conversation.getJid().toBareJid()); MessagePacket packet = mMessageGenerator.invite(conversation, contact); sendMessagePacket(conversation.getAccount(), packet); } public void directInvite(Conversation conversation, Jid jid) { MessagePacket packet = mMessageGenerator.directInvite(conversation, jid); - sendMessagePacket(conversation.getAccount(),packet); + sendMessagePacket(conversation.getAccount(), packet); } public void resetSendingToWaiting(Account account) { @@ -2499,7 +2498,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public int unreadCount() { int count = 0; - for(Conversation conversation : getConversations()) { + for (Conversation conversation : getConversations()) { count += conversation.unreadCount(); } return count; @@ -2534,8 +2533,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa boolean rc = false; if (mOnCaptchaRequested != null) { DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics(); - Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int)(captcha.getWidth() * metrics.scaledDensity), - (int)(captcha.getHeight() * metrics.scaledDensity), false); + Bitmap scaled = Bitmap.createScaledBitmap(captcha, (int) (captcha.getWidth() * metrics.scaledDensity), + (int) (captcha.getHeight() * metrics.scaledDensity), false); mOnCaptchaRequested.onCaptchaRequested(account, id, data, scaled); rc = true; @@ -2557,7 +2556,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } public void keyStatusUpdated() { - if(mOnKeyStatusUpdated != null) { + if (mOnKeyStatusUpdated != null) { mOnKeyStatusUpdated.onKeyStatusUpdated(); } } @@ -2582,7 +2581,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public void markRead(final Conversation conversation) { mNotificationService.clear(conversation); - for(Message message : conversation.markRead()) { + for (Message message : conversation.markRead()) { databaseBackend.updateMessage(message); } updateUnreadCountBadge(); @@ -2630,7 +2629,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa final MemorizingTrustManager tm; final boolean dontTrustSystemCAs = getPreferences().getBoolean("dont_trust_system_cas", false); if (dontTrustSystemCAs) { - tm = new MemorizingTrustManager(getApplicationContext(), null); + tm = new MemorizingTrustManager(getApplicationContext(), null); } else { tm = new MemorizingTrustManager(getApplicationContext()); } @@ -2791,7 +2790,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa for (final Message msg : messages) { msg.setTime(System.currentTimeMillis()); markMessage(msg, Message.STATUS_WAITING); - this.resendMessage(msg,false); + this.resendMessage(msg, false); } } @@ -2840,6 +2839,7 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public interface OnAccountCreated { void onAccountCreated(Account account); + void informUser(int r); } @@ -2877,9 +2877,9 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public interface OnCaptchaRequested { void onCaptchaRequested(Account account, - String id, - Data data, - Bitmap captcha); + String id, + Data data, + Bitmap captcha); } public interface OnRosterUpdate { diff --git a/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java b/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java index d21682a79..f311688ec 100644 --- a/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java +++ b/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java @@ -783,7 +783,7 @@ public class XmppConnection implements Runnable { String urlString = url.findChildContent("value"); URL uri = new URL(urlString); captcha = BitmapFactory.decodeStream(uri.openConnection().getInputStream()); - } catch(IOException e) { + } catch (IOException e) { Log.e(Config.LOGTAG, e.toString()); } } @@ -884,7 +884,7 @@ public class XmppConnection implements Runnable { public void onIqPacketReceived(Account account, IqPacket packet) { if (packet.getType() == IqPacket.TYPE.RESULT) { sendPostBindInitialization(); - } else if (packet.getType() != IqPacket.TYPE.TIMEOUT){ + } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) { Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions"); disconnect(true); } @@ -1139,44 +1139,41 @@ public class XmppConnection implements Runnable { } public void disconnect(final boolean force) { - Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting"); - try { - if (force) { + Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force="+Boolean.valueOf(force)); + if (force) { + try { socket.close(); - return; + } catch(Exception e) { + Log.d(Config.LOGTAG,account.getJid().toBareJid().toString()+": exception during force close ("+e.getMessage()+")"); } - new Thread(new Runnable() { - - @Override - public void run() { - if (tagWriter.isActive()) { - tagWriter.finish(); - try { - int i = 0; - boolean warned = false; - while (!tagWriter.finished() && socket.isConnected() && i <= 10) { - if (!warned) { - Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish"); - warned = true; - } - Thread.sleep(200); - i++; - } - if (warned) { - Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished"); - } - tagWriter.writeTag(Tag.end("stream:stream")); - socket.close(); - } catch (final IOException e) { - Log.d(Config.LOGTAG,"io exception during disconnect"); - } catch (final InterruptedException e) { - Log.d(Config.LOGTAG, "interrupted"); + return; + } else { + resetStreamId(); + if (tagWriter.isActive()) { + tagWriter.finish(); + try { + int i = 0; + boolean warned = false; + while (!tagWriter.finished() && socket.isConnected() && i <= 10) { + if (!warned) { + Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish"); + warned = true; } + Thread.sleep(200); + i++; + } + if (warned) { + Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished"); } + Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closing stream"); + tagWriter.writeTag(Tag.end("stream:stream")); + socket.close(); + } catch (final IOException e) { + Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during disconnect ("+e.getMessage()+")"); + } catch (final InterruptedException e) { + Log.d(Config.LOGTAG, "interrupted"); } - }).start(); - } catch (final IOException e) { - Log.d(Config.LOGTAG, "io exception during disconnect"); + } } } -- cgit v1.2.3 From cfeb67d71da01bc95ed713d6591fa6e79fc08dd6 Mon Sep 17 00:00:00 2001 From: Daniel Gultsch Date: Fri, 16 Oct 2015 23:48:42 +0200 Subject: introduced code to verify omemo device keys with x509 certificates. cleaned up TrustKeysActivity to automatically close if there is nothing to do --- .../crypto/axolotl/AxolotlService.java | 86 +++++++++++++++++----- .../eu/siacs/conversations/entities/Account.java | 3 + .../siacs/conversations/generator/IqGenerator.java | 10 ++- .../eu/siacs/conversations/parser/IqParser.java | 29 ++++++++ .../services/XmppConnectionService.java | 9 ++- .../siacs/conversations/ui/TrustKeysActivity.java | 80 ++++++++++++-------- .../eu/siacs/conversations/utils/CryptoHelper.java | 28 ++++++- .../siacs/conversations/xmpp/XmppConnection.java | 10 ++- 8 files changed, 190 insertions(+), 65 deletions(-) (limited to 'src/main/java/eu/siacs') diff --git a/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java b/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java index 58e5a0957..ca75ec992 100644 --- a/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java +++ b/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java @@ -1,10 +1,10 @@ package eu.siacs.conversations.crypto.axolotl; import android.security.KeyChain; -import android.security.KeyChainException; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; +import android.util.Pair; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.whispersystems.libaxolotl.AxolotlAddress; @@ -20,11 +20,9 @@ import org.whispersystems.libaxolotl.state.PreKeyRecord; import org.whispersystems.libaxolotl.state.SignedPreKeyRecord; import org.whispersystems.libaxolotl.util.KeyHelper; -import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Security; import java.security.Signature; -import java.security.SignatureException; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.HashMap; @@ -43,12 +41,13 @@ import eu.siacs.conversations.parser.IqParser; import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.utils.SerialSingleThreadExecutor; import eu.siacs.conversations.xml.Element; +import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded; import eu.siacs.conversations.xmpp.OnIqPacketReceived; import eu.siacs.conversations.xmpp.jid.InvalidJidException; import eu.siacs.conversations.xmpp.jid.Jid; import eu.siacs.conversations.xmpp.stanzas.IqPacket; -public class AxolotlService { +public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl"; public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist"; @@ -71,6 +70,15 @@ public class AxolotlService { private int numPublishTriesOnEmptyPep = 0; private boolean pepBroken = false; + @Override + public void onAdvancedStreamFeaturesAvailable(Account account) { + if (account.getXmppConnection().getFeatures().pep()) { + publishBundlesIfNeeded(true, false); + } else { + Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping OMEMO initialization"); + } + } + private static class AxolotlAddressMap { protected Map> map; protected final Object MAP_LOCK = new Object(); @@ -402,7 +410,6 @@ public class AxolotlService { byte[] signature = verifier.sign(); IqPacket packet = mXmppConnectionService.getIqGenerator().publishVerification(signature, chain, getOwnDeviceId()); Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": publish verification for device "+getOwnDeviceId()); - Log.d(Config.LOGTAG,"verification : "+packet.toString()); mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() { @Override public void onIqPacketReceived(Account account, IqPacket packet) { @@ -565,6 +572,50 @@ public class AxolotlService { axolotlStore.setFingerprintTrust(fingerprint, trust); } + private void verifySessionWithPEP(final XmppAxolotlSession session, final IdentityKey identityKey) { + final AxolotlAddress address = session.getRemoteAddress(); + try { + IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId()); + mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() { + @Override + public void onIqPacketReceived(Account account, IqPacket packet) { + Pair verification = mXmppConnectionService.getIqParser().verification(packet); + if (verification != null) { + try { + Signature verifier = Signature.getInstance("sha256WithRSA"); + verifier.initVerify(verification.first[0]); + verifier.update(identityKey.serialize()); + if (verifier.verify(verification.second)) { + try { + mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA"); + Log.d(Config.LOGTAG, "verified session with x.509 signature"); + setFingerprintTrust(session.getFingerprint(), XmppAxolotlSession.Trust.TRUSTED); + } catch (Exception e) { + Log.d(Config.LOGTAG,"could not verify certificate"); + } + } + } catch (Exception e) { + Log.d(Config.LOGTAG, "error during verification " + e.getMessage()); + } + } else { + Log.d(Config.LOGTAG, " unable to parse verification"); + } + finishBuildingSessionsFromPEP(address); + } + }); + } catch (InvalidJidException e) { + finishBuildingSessionsFromPEP(address); + } + } + + private void finishBuildingSessionsFromPEP(final AxolotlAddress address) { + AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0); + if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING) + && !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) { + mXmppConnectionService.keyStatusUpdated(); + } + } + private void buildSessionFromPEP(final AxolotlAddress address) { Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.toString()); if (address.getDeviceId() == getOwnDeviceId()) { @@ -576,13 +627,6 @@ public class AxolotlService { Jid.fromString(address.getName()), address.getDeviceId()); Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket); mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() { - private void finish() { - AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0); - if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING) - && !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) { - mXmppConnectionService.keyStatusUpdated(); - } - } @Override public void onIqPacketReceived(Account account, IqPacket packet) { @@ -594,7 +638,7 @@ public class AxolotlService { if (preKeyBundleList.isEmpty() || bundle == null) { Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet); fetchStatusMap.put(address, FetchStatus.ERROR); - finish(); + finishBuildingSessionsFromPEP(address); return; } Random random = new Random(); @@ -602,7 +646,7 @@ public class AxolotlService { if (preKey == null) { //should never happen fetchStatusMap.put(address, FetchStatus.ERROR); - finish(); + finishBuildingSessionsFromPEP(address); return; } @@ -617,17 +661,21 @@ public class AxolotlService { XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", "")); sessions.put(address, session); fetchStatusMap.put(address, FetchStatus.SUCCESS); + if (Config.X509_VERIFICATION) { + verifySessionWithPEP(session, bundle.getIdentityKey()); + } else { + finishBuildingSessionsFromPEP(address); + } } catch (UntrustedIdentityException | InvalidKeyException e) { Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": " + e.getClass().getName() + ", " + e.getMessage()); fetchStatusMap.put(address, FetchStatus.ERROR); + finishBuildingSessionsFromPEP(address); } - - finish(); } else { fetchStatusMap.put(address, FetchStatus.ERROR); Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error")); - finish(); + finishBuildingSessionsFromPEP(address); } } }); @@ -699,9 +747,9 @@ public class AxolotlService { return newSessions; } - public boolean hasPendingKeyFetches(Conversation conversation) { + public boolean hasPendingKeyFetches(Account account, Contact contact) { AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0); - AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(), 0); + AxolotlAddress foreignAddress = new AxolotlAddress(contact.getJid().toBareJid().toString(), 0); return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING) || fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING); diff --git a/src/main/java/eu/siacs/conversations/entities/Account.java b/src/main/java/eu/siacs/conversations/entities/Account.java index 0eb38c9fd..ebfd98055 100644 --- a/src/main/java/eu/siacs/conversations/entities/Account.java +++ b/src/main/java/eu/siacs/conversations/entities/Account.java @@ -297,6 +297,9 @@ public class Account extends AbstractEntity { public void initAccountServices(final XmppConnectionService context) { this.mOtrService = new OtrService(context, this); this.axolotlService = new AxolotlService(this, context); + if (xmppConnection != null) { + xmppConnection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService); + } } public OtrService getOtrService() { diff --git a/src/main/java/eu/siacs/conversations/generator/IqGenerator.java b/src/main/java/eu/siacs/conversations/generator/IqGenerator.java index fb69860db..7457cad8b 100644 --- a/src/main/java/eu/siacs/conversations/generator/IqGenerator.java +++ b/src/main/java/eu/siacs/conversations/generator/IqGenerator.java @@ -137,9 +137,13 @@ public class IqGenerator extends AbstractGenerator { public IqPacket retrieveBundlesForDevice(final Jid to, final int deviceid) { final IqPacket packet = retrieve(AxolotlService.PEP_BUNDLES+":"+deviceid, null); - if(to != null) { - packet.setTo(to); - } + packet.setTo(to); + return packet; + } + + public IqPacket retrieveVerificationForDevice(final Jid to, final int deviceid) { + final IqPacket packet = retrieve(AxolotlService.PEP_VERIFICATION+":"+deviceid, null); + packet.setTo(to); return packet; } diff --git a/src/main/java/eu/siacs/conversations/parser/IqParser.java b/src/main/java/eu/siacs/conversations/parser/IqParser.java index f6446cfd1..e26a493f5 100644 --- a/src/main/java/eu/siacs/conversations/parser/IqParser.java +++ b/src/main/java/eu/siacs/conversations/parser/IqParser.java @@ -3,6 +3,7 @@ package eu.siacs.conversations.parser; import android.support.annotation.NonNull; import android.util.Base64; import android.util.Log; +import android.util.Pair; import org.whispersystems.libaxolotl.IdentityKey; import org.whispersystems.libaxolotl.InvalidKeyException; @@ -10,6 +11,10 @@ import org.whispersystems.libaxolotl.ecc.Curve; import org.whispersystems.libaxolotl.ecc.ECPublicKey; import org.whispersystems.libaxolotl.state.PreKeyBundle; +import java.io.ByteArrayInputStream; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -204,6 +209,30 @@ public class IqParser extends AbstractParser implements OnIqPacketReceived { return preKeyRecords; } + public Pair verification(final IqPacket packet) { + Element item = getItem(packet); + Element verification = item != null ? item.findChild("verification",AxolotlService.PEP_PREFIX) : null; + Element chain = verification != null ? verification.findChild("chain") : null; + Element signature = verification != null ? verification.findChild("signature") : null; + if (chain != null && signature != null) { + List certElements = chain.getChildren(); + X509Certificate[] certificates = new X509Certificate[certElements.size()]; + try { + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + int i = 0; + for(Element cert : certElements) { + certificates[i] = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.getContent(),Base64.DEFAULT))); + ++i; + } + return new Pair<>(certificates,Base64.decode(signature.getContent(),Base64.DEFAULT)); + } catch (CertificateException e) { + return null; + } + } else { + return null; + } + } + public PreKeyBundle bundle(final IqPacket bundle) { Element bundleItem = getItem(bundle); if(bundleItem == null) { diff --git a/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java b/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java index bb4a1ce96..5bfdd60fb 100644 --- a/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java +++ b/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java @@ -60,6 +60,7 @@ import de.duenndns.ssl.MemorizingTrustManager; import eu.siacs.conversations.Config; import eu.siacs.conversations.R; import eu.siacs.conversations.crypto.PgpEngine; +import eu.siacs.conversations.crypto.axolotl.AxolotlService; import eu.siacs.conversations.crypto.axolotl.XmppAxolotlMessage; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Blockable; @@ -256,7 +257,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa mMessageArchiveService.executePendingQueries(account); mJingleConnectionManager.cancelInTransmission(); syncDirtyContacts(account); - account.getAxolotlService().publishBundlesIfNeeded(true, false); } }; private OnStatusChanged statusListener = new OnStatusChanged() { @@ -459,7 +459,6 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa final String action = intent == null ? null : intent.getAction(); boolean interactive = false; if (action != null) { - Log.d(Config.LOGTAG, "action: " + action); switch (action) { case ConnectivityManager.CONNECTIVITY_ACTION: if (hasInternetConnection() && Config.RESET_ATTEMPT_COUNT_ON_NETWORK_CHANGE) { @@ -760,6 +759,10 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa connection.setOnBindListener(this.mOnBindListener); connection.setOnMessageAcknowledgeListener(this.mOnMessageAcknowledgedListener); connection.addOnAdvancedStreamFeaturesAvailableListener(this.mMessageArchiveService); + AxolotlService axolotlService = account.getAxolotlService(); + if (axolotlService != null) { + connection.addOnAdvancedStreamFeaturesAvailableListener(axolotlService); + } return connection; } @@ -1066,8 +1069,8 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa public void run() { Log.d(Config.LOGTAG, "restoring roster"); for (Account account : accounts) { - databaseBackend.readRoster(account.getRoster()); account.initAccountServices(XmppConnectionService.this); + databaseBackend.readRoster(account.getRoster()); } getBitmapCache().evictAll(); Looper.prepare(); diff --git a/src/main/java/eu/siacs/conversations/ui/TrustKeysActivity.java b/src/main/java/eu/siacs/conversations/ui/TrustKeysActivity.java index ab3130748..99ab342d6 100644 --- a/src/main/java/eu/siacs/conversations/ui/TrustKeysActivity.java +++ b/src/main/java/eu/siacs/conversations/ui/TrustKeysActivity.java @@ -8,6 +8,7 @@ import android.widget.Button; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.TextView; +import android.widget.Toast; import org.whispersystems.libaxolotl.IdentityKey; @@ -16,6 +17,7 @@ import java.util.Map; import java.util.Set; import eu.siacs.conversations.R; +import eu.siacs.conversations.crypto.axolotl.AxolotlService; import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Contact; @@ -27,11 +29,11 @@ import eu.siacs.conversations.xmpp.jid.Jid; public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdated { private Jid accountJid; private Jid contactJid; - private boolean hasOtherTrustedKeys = false; - private boolean hasPendingFetches = false; + private boolean hasNoTrustedKeys = true; private Contact contact; + private Account mAccount; private TextView keyErrorMessage; private LinearLayout keyErrorMessageCard; private TextView ownKeysTitle; @@ -50,10 +52,7 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate @Override public void onClick(View v) { commitTrusts(); - Intent data = new Intent(); - data.putExtra("choice", getIntent().getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID)); - setResult(RESULT_OK, data); - finish(); + finishOk(); } }; @@ -157,11 +156,11 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate foreignKeysTitle.setText(contactJid.toString()); foreignKeysCard.setVisibility(View.VISIBLE); } - if(hasPendingFetches) { + if(hasPendingKeyFetches()) { setFetching(); lock(); } else { - if (!hasForeignKeys && !hasOtherTrustedKeys) { + if (!hasForeignKeys && hasNoOtherTrustedKeys()) { keyErrorMessageCard.setVisibility(View.VISIBLE); keyErrorMessage.setText(R.string.error_no_keys_to_trust); ownKeys.removeAllViews(); ownKeysCard.setVisibility(View.GONE); @@ -172,12 +171,13 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate } } - private void getFingerprints(final Account account) { - Set ownKeysSet = account.getAxolotlService().getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED); - Set foreignKeysSet = account.getAxolotlService().getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, contact); + private boolean reloadFingerprints() { + AxolotlService service = this.mAccount.getAxolotlService(); + Set ownKeysSet = service.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED); + Set foreignKeysSet = service.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, contact); if (hasNoTrustedKeys) { - ownKeysSet.addAll(account.getAxolotlService().getKeysWithTrust(XmppAxolotlSession.Trust.UNTRUSTED)); - foreignKeysSet.addAll(account.getAxolotlService().getKeysWithTrust(XmppAxolotlSession.Trust.UNTRUSTED, contact)); + ownKeysSet.addAll(service.getKeysWithTrust(XmppAxolotlSession.Trust.UNTRUSTED)); + foreignKeysSet.addAll(service.getKeysWithTrust(XmppAxolotlSession.Trust.UNTRUSTED, contact)); } for(final IdentityKey identityKey : ownKeysSet) { if(!ownKeysToTrust.containsKey(identityKey)) { @@ -189,39 +189,55 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate foreignKeysToTrust.put(identityKey.getFingerprint().replaceAll("\\s", ""), false); } } + return ownKeysSet.size() + foreignKeysSet.size() > 0; } @Override public void onBackendConnected() { if ((accountJid != null) && (contactJid != null)) { - final Account account = xmppConnectionService - .findAccountByJid(accountJid); - if (account == null) { + this.mAccount = xmppConnectionService.findAccountByJid(accountJid); + if (this.mAccount == null) { return; } - this.contact = account.getRoster().getContact(contactJid); + this.contact = this.mAccount.getRoster().getContact(contactJid); ownKeysToTrust.clear(); foreignKeysToTrust.clear(); - getFingerprints(account); - - if(account.getAxolotlService().getNumTrustedKeys(contact) > 0) { - hasOtherTrustedKeys = true; - } - Conversation conversation = xmppConnectionService.findOrCreateConversation(account, contactJid, false); - if(account.getAxolotlService().hasPendingKeyFetches(conversation)) { - hasPendingFetches = true; - } - + reloadFingerprints(); populateView(); } } + private boolean hasNoOtherTrustedKeys() { + return mAccount == null || mAccount.getAxolotlService().getNumTrustedKeys(contact) == 0; + } + + private boolean hasPendingKeyFetches() { + return mAccount != null && contact != null && mAccount.getAxolotlService().hasPendingKeyFetches(mAccount,contact); + } + + @Override public void onKeyStatusUpdated() { - final Account account = xmppConnectionService.findAccountByJid(accountJid); - hasPendingFetches = false; - getFingerprints(account); - refreshUi(); + boolean keysToTrust = reloadFingerprints(); + if (keysToTrust || hasPendingKeyFetches() || hasNoOtherTrustedKeys()) { + refreshUi(); + } else { + runOnUiThread(new Runnable() { + @Override + public void run() { + Toast.makeText(TrustKeysActivity.this, "Nothing to do", Toast.LENGTH_SHORT).show(); + finishOk(); + } + }); + + } + } + + private void finishOk() { + Intent data = new Intent(); + data.putExtra("choice", getIntent().getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID)); + setResult(RESULT_OK, data); + finish(); } private void commitTrusts() { @@ -248,7 +264,7 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate } private void lockOrUnlockAsNeeded() { - if (!hasOtherTrustedKeys && !foreignKeysToTrust.values().contains(true)){ + if (hasNoOtherTrustedKeys() && !foreignKeysToTrust.values().contains(true)){ lock(); } else { unlock(); diff --git a/src/main/java/eu/siacs/conversations/utils/CryptoHelper.java b/src/main/java/eu/siacs/conversations/utils/CryptoHelper.java index e9ad71971..8091a9966 100644 --- a/src/main/java/eu/siacs/conversations/utils/CryptoHelper.java +++ b/src/main/java/eu/siacs/conversations/utils/CryptoHelper.java @@ -1,16 +1,21 @@ package eu.siacs.conversations.utils; +import android.util.Log; import android.util.Pair; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.asn1.x500.style.IETFUtils; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; +import org.bouncycastle.jce.PrincipalUtil; import java.security.SecureRandom; import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; +import java.security.cert.X509Extension; import java.text.Normalizer; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; @@ -137,11 +142,26 @@ public final class CryptoHelper { } } - public static Pair extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, InvalidJidException { + public static Pair extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, InvalidJidException, CertificateParsingException { + Collection> alternativeNames = certificate.getSubjectAlternativeNames(); + List emails = new ArrayList<>(); + if (alternativeNames != null) { + for(List san : alternativeNames) { + Integer type = (Integer) san.get(0); + if (type == 1) { + emails.add((String) san.get(1)); + } + } + } X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject(); - //String xmpp = IETFUtils.valueToString(x500name.getRDNs(new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"))[0].getFirst().getValue()); - String email = IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue()); + if (emails.size() == 0) { + emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue())); + } String name = IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()); - return new Pair<>(Jid.fromString(email),name); + if (emails.size() >= 1) { + return new Pair<>(Jid.fromString(emails.get(0)), name); + } else { + return null; + } } } diff --git a/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java b/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java index f311688ec..186672488 100644 --- a/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java +++ b/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java @@ -947,11 +947,10 @@ public class XmppConnection implements Runnable { } } disco.put(jid, info); - if (account.getServer().equals(jid)) { + if ((jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid())) + && disco.containsKey(account.getServer()) + && disco.containsKey(account.getJid().toBareJid())) { enableAdvancedStreamFeatures(); - for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) { - listener.onAdvancedStreamFeaturesAvailable(account); - } } } else { Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco info for "+jid.toString()); @@ -969,6 +968,9 @@ public class XmppConnection implements Runnable { Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list"); this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser()); } + for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) { + listener.onAdvancedStreamFeaturesAvailable(account); + } } private void sendServiceDiscoveryItems(final Jid server) { -- cgit v1.2.3 From a83aae341fc681edc43928af1e37d4bb67e733d8 Mon Sep 17 00:00:00 2001 From: Daniel Gultsch Date: Sat, 17 Oct 2015 14:09:26 +0200 Subject: improved error reporting in trust keys activity --- .../crypto/axolotl/AxolotlService.java | 26 ++++++++++++++----- .../services/XmppConnectionService.java | 4 +-- .../conversations/ui/ContactDetailsActivity.java | 3 ++- .../conversations/ui/EditAccountActivity.java | 2 +- .../siacs/conversations/ui/TrustKeysActivity.java | 30 ++++++++++++++-------- .../conversations/xmpp/OnKeyStatusUpdated.java | 4 ++- 6 files changed, 47 insertions(+), 22 deletions(-) (limited to 'src/main/java/eu/siacs') diff --git a/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java b/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java index ca75ec992..d539e0787 100644 --- a/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java +++ b/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java @@ -175,9 +175,10 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { } } - private enum FetchStatus { + public enum FetchStatus { PENDING, SUCCESS, + SUCCESS_VERIFIED, ERROR } @@ -321,7 +322,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED, XmppAxolotlSession.Trust.UNTRUSTED); this.deviceIds.put(jid, deviceIds); - mXmppConnectionService.keyStatusUpdated(); + mXmppConnectionService.keyStatusUpdated(null); } public void wipeOtherPepDevices() { @@ -588,8 +589,11 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { if (verifier.verify(verification.second)) { try { mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA"); - Log.d(Config.LOGTAG, "verified session with x.509 signature"); + Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: "+session.getFingerprint()); setFingerprintTrust(session.getFingerprint(), XmppAxolotlSession.Trust.TRUSTED); + fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED); + finishBuildingSessionsFromPEP(address); + return; } catch (Exception e) { Log.d(Config.LOGTAG,"could not verify certificate"); } @@ -597,13 +601,13 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { } catch (Exception e) { Log.d(Config.LOGTAG, "error during verification " + e.getMessage()); } - } else { - Log.d(Config.LOGTAG, " unable to parse verification"); } + fetchStatusMap.put(address, FetchStatus.SUCCESS); finishBuildingSessionsFromPEP(address); } }); } catch (InvalidJidException e) { + fetchStatusMap.put(address, FetchStatus.SUCCESS); finishBuildingSessionsFromPEP(address); } } @@ -612,7 +616,15 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0); if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING) && !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) { - mXmppConnectionService.keyStatusUpdated(); + FetchStatus report = null; + if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.SUCCESS_VERIFIED) + | fetchStatusMap.getAll(address).containsValue(FetchStatus.SUCCESS_VERIFIED)) { + report = FetchStatus.SUCCESS_VERIFIED; + } else if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.ERROR) + || fetchStatusMap.getAll(address).containsValue(FetchStatus.ERROR)) { + report = FetchStatus.ERROR; + } + mXmppConnectionService.keyStatusUpdated(report); } } @@ -660,10 +672,10 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { builder.process(preKeyBundle); XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", "")); sessions.put(address, session); - fetchStatusMap.put(address, FetchStatus.SUCCESS); if (Config.X509_VERIFICATION) { verifySessionWithPEP(session, bundle.getIdentityKey()); } else { + fetchStatusMap.put(address, FetchStatus.SUCCESS); finishBuildingSessionsFromPEP(address); } } catch (UntrustedIdentityException | InvalidKeyException e) { diff --git a/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java b/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java index 5bfdd60fb..d9ae6a921 100644 --- a/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java +++ b/src/main/java/eu/siacs/conversations/services/XmppConnectionService.java @@ -2558,9 +2558,9 @@ public class XmppConnectionService extends Service implements OnPhoneContactsLoa } } - public void keyStatusUpdated() { + public void keyStatusUpdated(AxolotlService.FetchStatus report) { if (mOnKeyStatusUpdated != null) { - mOnKeyStatusUpdated.onKeyStatusUpdated(); + mOnKeyStatusUpdated.onKeyStatusUpdated(report); } } diff --git a/src/main/java/eu/siacs/conversations/ui/ContactDetailsActivity.java b/src/main/java/eu/siacs/conversations/ui/ContactDetailsActivity.java index c21be8993..10bdaab16 100644 --- a/src/main/java/eu/siacs/conversations/ui/ContactDetailsActivity.java +++ b/src/main/java/eu/siacs/conversations/ui/ContactDetailsActivity.java @@ -35,6 +35,7 @@ import java.util.List; import eu.siacs.conversations.Config; import eu.siacs.conversations.R; import eu.siacs.conversations.crypto.PgpEngine; +import eu.siacs.conversations.crypto.axolotl.AxolotlService; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Contact; import eu.siacs.conversations.entities.ListItem; @@ -479,7 +480,7 @@ public class ContactDetailsActivity extends XmppActivity implements OnAccountUpd } @Override - public void onKeyStatusUpdated() { + public void onKeyStatusUpdated(AxolotlService.FetchStatus report) { refreshUi(); } } diff --git a/src/main/java/eu/siacs/conversations/ui/EditAccountActivity.java b/src/main/java/eu/siacs/conversations/ui/EditAccountActivity.java index d962c57ea..d58f0fc29 100644 --- a/src/main/java/eu/siacs/conversations/ui/EditAccountActivity.java +++ b/src/main/java/eu/siacs/conversations/ui/EditAccountActivity.java @@ -708,7 +708,7 @@ public class EditAccountActivity extends XmppActivity implements OnAccountUpdate } @Override - public void onKeyStatusUpdated() { + public void onKeyStatusUpdated(AxolotlService.FetchStatus report) { refreshUi(); } diff --git a/src/main/java/eu/siacs/conversations/ui/TrustKeysActivity.java b/src/main/java/eu/siacs/conversations/ui/TrustKeysActivity.java index 99ab342d6..4bd0d42da 100644 --- a/src/main/java/eu/siacs/conversations/ui/TrustKeysActivity.java +++ b/src/main/java/eu/siacs/conversations/ui/TrustKeysActivity.java @@ -21,7 +21,6 @@ import eu.siacs.conversations.crypto.axolotl.AxolotlService; import eu.siacs.conversations.crypto.axolotl.XmppAxolotlSession; import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Contact; -import eu.siacs.conversations.entities.Conversation; import eu.siacs.conversations.xmpp.OnKeyStatusUpdated; import eu.siacs.conversations.xmpp.jid.InvalidJidException; import eu.siacs.conversations.xmpp.jid.Jid; @@ -30,8 +29,6 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate private Jid accountJid; private Jid contactJid; - private boolean hasNoTrustedKeys = true; - private Contact contact; private Account mAccount; private TextView keyErrorMessage; @@ -91,7 +88,6 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate this.contactJid = Jid.fromString(getIntent().getExtras().getString("contact")); } catch (final InvalidJidException ignored) { } - hasNoTrustedKeys = getIntent().getBooleanExtra("has_no_trusted", false); keyErrorMessageCard = (LinearLayout) findViewById(R.id.key_error_message_card); keyErrorMessage = (TextView) findViewById(R.id.key_error_message); @@ -172,11 +168,12 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate } private boolean reloadFingerprints() { + ownKeysToTrust.clear(); + foreignKeysToTrust.clear(); AxolotlService service = this.mAccount.getAxolotlService(); Set ownKeysSet = service.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED); Set foreignKeysSet = service.getKeysWithTrust(XmppAxolotlSession.Trust.UNDECIDED, contact); - if (hasNoTrustedKeys) { - ownKeysSet.addAll(service.getKeysWithTrust(XmppAxolotlSession.Trust.UNTRUSTED)); + if (hasNoOtherTrustedKeys() && ownKeysSet.size() == 0) { foreignKeysSet.addAll(service.getKeysWithTrust(XmppAxolotlSession.Trust.UNTRUSTED, contact)); } for(final IdentityKey identityKey : ownKeysSet) { @@ -200,8 +197,6 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate return; } this.contact = this.mAccount.getRoster().getContact(contactJid); - ownKeysToTrust.clear(); - foreignKeysToTrust.clear(); reloadFingerprints(); populateView(); } @@ -217,7 +212,23 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate @Override - public void onKeyStatusUpdated() { + public void onKeyStatusUpdated(final AxolotlService.FetchStatus report) { + if (report != null) { + runOnUiThread(new Runnable() { + @Override + public void run() { + switch (report) { + case ERROR: + Toast.makeText(TrustKeysActivity.this,R.string.error_fetching_omemo_key,Toast.LENGTH_SHORT).show(); + break; + case SUCCESS_VERIFIED: + Toast.makeText(TrustKeysActivity.this,R.string.verified_omemo_key_with_certificate,Toast.LENGTH_LONG).show(); + break; + } + } + }); + + } boolean keysToTrust = reloadFingerprints(); if (keysToTrust || hasPendingKeyFetches() || hasNoOtherTrustedKeys()) { refreshUi(); @@ -225,7 +236,6 @@ public class TrustKeysActivity extends XmppActivity implements OnKeyStatusUpdate runOnUiThread(new Runnable() { @Override public void run() { - Toast.makeText(TrustKeysActivity.this, "Nothing to do", Toast.LENGTH_SHORT).show(); finishOk(); } }); diff --git a/src/main/java/eu/siacs/conversations/xmpp/OnKeyStatusUpdated.java b/src/main/java/eu/siacs/conversations/xmpp/OnKeyStatusUpdated.java index 65ae133d5..e7fc582e4 100644 --- a/src/main/java/eu/siacs/conversations/xmpp/OnKeyStatusUpdated.java +++ b/src/main/java/eu/siacs/conversations/xmpp/OnKeyStatusUpdated.java @@ -1,5 +1,7 @@ package eu.siacs.conversations.xmpp; +import eu.siacs.conversations.crypto.axolotl.AxolotlService; + public interface OnKeyStatusUpdated { - public void onKeyStatusUpdated(); + public void onKeyStatusUpdated(AxolotlService.FetchStatus report); } -- cgit v1.2.3 From e9e31b1c9bb8c0e1e78207b843c5799b98f06cdd Mon Sep 17 00:00:00 2001 From: Daniel Gultsch Date: Sat, 17 Oct 2015 14:44:59 +0200 Subject: load axolotl session cache on first device update --- .../eu/siacs/conversations/crypto/axolotl/AxolotlService.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src/main/java/eu/siacs') diff --git a/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java b/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java index d539e0787..753de5a6d 100644 --- a/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java +++ b/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java @@ -322,6 +322,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED, XmppAxolotlSession.Trust.UNTRUSTED); this.deviceIds.put(jid, deviceIds); + findDevicesWithoutSession(jid); mXmppConnectionService.keyStatusUpdated(null); } @@ -697,8 +698,11 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { } public Set findDevicesWithoutSession(final Conversation conversation) { - Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + conversation.getContact().getJid().toBareJid()); - Jid contactJid = conversation.getContact().getJid().toBareJid(); + return findDevicesWithoutSession(conversation.getContact().getJid().toBareJid()); + } + + public Set findDevicesWithoutSession(final Jid contactJid) { + Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + contactJid); Set addresses = new HashSet<>(); if (deviceIds.get(contactJid) != null) { for (Integer foreignId : this.deviceIds.get(contactJid)) { -- cgit v1.2.3 From 0f405c2e112ebd5dbb6be535bbadd1c4a109d341 Mon Sep 17 00:00:00 2001 From: Daniel Gultsch Date: Sat, 17 Oct 2015 15:23:46 +0200 Subject: allow redownloading files from remote hosts. fixes #1504 --- .../eu/siacs/conversations/http/HttpDownloadConnection.java | 13 +++++++++++-- .../eu/siacs/conversations/ui/ConversationFragment.java | 3 ++- 2 files changed, 13 insertions(+), 3 deletions(-) (limited to 'src/main/java/eu/siacs') diff --git a/src/main/java/eu/siacs/conversations/http/HttpDownloadConnection.java b/src/main/java/eu/siacs/conversations/http/HttpDownloadConnection.java index 5fa7bf816..792a71e8b 100644 --- a/src/main/java/eu/siacs/conversations/http/HttpDownloadConnection.java +++ b/src/main/java/eu/siacs/conversations/http/HttpDownloadConnection.java @@ -22,6 +22,7 @@ import eu.siacs.conversations.R; import eu.siacs.conversations.entities.DownloadableFile; import eu.siacs.conversations.entities.Message; import eu.siacs.conversations.entities.Transferable; +import eu.siacs.conversations.entities.TransferablePlaceholder; import eu.siacs.conversations.persistance.FileBackend; import eu.siacs.conversations.services.AbstractConnectionManager; import eu.siacs.conversations.services.XmppConnectionService; @@ -66,7 +67,11 @@ public class HttpDownloadConnection implements Transferable { this.message = message; this.message.setTransferable(this); try { - mUrl = new URL(message.getBody()); + if (message.hasFileOnRemoteHost()) { + mUrl = message.getFileParams().url; + } else { + mUrl = new URL(message.getBody()); + } String[] parts = mUrl.getPath().toLowerCase().split("\\."); String lastPart = parts.length >= 1 ? parts[parts.length - 1] : null; String secondToLast = parts.length >= 2 ? parts[parts.length -2] : null; @@ -106,7 +111,11 @@ public class HttpDownloadConnection implements Transferable { public void cancel() { mHttpConnectionManager.finishConnection(this); - message.setTransferable(null); + if (message.isFileOrImage()) { + message.setTransferable(new TransferablePlaceholder(Transferable.STATUS_DELETED)); + } else { + message.setTransferable(null); + } mXmppConnectionService.updateConversationUi(); } diff --git a/src/main/java/eu/siacs/conversations/ui/ConversationFragment.java b/src/main/java/eu/siacs/conversations/ui/ConversationFragment.java index 64101539b..b8a1a7a88 100644 --- a/src/main/java/eu/siacs/conversations/ui/ConversationFragment.java +++ b/src/main/java/eu/siacs/conversations/ui/ConversationFragment.java @@ -489,7 +489,8 @@ public class ConversationFragment extends Fragment implements EditMessage.Keyboa || m.treatAsDownloadable() == Message.Decision.MUST) { copyUrl.setVisible(true); } - if (m.getType() == Message.TYPE_TEXT && m.getTransferable() == null && m.treatAsDownloadable() != Message.Decision.NEVER) { + if ((m.getType() == Message.TYPE_TEXT && m.getTransferable() == null && m.treatAsDownloadable() != Message.Decision.NEVER) + || (m.isFileOrImage() && m.getTransferable() instanceof TransferablePlaceholder && m.hasFileOnRemoteHost())){ downloadFile.setVisible(true); downloadFile.setTitle(activity.getString(R.string.download_x_file,UIHelper.getFileDescriptionString(activity, m))); } -- cgit v1.2.3 From 3c6c424d31be3e21d1bebd6288646f1cbc6881d9 Mon Sep 17 00:00:00 2001 From: Daniel Gultsch Date: Sat, 17 Oct 2015 15:51:21 +0200 Subject: don't retry building broken omemo keys --- .../conversations/crypto/axolotl/AxolotlService.java | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) (limited to 'src/main/java/eu/siacs') diff --git a/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java b/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java index 753de5a6d..ab3aefac0 100644 --- a/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java +++ b/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java @@ -179,6 +179,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { PENDING, SUCCESS, SUCCESS_VERIFIED, + TIMEOUT, ERROR } @@ -643,7 +644,9 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { @Override public void onIqPacketReceived(Account account, IqPacket packet) { - if (packet.getType() == IqPacket.TYPE.RESULT) { + if (packet.getType() == IqPacket.TYPE.TIMEOUT) { + fetchStatusMap.put(address, FetchStatus.TIMEOUT); + } else if (packet.getType() == IqPacket.TYPE.RESULT) { Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing..."); final IqParser parser = mXmppConnectionService.getIqParser(); final List preKeyBundleList = parser.preKeys(packet); @@ -715,7 +718,11 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { sessions.put(address, session); } else { Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId); - addresses.add(new AxolotlAddress(contactJid.toString(), foreignId)); + if (fetchStatusMap.get(address) != FetchStatus.ERROR) { + addresses.add(address); + } else { + Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken"); + } } } } @@ -733,7 +740,11 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { sessions.put(address, session); } else { Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId); - addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId)); + if (fetchStatusMap.get(address) != FetchStatus.ERROR) { + addresses.add(address); + } else { + Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken"); + } } } } @@ -749,7 +760,7 @@ public class AxolotlService implements OnAdvancedStreamFeaturesLoaded { for (AxolotlAddress address : addresses) { Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString()); FetchStatus status = fetchStatusMap.get(address); - if (status == null || status == FetchStatus.ERROR) { + if (status == null || status == FetchStatus.TIMEOUT) { fetchStatusMap.put(address, FetchStatus.PENDING); this.buildSessionFromPEP(address); newSessions = true; -- cgit v1.2.3