1package eu.siacs.conversations.ui;
2
3import android.app.ActionBar;
4import android.content.Intent;
5import android.os.Bundle;
6import android.util.Log;
7import android.view.Gravity;
8import android.view.Menu;
9import android.view.MenuItem;
10import android.view.View;
11import android.view.View.OnClickListener;
12import android.widget.Button;
13import android.widget.CompoundButton;
14import android.widget.LinearLayout;
15import android.widget.TextView;
16import android.widget.Toast;
17
18import com.google.zxing.integration.android.IntentIntegrator;
19import com.google.zxing.integration.android.IntentResult;
20
21import org.whispersystems.libaxolotl.IdentityKey;
22
23import java.util.ArrayList;
24import java.util.HashMap;
25import java.util.List;
26import java.util.Map;
27import java.util.Set;
28
29import eu.siacs.conversations.Config;
30import eu.siacs.conversations.OmemoActivity;
31import eu.siacs.conversations.R;
32import eu.siacs.conversations.crypto.axolotl.AxolotlService;
33import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
34import eu.siacs.conversations.entities.Account;
35import eu.siacs.conversations.entities.Conversation;
36import eu.siacs.conversations.utils.XmppUri;
37import eu.siacs.conversations.xmpp.OnKeyStatusUpdated;
38import eu.siacs.conversations.xmpp.jid.InvalidJidException;
39import eu.siacs.conversations.xmpp.jid.Jid;
40
41public class TrustKeysActivity extends OmemoActivity implements OnKeyStatusUpdated {
42 private List<Jid> contactJids;
43
44 private Account mAccount;
45 private Conversation mConversation;
46 private TextView keyErrorMessage;
47 private LinearLayout keyErrorMessageCard;
48 private TextView ownKeysTitle;
49 private LinearLayout ownKeys;
50 private LinearLayout ownKeysCard;
51 private LinearLayout foreignKeys;
52 private Button mSaveButton;
53 private Button mCancelButton;
54
55 private AxolotlService.FetchStatus lastFetchReport = AxolotlService.FetchStatus.SUCCESS;
56
57 private final Map<String, Boolean> ownKeysToTrust = new HashMap<>();
58 private final Map<Jid,Map<String, Boolean>> foreignKeysToTrust = new HashMap<>();
59
60 private final OnClickListener mSaveButtonListener = new OnClickListener() {
61 @Override
62 public void onClick(View v) {
63 commitTrusts();
64 finishOk();
65 }
66 };
67
68 private final OnClickListener mCancelButtonListener = new OnClickListener() {
69 @Override
70 public void onClick(View v) {
71 setResult(RESULT_CANCELED);
72 finish();
73 }
74 };
75 private XmppUri mPendingFingerprintVerificationUri = null;
76 private Toast mUseCameraHintToast = null;
77
78 @Override
79 protected void refreshUiReal() {
80 invalidateOptionsMenu();
81 populateView();
82 }
83
84 @Override
85 protected void onCreate(final Bundle savedInstanceState) {
86 super.onCreate(savedInstanceState);
87 setContentView(R.layout.activity_trust_keys);
88 this.contactJids = new ArrayList<>();
89 for(String jid : getIntent().getStringArrayExtra("contacts")) {
90 try {
91 this.contactJids.add(Jid.fromString(jid));
92 } catch (InvalidJidException e) {
93 e.printStackTrace();
94 }
95 }
96
97 keyErrorMessageCard = (LinearLayout) findViewById(R.id.key_error_message_card);
98 keyErrorMessage = (TextView) findViewById(R.id.key_error_message);
99 ownKeysTitle = (TextView) findViewById(R.id.own_keys_title);
100 ownKeys = (LinearLayout) findViewById(R.id.own_keys_details);
101 ownKeysCard = (LinearLayout) findViewById(R.id.own_keys_card);
102 foreignKeys = (LinearLayout) findViewById(R.id.foreign_keys);
103 mCancelButton = (Button) findViewById(R.id.cancel_button);
104 mCancelButton.setOnClickListener(mCancelButtonListener);
105 mSaveButton = (Button) findViewById(R.id.save_button);
106 mSaveButton.setOnClickListener(mSaveButtonListener);
107
108
109 if (getActionBar() != null) {
110 getActionBar().setHomeButtonEnabled(true);
111 getActionBar().setDisplayHomeAsUpEnabled(true);
112 }
113 }
114
115 @Override
116 public boolean onCreateOptionsMenu(Menu menu) {
117 getMenuInflater().inflate(R.menu.trust_keys, menu);
118 mUseCameraHintToast = Toast.makeText(this,R.string.use_camera_icon_to_scan_barcode,Toast.LENGTH_LONG);
119 ActionBar actionBar = getActionBar();
120 mUseCameraHintToast.setGravity(Gravity.TOP | Gravity.END, 0 ,actionBar == null ? 0 : actionBar.getHeight());
121 mUseCameraHintToast.show();
122 return super.onCreateOptionsMenu(menu);
123 }
124
125 @Override
126 public boolean onOptionsItemSelected(MenuItem item) {
127 switch (item.getItemId()) {
128 case R.id.action_scan_qr_code:
129 if (hasPendingKeyFetches()) {
130 Toast.makeText(this, R.string.please_wait_for_keys_to_be_fetched, Toast.LENGTH_SHORT).show();
131 } else {
132 new IntentIntegrator(this).initiateScan();
133 return true;
134 }
135 }
136 return super.onOptionsItemSelected(item);
137 }
138
139 @Override
140 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
141 IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
142 if (scanResult != null && scanResult.getFormatName() != null) {
143 String data = scanResult.getContents();
144 XmppUri uri = new XmppUri(data);
145 if (xmppConnectionServiceBound) {
146 processFingerprintVerification(uri);
147 populateView();
148 } else {
149 this.mPendingFingerprintVerificationUri =uri;
150 }
151 }
152 }
153
154 private void processFingerprintVerification(XmppUri uri) {
155 if (mConversation != null
156 && mAccount != null
157 && uri.hasFingerprints()
158 && mAccount.getAxolotlService().getCryptoTargets(mConversation).contains(uri.getJid())) {
159 boolean performedVerification = xmppConnectionService.verifyFingerprints(mAccount.getRoster().getContact(uri.getJid()),uri.getFingerprints());
160 boolean keys = reloadFingerprints();
161 if (performedVerification && !keys && !hasNoOtherTrustedKeys() && !hasPendingKeyFetches()) {
162 Toast.makeText(this,R.string.all_omemo_keys_have_been_verified, Toast.LENGTH_SHORT).show();
163 finishOk();
164 } else if (performedVerification) {
165 Toast.makeText(this,R.string.verified_fingerprints,Toast.LENGTH_SHORT).show();
166 }
167 } else {
168 Log.d(Config.LOGTAG,"xmpp uri was: "+uri.getJid()+" has Fingerprints: "+Boolean.toString(uri.hasFingerprints()));
169 Toast.makeText(this,R.string.barcode_does_not_contain_fingerprints_for_this_conversation,Toast.LENGTH_SHORT).show();
170 }
171 }
172
173 private void populateView() {
174 setTitle(getString(R.string.trust_omemo_fingerprints));
175 ownKeys.removeAllViews();
176 foreignKeys.removeAllViews();
177 boolean hasOwnKeys = false;
178 boolean hasForeignKeys = false;
179 for(final String fingerprint : ownKeysToTrust.keySet()) {
180 hasOwnKeys = true;
181 addFingerprintRowWithListeners(ownKeys, mAccount, fingerprint, false,
182 FingerprintStatus.createActive(ownKeysToTrust.get(fingerprint)), false, false,
183 new CompoundButton.OnCheckedChangeListener() {
184 @Override
185 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
186 ownKeysToTrust.put(fingerprint, isChecked);
187 // own fingerprints have no impact on locked status.
188 }
189 }
190 );
191 }
192
193 synchronized (this.foreignKeysToTrust) {
194 for (Map.Entry<Jid, Map<String, Boolean>> entry : foreignKeysToTrust.entrySet()) {
195 hasForeignKeys = true;
196 final LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.keys_card, foreignKeys, false);
197 final Jid jid = entry.getKey();
198 final TextView header = (TextView) layout.findViewById(R.id.foreign_keys_title);
199 final LinearLayout keysContainer = (LinearLayout) layout.findViewById(R.id.foreign_keys_details);
200 final TextView informNoKeys = (TextView) layout.findViewById(R.id.no_keys_to_accept);
201 header.setText(jid.toString());
202 final Map<String, Boolean> fingerprints = entry.getValue();
203 for (final String fingerprint : fingerprints.keySet()) {
204 addFingerprintRowWithListeners(keysContainer, mAccount, fingerprint, false,
205 FingerprintStatus.createActive(fingerprints.get(fingerprint)), false, false,
206 new CompoundButton.OnCheckedChangeListener() {
207 @Override
208 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
209 fingerprints.put(fingerprint, isChecked);
210 lockOrUnlockAsNeeded();
211 }
212 }
213 );
214 }
215 if (fingerprints.size() == 0) {
216 informNoKeys.setVisibility(View.VISIBLE);
217 informNoKeys.setText(getString(R.string.no_keys_just_confirm,mAccount.getRoster().getContact(jid).getDisplayName()));
218 } else {
219 informNoKeys.setVisibility(View.GONE);
220 }
221 foreignKeys.addView(layout);
222 }
223 }
224
225 ownKeysTitle.setText(mAccount.getJid().toBareJid().toString());
226 ownKeysCard.setVisibility(hasOwnKeys ? View.VISIBLE : View.GONE);
227 foreignKeys.setVisibility(hasForeignKeys ? View.VISIBLE : View.GONE);
228 if(hasPendingKeyFetches()) {
229 setFetching();
230 lock();
231 } else {
232 if (!hasForeignKeys && hasNoOtherTrustedKeys()) {
233 keyErrorMessageCard.setVisibility(View.VISIBLE);
234 if (lastFetchReport == AxolotlService.FetchStatus.ERROR
235 || mAccount.getAxolotlService().fetchMapHasErrors(contactJids)) {
236 keyErrorMessage.setText(R.string.error_no_keys_to_trust_server_error);
237 } else {
238 keyErrorMessage.setText(R.string.error_no_keys_to_trust);
239 }
240 ownKeys.removeAllViews();
241 ownKeysCard.setVisibility(View.GONE);
242 foreignKeys.removeAllViews();
243 foreignKeys.setVisibility(View.GONE);
244 }
245 lockOrUnlockAsNeeded();
246 setDone();
247 }
248 }
249
250 private boolean reloadFingerprints() {
251 List<Jid> acceptedTargets = mConversation == null ? new ArrayList<Jid>() : mConversation.getAcceptedCryptoTargets();
252 ownKeysToTrust.clear();
253 AxolotlService service = this.mAccount.getAxolotlService();
254 Set<IdentityKey> ownKeysSet = service.getKeysWithTrust(FingerprintStatus.createActiveUndecided());
255 for(final IdentityKey identityKey : ownKeysSet) {
256 if(!ownKeysToTrust.containsKey(identityKey)) {
257 ownKeysToTrust.put(identityKey.getFingerprint().replaceAll("\\s", ""), false);
258 }
259 }
260 synchronized (this.foreignKeysToTrust) {
261 foreignKeysToTrust.clear();
262 for (Jid jid : contactJids) {
263 Set<IdentityKey> foreignKeysSet = service.getKeysWithTrust(FingerprintStatus.createActiveUndecided(), jid);
264 if (hasNoOtherTrustedKeys(jid) && ownKeysSet.size() == 0) {
265 foreignKeysSet.addAll(service.getKeysWithTrust(FingerprintStatus.createActive(false), jid));
266 }
267 Map<String, Boolean> foreignFingerprints = new HashMap<>();
268 for (final IdentityKey identityKey : foreignKeysSet) {
269 if (!foreignFingerprints.containsKey(identityKey)) {
270 foreignFingerprints.put(identityKey.getFingerprint().replaceAll("\\s", ""), false);
271 }
272 }
273 if (foreignFingerprints.size() > 0 || !acceptedTargets.contains(jid)) {
274 foreignKeysToTrust.put(jid, foreignFingerprints);
275 }
276 }
277 }
278 return ownKeysSet.size() + foreignKeysToTrust.size() > 0;
279 }
280
281 public void onBackendConnected() {
282 Intent intent = getIntent();
283 this.mAccount = extractAccount(intent);
284 if (this.mAccount != null && intent != null) {
285 String uuid = intent.getStringExtra("conversation");
286 this.mConversation = xmppConnectionService.findConversationByUuid(uuid);
287 if (this.mPendingFingerprintVerificationUri != null) {
288 processFingerprintVerification(this.mPendingFingerprintVerificationUri);
289 this.mPendingFingerprintVerificationUri = null;
290 }
291 reloadFingerprints();
292 populateView();
293 }
294 }
295
296 private boolean hasNoOtherTrustedKeys() {
297 return mAccount == null || mAccount.getAxolotlService().anyTargetHasNoTrustedKeys(contactJids);
298 }
299
300 private boolean hasNoOtherTrustedKeys(Jid contact) {
301 return mAccount == null || mAccount.getAxolotlService().getNumTrustedKeys(contact) == 0;
302 }
303
304 private boolean hasPendingKeyFetches() {
305 return mAccount != null && mAccount.getAxolotlService().hasPendingKeyFetches(mAccount, contactJids);
306 }
307
308
309 @Override
310 public void onKeyStatusUpdated(final AxolotlService.FetchStatus report) {
311 final boolean keysToTrust = reloadFingerprints();
312 if (report != null) {
313 lastFetchReport = report;
314 runOnUiThread(new Runnable() {
315 @Override
316 public void run() {
317 if (mUseCameraHintToast != null && !keysToTrust) {
318 mUseCameraHintToast.cancel();
319 }
320 switch (report) {
321 case ERROR:
322 Toast.makeText(TrustKeysActivity.this,R.string.error_fetching_omemo_key,Toast.LENGTH_SHORT).show();
323 break;
324 case SUCCESS_TRUSTED:
325 Toast.makeText(TrustKeysActivity.this,R.string.blindly_trusted_omemo_keys,Toast.LENGTH_LONG).show();
326 break;
327 case SUCCESS_VERIFIED:
328 Toast.makeText(TrustKeysActivity.this,
329 Config.X509_VERIFICATION ? R.string.verified_omemo_key_with_certificate : R.string.all_omemo_keys_have_been_verified,
330 Toast.LENGTH_LONG).show();
331 break;
332 }
333 }
334 });
335
336 }
337 if (keysToTrust || hasPendingKeyFetches() || hasNoOtherTrustedKeys()) {
338 refreshUi();
339 } else {
340 runOnUiThread(new Runnable() {
341 @Override
342 public void run() {
343 finishOk();
344 }
345 });
346
347 }
348 }
349
350 private void finishOk() {
351 Intent data = new Intent();
352 data.putExtra("choice", getIntent().getIntExtra("choice", ConversationActivity.ATTACHMENT_CHOICE_INVALID));
353 setResult(RESULT_OK, data);
354 finish();
355 }
356
357 private void commitTrusts() {
358 for(final String fingerprint :ownKeysToTrust.keySet()) {
359 mAccount.getAxolotlService().setFingerprintTrust(
360 fingerprint,
361 FingerprintStatus.createActive(ownKeysToTrust.get(fingerprint)));
362 }
363 List<Jid> acceptedTargets = mConversation == null ? new ArrayList<Jid>() : mConversation.getAcceptedCryptoTargets();
364 synchronized (this.foreignKeysToTrust) {
365 for (Map.Entry<Jid, Map<String, Boolean>> entry : foreignKeysToTrust.entrySet()) {
366 Jid jid = entry.getKey();
367 Map<String, Boolean> value = entry.getValue();
368 if (!acceptedTargets.contains(jid)) {
369 acceptedTargets.add(jid);
370 }
371 for (final String fingerprint : value.keySet()) {
372 mAccount.getAxolotlService().setFingerprintTrust(
373 fingerprint,
374 FingerprintStatus.createActive(value.get(fingerprint)));
375 }
376 }
377 }
378 if (mConversation != null && mConversation.getMode() == Conversation.MODE_MULTI) {
379 mConversation.setAcceptedCryptoTargets(acceptedTargets);
380 xmppConnectionService.updateConversation(mConversation);
381 }
382 }
383
384 private void unlock() {
385 mSaveButton.setEnabled(true);
386 mSaveButton.setTextColor(getPrimaryTextColor());
387 }
388
389 private void lock() {
390 mSaveButton.setEnabled(false);
391 mSaveButton.setTextColor(getSecondaryTextColor());
392 }
393
394 private void lockOrUnlockAsNeeded() {
395 synchronized (this.foreignKeysToTrust) {
396 for (Jid jid : contactJids) {
397 Map<String, Boolean> fingerprints = foreignKeysToTrust.get(jid);
398 if (hasNoOtherTrustedKeys(jid) && (fingerprints == null || !fingerprints.values().contains(true))) {
399 lock();
400 return;
401 }
402 }
403 }
404 unlock();
405
406 }
407
408 private void setDone() {
409 mSaveButton.setText(getString(R.string.done));
410 }
411
412 private void setFetching() {
413 mSaveButton.setText(getString(R.string.fetching_keys));
414 }
415}