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
.nio
.file
.Files
;
48 import java
.nio
.file
.Paths
;
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 if (groupStore
== null) {
134 groupStore
= new JsonGroupStore();
136 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
140 ObjectNode rootNode
= jsonProcessot
.createObjectNode();
141 rootNode
.put("username", username
)
142 .put("password", password
)
143 .put("signalingKey", signalingKey
)
144 .put("preKeyIdOffset", preKeyIdOffset
)
145 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
146 .put("registered", registered
)
147 .putPOJO("axolotlStore", axolotlStore
)
148 .putPOJO("groupStore", groupStore
)
151 jsonProcessot
.writeValue(new File(getFileName()), rootNode
);
152 } catch (Exception e
) {
153 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
157 public void createNewIdentity() {
158 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
159 int registrationId
= KeyHelper
.generateRegistrationId(false);
160 axolotlStore
= new JsonAxolotlStore(identityKey
, registrationId
);
161 groupStore
= new JsonGroupStore();
165 public boolean isRegistered() {
169 public void register(boolean voiceVerication
) throws IOException
{
170 password
= Util
.getSecret(18);
172 accountManager
= new TextSecureAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
175 accountManager
.requestVoiceVerificationCode();
177 accountManager
.requestSmsVerificationCode();
182 private static final int BATCH_SIZE
= 100;
184 private List
<PreKeyRecord
> generatePreKeys() {
185 List
<PreKeyRecord
> records
= new LinkedList
<>();
187 for (int i
= 0; i
< BATCH_SIZE
; i
++) {
188 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
189 ECKeyPair keyPair
= Curve
.generateKeyPair();
190 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
192 axolotlStore
.storePreKey(preKeyId
, record);
196 preKeyIdOffset
= (preKeyIdOffset
+ BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
200 private PreKeyRecord
generateLastResortPreKey() {
201 if (axolotlStore
.containsPreKey(Medium
.MAX_VALUE
)) {
203 return axolotlStore
.loadPreKey(Medium
.MAX_VALUE
);
204 } catch (InvalidKeyIdException e
) {
205 axolotlStore
.removePreKey(Medium
.MAX_VALUE
);
209 ECKeyPair keyPair
= Curve
.generateKeyPair();
210 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
212 axolotlStore
.storePreKey(Medium
.MAX_VALUE
, record);
217 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
219 ECKeyPair keyPair
= Curve
.generateKeyPair();
220 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
221 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
223 axolotlStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
224 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
227 } catch (InvalidKeyException e
) {
228 throw new AssertionError(e
);
232 public void verifyAccount(String verificationCode
) throws IOException
{
233 verificationCode
= verificationCode
.replace("-", "");
234 signalingKey
= Util
.getSecret(52);
235 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, axolotlStore
.getLocalRegistrationId(), false);
237 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
240 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
242 PreKeyRecord lastResortKey
= generateLastResortPreKey();
244 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(axolotlStore
.getIdentityKeyPair());
246 accountManager
.setPreKeys(axolotlStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
250 private static List
<TextSecureAttachment
> getTextSecureAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
251 List
<TextSecureAttachment
> textSecureAttachments
= null;
252 if (attachments
!= null) {
253 textSecureAttachments
= new ArrayList
<>(attachments
.size());
254 for (String attachment
: attachments
) {
256 textSecureAttachments
.add(createAttachment(attachment
));
257 } catch (IOException e
) {
258 throw new AttachmentInvalidException(attachment
, e
);
262 return textSecureAttachments
;
265 private static TextSecureAttachmentStream
createAttachment(String attachment
) throws IOException
{
266 File attachmentFile
= new File(attachment
);
267 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
268 final long attachmentSize
= attachmentFile
.length();
269 String mime
= Files
.probeContentType(Paths
.get(attachment
));
270 return new TextSecureAttachmentStream(attachmentStream
, mime
, attachmentSize
, null);
273 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
275 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
276 final TextSecureDataMessage
.Builder messageBuilder
= TextSecureDataMessage
.newBuilder().withBody(messageText
);
277 if (attachments
!= null) {
278 messageBuilder
.withAttachments(getTextSecureAttachments(attachments
));
280 if (groupId
!= null) {
281 TextSecureGroup group
= TextSecureGroup
.newBuilder(TextSecureGroup
.Type
.DELIVER
)
284 messageBuilder
.asGroupMessage(group
);
286 TextSecureDataMessage message
= messageBuilder
.build();
288 sendMessage(message
, getGroupInfo(groupId
).members
);
291 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
292 TextSecureGroup group
= TextSecureGroup
.newBuilder(TextSecureGroup
.Type
.QUIT
)
296 TextSecureDataMessage message
= TextSecureDataMessage
.newBuilder()
297 .asGroupMessage(group
)
300 sendMessage(message
, getGroupInfo(groupId
).members
);
303 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
305 if (groupId
== null) {
307 g
= new GroupInfo(Util
.getSecretBytes(16));
308 g
.members
.add(getUsername());
310 g
= getGroupInfo(groupId
);
317 if (members
!= null) {
318 for (String member
: members
) {
320 g
.members
.add(canonicalizeNumber(member
));
321 } catch (InvalidNumberException e
) {
322 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
323 System
.err
.println("Aborting…");
329 TextSecureGroup
.Builder group
= TextSecureGroup
.newBuilder(TextSecureGroup
.Type
.UPDATE
)
332 .withMembers(new ArrayList
<>(g
.members
));
334 if (avatarFile
!= null) {
336 group
.withAvatar(createAttachment(avatarFile
));
339 } catch (IOException e
) {
340 throw new AttachmentInvalidException(avatarFile
, e
);
346 TextSecureDataMessage message
= TextSecureDataMessage
.newBuilder()
347 .asGroupMessage(group
.build())
350 sendMessage(message
, g
.members
);
354 public void sendMessage(String messageText
, List
<String
> attachments
,
355 Collection
<String
> recipients
)
356 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
357 final TextSecureDataMessage
.Builder messageBuilder
= TextSecureDataMessage
.newBuilder().withBody(messageText
);
358 if (attachments
!= null) {
359 messageBuilder
.withAttachments(getTextSecureAttachments(attachments
));
361 TextSecureDataMessage message
= messageBuilder
.build();
363 sendMessage(message
, recipients
);
366 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
367 TextSecureDataMessage message
= TextSecureDataMessage
.newBuilder()
368 .asEndSessionMessage()
371 sendMessage(message
, recipients
);
374 private void sendMessage(TextSecureDataMessage message
, Collection
<String
> recipients
)
375 throws IOException
, EncapsulatedExceptions
{
376 TextSecureMessageSender messageSender
= new TextSecureMessageSender(URL
, TRUST_STORE
, username
, password
,
377 axolotlStore
, USER_AGENT
, Optional
.<TextSecureMessageSender
.EventListener
>absent());
379 Set
<TextSecureAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
380 for (String recipient
: recipients
) {
382 recipientsTS
.add(getPushAddress(recipient
));
383 } catch (InvalidNumberException e
) {
384 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
385 System
.err
.println("Aborting sending.");
390 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
392 if (message
.isEndSession()) {
393 for (TextSecureAddress recipient
: recipientsTS
) {
394 handleEndSession(recipient
.getNumber());
399 private TextSecureContent
decryptMessage(TextSecureEnvelope envelope
) {
400 TextSecureCipher cipher
= new TextSecureCipher(new TextSecureAddress(username
), axolotlStore
);
402 return cipher
.decrypt(envelope
);
403 } catch (Exception e
) {
404 // TODO handle all exceptions
410 private void handleEndSession(String source
) {
411 axolotlStore
.deleteAllSessions(source
);
414 public interface ReceiveMessageHandler
{
415 void handleMessage(TextSecureEnvelope envelope
, TextSecureContent decryptedContent
, GroupInfo group
);
418 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
419 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
, USER_AGENT
);
420 TextSecureMessagePipe messagePipe
= null;
423 messagePipe
= messageReceiver
.createMessagePipe();
426 TextSecureEnvelope envelope
;
427 TextSecureContent content
= null;
428 GroupInfo group
= null;
430 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
431 if (!envelope
.isReceipt()) {
432 content
= decryptMessage(envelope
);
433 if (content
!= null) {
434 if (content
.getDataMessage().isPresent()) {
435 TextSecureDataMessage message
= content
.getDataMessage().get();
436 if (message
.getGroupInfo().isPresent()) {
437 TextSecureGroup groupInfo
= message
.getGroupInfo().get();
438 switch (groupInfo
.getType()) {
441 group
= groupStore
.getGroup(groupInfo
.getGroupId());
442 } catch (GroupNotFoundException e
) {
443 group
= new GroupInfo(groupInfo
.getGroupId());
446 if (groupInfo
.getAvatar().isPresent()) {
447 TextSecureAttachment avatar
= groupInfo
.getAvatar().get();
448 if (avatar
.isPointer()) {
449 long avatarId
= avatar
.asPointer().getId();
451 retrieveAttachment(avatar
.asPointer());
452 group
.avatarId
= avatarId
;
453 } catch (IOException
| InvalidMessageException e
) {
454 System
.err
.println("Failed to retrieve group avatar (" + avatarId
+ "): " + e
.getMessage());
459 if (groupInfo
.getName().isPresent()) {
460 group
.name
= groupInfo
.getName().get();
463 if (groupInfo
.getMembers().isPresent()) {
464 group
.members
.addAll(groupInfo
.getMembers().get());
467 groupStore
.updateGroup(group
);
471 group
= groupStore
.getGroup(groupInfo
.getGroupId());
472 } catch (GroupNotFoundException e
) {
477 group
= groupStore
.getGroup(groupInfo
.getGroupId());
478 group
.members
.remove(envelope
.getSource());
479 } catch (GroupNotFoundException e
) {
484 if (message
.isEndSession()) {
485 handleEndSession(envelope
.getSource());
487 if (message
.getAttachments().isPresent()) {
488 for (TextSecureAttachment attachment
: message
.getAttachments().get()) {
489 if (attachment
.isPointer()) {
491 retrieveAttachment(attachment
.asPointer());
492 } catch (IOException
| InvalidMessageException e
) {
493 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
501 handler
.handleMessage(envelope
, content
, group
);
502 } catch (TimeoutException e
) {
505 } catch (InvalidVersionException e
) {
506 System
.err
.println("Ignoring error: " + e
.getMessage());
511 if (messagePipe
!= null)
512 messagePipe
.shutdown();
516 public File
getAttachmentFile(long attachmentId
) {
517 return new File(attachmentsPath
+ "/" + attachmentId
);
520 private File
retrieveAttachment(TextSecureAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
521 final TextSecureMessageReceiver messageReceiver
= new TextSecureMessageReceiver(URL
, TRUST_STORE
, username
, password
, signalingKey
, USER_AGENT
);
523 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
524 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
526 new File(attachmentsPath
).mkdirs();
527 File outputFile
= getAttachmentFile(pointer
.getId());
528 OutputStream output
= null;
530 output
= new FileOutputStream(outputFile
);
531 byte[] buffer
= new byte[4096];
534 while ((read
= input
.read(buffer
)) != -1) {
535 output
.write(buffer
, 0, read
);
537 } catch (FileNotFoundException e
) {
541 if (output
!= null) {
545 if (!tmpFile
.delete()) {
546 System
.err
.println("Failed to delete temp file: " + tmpFile
);
549 if (pointer
.getPreview().isPresent()) {
550 File previewFile
= new File(outputFile
+ ".preview");
552 output
= new FileOutputStream(previewFile
);
553 byte[] preview
= pointer
.getPreview().get();
554 output
.write(preview
, 0, preview
.length
);
555 } catch (FileNotFoundException e
) {
559 if (output
!= null) {
567 public String
canonicalizeNumber(String number
) throws InvalidNumberException
{
568 String localNumber
= username
;
569 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
572 private TextSecureAddress
getPushAddress(String number
) throws InvalidNumberException
{
573 String e164number
= canonicalizeNumber(number
);
574 return new TextSecureAddress(e164number
);
577 public GroupInfo
getGroupInfo(byte[] groupId
) throws GroupNotFoundException
{
578 return groupStore
.getGroup(groupId
);
581 public void setGroupInfo(GroupInfo group
) {
582 groupStore
.updateGroup(group
);
585 public String
getUsername() {