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
);
482 // Don't send group message to ourself
483 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
484 membersSend
.remove(this.username
);
485 sendMessage(message
, membersSend
);
488 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
489 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
493 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
494 .asGroupMessage(group
)
497 final GroupInfo g
= groupStore
.getGroup(groupId
);
499 throw new GroupNotFoundException(groupId
);
501 g
.members
.remove(this.username
);
502 groupStore
.updateGroup(g
);
504 sendMessage(message
, g
.members
);
507 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
, UntrustedIdentityException
{
509 if (groupId
== null) {
511 g
= new GroupInfo(Util
.getSecretBytes(16));
512 g
.members
.add(username
);
514 g
= groupStore
.getGroup(groupId
);
516 throw new GroupNotFoundException(groupId
);
524 if (members
!= null) {
525 for (String member
: members
) {
527 g
.members
.add(canonicalizeNumber(member
));
528 } catch (InvalidNumberException e
) {
529 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
530 System
.err
.println("Aborting…");
536 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
539 .withMembers(new ArrayList
<>(g
.members
));
541 File aFile
= getGroupAvatarFile(g
.groupId
);
542 if (avatarFile
!= null) {
543 new File(avatarsPath
).mkdirs();
544 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
546 if (aFile
.exists()) {
548 group
.withAvatar(createAttachment(aFile
));
549 } catch (IOException e
) {
550 throw new AttachmentInvalidException(avatarFile
, e
);
554 groupStore
.updateGroup(g
);
556 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
557 .asGroupMessage(group
.build())
560 // Don't send group message to ourself
561 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
562 membersSend
.remove(this.username
);
563 sendMessage(message
, membersSend
);
568 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
569 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
, UntrustedIdentityException
{
570 List
<String
> recipients
= new ArrayList
<>(1);
571 recipients
.add(recipient
);
572 sendMessage(message
, attachments
, recipients
);
576 public void sendMessage(String messageText
, List
<String
> attachments
,
577 List
<String
> recipients
)
578 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
, UntrustedIdentityException
{
579 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
580 if (attachments
!= null) {
581 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
583 SignalServiceDataMessage message
= messageBuilder
.build();
585 sendMessage(message
, recipients
);
589 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
590 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
591 .asEndSessionMessage()
594 sendMessage(message
, recipients
);
597 private void requestSyncGroups() throws IOException
{
598 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
599 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
601 sendMessage(message
);
602 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
603 encapsulatedExceptions
.printStackTrace();
604 } catch (UntrustedIdentityException e
) {
609 private void requestSyncContacts() throws IOException
{
610 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
611 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
613 sendMessage(message
);
614 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
615 encapsulatedExceptions
.printStackTrace();
616 } catch (UntrustedIdentityException e
) {
621 private void sendMessage(SignalServiceSyncMessage message
)
622 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
623 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
624 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
625 messageSender
.sendMessage(message
);
628 private void sendMessage(SignalServiceDataMessage message
, Collection
<String
> recipients
)
629 throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
631 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
632 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
634 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
635 for (String recipient
: recipients
) {
637 recipientsTS
.add(getPushAddress(recipient
));
638 } catch (InvalidNumberException e
) {
639 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
640 System
.err
.println("Aborting sending.");
646 if (message
.getGroupInfo().isPresent()) {
647 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
649 // Send to all individually, so sync messages are sent correctly
650 for (SignalServiceAddress address
: recipientsTS
) {
651 messageSender
.sendMessage(address
, message
);
655 if (message
.isEndSession()) {
656 for (SignalServiceAddress recipient
: recipientsTS
) {
657 handleEndSession(recipient
.getNumber());
665 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) {
666 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
668 return cipher
.decrypt(envelope
);
669 } catch (Exception e
) {
670 // TODO handle all exceptions
676 private void handleEndSession(String source
) {
677 signalProtocolStore
.deleteAllSessions(source
);
680 public interface ReceiveMessageHandler
{
681 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
);
684 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
) {
685 if (message
.getGroupInfo().isPresent()) {
686 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
687 switch (groupInfo
.getType()) {
690 group
= groupStore
.getGroup(groupInfo
.getGroupId());
692 group
= new GroupInfo(groupInfo
.getGroupId());
695 if (groupInfo
.getAvatar().isPresent()) {
696 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
697 if (avatar
.isPointer()) {
699 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
700 } catch (IOException
| InvalidMessageException e
) {
701 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
706 if (groupInfo
.getName().isPresent()) {
707 group
.name
= groupInfo
.getName().get();
710 if (groupInfo
.getMembers().isPresent()) {
711 group
.members
.addAll(groupInfo
.getMembers().get());
714 groupStore
.updateGroup(group
);
719 group
= groupStore
.getGroup(groupInfo
.getGroupId());
721 group
.members
.remove(source
);
722 groupStore
.updateGroup(group
);
727 if (message
.isEndSession()) {
728 handleEndSession(isSync ? destination
: source
);
730 if (message
.getAttachments().isPresent()) {
731 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
732 if (attachment
.isPointer()) {
734 retrieveAttachment(attachment
.asPointer());
735 } catch (IOException
| InvalidMessageException e
) {
736 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
743 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
744 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
745 SignalServiceMessagePipe messagePipe
= null;
748 messagePipe
= messageReceiver
.createMessagePipe();
751 SignalServiceEnvelope envelope
;
752 SignalServiceContent content
= null;
754 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
);
755 if (!envelope
.isReceipt()) {
756 content
= decryptMessage(envelope
);
757 if (content
!= null) {
758 if (content
.getDataMessage().isPresent()) {
759 SignalServiceDataMessage message
= content
.getDataMessage().get();
760 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
);
762 if (content
.getSyncMessage().isPresent()) {
763 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
764 if (syncMessage
.getSent().isPresent()) {
765 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
766 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get());
768 if (syncMessage
.getRequest().isPresent()) {
769 RequestMessage rm
= syncMessage
.getRequest().get();
770 if (rm
.isContactsRequest()) {
773 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
774 encapsulatedExceptions
.printStackTrace();
775 } catch (UntrustedIdentityException e
) {
779 if (rm
.isGroupsRequest()) {
782 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
783 encapsulatedExceptions
.printStackTrace();
784 } catch (UntrustedIdentityException e
) {
789 if (syncMessage
.getGroups().isPresent()) {
791 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer()));
793 while ((g
= s
.read()) != null) {
794 GroupInfo syncGroup
= groupStore
.getGroup(g
.getId());
795 if (syncGroup
== null) {
796 syncGroup
= new GroupInfo(g
.getId());
798 if (g
.getName().isPresent()) {
799 syncGroup
.name
= g
.getName().get();
801 syncGroup
.members
.addAll(g
.getMembers());
802 syncGroup
.active
= g
.isActive();
804 if (g
.getAvatar().isPresent()) {
805 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
807 groupStore
.updateGroup(syncGroup
);
809 } catch (Exception e
) {
813 if (syncMessage
.getContacts().isPresent()) {
815 DeviceContactsInputStream s
= new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage
.getContacts().get().asPointer()));
817 while ((c
= s
.read()) != null) {
818 ContactInfo contact
= new ContactInfo();
819 contact
.number
= c
.getNumber();
820 if (c
.getName().isPresent()) {
821 contact
.name
= c
.getName().get();
823 contactStore
.updateContact(contact
);
825 if (c
.getAvatar().isPresent()) {
826 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
829 } catch (Exception e
) {
837 handler
.handleMessage(envelope
, content
);
838 } catch (TimeoutException e
) {
841 } catch (InvalidVersionException e
) {
842 System
.err
.println("Ignoring error: " + e
.getMessage());
846 if (messagePipe
!= null)
847 messagePipe
.shutdown();
851 public File
getContactAvatarFile(String number
) {
852 return new File(avatarsPath
, "contact-" + number
);
855 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
856 new File(avatarsPath
).mkdirs();
857 if (attachment
.isPointer()) {
858 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
859 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
861 SignalServiceAttachmentStream stream
= attachment
.asStream();
862 return retrieveAttachment(stream
, getContactAvatarFile(number
));
866 public File
getGroupAvatarFile(byte[] groupId
) {
867 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
870 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
871 new File(avatarsPath
).mkdirs();
872 if (attachment
.isPointer()) {
873 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
874 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
876 SignalServiceAttachmentStream stream
= attachment
.asStream();
877 return retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
881 public File
getAttachmentFile(long attachmentId
) {
882 return new File(attachmentsPath
, attachmentId
+ "");
885 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
886 new File(attachmentsPath
).mkdirs();
887 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
890 private File
retrieveAttachment(SignalServiceAttachmentStream stream
, File outputFile
) throws IOException
, InvalidMessageException
{
891 InputStream input
= stream
.getInputStream();
893 OutputStream output
= null;
895 output
= new FileOutputStream(outputFile
);
896 byte[] buffer
= new byte[4096];
899 while ((read
= input
.read(buffer
)) != -1) {
900 output
.write(buffer
, 0, read
);
902 } catch (FileNotFoundException e
) {
906 if (output
!= null) {
913 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
914 if (storePreview
&& pointer
.getPreview().isPresent()) {
915 File previewFile
= new File(outputFile
+ ".preview");
916 OutputStream output
= null;
918 output
= new FileOutputStream(previewFile
);
919 byte[] preview
= pointer
.getPreview().get();
920 output
.write(preview
, 0, preview
.length
);
921 } catch (FileNotFoundException e
) {
925 if (output
!= null) {
931 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
933 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
934 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
936 OutputStream output
= null;
938 output
= new FileOutputStream(outputFile
);
939 byte[] buffer
= new byte[4096];
942 while ((read
= input
.read(buffer
)) != -1) {
943 output
.write(buffer
, 0, read
);
945 } catch (FileNotFoundException e
) {
949 if (output
!= null) {
952 if (!tmpFile
.delete()) {
953 System
.err
.println("Failed to delete temp file: " + tmpFile
);
959 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
960 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
961 File file
= File
.createTempFile("ts_tmp", "tmp");
964 return messageReceiver
.retrieveAttachment(pointer
, file
);
967 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
968 String localNumber
= username
;
969 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
972 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
973 String e164number
= canonicalizeNumber(number
);
974 return new SignalServiceAddress(e164number
);
978 public boolean isRemote() {
982 private void sendGroups() throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
983 File groupsFile
= File
.createTempFile("multidevice-group-update", ".tmp");
986 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(new FileOutputStream(groupsFile
));
988 for (GroupInfo
record : groupStore
.getGroups()) {
989 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
990 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
997 if (groupsFile
.exists() && groupsFile
.length() > 0) {
998 FileInputStream contactsFileStream
= new FileInputStream(groupsFile
);
999 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1000 .withStream(contactsFileStream
)
1001 .withContentType("application/octet-stream")
1002 .withLength(groupsFile
.length())
1005 sendMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1008 groupsFile
.delete();
1012 private void sendContacts() throws IOException
, EncapsulatedExceptions
, UntrustedIdentityException
{
1013 File contactsFile
= File
.createTempFile("multidevice-contact-update", ".tmp");
1016 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(new FileOutputStream(contactsFile
));
1018 for (ContactInfo
record : contactStore
.getContacts()) {
1019 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1020 createContactAvatarAttachment(record.number
)));
1026 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1027 FileInputStream contactsFileStream
= new FileInputStream(contactsFile
);
1028 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1029 .withStream(contactsFileStream
)
1030 .withContentType("application/octet-stream")
1031 .withLength(contactsFile
.length())
1034 sendMessage(SignalServiceSyncMessage
.forContacts(attachmentStream
));
1037 contactsFile
.delete();
1041 public ContactInfo
getContact(String number
) {
1042 return contactStore
.getContact(number
);
1045 public GroupInfo
getGroup(byte[] groupId
) {
1046 return groupStore
.getGroup(groupId
);