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
;
50 public class Manager
{
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 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 if (!f
.exists() || f
.isDirectory()) {
86 public boolean userHasKeys() {
87 return axolotlStore
!= null;
90 public void load() throws IOException
, InvalidKeyException
{
91 JSONObject
in = new JSONObject(IOUtils
.toString(new FileInputStream(getFileName())));
92 username
= in.getString("username");
93 password
= in.getString("password");
94 if (in.has("signalingKey")) {
95 signalingKey
= in.getString("signalingKey");
97 if (in.has("preKeyIdOffset")) {
98 preKeyIdOffset
= in.getInt("preKeyIdOffset");
102 if (in.has("nextSignedPreKeyId")) {
103 nextSignedPreKeyId
= in.getInt("nextSignedPreKeyId");
105 nextSignedPreKeyId
= 0;
107 axolotlStore
= new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
108 registered
= in.getBoolean("registered");
109 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
);
113 String out
= new JSONObject().put("username", username
)
114 .put("password", password
)
115 .put("signalingKey", signalingKey
)
116 .put("preKeyIdOffset", preKeyIdOffset
)
117 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
118 .put("axolotlStore", axolotlStore
.getJson())
119 .put("registered", registered
).toString();
121 OutputStreamWriter writer
= new OutputStreamWriter(new FileOutputStream(getFileName()));
125 } catch (Exception e
) {
126 System
.out
.println("Saving file error: " + e
.getMessage());
131 public void createNewIdentity() {
132 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
133 int registrationId
= KeyHelper
.generateRegistrationId(false);
134 axolotlStore
= new JsonAxolotlStore(identityKey
, registrationId
);
138 public boolean isRegistered() {
142 public void register(boolean voiceVerication
) throws IOException
{
143 password
= Util
.getSecret(18);
145 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
);
148 accountManager
.requestVoiceVerificationCode();
150 accountManager
.requestSmsVerificationCode();
155 private static final int BATCH_SIZE
= 100;
157 private List
<PreKeyRecord
> generatePreKeys() {
158 List
<PreKeyRecord
> records
= new LinkedList
<>();
160 for (int i
= 0; i
< BATCH_SIZE
; i
++) {
161 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
162 ECKeyPair keyPair
= Curve
.generateKeyPair();
163 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
165 axolotlStore
.storePreKey(preKeyId
, record);
169 preKeyIdOffset
= (preKeyIdOffset
+ BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
173 private PreKeyRecord
generateLastResortPreKey() {
174 if (axolotlStore
.containsPreKey(Medium
.MAX_VALUE
)) {
176 return axolotlStore
.loadPreKey(Medium
.MAX_VALUE
);
177 } catch (InvalidKeyIdException e
) {
178 axolotlStore
.removePreKey(Medium
.MAX_VALUE
);
182 ECKeyPair keyPair
= Curve
.generateKeyPair();
183 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
185 axolotlStore
.storePreKey(Medium
.MAX_VALUE
, record);
190 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
192 ECKeyPair keyPair
= Curve
.generateKeyPair();
193 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
194 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
196 axolotlStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
197 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
200 } catch (InvalidKeyException e
) {
201 throw new AssertionError(e
);
205 public void verifyAccount(String verificationCode
) throws IOException
{
206 verificationCode
= verificationCode
.replace("-", "");
207 signalingKey
= Util
.getSecret(52);
208 accountManager
.verifyAccount(verificationCode
, signalingKey
, false, axolotlStore
.getLocalRegistrationId());
210 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
213 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
215 PreKeyRecord lastResortKey
= generateLastResortPreKey();
217 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(axolotlStore
.getIdentityKeyPair());
219 accountManager
.setPreKeys(axolotlStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
222 public void sendMessage(List
<TextSecureAddress
> recipients
, TextSecureDataMessage message
)
223 throws IOException
, EncapsulatedExceptions
{
224 TextSecureMessageSender messageSender
= new TextSecureMessageSender(URL
, TRUST_STORE
, username
, password
,
225 axolotlStore
, Optional
.<TextSecureMessageSender
.EventListener
>absent());
226 messageSender
.sendMessage(recipients
, message
);
229 public TextSecureContent
decryptMessage(TextSecureEnvelope envelope
) {
230 TextSecureCipher cipher
= new TextSecureCipher(new TextSecureAddress(username
), axolotlStore
);
232 return cipher
.decrypt(envelope
);
233 } catch (Exception e
) {
234 // TODO handle all exceptions
240 public void handleEndSession(String source
) {
241 axolotlStore
.deleteAllSessions(source
);
244 public interface ReceiveMessageHandler
{
245 void handleMessage(TextSecureEnvelope envelope
);
248 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
249 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
);
250 TextSecureMessagePipe messagePipe
= null;
253 messagePipe
= messageReceiver
.createMessagePipe();
256 TextSecureEnvelope envelope
;
258 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
259 handler
.handleMessage(envelope
);
260 } catch (TimeoutException e
) {
263 } catch (InvalidVersionException e
) {
264 System
.out
.println("Ignoring error: " + e
.getMessage());
269 if (messagePipe
!= null)
270 messagePipe
.shutdown();
274 public File
retrieveAttachment(TextSecureAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
275 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
);
277 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
278 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
280 new File(attachmentsPath
).mkdirs();
281 File outputFile
= new File(attachmentsPath
+ "/" + pointer
.getId());
282 OutputStream output
= null;
284 output
= new FileOutputStream(outputFile
);
285 byte[] buffer
= new byte[4096];
288 while ((read
= input
.read(buffer
)) != -1) {
289 output
.write(buffer
, 0, read
);
291 } catch (FileNotFoundException e
) {
295 if (output
!= null) {
303 public String
canonicalizeNumber(String number
) throws InvalidNumberException
{
304 String localNumber
= username
;
305 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
308 protected TextSecureAddress
getPushAddress(String number
) throws InvalidNumberException
{
309 String e164number
= canonicalizeNumber(number
);
310 return new TextSecureAddress(e164number
);