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 USER_AGENT
= "textsecure-cli";
56 private final static String settingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
57 private final static String dataPath
= settingsPath
+ "/data";
58 private final static String attachmentsPath
= settingsPath
+ "/attachments";
60 private String username
;
61 private String password
;
62 private String signalingKey
;
63 private int preKeyIdOffset
;
64 private int nextSignedPreKeyId
;
66 private boolean registered
= false;
68 private JsonAxolotlStore axolotlStore
;
69 private TextSecureAccountManager accountManager
;
71 public Manager(String username
) {
72 this.username
= username
;
75 public String
getFileName() {
76 new File(dataPath
).mkdirs();
77 return dataPath
+ "/" + username
;
80 public boolean userExists() {
81 File f
= new File(getFileName());
82 return !(!f
.exists() || f
.isDirectory());
85 public boolean userHasKeys() {
86 return axolotlStore
!= null;
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");
96 if (in.has("preKeyIdOffset")) {
97 preKeyIdOffset
= in.getInt("preKeyIdOffset");
101 if (in.has("nextSignedPreKeyId")) {
102 nextSignedPreKeyId
= in.getInt("nextSignedPreKeyId");
104 nextSignedPreKeyId
= 0;
106 axolotlStore
= new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
107 registered
= in.getBoolean("registered");
108 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
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();
120 OutputStreamWriter writer
= new OutputStreamWriter(new FileOutputStream(getFileName()));
124 } catch (Exception e
) {
125 System
.out
.println("Saving file error: " + e
.getMessage());
129 public void createNewIdentity() {
130 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
131 int registrationId
= KeyHelper
.generateRegistrationId(false);
132 axolotlStore
= new JsonAxolotlStore(identityKey
, registrationId
);
136 public boolean isRegistered() {
140 public void register(boolean voiceVerication
) throws IOException
{
141 password
= Util
.getSecret(18);
143 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
146 accountManager
.requestVoiceVerificationCode();
148 accountManager
.requestSmsVerificationCode();
153 private static final int BATCH_SIZE
= 100;
155 private List
<PreKeyRecord
> generatePreKeys() {
156 List
<PreKeyRecord
> records
= new LinkedList
<>();
158 for (int i
= 0; i
< BATCH_SIZE
; i
++) {
159 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
160 ECKeyPair keyPair
= Curve
.generateKeyPair();
161 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
163 axolotlStore
.storePreKey(preKeyId
, record);
167 preKeyIdOffset
= (preKeyIdOffset
+ BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
171 private PreKeyRecord
generateLastResortPreKey() {
172 if (axolotlStore
.containsPreKey(Medium
.MAX_VALUE
)) {
174 return axolotlStore
.loadPreKey(Medium
.MAX_VALUE
);
175 } catch (InvalidKeyIdException e
) {
176 axolotlStore
.removePreKey(Medium
.MAX_VALUE
);
180 ECKeyPair keyPair
= Curve
.generateKeyPair();
181 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
183 axolotlStore
.storePreKey(Medium
.MAX_VALUE
, record);
188 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
190 ECKeyPair keyPair
= Curve
.generateKeyPair();
191 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
192 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
194 axolotlStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
195 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
198 } catch (InvalidKeyException e
) {
199 throw new AssertionError(e
);
203 public void verifyAccount(String verificationCode
) throws IOException
{
204 verificationCode
= verificationCode
.replace("-", "");
205 signalingKey
= Util
.getSecret(52);
206 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, axolotlStore
.getLocalRegistrationId());
208 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
211 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
213 PreKeyRecord lastResortKey
= generateLastResortPreKey();
215 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(axolotlStore
.getIdentityKeyPair());
217 accountManager
.setPreKeys(axolotlStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
220 public void sendMessage(List
<TextSecureAddress
> recipients
, TextSecureDataMessage message
)
221 throws IOException
, EncapsulatedExceptions
{
222 TextSecureMessageSender messageSender
= new TextSecureMessageSender(URL
, TRUST_STORE
, username
, password
,
223 axolotlStore
, USER_AGENT
, Optional
.<TextSecureMessageSender
.EventListener
>absent());
224 messageSender
.sendMessage(recipients
, message
);
227 public TextSecureContent
decryptMessage(TextSecureEnvelope envelope
) {
228 TextSecureCipher cipher
= new TextSecureCipher(new TextSecureAddress(username
), axolotlStore
);
230 return cipher
.decrypt(envelope
);
231 } catch (Exception e
) {
232 // TODO handle all exceptions
238 public void handleEndSession(String source
) {
239 axolotlStore
.deleteAllSessions(source
);
242 public interface ReceiveMessageHandler
{
243 void handleMessage(TextSecureEnvelope envelope
);
246 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
247 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
, USER_AGENT
);
248 TextSecureMessagePipe messagePipe
= null;
251 messagePipe
= messageReceiver
.createMessagePipe();
254 TextSecureEnvelope envelope
;
256 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
257 handler
.handleMessage(envelope
);
258 } catch (TimeoutException e
) {
261 } catch (InvalidVersionException e
) {
262 System
.out
.println("Ignoring error: " + e
.getMessage());
267 if (messagePipe
!= null)
268 messagePipe
.shutdown();
272 public File
retrieveAttachment(TextSecureAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
273 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
, USER_AGENT
);
275 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
276 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
278 new File(attachmentsPath
).mkdirs();
279 File outputFile
= new File(attachmentsPath
+ "/" + pointer
.getId());
280 OutputStream output
= null;
282 output
= new FileOutputStream(outputFile
);
283 byte[] buffer
= new byte[4096];
286 while ((read
= input
.read(buffer
)) != -1) {
287 output
.write(buffer
, 0, read
);
289 } catch (FileNotFoundException e
) {
293 if (output
!= null) {
301 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
302 String localNumber
= username
;
303 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
306 TextSecureAddress
getPushAddress(String number
) throws InvalidNumberException
{
307 String e164number
= canonicalizeNumber(number
);
308 return new TextSecureAddress(e164number
);