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