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 com
.fasterxml
.jackson
.annotation
.JsonAutoDetect
;
20 import com
.fasterxml
.jackson
.annotation
.PropertyAccessor
;
21 import com
.fasterxml
.jackson
.databind
.DeserializationFeature
;
22 import com
.fasterxml
.jackson
.databind
.JsonNode
;
23 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
24 import com
.fasterxml
.jackson
.databind
.SerializationFeature
;
25 import com
.fasterxml
.jackson
.databind
.node
.ObjectNode
;
26 import org
.whispersystems
.libaxolotl
.*;
27 import org
.whispersystems
.libaxolotl
.ecc
.Curve
;
28 import org
.whispersystems
.libaxolotl
.ecc
.ECKeyPair
;
29 import org
.whispersystems
.libaxolotl
.state
.PreKeyRecord
;
30 import org
.whispersystems
.libaxolotl
.state
.SignedPreKeyRecord
;
31 import org
.whispersystems
.libaxolotl
.util
.KeyHelper
;
32 import org
.whispersystems
.libaxolotl
.util
.Medium
;
33 import org
.whispersystems
.libaxolotl
.util
.guava
.Optional
;
34 import org
.whispersystems
.textsecure
.api
.TextSecureAccountManager
;
35 import org
.whispersystems
.textsecure
.api
.TextSecureMessagePipe
;
36 import org
.whispersystems
.textsecure
.api
.TextSecureMessageReceiver
;
37 import org
.whispersystems
.textsecure
.api
.TextSecureMessageSender
;
38 import org
.whispersystems
.textsecure
.api
.crypto
.TextSecureCipher
;
39 import org
.whispersystems
.textsecure
.api
.messages
.TextSecureAttachmentPointer
;
40 import org
.whispersystems
.textsecure
.api
.messages
.TextSecureContent
;
41 import org
.whispersystems
.textsecure
.api
.messages
.TextSecureDataMessage
;
42 import org
.whispersystems
.textsecure
.api
.messages
.TextSecureEnvelope
;
43 import org
.whispersystems
.textsecure
.api
.push
.TextSecureAddress
;
44 import org
.whispersystems
.textsecure
.api
.push
.TrustStore
;
45 import org
.whispersystems
.textsecure
.api
.push
.exceptions
.EncapsulatedExceptions
;
46 import org
.whispersystems
.textsecure
.api
.util
.InvalidNumberException
;
47 import org
.whispersystems
.textsecure
.api
.util
.PhoneNumberFormatter
;
50 import java
.util
.LinkedList
;
51 import java
.util
.List
;
52 import java
.util
.concurrent
.TimeUnit
;
53 import java
.util
.concurrent
.TimeoutException
;
56 private final static String URL
= "https://textsecure-service.whispersystems.org";
57 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
59 public final static String PROJECT_NAME
= Manager
.class.getPackage().getImplementationTitle();
60 public final static String PROJECT_VERSION
= Manager
.class.getPackage().getImplementationVersion();
61 private final static String USER_AGENT
= PROJECT_NAME
+ " " + PROJECT_VERSION
;
63 private final static String settingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
64 private final static String dataPath
= settingsPath
+ "/data";
65 private final static String attachmentsPath
= settingsPath
+ "/attachments";
67 private final ObjectMapper jsonProcessot
= new ObjectMapper();
68 private String username
;
69 private String password
;
70 private String signalingKey
;
71 private int preKeyIdOffset
;
72 private int nextSignedPreKeyId
;
74 private boolean registered
= false;
76 private JsonAxolotlStore axolotlStore
;
77 private TextSecureAccountManager accountManager
;
79 public Manager(String username
) {
80 this.username
= username
;
81 jsonProcessot
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
82 jsonProcessot
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
83 jsonProcessot
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
84 jsonProcessot
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
87 public String
getFileName() {
88 new File(dataPath
).mkdirs();
89 return dataPath
+ "/" + username
;
92 public boolean userExists() {
93 File f
= new File(getFileName());
94 return !(!f
.exists() || f
.isDirectory());
97 public boolean userHasKeys() {
98 return axolotlStore
!= null;
101 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
102 JsonNode node
= parent
.get(name
);
104 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
111 public void load() throws IOException
, InvalidKeyException
{
112 JsonNode rootNode
= jsonProcessot
.readTree(new File(getFileName()));
114 username
= getNotNullNode(rootNode
, "username").asText();
115 password
= getNotNullNode(rootNode
, "password").asText();
116 if (rootNode
.has("signalingKey")) {
117 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
119 if (rootNode
.has("preKeyIdOffset")) {
120 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
124 if (rootNode
.has("nextSignedPreKeyId")) {
125 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
127 nextSignedPreKeyId
= 0;
129 axolotlStore
= jsonProcessot
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonAxolotlStore
.class); //new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
130 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
131 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
135 ObjectNode rootNode
= jsonProcessot
.createObjectNode();
136 rootNode
.put("username", username
)
137 .put("password", password
)
138 .put("signalingKey", signalingKey
)
139 .put("preKeyIdOffset", preKeyIdOffset
)
140 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
141 .put("registered", registered
)
142 .putPOJO("axolotlStore", axolotlStore
)
145 jsonProcessot
.writeValue(new File(getFileName()), rootNode
);
146 } catch (Exception e
) {
147 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
151 public void createNewIdentity() {
152 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
153 int registrationId
= KeyHelper
.generateRegistrationId(false);
154 axolotlStore
= new JsonAxolotlStore(identityKey
, registrationId
);
158 public boolean isRegistered() {
162 public void register(boolean voiceVerication
) throws IOException
{
163 password
= Util
.getSecret(18);
165 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
168 accountManager
.requestVoiceVerificationCode();
170 accountManager
.requestSmsVerificationCode();
175 private static final int BATCH_SIZE
= 100;
177 private List
<PreKeyRecord
> generatePreKeys() {
178 List
<PreKeyRecord
> records
= new LinkedList
<>();
180 for (int i
= 0; i
< BATCH_SIZE
; i
++) {
181 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
182 ECKeyPair keyPair
= Curve
.generateKeyPair();
183 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
185 axolotlStore
.storePreKey(preKeyId
, record);
189 preKeyIdOffset
= (preKeyIdOffset
+ BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
193 private PreKeyRecord
generateLastResortPreKey() {
194 if (axolotlStore
.containsPreKey(Medium
.MAX_VALUE
)) {
196 return axolotlStore
.loadPreKey(Medium
.MAX_VALUE
);
197 } catch (InvalidKeyIdException e
) {
198 axolotlStore
.removePreKey(Medium
.MAX_VALUE
);
202 ECKeyPair keyPair
= Curve
.generateKeyPair();
203 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
205 axolotlStore
.storePreKey(Medium
.MAX_VALUE
, record);
210 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
212 ECKeyPair keyPair
= Curve
.generateKeyPair();
213 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
214 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
216 axolotlStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
217 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
220 } catch (InvalidKeyException e
) {
221 throw new AssertionError(e
);
225 public void verifyAccount(String verificationCode
) throws IOException
{
226 verificationCode
= verificationCode
.replace("-", "");
227 signalingKey
= Util
.getSecret(52);
228 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, axolotlStore
.getLocalRegistrationId(), false);
230 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
233 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
235 PreKeyRecord lastResortKey
= generateLastResortPreKey();
237 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(axolotlStore
.getIdentityKeyPair());
239 accountManager
.setPreKeys(axolotlStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
242 public void sendMessage(List
<TextSecureAddress
> recipients
, TextSecureDataMessage message
)
243 throws IOException
, EncapsulatedExceptions
{
244 TextSecureMessageSender messageSender
= new TextSecureMessageSender(URL
, TRUST_STORE
, username
, password
,
245 axolotlStore
, USER_AGENT
, Optional
.<TextSecureMessageSender
.EventListener
>absent());
246 messageSender
.sendMessage(recipients
, message
);
249 public TextSecureContent
decryptMessage(TextSecureEnvelope envelope
) {
250 TextSecureCipher cipher
= new TextSecureCipher(new TextSecureAddress(username
), axolotlStore
);
252 return cipher
.decrypt(envelope
);
253 } catch (Exception e
) {
254 // TODO handle all exceptions
260 public void handleEndSession(String source
) {
261 axolotlStore
.deleteAllSessions(source
);
264 public interface ReceiveMessageHandler
{
265 void handleMessage(TextSecureEnvelope envelope
);
268 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
269 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
, USER_AGENT
);
270 TextSecureMessagePipe messagePipe
= null;
273 messagePipe
= messageReceiver
.createMessagePipe();
276 TextSecureEnvelope envelope
;
278 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
279 handler
.handleMessage(envelope
);
280 } catch (TimeoutException e
) {
283 } catch (InvalidVersionException e
) {
284 System
.err
.println("Ignoring error: " + e
.getMessage());
289 if (messagePipe
!= null)
290 messagePipe
.shutdown();
294 public File
retrieveAttachment(TextSecureAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
295 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
, USER_AGENT
);
297 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
298 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
300 new File(attachmentsPath
).mkdirs();
301 File outputFile
= new File(attachmentsPath
+ "/" + pointer
.getId());
302 OutputStream output
= null;
304 output
= new FileOutputStream(outputFile
);
305 byte[] buffer
= new byte[4096];
308 while ((read
= input
.read(buffer
)) != -1) {
309 output
.write(buffer
, 0, read
);
311 } catch (FileNotFoundException e
) {
315 if (output
!= null) {
319 if (!tmpFile
.delete()) {
320 System
.err
.println("Failed to delete temp file: " + tmpFile
);
323 if (pointer
.getPreview().isPresent()) {
324 File previewFile
= new File(outputFile
+ ".preview");
326 output
= new FileOutputStream(previewFile
);
327 byte[] preview
= pointer
.getPreview().get();
328 output
.write(preview
, 0, preview
.length
);
329 } catch (FileNotFoundException e
) {
333 if (output
!= null) {
341 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
342 String localNumber
= username
;
343 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
346 TextSecureAddress
getPushAddress(String number
) throws InvalidNumberException
{
347 String e164number
= canonicalizeNumber(number
);
348 return new TextSecureAddress(e164number
);