]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Manager.java
Fix coding issues
[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 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 private 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 return !(!f.exists() || f.isDirectory());
81 }
82
83 public boolean userHasKeys() {
84 return axolotlStore != null;
85 }
86
87 public void load() throws IOException, InvalidKeyException {
88 JSONObject in = new JSONObject(IOUtils.toString(new FileInputStream(getFileName())));
89 username = in.getString("username");
90 password = in.getString("password");
91 if (in.has("signalingKey")) {
92 signalingKey = in.getString("signalingKey");
93 }
94 if (in.has("preKeyIdOffset")) {
95 preKeyIdOffset = in.getInt("preKeyIdOffset");
96 } else {
97 preKeyIdOffset = 0;
98 }
99 if (in.has("nextSignedPreKeyId")) {
100 nextSignedPreKeyId = in.getInt("nextSignedPreKeyId");
101 } else {
102 nextSignedPreKeyId = 0;
103 }
104 axolotlStore = new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
105 registered = in.getBoolean("registered");
106 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password);
107 }
108
109 public void save() {
110 String out = new JSONObject().put("username", username)
111 .put("password", password)
112 .put("signalingKey", signalingKey)
113 .put("preKeyIdOffset", preKeyIdOffset)
114 .put("nextSignedPreKeyId", nextSignedPreKeyId)
115 .put("axolotlStore", axolotlStore.getJson())
116 .put("registered", registered).toString();
117 try {
118 OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(getFileName()));
119 writer.write(out);
120 writer.flush();
121 writer.close();
122 } catch (Exception e) {
123 System.out.println("Saving file error: " + e.getMessage());
124 }
125 }
126
127 public void createNewIdentity() {
128 IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
129 int registrationId = KeyHelper.generateRegistrationId(false);
130 axolotlStore = new JsonAxolotlStore(identityKey, registrationId);
131 registered = false;
132 }
133
134 public boolean isRegistered() {
135 return registered;
136 }
137
138 public void register(boolean voiceVerication) throws IOException {
139 password = Util.getSecret(18);
140
141 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password);
142
143 if (voiceVerication)
144 accountManager.requestVoiceVerificationCode();
145 else
146 accountManager.requestSmsVerificationCode();
147
148 registered = false;
149 }
150
151 private static final int BATCH_SIZE = 100;
152
153 private List<PreKeyRecord> generatePreKeys() {
154 List<PreKeyRecord> records = new LinkedList<>();
155
156 for (int i = 0; i < BATCH_SIZE; i++) {
157 int preKeyId = (preKeyIdOffset + i) % Medium.MAX_VALUE;
158 ECKeyPair keyPair = Curve.generateKeyPair();
159 PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
160
161 axolotlStore.storePreKey(preKeyId, record);
162 records.add(record);
163 }
164
165 preKeyIdOffset = (preKeyIdOffset + BATCH_SIZE + 1) % Medium.MAX_VALUE;
166 return records;
167 }
168
169 private PreKeyRecord generateLastResortPreKey() {
170 if (axolotlStore.containsPreKey(Medium.MAX_VALUE)) {
171 try {
172 return axolotlStore.loadPreKey(Medium.MAX_VALUE);
173 } catch (InvalidKeyIdException e) {
174 axolotlStore.removePreKey(Medium.MAX_VALUE);
175 }
176 }
177
178 ECKeyPair keyPair = Curve.generateKeyPair();
179 PreKeyRecord record = new PreKeyRecord(Medium.MAX_VALUE, keyPair);
180
181 axolotlStore.storePreKey(Medium.MAX_VALUE, record);
182
183 return record;
184 }
185
186 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
187 try {
188 ECKeyPair keyPair = Curve.generateKeyPair();
189 byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
190 SignedPreKeyRecord record = new SignedPreKeyRecord(nextSignedPreKeyId, System.currentTimeMillis(), keyPair, signature);
191
192 axolotlStore.storeSignedPreKey(nextSignedPreKeyId, record);
193 nextSignedPreKeyId = (nextSignedPreKeyId + 1) % Medium.MAX_VALUE;
194
195 return record;
196 } catch (InvalidKeyException e) {
197 throw new AssertionError(e);
198 }
199 }
200
201 public void verifyAccount(String verificationCode) throws IOException {
202 verificationCode = verificationCode.replace("-", "");
203 signalingKey = Util.getSecret(52);
204 accountManager.verifyAccount(verificationCode, signalingKey, false, axolotlStore.getLocalRegistrationId());
205
206 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
207 registered = true;
208
209 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
210
211 PreKeyRecord lastResortKey = generateLastResortPreKey();
212
213 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(axolotlStore.getIdentityKeyPair());
214
215 accountManager.setPreKeys(axolotlStore.getIdentityKeyPair().getPublicKey(), lastResortKey, signedPreKeyRecord, oneTimePreKeys);
216 }
217
218 public void sendMessage(List<TextSecureAddress> recipients, TextSecureDataMessage message)
219 throws IOException, EncapsulatedExceptions {
220 TextSecureMessageSender messageSender = new TextSecureMessageSender(URL, TRUST_STORE, username, password,
221 axolotlStore, Optional.<TextSecureMessageSender.EventListener>absent());
222 messageSender.sendMessage(recipients, message);
223 }
224
225 public TextSecureContent decryptMessage(TextSecureEnvelope envelope) {
226 TextSecureCipher cipher = new TextSecureCipher(new TextSecureAddress(username), axolotlStore);
227 try {
228 return cipher.decrypt(envelope);
229 } catch (Exception e) {
230 // TODO handle all exceptions
231 e.printStackTrace();
232 return null;
233 }
234 }
235
236 public void handleEndSession(String source) {
237 axolotlStore.deleteAllSessions(source);
238 }
239
240 public interface ReceiveMessageHandler {
241 void handleMessage(TextSecureEnvelope envelope);
242 }
243
244 public void receiveMessages(int timeoutSeconds, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException {
245 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey);
246 TextSecureMessagePipe messagePipe = null;
247
248 try {
249 messagePipe = messageReceiver.createMessagePipe();
250
251 while (true) {
252 TextSecureEnvelope envelope;
253 try {
254 envelope = messagePipe.read(timeoutSeconds, TimeUnit.SECONDS);
255 handler.handleMessage(envelope);
256 } catch (TimeoutException e) {
257 if (returnOnTimeout)
258 return;
259 } catch (InvalidVersionException e) {
260 System.out.println("Ignoring error: " + e.getMessage());
261 }
262 save();
263 }
264 } finally {
265 if (messagePipe != null)
266 messagePipe.shutdown();
267 }
268 }
269
270 public File retrieveAttachment(TextSecureAttachmentPointer pointer) throws IOException, InvalidMessageException {
271 final TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey);
272
273 File tmpFile = File.createTempFile("ts_attach_" + pointer.getId(), ".tmp");
274 InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile);
275
276 new File(attachmentsPath).mkdirs();
277 File outputFile = new File(attachmentsPath + "/" + pointer.getId());
278 OutputStream output = null;
279 try {
280 output = new FileOutputStream(outputFile);
281 byte[] buffer = new byte[4096];
282 int read;
283
284 while ((read = input.read(buffer)) != -1) {
285 output.write(buffer, 0, read);
286 }
287 } catch (FileNotFoundException e) {
288 e.printStackTrace();
289 return null;
290 } finally {
291 if (output != null) {
292 output.close();
293 }
294 tmpFile.delete();
295 }
296 return outputFile;
297 }
298
299 private String canonicalizeNumber(String number) throws InvalidNumberException {
300 String localNumber = username;
301 return PhoneNumberFormatter.formatNumber(number, localNumber);
302 }
303
304 TextSecureAddress getPushAddress(String number) throws InvalidNumberException {
305 String e164number = canonicalizeNumber(number);
306 return new TextSecureAddress(e164number);
307 }
308 }