aboutsummaryrefslogtreecommitdiffstats
path: root/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/linked/LinkedIdViewFragment.java
blob: 6ad7fa4433440bbe8c6d8ea1cc0d62a75fb28973 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package org.sufficientlysecure.keychain.ui.linked;

import java.io.IOException;
import java.util.Arrays;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.support.v4.app.Fragment;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewAnimator;

import org.spongycastle.util.encoders.Hex;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.operations.results.CertifyResult;
import org.sufficientlysecure.keychain.operations.results.LinkedVerifyResult;
import org.sufficientlysecure.keychain.pgp.WrappedUserAttribute;
import org.sufficientlysecure.keychain.pgp.linked.LinkedCookieResource;
import org.sufficientlysecure.keychain.pgp.linked.LinkedIdentity;
import org.sufficientlysecure.keychain.pgp.linked.LinkedResource;
import org.sufficientlysecure.keychain.pgp.linked.RawLinkedIdentity;
import org.sufficientlysecure.keychain.provider.KeychainContract.Certs;
import org.sufficientlysecure.keychain.service.CertifyActionsParcel;
import org.sufficientlysecure.keychain.service.CertifyActionsParcel.CertifyAction;
import org.sufficientlysecure.keychain.service.KeychainIntentService;
import org.sufficientlysecure.keychain.service.KeychainIntentServiceHandler;
import org.sufficientlysecure.keychain.service.PassphraseCacheService;
import org.sufficientlysecure.keychain.ui.PassphraseDialogActivity;
import org.sufficientlysecure.keychain.ui.adapter.LinkedIdsAdapter.ViewHolder;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils;
import org.sufficientlysecure.keychain.ui.util.KeyFormattingUtils.State;
import org.sufficientlysecure.keychain.ui.util.Notify;
import org.sufficientlysecure.keychain.ui.util.Notify.Style;
import org.sufficientlysecure.keychain.ui.widget.CertifyKeySpinner;
import org.sufficientlysecure.keychain.util.Log;
import org.sufficientlysecure.keychain.util.Preferences;


public class LinkedIdViewFragment extends Fragment {

    public static final int REQUEST_CODE_PASSPHRASE = 0x00008001;

    private static final String ARG_ENCODED_LID = "encoded_lid";
    private static final String ARG_VERIFIED = "verified";
    private static final String ARG_FINGERPRINT = "fingerprint";

    private RawLinkedIdentity mLinkedId;
    private LinkedCookieResource mLinkedResource;
    private Integer mVerified;

    private CardView vLinkedIdsCard;
    private Context mContext;
    private byte[] mFingerprint;
    private LayoutInflater mInflater;
    private LinearLayout vLinkedCerts;

    private View mCurrentCert;
    private boolean mInProgress;
    private ViewAnimator mButtonSwitcher;
    private CertifyKeySpinner vKeySpinner;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = getArguments();
        byte[] data = args.getByteArray(ARG_ENCODED_LID);

        try {
            mLinkedId = LinkedIdentity.fromAttributeData(data);
        } catch (IOException e) {
            // TODO um…
            e.printStackTrace();
            throw new AssertionError("reconstruction of user attribute must succeed!");
        }

        if (mLinkedId instanceof LinkedIdentity) {
            LinkedResource res = ((LinkedIdentity) mLinkedId).mResource;
            mLinkedResource = (LinkedCookieResource) res;
        }

        mVerified = args.containsKey(ARG_VERIFIED) ? args.getInt(ARG_VERIFIED) : null;
        mFingerprint = args.getByteArray(ARG_FINGERPRINT);

