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/>.
17 package org
.asamk
.signal
;
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
.apache
.http
.util
.TextUtils
;
27 import org
.asamk
.Signal
;
28 import org
.whispersystems
.libsignal
.*;
29 import org
.whispersystems
.libsignal
.ecc
.Curve
;
30 import org
.whispersystems
.libsignal
.ecc
.ECKeyPair
;
31 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
32 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
33 import org
.whispersystems
.libsignal
.state
.SignalProtocolStore
;
34 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
35 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
36 import org
.whispersystems
.libsignal
.util
.Medium
;
37 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
38 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
39 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
40 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
41 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
42 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
43 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
44 import org
.whispersystems
.signalservice
.api
.messages
.*;
45 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
46 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
47 import org
.whispersystems
.signalservice
.api
.push
.TrustStore
;
48 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
49 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
50 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
51 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
52 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
56 import java
.net
.URISyntaxException
;
57 import java
.net
.URLDecoder
;
58 import java
.net
.URLEncoder
;
59 import java
.nio
.file
.Files
;
60 import java
.nio
.file
.Paths
;
61 import java
.nio
.file
.StandardCopyOption
;
63 import java
.util
.concurrent
.TimeUnit
;
64 import java
.util
.concurrent
.TimeoutException
;
66 class Manager
implements Signal
{
67 private final static String URL
= "https://textsecure-service.whispersystems.org";
68 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
70 public final static String PROJECT_NAME
= Manager
.class.getPackage().getImplementationTitle();
71 public final static String PROJECT_VERSION
= Manager
.class.getPackage().getImplementationVersion();
72 private final static String USER_AGENT
= PROJECT_NAME
== null ?
null : PROJECT_NAME
+ " " + PROJECT_VERSION
;
74 private final static int PREKEY_MINIMUM_COUNT
= 20;
75 private static final int PREKEY_BATCH_SIZE
= 100;
77 private final String settingsPath
;
78 private final String dataPath
;
79 private final String attachmentsPath
;
80 private final String avatarsPath
;
82 private final ObjectMapper jsonProcessot
= new ObjectMapper();
83 private String username
;
84 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
85 private String password
;
86 private String signalingKey
;
87 private int preKeyIdOffset
;
88 private int nextSignedPreKeyId
;
90 private boolean registered
= false;
92 private SignalProtocolStore signalProtocolStore
;
93 private SignalServiceAccountManager accountManager
;
94 private JsonGroupStore groupStore
;
95 private JsonContactsStore contactStore
;
97 public Manager(String username
, String settingsPath
) {
98 this.username
= username
;
99 this.settingsPath
= settingsPath
;
100 this.dataPath
= this.settingsPath
+ "/data";
101 this.attachmentsPath
= this.settingsPath
+ "/attachments";
102 this.avatarsPath
= this.settingsPath
+ "/avatars";
104 jsonProcessot
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
105 jsonProcessot
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
106 jsonProcessot
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
107 jsonProcessot
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
110 public String
getUsername() {
114 public int getDeviceId() {
118 public String
getFileName() {
119 new File(dataPath
).mkdirs();
120 return dataPath
+ "/" + username
;
123 public boolean userExists() {
124 if (username
== null) {
127 File f
= new File(getFileName());
128 return !(!f
.exists() || f
.isDirectory());
131 public boolean userHasKeys() {
132 return signalProtocolStore
!= null;
135 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
136 JsonNode node
= parent
.get(name
);
138 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
144 public void load() throws IOException
, InvalidKeyException
{
145 JsonNode rootNode
= jsonProcessot
.readTree(new File(getFileName()));
147 JsonNode node
= rootNode
.get("deviceId");
149 deviceId
= node
.asInt();
151 username
= getNotNullNode(rootNode
, "username").asText();
152 password
= getNotNullNode(rootNode
, "password").asText();
153 if (rootNode
.has("signalingKey")) {
154 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
156 if (rootNode
.has("preKeyIdOffset")) {
157 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
161 if (rootNode
.has("nextSignedPreKeyId")) {
162 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
164 nextSignedPreKeyId
= 0;
166 signalProtocolStore
= jsonProcessot
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
167 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
168 JsonNode groupStoreNode
= rootNode
.get("groupStore");
169 if (groupStoreNode
!= null) {
170 groupStore
= jsonProcessot
.convertValue(groupStoreNode
, JsonGroupStore
.class);
172 if (groupStore
== null) {
173 groupStore
= new JsonGroupStore();
175 // Copy group avatars that were previously stored in the attachments folder
176 // to the new avatar folder
177 if (groupStore
.groupsWithLegacyAvatarId
.size() > 0) {
178 for (GroupInfo g
: groupStore
.groupsWithLegacyAvatarId
) {
179 File avatarFile
= getGroupAvatarFile(g
.groupId
);
180 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
181 if (!avatarFile
.exists() && attachmentFile
.exists()) {
183 new File(avatarsPath
).mkdirs();
184 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
185 } catch (Exception e
) {
190 groupStore
.groupsWithLegacyAvatarId
.clear();
194 JsonNode contactStoreNode
= rootNode
.get("contactStore");
195 if (contactStoreNode
!= null) {
196 contactStore
= jsonProcessot
.convertValue(contactStoreNode
, JsonContactsStore
.class);
198 if (contactStore
== null) {
199 contactStore
= new JsonContactsStore();
202 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, deviceId
, USER_AGENT
);
204 if (registered
&& accountManager
.getPreKeysCount() < PREKEY_MINIMUM_COUNT
) {
208 } catch (AuthorizationFailedException e
) {
209 System
.err
.println("Authorization failed, was the number registered elsewhere?");
213 private void save() {
214 if (username
== null) {
217 ObjectNode rootNode
= jsonProcessot
.createObjectNode();
218 rootNode
.put("username", username
)
219 .put("deviceId", deviceId
)
220 .put("password", password
)
221 .put("signalingKey", signalingKey
)
222 .put("preKeyIdOffset", preKeyIdOffset
)
223 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
224 .put("registered", registered
)
225 .putPOJO("axolotlStore", signalProtocolStore
)
226 .putPOJO("groupStore", groupStore
)
227 .putPOJO("contactStore", contactStore
)
230 jsonProcessot
.writeValue(new File(getFileName()), rootNode
);
231 } catch (Exception e
) {
232 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
236 public void createNewIdentity() {
237 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
238 int registrationId
= KeyHelper
.generateRegistrationId(false);
239 signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
240 groupStore
= new JsonGroupStore();
245 public boolean isRegistered() {
249 public void register(boolean voiceVerication
) throws IOException
{
250 password
= Util
.getSecret(18);
252 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
255 accountManager
.requestVoiceVerificationCode();
257 accountManager
.requestSmsVerificationCode();
263 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
264 password
= Util
.getSecret(18);
266 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
267 String uuid
= accountManager
.getNewDeviceUuid();
271 return new URI("tsdevice:/?uuid=" + URLEncoder
.encode(uuid
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(signalProtocolStore
.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
272 } catch (URISyntaxException e
) {
278 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
279 signalingKey
= Util
.getSecret(52);
280 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(signalProtocolStore
.getIdentityKeyPair(), signalingKey
, false, true, signalProtocolStore
.getLocalRegistrationId(), deviceName
);
281 deviceId
= ret
.getDeviceId();
282 username
= ret
.getNumber();
283 // TODO do this check before actually registering
285 throw new UserAlreadyExists(username
, getFileName());
287 signalProtocolStore
= new JsonSignalProtocolStore(ret
.getIdentity(), signalProtocolStore
.getLocalRegistrationId());
293 requestSyncContacts();
298 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
299 return accountManager
.getDevices();
302 public void removeLinkedDevices(int deviceId
) throws IOException
{
303 accountManager
.removeDevice(deviceId
);
306 public static Map
<String
, String
> getQueryMap(String query
) {
307 String
[] params
= query
.split("&");
308 Map
<String
, String
> map
= new HashMap
<>();
309 for (String param
: params
) {
312 name
= URLDecoder
.decode(param
.split("=")[0], "utf-8");
313 } catch (UnsupportedEncodingException e
) {
318 value
= URLDecoder
.decode(param
.split("=")[1], "utf-8");
319 } catch (UnsupportedEncodingException e
) {
322 map
.put(name
, value
);
327 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
328 Map
<String
, String
> query
= getQueryMap(linkUri
.getRawQuery());
329 String deviceIdentifier
= query
.get("uuid");
330 String publicKeyEncoded
= query
.get("pub_key");
332 if (TextUtils
.isEmpty(deviceIdentifier
) || TextUtils
.isEmpty(publicKeyEncoded
)) {
333 throw new RuntimeException("Invalid device link uri");
336 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
338 addDevice(deviceIdentifier
, deviceKey
);
341 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
342 IdentityKeyPair identityKeyPair
= signalProtocolStore
.getIdentityKeyPair();
343 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
345 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, verificationCode
);
348 private List
<PreKeyRecord
> generatePreKeys() {
349 List
<PreKeyRecord
> records
= new LinkedList
<>();
351 for (int i
= 0; i
< PREKEY_BATCH_SIZE
; i
++) {
352 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
353 ECKeyPair keyPair
= Curve
.generateKeyPair();
354 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
356 signalProtocolStore
.storePreKey(preKeyId
, record);
360 preKeyIdOffset
= (preKeyIdOffset
+ PREKEY_BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
366 private PreKeyRecord
getOrGenerateLastResortPreKey() {
367 if (signalProtocolStore
.containsPreKey(Medium
.MAX_VALUE
)) {
369 return signalProtocolStore
.loadPreKey(Medium
.MAX_VALUE
);
370 } catch (InvalidKeyIdException e
) {
371 signalProtocolStore
.removePreKey(Medium
.MAX_VALUE
);
375 ECKeyPair keyPair
= Curve
.generateKeyPair();
376 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
378 signalProtocolStore
.storePreKey(Medium
.MAX_VALUE
, record);
384 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
386 ECKeyPair keyPair
= Curve
.generateKeyPair();
387 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
388 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
390 signalProtocolStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
391 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
395 } catch (InvalidKeyException e
) {
396 throw new AssertionError(e
);
400 public void verifyAccount(String verificationCode
) throws IOException
{
401 verificationCode
= verificationCode
.replace("-", "");
402 signalingKey
= Util
.getSecret(52);
403 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, signalProtocolStore
.getLocalRegistrationId(), false, true);
405 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
412 private void refreshPreKeys() throws IOException
{
413 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
414 PreKeyRecord lastResortKey
= getOrGenerateLastResortPreKey();
415 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(signalProtocolStore
.getIdentityKeyPair());
417 accountManager
.setPreKeys(signalProtocolStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
421 private static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
422 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
423 if (attachments
!= null) {
424 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
425 for (String attachment
: attachments
) {
427 SignalServiceAttachments
.add(createAttachment(new File(attachment
)));
428 } catch (IOException e
) {
429 throw new AttachmentInvalidException(attachment
, e
);
433 return SignalServiceAttachments
;
436 private static SignalServiceAttachmentStream
createAttachment(File attachmentFile
) throws IOException
{
437 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
438 final long attachmentSize
= attachmentFile
.length();
439 String mime
= Files
.probeContentType(attachmentFile
.toPath());
440 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, null);
443 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
444 File file
= getGroupAvatarFile(groupId
);
445 if (!file
.exists()) {
446 return Optional
.absent();
449 return Optional
.of(createAttachment(file
));
452 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
453 File file
= getContactAvatarFile(number
);
454 if (!file
.exists()) {
455 return Optional
.absent();
458 return Optional
.of(createAttachment(file
));
462 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
464 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
465 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
466 if (attachments
!= null) {
467 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
469 if (groupId
!= null) {
470 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
473 messageBuilder
.asGroupMessage(group
);
475 SignalServiceDataMessage message
= messageBuilder
.build();
477 GroupInfo g
= groupStore
.getGroup(groupId
);
479 throw new GroupNotFoundException(groupId
);
481 Set
<String
> members
= g
.members
;
482 members
.remove(this.username
);
483 sendMessage(message
, members
);
486 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
487 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
491 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
492 .asGroupMessage(group
)
495 final GroupInfo g
= groupStore
.getGroup(groupId
);
497 throw new GroupNotFoundException(groupId
);
499 g
.members
.remove(this.username
);
500 groupStore
.updateGroup(g
);
502 sendMessage(message
, g
.members
);
505 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
507 if (groupId
== null) {
509 g
= new GroupInfo(Util
.getSecretBytes(16));
510 g
.members
.add(username
);
512 g
= groupStore
.getGroup(groupId
);
514 throw new GroupNotFoundException(groupId
);
522 if (members
!= null) {
523 for (String member
: members
) {
525 g
.members
.add(canonicalizeNumber(member
));
526 } catch (InvalidNumberException e
) {
527 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
528 System
.err
.println("Aborting…");
534 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
537 .withMembers(new ArrayList
<>(g
.members
));
539 File aFile
= getGroupAvatarFile(g
.groupId
);
540 if (avatarFile
!= null) {
541 new File(avatarsPath
).mkdirs();
542 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
544 if (aFile
.exists()) {
546 group
.withAvatar(createAttachment(aFile
));
547 } catch (IOException e
) {
548 throw new AttachmentInvalidException(avatarFile
, e
);
552 groupStore
.updateGroup(g
);
554 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
555 .asGroupMessage(group
.build())
558 final Set
<String
> membersSend
= g
.members
;
559 membersSend
.remove(this.username
);
560 sendMessage(message
, membersSend
);
565 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
566 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
, UntrustedIdentityException
{
567 List
<String
> recipients
= new ArrayList
<>(1);
568 recipients
.add(recipient
);
569 sendMessage(message
, attachments
, recipients
);
573 public void sendMessage(String messageText
, List
<String
> attachments
,
574 List
<String
> recipients
)
575 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
, UntrustedIdentityException
{
576 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
577 if (attachments
!= null) {
578 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
580 SignalServiceDataMessage message
= messageBuilder
.build();
582 sendMessage(message
, recipients
);
586 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
587 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
588 .asEndSessionMessage()
591 sendMessage(message
, recipients
);
594 private void requestSyncGroups() throws IOException
{
595 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
596 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
598 sendMessage(message
);
599 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
600 encapsulatedExceptions
.printStackTrace();
601 } catch (UntrustedIdentityException e
) {
606 private void requestSyncContacts() throws IOException
{
607 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
608 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
610 sendMessage(message
);
611 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
612 encapsulatedExceptions
.printStackTrace();
613 } catch (UntrustedIdentityException e
) {
618 private void sendMessage(SignalServiceSyncMessage message
)
619 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
620 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
621 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
622 messageSender
.sendMessage(message
);
625 private void sendMessage(SignalServiceDataMessage message
, Collection
<String
> recipients
)
626 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
628 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
629 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
631 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
632 for (String recipient
: recipients
) {
634 recipientsTS
.add(getPushAddress(recipient
));
635 } catch (InvalidNumberException e
) {
636 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
637 System
.err
.println("Aborting sending.");
643 if (message
.getGroupInfo().isPresent()) {
644 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
646 // Send to all individually, so sync messages are sent correctly
647 for (SignalServiceAddress address
: recipientsTS
) {
648 messageSender
.sendMessage(address
, message
);
652 if (message
.isEndSession()) {
653 for (SignalServiceAddress recipient
: recipientsTS
) {
654 handleEndSession(recipient
.getNumber());
662 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) {
663 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
665 return cipher
.decrypt(envelope
);
666 } catch (Exception e
) {
667 // TODO handle all exceptions
673 private void handleEndSession(String source
) {
674 signalProtocolStore
.deleteAllSessions(source
);
677 public interface ReceiveMessageHandler
{
678 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
);
681 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
) {
682 if (message
.getGroupInfo().isPresent()) {
683 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
684 switch (groupInfo
.getType()) {
687 group
= groupStore
.getGroup(groupInfo
.getGroupId());
689 group
= new GroupInfo(groupInfo
.getGroupId());
692 if (groupInfo
.getAvatar().isPresent()) {
693 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
694 if (avatar
.isPointer()) {
696 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
697 } catch (IOException
| InvalidMessageException e
) {
698 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
703 if (groupInfo
.getName().isPresent()) {
704 group
.name
= groupInfo
.getName().get();
707 if (groupInfo
.getMembers().isPresent()) {
708 group
.members
.addAll(groupInfo
.getMembers().get());
711 groupStore
.updateGroup(group
);
716 group
= groupStore
.getGroup(groupInfo
.getGroupId());
718 group
.members
.remove(source
);
719 groupStore
.updateGroup(group
);
724 if (message
.isEndSession()) {
725 handleEndSession(isSync ? destination
: source
);
727 if (message
.getAttachments().isPresent()) {
728 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
729 if (attachment
.isPointer()) {
731 retrieveAttachment(attachment
.asPointer());
732 } catch (IOException
| InvalidMessageException e
) {
733 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
740 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
741 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
742 SignalServiceMessagePipe messagePipe
= null;
745 messagePipe
= messageReceiver
.createMessagePipe();
748 SignalServiceEnvelope envelope
;
749 SignalServiceContent content
= null;
751 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
752 if (!envelope
.isReceipt()) {
753 content
= decryptMessage(envelope
);
754 if (content
!= null) {
755 if (content
.getDataMessage().isPresent()) {
756 SignalServiceDataMessage message
= content
.getDataMessage().get();
757 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
);
759 if (content
.getSyncMessage().isPresent()) {
760 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
761 if (syncMessage
.getSent().isPresent()) {
762 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
763 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get());
765 if (syncMessage
.getRequest().isPresent()) {
766 RequestMessage rm
= syncMessage
.getRequest().get();
767 if (rm
.isContactsRequest()) {
770 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
771 encapsulatedExceptions
.printStackTrace();
772 } catch (UntrustedIdentityException e
) {
776 if (rm
.isGroupsRequest()) {
779 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
780 encapsulatedExceptions
.printStackTrace();
781 } catch (UntrustedIdentityException e
) {
786 if (syncMessage
.getGroups().isPresent()) {
788 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer()));
790 while ((g
= s
.read()) != null) {
791 GroupInfo syncGroup
= groupStore
.getGroup(g
.getId());
792 if (syncGroup
== null) {
793 syncGroup
= new GroupInfo(g
.getId());
795 if (g
.getName().isPresent()) {
796 syncGroup
.name
= g
.getName().get();
798 syncGroup
.members
.addAll(g
.getMembers());
799 syncGroup
.active
= g
.isActive();
801 if (g
.getAvatar().isPresent()) {
802 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
804 groupStore
.updateGroup(syncGroup
);
806 } catch (Exception e
) {
810 if (syncMessage
.getContacts().isPresent()) {
812 DeviceContactsInputStream s
= new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage
.getContacts().get().asPointer()));
814 while ((c
= s
.read()) != null) {
815 ContactInfo contact
= new ContactInfo();
816 contact
.number
= c
.getNumber();
817 if (c
.getName().isPresent()) {
818 contact
.name
= c
.getName().get();
820 contactStore
.updateContact(contact
);
822 if (c
.getAvatar().isPresent()) {
823 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
826 } catch (Exception e
) {
834 handler
.handleMessage(envelope
, content
);
835 } catch (TimeoutException e
) {
838 } catch (InvalidVersionException e
) {
839 System
.err
.println("Ignoring error: " + e
.getMessage());
843 if (messagePipe
!= null)
844 messagePipe
.shutdown();
848 public File
getContactAvatarFile(String number
) {
849 return new File(avatarsPath
, "contact-" + number
);
852 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
853 new File(avatarsPath
).mkdirs();
854 if (attachment
.isPointer()) {
855 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
856 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
858 SignalServiceAttachmentStream stream
= attachment
.asStream();
859 return retrieveAttachment(stream
, getContactAvatarFile(number
));
863 public File
getGroupAvatarFile(byte[] groupId
) {
864 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
867 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
868 new File(avatarsPath
).mkdirs();
869 if (attachment
.isPointer()) {
870 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
871 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
873 SignalServiceAttachmentStream stream
= attachment
.asStream();
874 return retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
878 public File
getAttachmentFile(long attachmentId
) {
879 return new File(attachmentsPath
, attachmentId
+ "");
882 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
883 new File(attachmentsPath
).mkdirs();
884 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
887 private File
retrieveAttachment(SignalServiceAttachmentStream stream
, File outputFile
) throws IOException
, InvalidMessageException
{
888 InputStream input
= stream
.getInputStream();
890 OutputStream output
= null;
892 output
= new FileOutputStream(outputFile
);
893 byte[] buffer
= new byte[4096];
896 while ((read
= input
.read(buffer
)) != -1) {
897 output
.write(buffer
, 0, read
);
899 } catch (FileNotFoundException e
) {
903 if (output
!= null) {
910 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
911 if (storePreview
&& pointer
.getPreview().isPresent()) {
912 File previewFile
= new File(outputFile
+ ".preview");
913 OutputStream output
= null;
915 output
= new FileOutputStream(previewFile
);
916 byte[] preview
= pointer
.getPreview().get();
917 output
.write(preview
, 0, preview
.length
);
918 } catch (FileNotFoundException e
) {
922 if (output
!= null) {
928 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
930 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
931 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
933 OutputStream output
= null;
935 output
= new FileOutputStream(outputFile
);
936 byte[] buffer
= new byte[4096];
939 while ((read
= input
.read(buffer
)) != -1) {
940 output
.write(buffer
, 0, read
);
942 } catch (FileNotFoundException e
) {
946 if (output
!= null) {
949 if (!tmpFile
.delete()) {
950 System
.err
.println("Failed to delete temp file: " + tmpFile
);
956 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
957 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
958 File file
= File
.createTempFile("ts_tmp", "tmp");
961 return messageReceiver
.retrieveAttachment(pointer
, file
);
964 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
965 String localNumber
= username
;
966 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
969 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
970 String e164number
= canonicalizeNumber(number
);
971 return new SignalServiceAddress(e164number
);
975 public boolean isRemote() {
979 private void sendGroups() throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
980 File groupsFile
= File
.createTempFile("multidevice-group-update", ".tmp");
983 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(new FileOutputStream(groupsFile
));
985 for (GroupInfo
record : groupStore
.getGroups()) {
986 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
987 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
994 if (groupsFile
.exists() && groupsFile
.length() > 0) {
995 FileInputStream contactsFileStream
= new FileInputStream(groupsFile
);
996 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
997 .withStream(contactsFileStream
)
998 .withContentType("application/octet-stream")
999 .withLength(groupsFile
.length())
1002 sendMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1005 groupsFile
.delete();
1009 private void sendContacts() throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
1010 File contactsFile
= File
.createTempFile("multidevice-contact-update", ".tmp");
1013 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(new FileOutputStream(contactsFile
));
1015 for (ContactInfo
record : contactStore
.getContacts()) {
1016 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1017 createContactAvatarAttachment(record.number
)));
1023 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1024 FileInputStream contactsFileStream
= new FileInputStream(contactsFile
);
1025 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1026 .withStream(contactsFileStream
)
1027 .withContentType("application/octet-stream")
1028 .withLength(contactsFile
.length())
1031 sendMessage(SignalServiceSyncMessage
.forContacts(attachmentStream
));
1034 contactsFile
.delete();
1038 public ContactInfo
getContact(String number
) {
1039 return contactStore
.getContact(number
);
1042 public GroupInfo
getGroup(byte[] groupId
) {
1043 return groupStore
.getGroup(groupId
);