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