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