]> nmode's Git Repositories - signal-cli/blob - src/main/java/cli/Manager.java
77e89556bb01a520a58b19e3c24ab1da6679f4f8
[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.IdentityKeyPair;
22 import org.whispersystems.libaxolotl.InvalidKeyException;
23 import org.whispersystems.libaxolotl.InvalidKeyIdException;
24 import org.whispersystems.libaxolotl.InvalidVersionException;
25 import org.whispersystems.libaxolotl.ecc.Curve;
26 import org.whispersystems.libaxolotl.ecc.ECKeyPair;
27 import org.whispersystems.libaxolotl.state.PreKeyRecord;
28 import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
29 import org.whispersystems.libaxolotl.util.KeyHelper;
30 import org.whispersystems.libaxolotl.util.Medium;
31 import org.whispersystems.libaxolotl.util.guava.Optional;
32 import org.whispersystems.textsecure.api.TextSecureAccountManager;
33 import org.whispersystems.textsecure.api.TextSecureMessagePipe;
34 import org.whispersystems.textsecure.api.TextSecureMessageReceiver;
35 import org.whispersystems.textsecure.api.TextSecureMessageSender;
36 import org.whispersystems.textsecure.api.crypto.TextSecureCipher;
37 import org.whispersystems.textsecure.api.messages.TextSecureContent;
38 import org.whispersystems.textsecure.api.messages.TextSecureDataMessage;
39 import org.whispersystems.textsecure.api.messages.TextSecureEnvelope;
40 import org.whispersystems.textsecure.api.push.TextSecureAddress;
41 import org.whispersystems.textsecure.api.push.TrustStore;
42 import org.whispersystems.textsecure.api.push.exceptions.EncapsulatedExceptions;
43 import org.whispersystems.textsecure.api.util.InvalidNumberException;
44 import org.whispersystems.textsecure.api.util.PhoneNumberFormatter;
45
46 import java.io.*;
47 import java.util.LinkedList;
48 import java.util.List;
49 import java.util.concurrent.TimeUnit;
50 import java.util.concurrent.TimeoutException;
51
52 public class Manager {
53 private final static String URL = "https://textsecure-service.whispersystems.org";
54 private final static TrustStore TRUST_STORE = new WhisperTrustStore();
55
56 private final static String settingsPath = System.getProperty("user.home") + "/.config/textsecure";
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 String path = settingsPath + "/data";
75 new File(path).mkdirs();
76 return path + "/" + username;
77 }
78
79 public boolean userExists() {
80 File f = new File(getFileName());
81 if (!f.exists() || f.isDirectory()) {
82 return false;
83 }
84 return true;
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);
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.out.println("Saving file error: " + e.getMessage());
128 return;
129 }
130 }
131
132 public void createNewIdentity() {
133 IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
134 int registrationId = KeyHelper.generateRegistrationId(false);
135 axolotlStore = new JsonAxolotlStore(identityKey, registrationId);
136 registered = false;
137 }
138
139 public boolean isRegistered() {
140 return registered;
141 }
142
143 public void register(boolean voiceVerication) throws IOException {
144 password = Util.getSecret(18);
145
146 accountManager = new TextSecureAccountManager(URL, TRUST_STORE, username, password);
147
148 if (voiceVerication)
149 accountManager.requestVoiceVerificationCode();
150 else
151 accountManager.requestSmsVerificationCode();
152
153 registered = false;
154 }
155
156 private static final int BATCH_SIZE = 100;
157
158 private List<PreKeyRecord> generatePreKeys() {
159 List<PreKeyRecord> records = new LinkedList<>();
160
161 for (int i = 0; i < BATCH_SIZE; i++) {
162 int preKeyId = (preKeyIdOffset + i) % Medium.MAX_VALUE;
163 ECKeyPair keyPair = Curve.generateKeyPair();
164 PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
165
166 axolotlStore.storePreKey(preKeyId, record);
167 records.add(record);
168 }
169
170 preKeyIdOffset = (preKeyIdOffset + BATCH_SIZE + 1) % Medium.MAX_VALUE;
171 return records;
172 }
173
174 private PreKeyRecord generateLastResortPreKey() {
175 if (axolotlStore.containsPreKey(Medium.MAX_VALUE)) {
176 try {
177 return axolotlStore.loadPreKey(Medium.MAX_VALUE);
178 } catch (InvalidKeyIdException e) {
179 axolotlStore.removePreKey(Medium.MAX_VALUE);
180 }
181 }
182
183 ECKeyPair keyPair = Curve.generateKeyPair();
184 PreKeyRecord record = new PreKeyRecord(Medium.MAX_VALUE, keyPair);
185
186 axolotlStore.storePreKey(Medium.MAX_VALUE, record);
187
188 return record;
189 }
190
191 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
192 try {
193 ECKeyPair keyPair = Curve.generateKeyPair();
194 byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
195 SignedPreKeyRecord record = new SignedPreKeyRecord(nextSignedPreKeyId, System.currentTimeMillis(), keyPair, signature);
196
197 axolotlStore.storeSignedPreKey(nextSignedPreKeyId, record);
198 nextSignedPreKeyId = (nextSignedPreKeyId + 1) % Medium.MAX_VALUE;
199
200 return record;
201 } catch (InvalidKeyException e) {
202 throw new AssertionError(e);
203 }
204 }
205
206 public void verifyAccount(String verificationCode) throws IOException {
207 verificationCode = verificationCode.replace("-", "");
208 signalingKey = Util.getSecret(52);
209 accountManager.verifyAccount(verificationCode, signalingKey, false, axolotlStore.getLocalRegistrationId());
210
211 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
212 registered = true;
213
214 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
215
216 PreKeyRecord lastResortKey = generateLastResortPreKey();
217
218 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(axolotlStore.getIdentityKeyPair());
219
220 accountManager.setPreKeys(axolotlStore.getIdentityKeyPair().getPublicKey(), lastResortKey, signedPreKeyRecord, oneTimePreKeys);
221 }
222
223 public void sendMessage(List<TextSecureAddress> recipients, TextSecureDataMessage message)
224 throws IOException, EncapsulatedExceptions {
225 TextSecureMessageSender messageSender = new TextSecureMessageSender(URL, TRUST_STORE, username, password,
226 axolotlStore, Optional.<TextSecureMessageSender.EventListener>absent());
227 messageSender.sendMessage(recipients, message);
228 }
229
230 public TextSecureContent decryptMessage(TextSecureEnvelope envelope) {
231 TextSecureCipher cipher = new TextSecureCipher(new TextSecureAddress(username), axolotlStore);
232 try {
233 return cipher.decrypt(envelope);
234 } catch (Exception e) {
235 // TODO handle all exceptions
236 e.printStackTrace();
237 return null;
238 }
239 }
240
241 public void handleEndSession(String source) {
242 axolotlStore.deleteAllSessions(source);
243 }
244
245 public interface ReceiveMessageHandler {
246 void handleMessage(TextSecureEnvelope envelope);
247 }
248
249 public void receiveMessages(int timeoutSeconds, boolean returnOnTimeout, ReceiveMessageHandler handler) throws IOException {
250 TextSecureMessageReceiver messageReceiver = new TextSecureMessageReceiver(URL, TRUST_STORE, username, password, signalingKey);
251 TextSecureMessagePipe messagePipe = null;
252
253 try {
254 messagePipe = messageReceiver.createMessagePipe();
255
256 while (true) {
257 TextSecureEnvelope envelope;
258 try {
259 envelope = messagePipe.read(timeoutSeconds, TimeUnit.SECONDS);
260 handler.handleMessage(envelope);
261 } catch (TimeoutException e) {
262 if (returnOnTimeout)
263 return;
264 } catch (InvalidVersionException e) {
265 System.out.println("Ignoring error: " + e.getMessage());
266 }
267 save();
268 }
269 } finally {
270 if (messagePipe != null)
271 messagePipe.shutdown();
272 }
273 }
274
275 public String canonicalizeNumber(String number) throws InvalidNumberException {
276 String localNumber = username;
277 return PhoneNumberFormatter.formatNumber(number, localNumber);
278 }
279
280 protected TextSecureAddress getPushAddress(String number) throws InvalidNumberException {
281 String e164number = canonicalizeNumber(number);
282 return new TextSecureAddress(e164number);
283 }
284 }