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
.*;
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
;
45 import java
.util
.LinkedList
;
46 import java
.util
.List
;
47 import java
.util
.concurrent
.TimeUnit
;
48 import java
.util
.concurrent
.TimeoutException
;
51 private final static String URL
= "https://textsecure-service.whispersystems.org";
52 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
54 private final static String settingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
55 private final static String dataPath
= settingsPath
+ "/data";
56 private final static String attachmentsPath
= settingsPath
+ "/attachments";
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 private TextSecureAccountManager accountManager
;
69 public Manager(String username
) {
70 this.username
= username
;
73 public String
getFileName() {
74 new File(dataPath
).mkdirs();
75 return dataPath
+ "/" + username
;
78 public boolean userExists() {
79 File f
= new File(getFileName());
80 return !(!f
.exists() || f
.isDirectory());
83 public boolean userHasKeys() {
84 return axolotlStore
!= null;
87 public void load() throws IOException
, InvalidKeyException
{
88 JSONObject
in = new JSONObject(IOUtils
.toString(new FileInputStream(getFileName())));
89 username
= in.getString("username");
90 password
= in.getString("password");
91 if (in.has("signalingKey")) {
92 signalingKey
= in.getString("signalingKey");
94 if (in.has("preKeyIdOffset")) {
95 preKeyIdOffset
= in.getInt("preKeyIdOffset");
99 if (in.has("nextSignedPreKeyId")) {
100 nextSignedPreKeyId
= in.getInt("nextSignedPreKeyId");
102 nextSignedPreKeyId
= 0;
104 axolotlStore
= new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
105 registered
= in.getBoolean("registered");
106 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
);
110 String out
= new JSONObject().put("username", username
)
111 .put("password", password
)
112 .put("signalingKey", signalingKey
)
113 .put("preKeyIdOffset", preKeyIdOffset
)
114 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
115 .put("axolotlStore", axolotlStore
.getJson())
116 .put("registered", registered
).toString();
118 OutputStreamWriter writer
= new OutputStreamWriter(new FileOutputStream(getFileName()));
122 } catch (Exception e
) {
123 System
.out
.println("Saving file error: " + e
.getMessage());
127 public void createNewIdentity() {
128 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
129 int registrationId
= KeyHelper
.generateRegistrationId(false);
130 axolotlStore
= new JsonAxolotlStore(identityKey
, registrationId
);
134 public boolean isRegistered() {
138 public void register(boolean voiceVerication
) throws IOException
{
139 password
= Util
.getSecret(18);
141 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
);
144 accountManager
.requestVoiceVerificationCode();
146 accountManager
.requestSmsVerificationCode();
151 private static final int BATCH_SIZE
= 100;
153 private List
<PreKeyRecord
> generatePreKeys() {
154 List
<PreKeyRecord
> records
= new LinkedList
<>();
156 for (int i
= 0; i
< BATCH_SIZE
; i
++) {
157 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
158 ECKeyPair keyPair
= Curve
.generateKeyPair();
159 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
161 axolotlStore
.storePreKey(preKeyId
, record);
165 preKeyIdOffset
= (preKeyIdOffset
+ BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
169 private PreKeyRecord
generateLastResortPreKey() {
170 if (axolotlStore
.containsPreKey(Medium
.MAX_VALUE
)) {
172 return axolotlStore
.loadPreKey(Medium
.MAX_VALUE
);
173 } catch (InvalidKeyIdException e
) {
174 axolotlStore
.removePreKey(Medium
.MAX_VALUE
);
178 ECKeyPair keyPair
= Curve
.generateKeyPair();
179 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
181 axolotlStore
.storePreKey(Medium
.MAX_VALUE
, record);
186 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
188 ECKeyPair keyPair
= Curve
.generateKeyPair();
189 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
190 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
192 axolotlStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
193 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
196 } catch (InvalidKeyException e
) {
197 throw new AssertionError(e
);
201 public void verifyAccount(String verificationCode
) throws IOException
{
202 verificationCode
= verificationCode
.replace("-", "");
203 signalingKey
= Util
.getSecret(52);
204 accountManager
.verifyAccount(verificationCode
, signalingKey
, false, axolotlStore
.getLocalRegistrationId());
206 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
209 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
211 PreKeyRecord lastResortKey
= generateLastResortPreKey();
213 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(axolotlStore
.getIdentityKeyPair());
215 accountManager
.setPreKeys(axolotlStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
218 public void sendMessage(List
<TextSecureAddress
> recipients
, TextSecureDataMessage message
)
219 throws IOException
, EncapsulatedExceptions
{
220 TextSecureMessageSender messageSender
= new TextSecureMessageSender(URL
, TRUST_STORE
, username
, password
,
221 axolotlStore
, Optional
.<TextSecureMessageSender
.EventListener
>absent());
222 messageSender
.sendMessage(recipients
, message
);
225 public TextSecureContent
decryptMessage(TextSecureEnvelope envelope
) {
226 TextSecureCipher cipher
= new TextSecureCipher(new TextSecureAddress(username
), axolotlStore
);
228 return cipher
.decrypt(envelope
);
229 } catch (Exception e
) {
230 // TODO handle all exceptions
236 public void handleEndSession(String source
) {
237 axolotlStore
.deleteAllSessions(source
);
240 public interface ReceiveMessageHandler
{
241 void handleMessage(TextSecureEnvelope envelope
);
244 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
245 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
);
246 TextSecureMessagePipe messagePipe
= null;
249 messagePipe
= messageReceiver
.createMessagePipe();
252 TextSecureEnvelope envelope
;
254 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
255 handler
.handleMessage(envelope
);
256 } catch (TimeoutException e
) {
259 } catch (InvalidVersionException e
) {
260 System
.out
.println("Ignoring error: " + e
.getMessage());
265 if (messagePipe
!= null)
266 messagePipe
.shutdown();
270 public File
retrieveAttachment(TextSecureAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
271 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
);
273 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
274 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
276 new File(attachmentsPath
).mkdirs();
277 File outputFile
= new File(attachmentsPath
+ "/" + pointer
.getId());
278 OutputStream output
= null;
280 output
= new FileOutputStream(outputFile
);
281 byte[] buffer
= new byte[4096];
284 while ((read
= input
.read(buffer
)) != -1) {
285 output
.write(buffer
, 0, read
);
287 } catch (FileNotFoundException e
) {
291 if (output
!= null) {
299 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
300 String localNumber
= username
;
301 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
304 TextSecureAddress
getPushAddress(String number
) throws InvalidNumberException
{
305 String e164number
= canonicalizeNumber(number
);
306 return new TextSecureAddress(e164number
);