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
.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
;
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";
56 private String username
;
57 private String password
;
58 private String signalingKey
;
59 private int preKeyIdOffset
;
60 private int nextSignedPreKeyId
;
62 private boolean registered
= false;
64 private JsonAxolotlStore axolotlStore
;
65 TextSecureAccountManager accountManager
;
67 public Manager(String username
) {
68 this.username
= username
;
71 private String
getFileName() {
72 String path
= settingsPath
+ "/data";
73 new File(path
).mkdirs();
74 return path
+ "/" + username
;
77 public boolean userExists() {
78 File f
= new File(getFileName());
79 if (!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
);
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());
130 public void createNewIdentity() {
131 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
132 int registrationId
= KeyHelper
.generateRegistrationId(false);
133 axolotlStore
= new JsonAxolotlStore(identityKey
, registrationId
);
137 public boolean isRegistered() {
141 public void register(boolean voiceVerication
) throws IOException
{
142 password
= Util
.getSecret(18);
144 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
);
147 accountManager
.requestVoiceVerificationCode();
149 accountManager
.requestSmsVerificationCode();
154 private static final int BATCH_SIZE
= 100;
156 private List
<PreKeyRecord
> generatePreKeys() {
157 List
<PreKeyRecord
> records
= new LinkedList
<>();
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
);
164 axolotlStore
.storePreKey(preKeyId
, record);
168 preKeyIdOffset
= (preKeyIdOffset
+ BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
172 private PreKeyRecord
generateLastResortPreKey() {
173 if (axolotlStore
.containsPreKey(Medium
.MAX_VALUE
)) {
175 return axolotlStore
.loadPreKey(Medium
.MAX_VALUE
);
176 } catch (InvalidKeyIdException e
) {
177 axolotlStore
.removePreKey(Medium
.MAX_VALUE
);
181 ECKeyPair keyPair
= Curve
.generateKeyPair();
182 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
184 axolotlStore
.storePreKey(Medium
.MAX_VALUE
, record);
189 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
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
);
195 axolotlStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
196 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
199 } catch (InvalidKeyException e
) {
200 throw new AssertionError(e
);
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());
209 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
212 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
214 PreKeyRecord lastResortKey
= generateLastResortPreKey();
216 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(axolotlStore
.getIdentityKeyPair());
218 accountManager
.setPreKeys(axolotlStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
221 public TextSecureMessageSender
getMessageSender() {
222 return new TextSecureMessageSender(URL
, TRUST_STORE
, username
, password
,
223 axolotlStore
, Optional
.<TextSecureMessageSender
.EventListener
>absent());
226 public TextSecureContent
decryptMessage(TextSecureEnvelope envelope
) {
227 TextSecureCipher cipher
= new TextSecureCipher(new TextSecureAddress(username
), axolotlStore
);
229 return cipher
.decrypt(envelope
);
230 } catch (Exception e
) {
231 // TODO handle all exceptions
237 public void handleEndSession(String source
) {
238 axolotlStore
.deleteAllSessions(source
);
241 public interface ReceiveMessageHandler
{
242 void handleMessage(TextSecureEnvelope envelope
);
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;
250 messagePipe
= messageReceiver
.createMessagePipe();
253 TextSecureEnvelope envelope
;
255 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
256 handler
.handleMessage(envelope
);
257 } catch (TimeoutException e
) {
260 } catch (InvalidVersionException e
) {
261 System
.out
.println("Ignoring error: " + e
.getMessage());
266 if (messagePipe
!= null)
267 messagePipe
.shutdown();
271 public String
canonicalizeNumber(String number
) throws InvalidNumberException
{
272 String localNumber
= username
;
273 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
276 protected TextSecureAddress
getPushAddress(String number
) throws InvalidNumberException
{
277 String e164number
= canonicalizeNumber(number
);
278 return new TextSecureAddress(e164number
);