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 // internal
145 public static final String EXTRA_NFC_DATA = "nfc_data";
146
147 // GET_KEY
148 public static final String EXTRA_KEY_ID = "key_id";
149 public static final String RESULT_KEY_IDS = "key_ids";
150
151 /* Service Intent returns */
152 public static final String RESULT_CODE = "result_code";
153
154 // get actual error object from RESULT_ERROR
155 public static final int RESULT_CODE_ERROR = 0;
156 // success!
157 public static final int RESULT_CODE_SUCCESS = 1;
158 // get PendingIntent from RESULT_INTENT, start PendingIntent with startIntentSenderForResult,
159 // and execute service method again in onActivityResult
160 public static final int RESULT_CODE_USER_INTERACTION_REQUIRED = 2;
161
162 public static final String RESULT_ERROR = "error";
163 public static final String RESULT_INTENT = "intent";
164
165 // DECRYPT_VERIFY
166 public static final String RESULT_SIGNATURE = "signature";
167
168 IOpenPgpService mService;
169 Context mContext;
170
171 public OpenPgpApi(Context context, IOpenPgpService service) {
172 this.mContext = context;
173 this.mService = service;
174 }
175
176 public interface IOpenPgpCallback {
177 void onReturn(final Intent result);
178 }
179
180 private class OpenPgpAsyncTask extends AsyncTask<Void, Integer, Intent> {
181 Intent data;
182 InputStream is;
183 OutputStream os;
184 IOpenPgpCallback callback;
185
186 private OpenPgpAsyncTask(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
187 this.data = data;
188 this.is = is;
189 this.os = os;
190 this.callback = callback;
191 }
192
193 @Override
194 protected Intent doInBackground(Void... unused) {
195 return executeApi(data, is, os);
196 }
197
198 protected void onPostExecute(Intent result) {
199 callback.onReturn(result);
200 }
201
202 }
203
204 @TargetApi(Build.VERSION_CODES.HONEYCOMB)
205 public void executeApiAsync(Intent data, InputStream is, OutputStream os, IOpenPgpCallback callback) {
206 OpenPgpAsyncTask task = new OpenPgpAsyncTask(data, is, os, callback);
207
208 // don't serialize async tasks!
209 // http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
210 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
211 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
212 } else {
213 task.execute((Void[]) null);
214 }
215 }
216
217 public Intent executeApi(Intent data, InputStream is, OutputStream os) {
218 try {
219 data.putExtra(EXTRA_API_VERSION, OpenPgpApi.API_VERSION);
220
221 Intent result;
222
223 // pipe the input and output
224 ParcelFileDescriptor input = null;
225 if (is != null) {
226 input = ParcelFileDescriptorUtil.pipeFrom(is,
227 new ParcelFileDescriptorUtil.IThreadListener() {
228
229 @Override
230 public void onThreadFinished(Thread thread) {
231 //Log.d(OpenPgpApi.TAG, "Copy to service finished");
232 }
233 }
234 );
235 }
236 ParcelFileDescriptor output = null;
237 if (os != null) {
238 output = ParcelFileDescriptorUtil.pipeTo(os,
239 new ParcelFileDescriptorUtil.IThreadListener() {
240
241 @Override
242 public void onThreadFinished(Thread thread) {
243 //Log.d(OpenPgpApi.TAG, "Service finished writing!");
244 }
245 }
246 );
247 }
248
249 // blocks until result is ready
250 result = mService.execute(data, input, output);
251 // close() is required to halt the TransferThread
252 if (output != null) {
253 output.close();
254 }
255 // TODO: close input?
256
257 // set class loader to current context to allow unparcelling
258 // of OpenPgpError and OpenPgpSignatureResult
259 // http://stackoverflow.com/a/3806769
260 result.setExtrasClassLoader(mContext.getClassLoader());
261
262 return result;
263 } catch (Exception e) {
264 Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e);
265 Intent result = new Intent();
266 result.putExtra(RESULT_CODE, RESULT_CODE_ERROR);
267 result.putExtra(RESULT_ERROR,
268 new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage()));
269 return result;
270 }
271 }
272
273}