OpenPgpApi.java

  1/*
  2 * Copyright (C) 2014 Dominik Schürmann <dominik@dominikschuermann.de>
  3 *
  4 * Licensed under the Apache License, Version 2.0 (the "License");
  5 * you may not use this file except in compliance with the License.
  6 * You may obtain a copy of the License at
  7 *
  8 *      http://www.apache.org/licenses/LICENSE-2.0
  9 *
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS,
 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13 * See the License for the specific language governing permissions and
 14 * limitations under the License.
 15 */
 16
 17package org.openintents.openpgp.util;
 18
 19import android.annotation.TargetApi;
 20import android.content.Context;
 21import android.content.Intent;
 22import android.os.AsyncTask;
 23import android.os.Build;
 24import android.os.ParcelFileDescriptor;
 25import android.util.Log;
 26
 27import org.openintents.openpgp.IOpenPgpService;
 28import org.openintents.openpgp.OpenPgpError;
 29
 30import java.io.InputStream;
 31import java.io.OutputStream;
 32
 33public class OpenPgpApi {
 34
 35    public static final String TAG = "OpenPgp API";
 36
 37    public static final int API_VERSION = 3;
 38    public static final String SERVICE_INTENT = "org.openintents.openpgp.IOpenPgpService";
 39
 40    /**
 41     * General extras
 42     * --------------
 43     *
 44     * required extras:
 45     * int           EXTRA_API_VERSION           (always required)
 46     *
 47     * returned extras:
 48     * int           RESULT_CODE                 (RESULT_CODE_ERROR, RESULT_CODE_SUCCESS or RESULT_CODE_USER_INTERACTION_REQUIRED)
 49     * OpenPgpError  RESULT_ERROR                (if RESULT_CODE == RESULT_CODE_ERROR)
 50     * PendingIntent RESULT_INTENT               (if RESULT_CODE == RESULT_CODE_USER_INTERACTION_REQUIRED)
 51     */
 52
 53    /**
 54     * Sign only
 55     * <p/>
 56     * optional extras:
 57     * boolean       EXTRA_REQUEST_ASCII_ARMOR   (request ascii armor for ouput)
 58     * String        EXTRA_PASSPHRASE            (key passphrase)
 59     */
 60    public static final String ACTION_SIGN = "org.openintents.openpgp.action.SIGN";
 61
 62    /**
 63     * Encrypt
 64     * <p/>
 65     * required extras:
 66     * String[]      EXTRA_USER_IDS              (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
 67     * or
 68     * long[]        EXTRA_KEY_IDS
 69     * <p/>
 70     * optional extras:
 71     * boolean       EXTRA_REQUEST_ASCII_ARMOR   (request ascii armor for ouput)
 72     * String        EXTRA_PASSPHRASE            (key passphrase)
 73     */
 74    public static final String ACTION_ENCRYPT = "org.openintents.openpgp.action.ENCRYPT";
 75
 76    /**
 77     * Sign and encrypt
 78     * <p/>
 79     * required extras:
 80     * String[]      EXTRA_USER_IDS              (=emails of recipients, if more than one key has a user_id, a PendingIntent is returned via RESULT_INTENT)
 81     * or
 82     * long[]        EXTRA_KEY_IDS
 83     * <p/>
 84     * optional extras:
 85     * boolean       EXTRA_REQUEST_ASCII_ARMOR   (request ascii armor for ouput)
 86     * String        EXTRA_PASSPHRASE            (key passphrase)
 87     */
 88    public static final String ACTION_SIGN_AND_ENCRYPT = "org.openintents.openpgp.action.SIGN_AND_ENCRYPT";
 89
 90    /**
 91     * Decrypts and verifies given input stream. This methods handles encrypted-only, signed-and-encrypted,
 92     * and also signed-only input.
 93     * <p/>
 94     * If OpenPgpSignatureResult.getStatus() == OpenPgpSignatureResult.SIGNATURE_UNKNOWN_PUB_KEY
 95     * in addition a PendingIntent is returned via RESULT_INTENT to download missing keys.
 96     * <p/>
 97     * optional extras:
 98     * boolean       EXTRA_REQUEST_ASCII_ARMOR   (request ascii armor for ouput)
 99     * <p/>
100     * returned extras:
101     * OpenPgpSignatureResult   RESULT_SIGNATURE
102     */
103    public static final String ACTION_DECRYPT_VERIFY = "org.openintents.openpgp.action.DECRYPT_VERIFY";
104
105    /**
106     * Get key ids based on given user ids (=emails)
107     * <p/>
108     * required extras:
109     * String[]      EXTRA_USER_IDS
110     * <p/>
111     * returned extras:
112     * long[]        RESULT_KEY_IDS
113     */
114    public static final String ACTION_GET_KEY_IDS = "org.openintents.openpgp.action.GET_KEY_IDS";
115
116    /**
117     * This action returns RESULT_CODE_SUCCESS if the OpenPGP Provider already has the key
118     * corresponding to the given key id in its database.
119     * <p/>
120     * It returns RESULT_CODE_USER_INTERACTION_REQUIRED if the Provider does not have the key.
121     * The PendingIntent from RESULT_INTENT can be used to retrieve those from a keyserver.
122     * <p/>
123     * required extras:
124     * long        EXTRA_KEY_ID
125     */
126    public static final String ACTION_GET_KEY = "org.openintents.openpgp.action.GET_KEY";
127
128    /* Intent extras */
129    public static final String EXTRA_API_VERSION = "api_version";
130
131    public static final String EXTRA_ACCOUNT_NAME = "account_name";
132
133    // SIGN, ENCRYPT, SIGN_AND_ENCRYPT, DECRYPT_VERIFY
134    // request ASCII Armor for output
135    // OpenPGP Radix-64, 33 percent overhead compared to binary, see http://tools.ietf.org/html/rfc4880#page-53)
136    public static final String EXTRA_REQUEST_ASCII_ARMOR = "ascii_armor";
137
138    // ENCRYPT, SIGN_AND_ENCRYPT
139    public static final String EXTRA_USER_IDS = "user_ids";
140    public static final String EXTRA_KEY_IDS = "key_ids";
141    // optional extras:
142    public static final String EXTRA_PASSPHRASE = "passphrase";
143
144    // GET_KEY
145    public static final String EXTRA_KEY_ID = "key_id";
146    public static final String RESULT_KEY_IDS = "key_ids";
147
148    /* Service Intent returns */
149    public static final String RESULT_CODE = "result_code";
150
151    // get actual error object from RESULT_ERROR
152    public static final int RESULT_CODE_ERROR = 0;
153    // success!
154    public static final int RESULT_CODE_SUCCESS = 1;
155    // get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult,
156    // and execute service method again in onActivityResult
157    public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
158
159    public static final String RESULT_ERROR = "error";
160    public static final String RESULT_INTENT = "intent";
161
162    // DECRYPT_VERIFY
163    public static final String RESULT_SIGNATURE = "signature";
164
165    IOpenPgpService mService;
166    Context mContext;
167
168    public OpenPgpApi(Context context, IOpenPgpService service) {
169        this.mContext = context;
170        this.mService = service;
171    }
172
173    public interface IOpenPgpCallback {
174        void onReturn(final Intent result);
175    }
176
177    private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
178        Intent data;
179        InputStream is;
180        OutputStream os;
181        IOpenPgpCallback callback;
182
183        private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
184            this.data = data;
185            this.is = is;
186            this.os = os;
187            this.callback = callback;
188        }
189
190        @Override
191        protected Intent doInBackground(Void... unused) {
192            return executeApi(data, is, os);
193        }
194
195        protected void onPostExecute(Intent result) {
196            callback.onReturn(result);
197        }
198
199    }
200
201    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
202    public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
203        OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
204
205        // don't serialize async tasks!
206        // http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
207        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
208            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
209        } else {
210            task.execute((Void[]) null);
211        }
212    }
213
214    public Intent executeApi(Intent data, InputStream is, OutputStream os) {
215        try {
216            data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
217
218            Intent result;
219
220            // pipe the input and output
221            ParcelFileDescriptor input = null;
222            if (is != null) {
223                input = ParcelFileDescriptorUtil.pipeFrom(is,
224                        new ParcelFileDescriptorUtil.IThreadListener() {
225
226                            @Override
227                            public void onThreadFinished(Thread thread) {
228                                //Log.d(OpenPgpApi.TAG, "Copy to service finished");
229                            }
230                        }
231                );
232            }
233            ParcelFileDescriptor output = null;
234            if (os != null) {
235                output = ParcelFileDescriptorUtil.pipeTo(os,
236                        new ParcelFileDescriptorUtil.IThreadListener() {
237
238                            @Override
239                            public void onThreadFinished(Thread thread) {
240                                //Log.d(OpenPgpApi.TAG, "Service finished writing!");
241                            }
242                        }
243                );
244            }
245
246            // blocks until result is ready
247            result = mService.execute(data, input, output);
248            // close() is required to halt the TransferThread
249            if (output != null) {
250                output.close();
251            }
252            // TODO: close input?
253
254            // set class loader to current context to allow unparcelling
255            // of OpenPgpError and OpenPgpSignatureResult
256            // http://stackoverflow.com/a/3806769
257            result.setExtrasClassLoader(mContext.getClassLoader());
258
259            return result;
260        } catch (Exception e) {
261            Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
262            Intent result = new Intent();
263            result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
264            result.putExtra(RESULT_ERROR,
265                    new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
266            return result;
267        }
268    }
269
270}