2 * Copyright (C) 2015 AsamK
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.
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.
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/>.
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
;
47 import java
.util
.LinkedList
;
48 import java
.util
.List
;
49 import java
.util
.concurrent
.TimeUnit
;
50 import java
.util
.concurrent
.TimeoutException
;
52 public class Manager
{
53 private final static String URL
= "https://textsecure-service.whispersystems.org";
54 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
56 private final static String settingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
58 private String username
;
59 private String password
;
60 private String signalingKey
;
61 private int preKeyIdOffset
;
62 private int nextSignedPreKeyId
;
64 private boolean registered
= false;
66 private JsonAxolotlStore axolotlStore
;
67 TextSecureAccountManager accountManager
;
69 public Manager(String username
) {
70 this.username
= username
;
73 public String
getFileName() {
74 String path
= settingsPath
+ "/data";
75 new File(path
).mkdirs();
76 return path
+ "/" + username
;
79 public boolean userExists() {
80 File f
= new File(getFileName());
81 if (!f
.exists() || f
.isDirectory()) {
87 public boolean userHasKeys() {
88 return axolotlStore
!= null;
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");
98 if (in.has("preKeyIdOffset")) {
99 preKeyIdOffset
= in.getInt("preKeyIdOffset");
103 if (in.has("nextSignedPreKeyId")) {
104 nextSignedPreKeyId
= in.getInt("nextSignedPreKeyId");
106 nextSignedPreKeyId
= 0;
108 axolotlStore
= new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
109 registered
= in.getBoolean("registered");
110 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
);
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();
122 OutputStreamWriter writer
= new OutputStreamWriter(new FileOutputStream(getFileName()));
126 } catch (Exception e
) {
127 System
.out
.println("Saving file error: " + e
.getMessage());
132 public void createNewIdentity() {
133 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
134 int registrationId
= KeyHelper
.generateRegistrationId(false);
135 axolotlStore
= new JsonAxolotlStore(identityKey
, registrationId
);
139 public boolean isRegistered() {
143 public void register(boolean voiceVerication
) throws IOException
{
144 password
= Util
.getSecret(18);
146 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
);
149 accountManager
.requestVoiceVerificationCode();
151 accountManager
.requestSmsVerificationCode();
156 private static final int BATCH_SIZE
= 100;
158 private List
<PreKeyRecord
> generatePreKeys() {
159 List
<PreKeyRecord
> records
= new LinkedList
<>();
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
);
166 axolotlStore
.storePreKey(preKeyId
, record);
170 preKeyIdOffset
= (preKeyIdOffset
+ BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
174 private PreKeyRecord
generateLastResortPreKey() {
175 if (axolotlStore
.containsPreKey(Medium
.MAX_VALUE
)) {
177 return axolotlStore
.loadPreKey(Medium
.MAX_VALUE
);
178 } catch (InvalidKeyIdException e
) {
179 axolotlStore
.removePreKey(Medium
.MAX_VALUE
);
183 ECKeyPair keyPair
= Curve
.generateKeyPair();
184 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
186 axolotlStore
.storePreKey(Medium
.MAX_VALUE
, record);
191 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
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
);
197 axolotlStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
198 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
201 } catch (InvalidKeyException e
) {
202 throw new AssertionError(e
);
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());
211 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
214 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
216 PreKeyRecord lastResortKey
= generateLastResortPreKey();
218 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(axolotlStore
.getIdentityKeyPair());
220 accountManager
.setPreKeys(axolotlStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
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
);
230 public TextSecureContent
decryptMessage(TextSecureEnvelope envelope
) {
231 TextSecureCipher cipher
= new TextSecureCipher(new TextSecureAddress(username
), axolotlStore
);
233 return cipher
.decrypt(envelope
);
234 } catch (Exception e
) {
235 // TODO handle all exceptions
241 public void handleEndSession(String source
) {
242 axolotlStore
.deleteAllSessions(source
);
245 public interface ReceiveMessageHandler
{
246 void handleMessage(TextSecureEnvelope envelope
);
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;
254 messagePipe
= messageReceiver
.createMessagePipe();
257 TextSecureEnvelope envelope
;
259 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
260 handler
.handleMessage(envelope
);
261 } catch (TimeoutException e
) {
264 } catch (InvalidVersionException e
) {
265 System
.out
.println("Ignoring error: " + e
.getMessage());
270 if (messagePipe
!= null)
271 messagePipe
.shutdown();
275 public String
canonicalizeNumber(String number
) throws InvalidNumberException
{
276 String localNumber
= username
;
277 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
280 protected TextSecureAddress
getPushAddress(String number
) throws InvalidNumberException
{
281 String e164number
= canonicalizeNumber(number
);
282 return new TextSecureAddress(e164number
);