        mContext = getActivity();
        mInflater = getLayoutInflater(savedInstanceState);

    }

    public static Fragment newInstance(RawLinkedIdentity id,
            Integer isVerified, byte[] fingerprint) throws IOException {
        LinkedIdViewFragment frag = new LinkedIdViewFragment();

        Bundle args = new Bundle();
        args.putByteArray(ARG_ENCODED_LID, id.toUserAttribute().getEncoded());
        if (isVerified != null) {
            args.putInt(ARG_VERIFIED, isVerified);
        }
        args.putByteArray(ARG_FINGERPRINT, fingerprint);
        frag.setArguments(args);

        return frag;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup superContainer, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.linked_id_view_fragment, null);

        vLinkedIdsCard = (CardView) root.findViewById(R.id.card_linked_ids);
        vLinkedCerts = (LinearLayout) root.findViewById(R.id.linked_id_certs);
        vKeySpinner = (CertifyKeySpinner) root.findViewById(R.id.cert_key_spinner);

        View back = root.findViewById(R.id.back_button);
        back.setClickable(true);
        back.findViewById(R.id.back_button).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().popBackStack();
            }
        });

        ViewHolder holder = new ViewHolder(root);

        if (mVerified != null) {
            holder.vVerified.setVisibility(View.VISIBLE);
            switch (mVerified) {
                case Certs.VERIFIED_SECRET:
                    KeyFormattingUtils.setStatusImage(mContext, holder.vVerified,
                            null, State.VERIFIED, KeyFormattingUtils.DEFAULT_COLOR);
                    break;
                case Certs.VERIFIED_SELF:
                    KeyFormattingUtils.setStatusImage(mContext, holder.vVerified,
                            null, State.UNVERIFIED, KeyFormattingUtils.DEFAULT_COLOR);
                    break;
                default:
                    KeyFormattingUtils.setStatusImage(mContext, holder.vVerified,
                            null, State.INVALID, KeyFormattingUtils.DEFAULT_COLOR);
                    break;
            }
        } else {
            holder.vVerified.setVisibility(View.GONE);
        }

        holder.setData(mContext, mLinkedId);

        // no resource, nothing further we can do…
        if (mLinkedResource == null) {
            root.findViewById(R.id.button_view).setVisibility(View.GONE);
            root.findViewById(R.id.button_verify).setVisibility(View.GONE);
            return root;
        }

        View button_view = root.findViewById(R.id.button_view);
        if (mLinkedResource.isViewable()) {
            button_view.setVisibility(View.VISIBLE);
            button_view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = mLinkedResource.getViewIntent();
                    if (intent == null) {
                        return;
                    }
                    getActivity().startActivity(intent);
                }
            });
        } else {
            button_view.setVisibility(View.GONE);
        }

        mButtonSwitcher = (ViewAnimator) root.findViewById(R.id.button_animator);

        View button_verify = root.findViewById(R.id.button_verify);
        button_verify.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                verifyResource();
            }
        });

        View button_retry = root.findViewById(R.id.button_retry);
        button_retry.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                verifyResource();
            }
        });

        View button_confirm = root.findViewById(R.id.button_confirm);
        button_confirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                initiateCertifying();
            }
        });

        return root;
    }

    static class ViewHolderCert {
        final ViewAnimator vProgress;
        final ImageView vIcon;
        final TextView vText;

        ViewHolderCert(View view) {
            vProgress = (ViewAnimator) view.findViewById(R.id.linked_cert_progress);
            vIcon = (ImageView) view.findViewById(R.id.linked_cert_icon);
            vText = (TextView) view.findViewById(R.id.linked_cert_text);
        }
        void setShowProgress(boolean show) {
            vProgress.setDisplayedChild(show ? 0 : 1);
        }
    }

    void showButton(int which) {
        if (mButtonSwitcher.getDisplayedChild() == which) {
            return;
        }
        mButtonSwitcher.setDisplayedChild(which);
    }

    void verifyResource() {

        // only one at a time
        synchronized (this) {
            if (mInProgress) {
                return;
            }
            mInProgress = true;
        }

        // is there a current certification? if not create a new one
        final ViewHolderCert holder;
        if (mCurrentCert == null) {
            mCurrentCert = mInflater.inflate(R.layout.linked_id_cert, null);
            holder = new ViewHolderCert(mCurrentCert);
            mCurrentCert.setTag(holder);
            vLinkedCerts.addView(mCurrentCert);
        } else {
            holder = (ViewHolderCert) mCurrentCert.getTag();
        }

        vKeySpinner.setVisibility(View.GONE);
        holder.setShowProgress(true);
        holder.vText.setText("Verifying…");

        new AsyncTask<Void,Void,LinkedVerifyResult>() {
            @Override
            protected LinkedVerifyResult doInBackground(Void... params) {
                long timer = System.currentTimeMillis();
                LinkedVerifyResult result = mLinkedResource.verify(mFingerprint, mLinkedId.mNonce);

                // ux flow: this operation should take at last a second
                timer = System.currentTimeMillis() -timer;
                if (timer < 1000) try {
                    Thread.sleep(1000 -timer);
                } catch (InterruptedException e) {
                    // never mind
                }

                return result;
            }

            @Override
            protected void onPostExecute(LinkedVerifyResult result) {
                holder.setShowProgress(false);
                if (result.success()) {
                    holder.vText.setText("Ok");
                    setupForConfirmation();
                } else {
                    showButton(1);
                    holder.vText.setText("Error");
                }
                mInProgress = false;
            }
        }.execute();

    }

    void setupForConfirmation() {

        // button is 'confirm'
        showButton(2);

        vKeySpinner.setVisibility(View.VISIBLE);

    }

    private void initiateCertifying() {
        // get the user's passphrase for this key (if required)
        String passphrase;
        long certifyKeyId = vKeySpinner.getSelectedItemId();
        try {
            passphrase = PassphraseCacheService.getCachedPassphrase(
                    getActivity(), certifyKeyId, certifyKeyId);
        } catch (PassphraseCacheService.KeyNotFoundException e) {
            Log.e(Constants.TAG, "Key not found!", e);
            getActivity().finish();
            return;
        }
        if (passphrase == null) {
            Intent intent = new Intent(getActivity(), PassphraseDialogActivity.class);
            intent.putExtra(PassphraseDialogActivity.EXTRA_SUBKEY_ID, certifyKeyId);
            startActivityForResult(intent, REQUEST_CODE_PASSPHRASE);
            // bail out; need to wait until the user has entered the passphrase before trying again
        } else {
            certifyResource(certifyKeyId, "");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PASSPHRASE: {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    String passphrase = data.getStringExtra(
                            PassphraseDialogActivity.MESSAGE_DATA_PASSPHRASE);
                    long certifyKeyId = data.getLongExtra(PassphraseDialogActivity.EXTRA_KEY_ID, 0L);
                    if (certifyKeyId == 0L) {
                        throw new AssertionError("key id must not be 0");
                    }
                    certifyResource(certifyKeyId, passphrase);
                }
                return;
            }

            default: {
                super.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    private void certifyResource(long certifyKeyId, String passphrase) {

        Bundle data = new Bundle();
        {

            long masterKeyId = KeyFormattingUtils.convertFingerprintToKeyId(mFingerprint);
            CertifyAction action = new CertifyAction(masterKeyId, null,
                    Arrays.asList(mLinkedId.toUserAttribute()));

            // fill values for this action
            CertifyActionsParcel parcel = new CertifyActionsParcel(certifyKeyId);
            parcel.mCertifyActions.addAll(Arrays.asList(action));

            data.putParcelable(KeychainIntentService.CERTIFY_PARCEL, parcel);
            /* if (mUploadKeyCheckbox.isChecked()) {
                String keyserver = Preferences.getPreferences(getActivity()).getPreferredKeyserver();
                data.putString(KeychainIntentService.UPLOAD_KEY_SERVER, keyserver);
            } */
        }

        // Send all information needed to service to sign key in other thread
        Intent intent = new Intent(getActivity(), KeychainIntentService.class);
        intent.setAction(KeychainIntentService.ACTION_CERTIFY_KEYRING);
        intent.putExtra(KeychainIntentService.EXTRA_DATA, data);

        // Message is received after signing is done in KeychainIntentService
        KeychainIntentServiceHandler saveHandler = new KeychainIntentServiceHandler(getActivity(),
                getString(R.string.progress_certifying), ProgressDialog.STYLE_SPINNER, false) {
            public void handleMessage(Message message) {
                // handle messages by standard KeychainIntentServiceHandler first
                super.handleMessage(message);

                if (message.arg1 == KeychainIntentServiceHandler.MESSAGE_OKAY) {
                    Bundle data = message.getData();
                    CertifyResult result = data.getParcelable(CertifyResult.EXTRA_RESULT);

                    result.createNotify(getActivity()).show();
                }
            }
        };

        // Create a new Messenger for the communication back
        Messenger messenger = new Messenger(saveHandler);
        intent.putExtra(KeychainIntentService.EXTRA_MESSENGER, messenger);

        // show progress dialog
        saveHandler.showProgressDialog(getActivity());

        // start service with intent
        getActivity().startService(intent);

    }

}