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
.*;
40 import org
.whispersystems
.textsecure
.api
.push
.TextSecureAddress
;
41 import org
.whispersystems
.textsecure
.api
.push
.TrustStore
;
42 import org
.whispersystems
.textsecure
.api
.push
.exceptions
.EncapsulatedExceptions
;
43 import org
.whispersystems
.textsecure
.api
.util
.InvalidNumberException
;
44 import org
.whispersystems
.textsecure
.api
.util
.PhoneNumberFormatter
;
47 import java
.util
.ArrayList
;
48 import java
.util
.LinkedList
;
49 import java
.util
.List
;
50 import java
.util
.concurrent
.TimeUnit
;
51 import java
.util
.concurrent
.TimeoutException
;
54 private final static String URL
= "https://textsecure-service.whispersystems.org";
55 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
57 public final static String PROJECT_NAME
= Manager
.class.getPackage().getImplementationTitle();
58 public final static String PROJECT_VERSION
= Manager
.class.getPackage().getImplementationVersion();
59 private final static String USER_AGENT
= PROJECT_NAME
+ " " + PROJECT_VERSION
;
61 private final static String settingsPath
= System
.getProperty("user.home") + "/.config/textsecure";
62 private final static String dataPath
= settingsPath
+ "/data";
63 private final static String attachmentsPath
= settingsPath
+ "/attachments";
65 private final ObjectMapper jsonProcessot
= new ObjectMapper();
66 private String username
;
67 private String password
;
68 private String signalingKey
;
69 private int preKeyIdOffset
;
70 private int nextSignedPreKeyId
;
72 private boolean registered
= false;
74 private JsonAxolotlStore axolotlStore
;
75 private TextSecureAccountManager accountManager
;
76 private JsonGroupStore groupStore
;
78 public Manager(String username
) {
79 this.username
= username
;
80 jsonProcessot
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
81 jsonProcessot
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
82 jsonProcessot
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
83 jsonProcessot
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
86 public String
getFileName() {
87 new File(dataPath
).mkdirs();
88 return dataPath
+ "/" + username
;
91 public boolean userExists() {
92 File f
= new File(getFileName());
93 return !(!f
.exists() || f
.isDirectory());
96 public boolean userHasKeys() {
97 return axolotlStore
!= null;
100 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
101 JsonNode node
= parent
.get(name
);
103 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
109 public void load() throws IOException
, InvalidKeyException
{
110 JsonNode rootNode
= jsonProcessot
.readTree(new File(getFileName()));
112 username
= getNotNullNode(rootNode
, "username").asText();
113 password
= getNotNullNode(rootNode
, "password").asText();
114 if (rootNode
.has("signalingKey")) {
115 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
117 if (rootNode
.has("preKeyIdOffset")) {
118 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
122 if (rootNode
.has("nextSignedPreKeyId")) {
123 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
125 nextSignedPreKeyId
= 0;
127 axolotlStore
= jsonProcessot
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonAxolotlStore
.class); //new JsonAxolotlStore(in.getJSONObject("axolotlStore"));
128 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
129 JsonNode groupStoreNode
= rootNode
.get("groupStore");
130 if (groupStoreNode
!= null) {
131 groupStore
= jsonProcessot
.convertValue(groupStoreNode
, JsonGroupStore
.class);
133 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
137 ObjectNode rootNode
= jsonProcessot
.createObjectNode();
138 rootNode
.put("username", username
)
139 .put("password", password
)
140 .put("signalingKey", signalingKey
)
141 .put("preKeyIdOffset", preKeyIdOffset
)
142 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
143 .put("registered", registered
)
144 .putPOJO("axolotlStore", axolotlStore
)
145 .putPOJO("groupStore", groupStore
)
148 jsonProcessot
.writeValue(new File(getFileName()), rootNode
);
149 } catch (Exception e
) {
150 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
154 public void createNewIdentity() {
155 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
156 int registrationId
= KeyHelper
.generateRegistrationId(false);
157 axolotlStore
= new JsonAxolotlStore(identityKey
, registrationId
);
158 groupStore
= new JsonGroupStore();
162 public boolean isRegistered() {
166 public void register(boolean voiceVerication
) throws IOException
{
167 password
= Util
.getSecret(18);
169 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
172 accountManager
.requestVoiceVerificationCode();
174 accountManager
.requestSmsVerificationCode();
179 private static final int BATCH_SIZE
= 100;
181 private List
<PreKeyRecord
> generatePreKeys() {
182 List
<PreKeyRecord
> records
= new LinkedList
<>();
184 for (int i
= 0; i
< BATCH_SIZE
; i
++) {
185 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
186 ECKeyPair keyPair
= Curve
.generateKeyPair();
187 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
189 axolotlStore
.storePreKey(preKeyId
, record);
193 preKeyIdOffset
= (preKeyIdOffset
+ BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
197 private PreKeyRecord
generateLastResortPreKey() {
198 if (axolotlStore
.containsPreKey(Medium
.MAX_VALUE
)) {
200 return axolotlStore
.loadPreKey(Medium
.MAX_VALUE
);
201 } catch (InvalidKeyIdException e
) {
202 axolotlStore
.removePreKey(Medium
.MAX_VALUE
);
206 ECKeyPair keyPair
= Curve
.generateKeyPair();
207 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
209 axolotlStore
.storePreKey(Medium
.MAX_VALUE
, record);
214 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
216 ECKeyPair keyPair
= Curve
.generateKeyPair();
217 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
218 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
220 axolotlStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
221 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
224 } catch (InvalidKeyException e
) {
225 throw new AssertionError(e
);
229 public void verifyAccount(String verificationCode
) throws IOException
{
230 verificationCode
= verificationCode
.replace("-", "");
231 signalingKey
= Util
.getSecret(52);
232 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, axolotlStore
.getLocalRegistrationId(), false);
234 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
237 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
239 PreKeyRecord lastResortKey
= generateLastResortPreKey();
241 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(axolotlStore
.getIdentityKeyPair());
243 accountManager
.setPreKeys(axolotlStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
246 public void sendMessage(List
<String
> recipients
, TextSecureDataMessage message
)
247 throws IOException
, EncapsulatedExceptions
{
248 TextSecureMessageSender messageSender
= new TextSecureMessageSender(URL
, TRUST_STORE
, username
, password
,
249 axolotlStore
, USER_AGENT
, Optional
.<TextSecureMessageSender
.EventListener
>absent());
251 List
<TextSecureAddress
> recipientsTS
= new ArrayList
<>(recipients
.size());
252 for (String recipient
: recipients
) {
254 recipientsTS
.add(getPushAddress(recipient
));
255 } catch (InvalidNumberException e
) {
256 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
257 System
.err
.println("Aborting sending.");
262 messageSender
.sendMessage(recipientsTS
, message
);
264 if (message
.isEndSession()) {
265 for (TextSecureAddress recipient
: recipientsTS
) {
266 handleEndSession(recipient
.getNumber());
271 private TextSecureContent
decryptMessage(TextSecureEnvelope envelope
) {
272 TextSecureCipher cipher
= new TextSecureCipher(new TextSecureAddress(username
), axolotlStore
);
274 return cipher
.decrypt(envelope
);
275 } catch (Exception e
) {
276 // TODO handle all exceptions
282 private void handleEndSession(String source
) {
283 axolotlStore
.deleteAllSessions(source
);
286 public interface ReceiveMessageHandler
{
287 void handleMessage(TextSecureEnvelope envelope
, TextSecureContent decryptedContent
, GroupInfo group
);
290 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
291 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
, USER_AGENT
);
292 TextSecureMessagePipe messagePipe
= null;
295 messagePipe
= messageReceiver
.createMessagePipe();
298 TextSecureEnvelope envelope
;
299 TextSecureContent content
= null;
300 GroupInfo group
= null;
302 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
303 if (!envelope
.isReceipt()) {
304 content
= decryptMessage(envelope
);
305 if (content
!= null) {
306 if (content
.getDataMessage().isPresent()) {
307 TextSecureDataMessage message
= content
.getDataMessage().get();
308 if (message
.getGroupInfo().isPresent()) {
309 TextSecureGroup groupInfo
= message
.getGroupInfo().get();
310 switch (groupInfo
.getType()) {
313 if (groupInfo
.getAvatar().isPresent()) {
314 TextSecureAttachment avatar
= groupInfo
.getAvatar().get();
315 if (avatar
.isPointer()) {
316 avatarId
= avatar
.asPointer().getId();
318 retrieveAttachment(avatar
.asPointer());
319 } catch (IOException
| InvalidMessageException e
) {
320 System
.err
.println("Failed to retrieve group avatar (" + avatarId
+ "): " + e
.getMessage());
325 group
= new GroupInfo(groupInfo
.getGroupId(), groupInfo
.getName().get(), groupInfo
.getMembers().get(), avatarId
);
326 groupStore
.updateGroup(group
);
329 group
= groupStore
.getGroup(groupInfo
.getGroupId());
332 group
= groupStore
.getGroup(groupInfo
.getGroupId());
334 group
.members
.remove(envelope
.getSource());
339 if (message
.isEndSession()) {
340 handleEndSession(envelope
.getSource());
342 if (message
.getAttachments().isPresent()) {
343 for (TextSecureAttachment attachment
: message
.getAttachments().get()) {
344 if (attachment
.isPointer()) {
346 retrieveAttachment(attachment
.asPointer());
347 } catch (IOException
| InvalidMessageException e
) {
348 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
356 handler
.handleMessage(envelope
, content
, group
);
357 } catch (TimeoutException e
) {
360 } catch (InvalidVersionException e
) {
361 System
.err
.println("Ignoring error: " + e
.getMessage());
366 if (messagePipe
!= null)
367 messagePipe
.shutdown();
371 public File
getAttachmentFile(long attachmentId
) {
372 return new File(attachmentsPath
+ "/" + attachmentId
);
375 private File
retrieveAttachment(TextSecureAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
376 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
, USER_AGENT
);
378 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
379 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
381 new File(attachmentsPath
).mkdirs();
382 File outputFile
= getAttachmentFile(pointer
.getId());
383 OutputStream output
= null;
385 output
= new FileOutputStream(outputFile
);
386 byte[] buffer
= new byte[4096];
389 while ((read
= input
.read(buffer
)) != -1) {
390 output
.write(buffer
, 0, read
);
392 } catch (FileNotFoundException e
) {
396 if (output
!= null) {
400 if (!tmpFile
.delete()) {
401 System
.err
.println("Failed to delete temp file: " + tmpFile
);
404 if (pointer
.getPreview().isPresent()) {
405 File previewFile
= new File(outputFile
+ ".preview");
407 output
= new FileOutputStream(previewFile
);
408 byte[] preview
= pointer
.getPreview().get();
409 output
.write(preview
, 0, preview
.length
);
410 } catch (FileNotFoundException e
) {
414 if (output
!= null) {
422 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
423 String localNumber
= username
;
424 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
427 private TextSecureAddress
getPushAddress(String number
) throws InvalidNumberException
{
428 String e164number
= canonicalizeNumber(number
);
429 return new TextSecureAddress(e164number
);
432 public GroupInfo
getGroupInfo(byte[] groupId
) {
433 return groupStore
.getGroup(groupId
);