]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Manager.java
Implement downloading attachments
[signal-cli] / src / main / java / cli / Manager.java
1 /**
2 * Copyright (C) 2015 AsamK
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package cli;
18
19 import org.apache.commons.io.IOUtils;
20 import org.json.JSONObject;
21 import org.whispersystems.libaxolotl.*;
22 import org.whispersystems.libaxolotl.ecc.Curve;
23 import org.whispersystems.libaxolotl.ecc.ECKeyPair;
24 import org.whispersystems.libaxolotl.state.PreKeyRecord;
25 import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
26 import org.whispersystems.libaxolotl.util.KeyHelper;
27 import org.whispersystems.libaxolotl.util.Medium;
28 import org.whispersystems.libaxolotl.util.guava.Optional;
29 import org.whispersystems.textsecure.api.TextSecureAccountManager;
30 import org.whispersystems.textsecure.api.TextSecureMessagePipe;
31 import org.whispersystems.textsecure.api.TextSecureMessageReceiver;
32 import org.whispersystems.textsecure.api.TextSecureMessageSender;
33 import org.whispersystems.textsecure.api.crypto.TextSecureCipher;
34 import org.whispersystems.textsecure.api.messages.TextSecureAttachmentPointer;
35 import org.whispersystems.textsecure.api.messages.TextSecureContent;
36 import org.whispersystems.textsecure.api.messages.TextSecureDataMessage;
37 import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
38 import org.whispersystems.textsecure.api.push.TextSecureAddress;
39 import org.whispersystems.textsecure.api.push.TrustStore;
40 import org.whispersystems.textsecure.api.push.exceptions.EncapsulatedExceptions;
41 import org.whispersystems.textsecure.api.util.InvalidNumberException;
42 import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
43
44 import java.io.*;
45 import java.util.LinkedList;
46 import java.util.List;
47 import java.util.concurrent.TimeUnit;
48 import java.util.concurrent.TimeoutException;
49
50 public class Manager {
51 private final static String URL = "https://textsecure-service.whispersystems.org";
52 private final static TrustStore TRUST_STORE = new WhisperTrustStore();
53
54 private final static String settingsPath = System.getProperty("user.home") + "/.config/textsecure";
55 private final static String dataPath = settingsPath + "/data";
56 private final static String attachmentsPath = settingsPath + "/attachments";
57
58 private String username;
59 private String password;
60 private String signalingKey;
61 private int preKeyIdOffset;
62 private int nextSignedPreKeyId;
63
64 private boolean registered = false;
65
66 private JsonAxolotlStore axolotlStore;
67 TextSecureAccountManager accountManager;
68
69 public Manager(String username) {
70 this.username = username;
71 }
72
73 public String getFileName() {
74 new File(dataPath).mkdirs();
75 return dataPath + "/" + username;
76 }
77
78 public boolean userExists() {
79 File f = new File(getFileName());
80 if (!f.exists() || f.isDirectory()) {
81 return false;
82 }
83 return true;
84 }
85
86 public boolean userHasKeys() {
87 return axolotlStore != null;
88 }
89
90 public void load() throws IOException, InvalidKeyException {
91 JSONObject in = new JSONObject(IOUtils.toString(new FileInputStream(getFileName())));
92 username = in.getString("username");
93 password = in.getString("password");
94 if (in.has("signalingKey")) {
95 signalingKey = in.getString("signalingKey");
96 }
97 if (in.has("preKeyIdOffset")) {
98 preKeyIdOffset = in.getInt("preKeyIdOffset");
99 } else {
100 preKeyIdOffset = 0;
101 }
102 if (in.has("nextSignedPreKeyId")) {
103 nextSignedPreKeyId = in.getInt("nextSignedPreKeyId");
104 } else {
105 nextSignedPreKeyId = 0;
106 }
107 axolotlStore = new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
108 registered = in.getBoolean("registered");
109 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password);
110 }
111
112 public void save() {
113 String out = new JSONObject().put("username", username)
114 .put("password", password)
115 .put("signalingKey", signalingKey)
116 .put("preKeyIdOffset", preKeyIdOffset)
117 .put("nextSignedPreKeyId", nextSignedPreKeyId)
118 .put("axolotlStore", axolotlStore.getJson())
119 .put("registered", registered).toString();
120 try {
121 OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(getFileName()));
122 writer.write(out);
123 writer.flush();
124 writer.close();
125 } catch (Exception e) {
126 System.out.println("Saving file error: " + e.getMessage());
127 return;
128 }
129 }
130
131 public void createNewIdentity() {
132 IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
133 int registrationId = KeyHelper.generateRegistrationId(false);
134 axolotlStore = new JsonAxolotlStore(identityKey, registrationId);
135 registered = false;
136 }
137
138 public boolean isRegistered() {
139 return registered;
140 }
141
142 public void register(boolean voiceVerication) throws IOException {
143 password = Util.getSecret(18);
144
145 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password);
146
147 if (voiceVerication)
148 accountManager.requestVoiceVerificationCode();
149 else
150 accountManager.requestSmsVerificationCode();
151
152 registered = false;
153 }
154
155 private static final int BATCH_SIZE = 100;
156
157 private List<PreKeyRecord> generatePreKeys() {
158 List<PreKeyRecord> records = new LinkedList<>();
159
160 for (int i = 0; i < BATCH_SIZE; i++) {
161 int preKeyId = (preKeyIdOffset + i) % Medium.MAX_VALUE;
162 ECKeyPair keyPair = Curve.generateKeyPair();
163 PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
164
165 axolotlStore.storePreKey(preKeyId, record);
166 records.add(record);
167 }
168
169 preKeyIdOffset = (preKeyIdOffset + BATCH_SIZE + 1) % Medium.MAX_VALUE;
170 return records;
171 }
172
173 private PreKeyRecord generateLastResortPreKey() {
174 if (axolotlStore.containsPreKey(Medium.MAX_VALUE)) {
175 try {
176 return axolotlStore.loadPreKey(Medium.MAX_VALUE);
177 } catch (InvalidKeyIdException e) {
178 axolotlStore.removePreKey(Medium.MAX_VALUE);
179 }
180 }
181
182 ECKeyPair keyPair = Curve.generateKeyPair();
183 PreKeyRecord record = new PreKeyRecord(Medium.MAX_VALUE, keyPair);
184
185 axolotlStore.storePreKey(Medium.MAX_VALUE, record);
186
187 return record;
188 }
189
190 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
191 try {
192 ECKeyPair keyPair = Curve.generateKeyPair();
193 byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
194 SignedPreKeyRecord record = new SignedPreKeyRecord(nextSignedPreKeyId, System.currentTimeMillis(), keyPair, signature);
195
196 axolotlStore.storeSignedPreKey(nextSignedPreKeyId, record);
197 nextSignedPreKeyId = (nextSignedPreKeyId + 1) % Medium.MAX_VALUE;
198
199 return record;
200 } catch (InvalidKeyException e) {
201 throw new AssertionError(e);
202 }
203 }
204
205 public void verifyAccount(String verificationCode) throws IOException {
206 verificationCode = verificationCode.replace("-", "");
207 signalingKey = Util.getSecret(52);
208 accountManager.verifyAccount(verificationCode, signalingKey, false, axolotlStore.getLocalRegistrationId());
209
210 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
211 registered = true;
212
213 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
214
215 PreKeyRecord lastResortKey = generateLastResortPreKey();
216
217 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(axolotlStore.getIdentityKeyPair());
218
219 accountManager.setPreKeys(axolotlStore.getIdentityKeyPair().getPublicKey(), lastResortKey, signedPreKeyRecord, oneTimePreKeys);
220 }
221
222 public void sendMessage(List<TextSecureAddress> recipients, TextSecureDataMessage message)
223 throws IOException, EncapsulatedExceptions {
224 TextSecureMessageSender messageSender = new TextSecureMessageSender(URL, TRUST_STORE, username, password,
225 axolotlStore, Optional.<TextSecureMessageSender.EventListener>absent());
226 messageSender.sendMessage(recipients, message);
227 }
228
229 public TextSecureContent decryptMessage(TextSecureEnvelope envelope) {
230 TextSecureCipher cipher = new TextSecureCipher(new TextSecureAddress(username), axolotlStore);
231 try {
232 return cipher.decrypt(envelope);
233 } catch (Exception e) {
234 // TODO handle all exceptions
235 e.printStackTrace();
236 return null;
237 }
238 }
239
240 public void handleEndSession(String source) {
241 axolotlStore.deleteAllSessions(source);
242 }
243
244 public interface ReceiveMessageHandler {
245 void handleMessage(TextSecureEnvelope envelope);
246 }
247
248 public void receiveMessages(int timeoutSeconds, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException {
249 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey);
250 TextSecureMessagePipe messagePipe = null;
251
252 try {
253 messagePipe = messageReceiver.createMessagePipe();
254
255 while (true) {
256 TextSecureEnvelope envelope;
257 try {
258 envelope = messagePipe.read(timeoutSeconds, TimeUnit.SECONDS);
259 handler.handleMessage(envelope);
260 } catch (TimeoutException e) {
261 if (returnOnTimeout)
262 return;
263 } catch (InvalidVersionException e) {
264 System.out.println("Ignoring error: " + e.getMessage());
265 }
266 save();
267 }
268 } finally {
269 if (messagePipe != null)
270 messagePipe.shutdown();
271 }
272 }
273
274 public File retrieveAttachment(TextSecureAttachmentPointer pointer) throws IOException, InvalidMessageException {
275 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey);
276
277 File tmpFile = File.createTempFile("ts_attach_" + pointer.getId(), ".tmp");
278 InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile);
279
280 new File(attachmentsPath).mkdirs();
281 File outputFile = new File(attachmentsPath + "/" + pointer.getId());
282 OutputStream output = null;
283 try {
284 output = new FileOutputStream(outputFile);
285 byte[] buffer = new byte[4096];
286 int read;
287
288 while ((read = input.read(buffer)) != -1) {
289 output.write(buffer, 0, read);
290 }
291 } catch (FileNotFoundException e) {
292 e.printStackTrace();
293 return null;
294 } finally {
295 if (output != null) {
296 output.close();
297 }
298 tmpFile.delete();
299 }
300 return outputFile;
301 }
302
303 public String canonicalizeNumber(String number) throws InvalidNumberException {
304 String localNumber = username;
305 return PhoneNumberFormatter.formatNumber(number, localNumber);
306 }
307
308 protected TextSecureAddress getPushAddress(String number) throws InvalidNumberException {
309 String e164number = canonicalizeNumber(number);
310 return new TextSecureAddress(e164number);
311 }
312 }