]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Manager.java
Add -v and --version command line arguments
[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 public final static String PROJECT_NAME = Manager.class.getPackage().getImplementationTitle();
55 public final static String PROJECT_VERSION = Manager.class.getPackage().getImplementationVersion();
56 private final static String USER_AGENT = PROJECT_NAME + " " + PROJECT_VERSION;
57
58 private final static String settingsPath = System.getProperty("user.home") + "/.config/textsecure";
59 private final static String dataPath = settingsPath + "/data";
60 private final static String attachmentsPath = settingsPath + "/attachments";
61
62 private String username;
63 private String password;
64 private String signalingKey;
65 private int preKeyIdOffset;
66 private int nextSignedPreKeyId;
67
68 private boolean registered = false;
69
70 private JsonAxolotlStore axolotlStore;
71 private TextSecureAccountManager accountManager;
72
73 public Manager(String username) {
74 this.username = username;
75 }
76
77 public String getFileName() {
78 new File(dataPath).mkdirs();
79 return dataPath + "/" + username;
80 }
81
82 public boolean userExists() {
83 File f = new File(getFileName());
84 return !(!f.exists() || f.isDirectory());
85 }
86
87 public boolean userHasKeys() {
88 return axolotlStore != null;
89 }
90
91 public void load() throws IOException, InvalidKeyException {
92 JSONObject in = new JSONObject(IOUtils.toString(new FileInputStream(getFileName())));
93 username = in.getString("username");
94 password = in.getString("password");
95 if (in.has("signalingKey")) {
96 signalingKey = in.getString("signalingKey");
97 }
98 if (in.has("preKeyIdOffset")) {
99 preKeyIdOffset = in.getInt("preKeyIdOffset");
100 } else {
101 preKeyIdOffset = 0;
102 }
103 if (in.has("nextSignedPreKeyId")) {
104 nextSignedPreKeyId = in.getInt("nextSignedPreKeyId");
105 } else {
106 nextSignedPreKeyId = 0;
107 }
108 axolotlStore = new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
109 registered = in.getBoolean("registered");
110 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password, USER_AGENT);
111 }
112
113 public void save() {
114 String out = new JSONObject().put("username", username)
115 .put("password", password)
116 .put("signalingKey", signalingKey)
117 .put("preKeyIdOffset", preKeyIdOffset)
118 .put("nextSignedPreKeyId", nextSignedPreKeyId)
119 .put("axolotlStore", axolotlStore.getJson())
120 .put("registered", registered).toString();
121 try {
122 OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(getFileName()));
123 writer.write(out);
124 writer.flush();
125 writer.close();
126 } catch (Exception e) {
127 System.err.println("Saving file error: " + e.getMessage());
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, USER_AGENT);
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.verifyAccountWithCode(verificationCode, signalingKey, axolotlStore.getLocalRegistrationId(), false);
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, USER_AGENT, 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, USER_AGENT);
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.err.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, USER_AGENT);
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 output = null;
298 }
299 if (!tmpFile.delete()) {
300 System.err.println("Failed to delete temp file: " + tmpFile);
301 }
302 }
303 if (pointer.getPreview().isPresent()) {
304 File previewFile = new File(outputFile + ".preview");
305 try {
306 output = new FileOutputStream(previewFile);
307 byte[] preview = pointer.getPreview().get();
308 output.write(preview, 0, preview.length);
309 } catch (FileNotFoundException e) {
310 e.printStackTrace();
311 return null;
312 } finally {
313 if (output != null) {
314 output.close();
315 }
316 }
317 }
318 return outputFile;
319 }
320
321 private String canonicalizeNumber(String number) throws InvalidNumberException {
322 String localNumber = username;
323 return PhoneNumberFormatter.formatNumber(number, localNumber);
324 }
325
326 TextSecureAddress getPushAddress(String number) throws InvalidNumberException {
327 String e164number = canonicalizeNumber(number);
328 return new TextSecureAddress(e164number);
329 }
330 }