2 Copyright (C) 2015-2018 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
.manager
;
19 import org
.asamk
.Signal
;
20 import org
.asamk
.signal
.*;
21 import org
.asamk
.signal
.storage
.SignalAccount
;
22 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
23 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
24 import org
.asamk
.signal
.storage
.groups
.JsonGroupStore
;
25 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
26 import org
.asamk
.signal
.storage
.threads
.ThreadInfo
;
27 import org
.asamk
.signal
.util
.IOUtils
;
28 import org
.asamk
.signal
.util
.Util
;
29 import org
.signal
.libsignal
.metadata
.*;
30 import org
.whispersystems
.libsignal
.*;
31 import org
.whispersystems
.libsignal
.ecc
.Curve
;
32 import org
.whispersystems
.libsignal
.ecc
.ECKeyPair
;
33 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
34 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
35 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
36 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
37 import org
.whispersystems
.libsignal
.util
.Medium
;
38 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
39 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
40 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
41 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
42 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
43 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
44 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
45 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
46 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
47 import org
.whispersystems
.signalservice
.api
.messages
.*;
48 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
49 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
50 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
51 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
52 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
53 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
54 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
55 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
56 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
57 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
58 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
59 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
60 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
61 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
65 import java
.nio
.file
.Files
;
66 import java
.nio
.file
.Paths
;
67 import java
.nio
.file
.StandardCopyOption
;
69 import java
.util
.concurrent
.TimeUnit
;
70 import java
.util
.concurrent
.TimeoutException
;
72 public class Manager
implements Signal
{
74 private final String settingsPath
;
75 private final String dataPath
;
76 private final String attachmentsPath
;
77 private final String avatarsPath
;
78 private final SleepTimer timer
= new UptimeSleepTimer();
80 private SignalAccount account
;
81 private String username
;
82 private SignalServiceAccountManager accountManager
;
83 private SignalServiceMessagePipe messagePipe
= null;
84 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
86 public Manager(String username
, String settingsPath
) {
87 this.username
= username
;
88 this.settingsPath
= settingsPath
;
89 this.dataPath
= this.settingsPath
+ "/data";
90 this.attachmentsPath
= this.settingsPath
+ "/attachments";
91 this.avatarsPath
= this.settingsPath
+ "/avatars";
95 public String
getUsername() {
99 private IdentityKey
getIdentity() {
100 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
103 public int getDeviceId() {
104 return account
.getDeviceId();
107 private String
getMessageCachePath() {
108 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
111 private String
getMessageCachePath(String sender
) {
112 return getMessageCachePath() + "/" + sender
.replace("/", "_");
115 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
116 String cachePath
= getMessageCachePath(sender
);
117 IOUtils
.createPrivateDirectories(cachePath
);
118 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
121 public boolean userHasKeys() {
122 return account
!= null && account
.getSignalProtocolStore() != null;
125 public void init() throws IOException
{
126 if (!SignalAccount
.userExists(dataPath
, username
)) {
129 account
= SignalAccount
.load(dataPath
, username
);
131 migrateLegacyConfigs();
133 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
135 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
139 } catch (AuthorizationFailedException e
) {
140 System
.err
.println("Authorization failed, was the number registered elsewhere?");
145 private void migrateLegacyConfigs() {
146 // Copy group avatars that were previously stored in the attachments folder
147 // to the new avatar folder
148 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
149 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
150 File avatarFile
= getGroupAvatarFile(g
.groupId
);
151 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
152 if (!avatarFile
.exists() && attachmentFile
.exists()) {
154 IOUtils
.createPrivateDirectories(avatarsPath
);
155 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
156 } catch (Exception e
) {
161 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
164 if (account
.getProfileKey() == null) {
165 // Old config file, creating new profile key
166 account
.setProfileKey(KeyUtils
.createProfileKey());
171 private void createNewIdentity() throws IOException
{
172 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
173 int registrationId
= KeyHelper
.generateRegistrationId(false);
174 if (username
== null) {
175 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
177 byte[] profileKey
= KeyUtils
.createProfileKey();
178 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
183 public boolean isRegistered() {
184 return account
!= null && account
.isRegistered();
187 public void register(boolean voiceVerification
) throws IOException
{
188 if (account
== null) {
191 account
.setPassword(KeyUtils
.createPassword());
192 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, account
.getUsername(), account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
194 if (voiceVerification
) {
195 accountManager
.requestVoiceVerificationCode(Locale
.getDefault(), Optional
.<String
>absent(), Optional
.<String
>absent());
197 accountManager
.requestSmsVerificationCode(false, Optional
.<String
>absent(), Optional
.<String
>absent());
200 account
.setRegistered(false);
204 public void updateAccountAttributes() throws IOException
{
205 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
208 public void setProfileName(String name
) throws IOException
{
209 accountManager
.setProfileName(account
.getProfileKey(), name
);
212 public void setProfileAvatar(File avatar
) throws IOException
{
213 accountManager
.setProfileAvatar(account
.getProfileKey(), Utils
.createStreamDetailsFromFile(avatar
));
216 public void unregister() throws IOException
{
217 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
218 // If this is the master device, other users can't send messages to this number anymore.
219 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
220 accountManager
.setGcmId(Optional
.<String
>absent());
222 account
.setRegistered(false);
226 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
227 if (account
== null) {
230 account
.setPassword(KeyUtils
.createPassword());
231 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
232 String uuid
= accountManager
.getNewDeviceUuid();
234 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
237 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
238 account
.setSignalingKey(KeyUtils
.createSignalingKey());
239 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
241 username
= ret
.getNumber();
242 // TODO do this check before actually registering
243 if (SignalAccount
.userExists(dataPath
, username
)) {
244 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
247 // Create new account with the synced identity
248 byte[] profileKey
= ret
.getProfileKey();
249 if (profileKey
== null) {
250 profileKey
= KeyUtils
.createProfileKey();
252 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
257 requestSyncContacts();
258 requestSyncBlocked();
259 requestSyncConfiguration();
264 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
265 List
<DeviceInfo
> devices
= accountManager
.getDevices();
266 account
.setMultiDevice(devices
.size() > 1);
271 public void removeLinkedDevices(int deviceId
) throws IOException
{
272 accountManager
.removeDevice(deviceId
);
273 List
<DeviceInfo
> devices
= accountManager
.getDevices();
274 account
.setMultiDevice(devices
.size() > 1);
278 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
279 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
281 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
284 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
285 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
286 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
288 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
289 account
.setMultiDevice(true);
293 private List
<PreKeyRecord
> generatePreKeys() {
294 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
296 final int offset
= account
.getPreKeyIdOffset();
297 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
298 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
299 ECKeyPair keyPair
= Curve
.generateKeyPair();
300 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
305 account
.addPreKeys(records
);
311 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
313 ECKeyPair keyPair
= Curve
.generateKeyPair();
314 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
315 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
317 account
.addSignedPreKey(record);
321 } catch (InvalidKeyException e
) {
322 throw new AssertionError(e
);
326 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
327 verificationCode
= verificationCode
.replace("-", "");
328 account
.setSignalingKey(KeyUtils
.createSignalingKey());
329 // TODO make unrestricted unidentified access configurable
330 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
332 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
333 account
.setRegistered(true);
334 account
.setRegistrationLockPin(pin
);
340 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
341 accountManager
.setPin(pin
);
342 if (pin
.isPresent()) {
343 account
.setRegistrationLockPin(pin
.get());
345 account
.setRegistrationLockPin(null);
350 private void refreshPreKeys() throws IOException
{
351 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
352 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
353 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
355 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
358 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
359 File file
= getGroupAvatarFile(groupId
);
360 if (!file
.exists()) {
361 return Optional
.absent();
364 return Optional
.of(Utils
.createAttachment(file
));
367 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
368 File file
= getContactAvatarFile(number
);
369 if (!file
.exists()) {
370 return Optional
.absent();
373 return Optional
.of(Utils
.createAttachment(file
));
376 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
377 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
379 throw new GroupNotFoundException(groupId
);
381 for (String member
: g
.members
) {
382 if (member
.equals(this.username
)) {
386 throw new NotAGroupMemberException(groupId
, g
.name
);
389 public List
<GroupInfo
> getGroups() {
390 return account
.getGroupStore().getGroups();
394 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
396 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
397 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
398 if (attachments
!= null) {
399 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
401 if (groupId
!= null) {
402 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
405 messageBuilder
.asGroupMessage(group
);
407 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
408 if (thread
!= null) {
409 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
412 final GroupInfo g
= getGroupForSending(groupId
);
414 // Don't send group message to ourself
415 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
416 membersSend
.remove(this.username
);
417 sendMessageLegacy(messageBuilder
, membersSend
);
420 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
421 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
425 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
426 .asGroupMessage(group
);
428 final GroupInfo g
= getGroupForSending(groupId
);
429 g
.members
.remove(this.username
);
430 account
.getGroupStore().updateGroup(g
);
432 sendMessageLegacy(messageBuilder
, g
.members
);
435 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
437 if (groupId
== null) {
439 g
= new GroupInfo(KeyUtils
.createGroupId());
440 g
.members
.add(username
);
442 g
= getGroupForSending(groupId
);
449 if (members
!= null) {
450 Set
<String
> newMembers
= new HashSet
<>();
451 for (String member
: members
) {
453 member
= Utils
.canonicalizeNumber(member
, username
);
454 } catch (InvalidNumberException e
) {
455 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
456 System
.err
.println("Aborting…");
459 if (g
.members
.contains(member
)) {
462 newMembers
.add(member
);
463 g
.members
.add(member
);
465 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
466 if (contacts
.size() != newMembers
.size()) {
467 // Some of the new members are not registered on Signal
468 for (ContactTokenDetails contact
: contacts
) {
469 newMembers
.remove(contact
.getNumber());
471 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
472 System
.err
.println("Aborting…");
477 if (avatarFile
!= null) {
478 IOUtils
.createPrivateDirectories(avatarsPath
);
479 File aFile
= getGroupAvatarFile(g
.groupId
);
480 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
483 account
.getGroupStore().updateGroup(g
);
485 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
487 // Don't send group message to ourself
488 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
489 membersSend
.remove(this.username
);
490 sendMessageLegacy(messageBuilder
, membersSend
);
494 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
495 if (groupId
== null) {
498 GroupInfo g
= getGroupForSending(groupId
);
500 if (!g
.members
.contains(recipient
)) {
504 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
506 // Send group message only to the recipient who requested it
507 final List
<String
> membersSend
= new ArrayList
<>();
508 membersSend
.add(recipient
);
509 sendMessageLegacy(messageBuilder
, membersSend
);
512 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
513 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
516 .withMembers(new ArrayList
<>(g
.members
));
518 File aFile
= getGroupAvatarFile(g
.groupId
);
519 if (aFile
.exists()) {
521 group
.withAvatar(Utils
.createAttachment(aFile
));
522 } catch (IOException e
) {
523 throw new AttachmentInvalidException(aFile
.toString(), e
);
527 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
528 .asGroupMessage(group
.build());
530 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
531 if (thread
!= null) {
532 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
535 return messageBuilder
;
538 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
539 if (groupId
== null) {
543 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
546 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
547 .asGroupMessage(group
.build());
549 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
550 if (thread
!= null) {
551 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
554 // Send group info request message to the recipient who sent us a message with this groupId
555 final List
<String
> membersSend
= new ArrayList
<>();
556 membersSend
.add(recipient
);
557 sendMessageLegacy(messageBuilder
, membersSend
);
561 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
562 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
563 List
<String
> recipients
= new ArrayList
<>(1);
564 recipients
.add(recipient
);
565 sendMessage(message
, attachments
, recipients
);
569 public void sendMessage(String messageText
, List
<String
> attachments
,
570 List
<String
> recipients
)
571 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
572 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
573 if (attachments
!= null) {
574 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
576 messageBuilder
.withProfileKey(account
.getProfileKey());
577 sendMessageLegacy(messageBuilder
, recipients
);
581 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
582 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
583 .asEndSessionMessage();
585 sendMessageLegacy(messageBuilder
, recipients
);
589 public String
getContactName(String number
) {
590 ContactInfo contact
= account
.getContactStore().getContact(number
);
591 if (contact
== null) {
599 public void setContactName(String number
, String name
) {
600 ContactInfo contact
= account
.getContactStore().getContact(number
);
601 if (contact
== null) {
602 contact
= new ContactInfo();
603 contact
.number
= number
;
604 System
.err
.println("Add contact " + number
+ " named " + name
);
606 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
609 account
.getContactStore().updateContact(contact
);
614 public List
<byte[]> getGroupIds() {
615 List
<GroupInfo
> groups
= getGroups();
616 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
617 for (GroupInfo group
: groups
) {
618 ids
.add(group
.groupId
);
624 public String
getGroupName(byte[] groupId
) {
625 GroupInfo group
= getGroup(groupId
);
634 public List
<String
> getGroupMembers(byte[] groupId
) {
635 GroupInfo group
= getGroup(groupId
);
637 return new ArrayList
<>();
639 return new ArrayList
<>(group
.members
);
644 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
645 if (groupId
.length
== 0) {
648 if (name
.isEmpty()) {
651 if (members
.size() == 0) {
654 if (avatar
.isEmpty()) {
657 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
661 * Change the expiration timer for a thread (number of groupId)
663 * @param numberOrGroupId
664 * @param messageExpirationTimer
666 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
667 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
668 thread
.messageExpirationTime
= messageExpirationTimer
;
669 account
.getThreadStore().updateThread(thread
);
672 private void requestSyncGroups() throws IOException
{
673 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
674 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
676 sendSyncMessage(message
);
677 } catch (UntrustedIdentityException e
) {
682 private void requestSyncContacts() throws IOException
{
683 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
684 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
686 sendSyncMessage(message
);
687 } catch (UntrustedIdentityException e
) {
692 private void requestSyncBlocked() throws IOException
{
693 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
694 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
696 sendSyncMessage(message
);
697 } catch (UntrustedIdentityException e
) {
702 private void requestSyncConfiguration() throws IOException
{
703 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
704 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
706 sendSyncMessage(message
);
707 } catch (UntrustedIdentityException e
) {
712 private byte[] getSelfUnidentifiedAccessKey() {
713 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
716 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
721 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
723 return Optional
.absent();
726 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
727 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
728 for (SignalServiceAddress recipient
: recipients
) {
729 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
734 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
736 return Optional
.absent();
739 private void sendSyncMessage(SignalServiceSyncMessage message
)
740 throws IOException
, UntrustedIdentityException
{
741 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
742 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
744 messageSender
.sendMessage(message
, getAccessForSync());
745 } catch (UntrustedIdentityException e
) {
746 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
752 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
754 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
755 throws EncapsulatedExceptions
, IOException
{
756 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
758 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
759 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
760 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
762 for (SendMessageResult result
: results
) {
763 if (result
.isUnregisteredFailure()) {
764 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
765 } else if (result
.isNetworkFailure()) {
766 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
767 } else if (result
.getIdentityFailure() != null) {
768 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
771 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
772 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
776 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
778 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
779 if (recipientsTS
== null) {
781 return Collections
.emptyList();
784 SignalServiceDataMessage message
= null;
786 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
787 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
789 message
= messageBuilder
.build();
790 if (message
.getGroupInfo().isPresent()) {
792 final boolean isRecipientUpdate
= false;
793 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
794 for (SendMessageResult r
: result
) {
795 if (r
.getIdentityFailure() != null) {
796 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
800 } catch (UntrustedIdentityException e
) {
801 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
802 return Collections
.emptyList();
804 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(new SignalServiceAddress(username
))) {
805 SignalServiceAddress recipient
= new SignalServiceAddress(username
);
806 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
807 SentTranscriptMessage transcript
= new SentTranscriptMessage(recipient
.getNumber(),
808 message
.getTimestamp(),
810 message
.getExpiresInSeconds(),
811 Collections
.singletonMap(recipient
.getNumber(), unidentifiedAccess
.isPresent()),
813 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
815 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
817 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
818 } catch (UntrustedIdentityException e
) {
819 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
820 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
824 // Send to all individually, so sync messages are sent correctly
825 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
826 for (SignalServiceAddress address
: recipientsTS
) {
827 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
828 if (thread
!= null) {
829 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
831 messageBuilder
.withExpiration(0);
833 message
= messageBuilder
.build();
835 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
837 } catch (UntrustedIdentityException e
) {
838 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
839 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
845 if (message
!= null && message
.isEndSession()) {
846 for (SignalServiceAddress recipient
: recipientsTS
) {
847 handleEndSession(recipient
.getNumber());
854 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
855 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
857 return cipher
.decrypt(envelope
);
858 } catch (ProtocolUntrustedIdentityException e
) {
859 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
860 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
865 private void handleEndSession(String source
) {
866 account
.getSignalProtocolStore().deleteAllSessions(source
);
869 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
871 if (message
.getGroupInfo().isPresent()) {
872 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
873 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
874 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
875 switch (groupInfo
.getType()) {
878 group
= new GroupInfo(groupInfo
.getGroupId());
881 if (groupInfo
.getAvatar().isPresent()) {
882 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
883 if (avatar
.isPointer()) {
885 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
886 } catch (IOException
| InvalidMessageException e
) {
887 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
892 if (groupInfo
.getName().isPresent()) {
893 group
.name
= groupInfo
.getName().get();
896 if (groupInfo
.getMembers().isPresent()) {
897 group
.members
.addAll(groupInfo
.getMembers().get());
900 account
.getGroupStore().updateGroup(group
);
905 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
906 } catch (IOException
| EncapsulatedExceptions e
) {
914 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
915 } catch (IOException
| EncapsulatedExceptions e
) {
919 group
.members
.remove(source
);
920 account
.getGroupStore().updateGroup(group
);
926 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
927 } catch (IOException
| EncapsulatedExceptions e
) {
929 } catch (NotAGroupMemberException e
) {
930 // We have left this group, so don't send a group update message
937 threadId
= destination
;
942 if (message
.isEndSession()) {
943 handleEndSession(isSync ? destination
: source
);
945 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
946 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
947 if (thread
== null) {
948 thread
= new ThreadInfo();
949 thread
.id
= threadId
;
951 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
952 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
953 account
.getThreadStore().updateThread(thread
);
956 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
957 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
958 if (attachment
.isPointer()) {
960 retrieveAttachment(attachment
.asPointer());
961 } catch (IOException
| InvalidMessageException e
) {
962 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
967 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
968 if (source
.equals(username
)) {
969 this.account
.setProfileKey(message
.getProfileKey().get());
971 ContactInfo contact
= account
.getContactStore().getContact(source
);
972 if (contact
== null) {
973 contact
= new ContactInfo();
974 contact
.number
= source
;
976 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
980 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
981 final File cachePath
= new File(getMessageCachePath());
982 if (!cachePath
.exists()) {
985 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
986 if (!dir
.isDirectory()) {
990 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
991 if (!fileEntry
.isFile()) {
994 SignalServiceEnvelope envelope
;
996 envelope
= Utils
.loadEnvelope(fileEntry
);
997 if (envelope
== null) {
1000 } catch (IOException e
) {
1001 e
.printStackTrace();
1004 SignalServiceContent content
= null;
1005 if (!envelope
.isReceipt()) {
1007 content
= decryptMessage(envelope
);
1008 } catch (Exception e
) {
1011 handleMessage(envelope
, content
, ignoreAttachments
);
1014 handler
.handleMessage(envelope
, content
, null);
1016 Files
.delete(fileEntry
.toPath());
1017 } catch (IOException e
) {
1018 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1021 // Try to delete directory if empty
1026 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1027 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1028 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1031 if (messagePipe
== null) {
1032 messagePipe
= messageReceiver
.createMessagePipe();
1036 SignalServiceEnvelope envelope
;
1037 SignalServiceContent content
= null;
1038 Exception exception
= null;
1039 final long now
= new Date().getTime();
1041 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1043 public void onMessage(SignalServiceEnvelope envelope
) {
1044 // store message on disk, before acknowledging receipt to the server
1046 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1047 Utils
.storeEnvelope(envelope
, cacheFile
);
1048 } catch (IOException e
) {
1049 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1053 } catch (TimeoutException e
) {
1054 if (returnOnTimeout
)
1057 } catch (InvalidVersionException e
) {
1058 System
.err
.println("Ignoring error: " + e
.getMessage());
1061 if (!envelope
.isReceipt()) {
1063 content
= decryptMessage(envelope
);
1064 } catch (Exception e
) {
1067 handleMessage(envelope
, content
, ignoreAttachments
);
1070 handler
.handleMessage(envelope
, content
, exception
);
1071 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1072 File cacheFile
= null;
1074 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1075 Files
.delete(cacheFile
.toPath());
1076 // Try to delete directory if empty
1077 new File(getMessageCachePath()).delete();
1078 } catch (IOException e
) {
1079 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1084 if (messagePipe
!= null) {
1085 messagePipe
.shutdown();
1091 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1092 if (content
!= null) {
1093 if (content
.getDataMessage().isPresent()) {
1094 SignalServiceDataMessage message
= content
.getDataMessage().get();
1095 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1097 if (content
.getSyncMessage().isPresent()) {
1098 account
.setMultiDevice(true);
1099 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1100 if (syncMessage
.getSent().isPresent()) {
1101 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1102 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1104 if (syncMessage
.getRequest().isPresent()) {
1105 RequestMessage rm
= syncMessage
.getRequest().get();
1106 if (rm
.isContactsRequest()) {
1109 } catch (UntrustedIdentityException
| IOException e
) {
1110 e
.printStackTrace();
1113 if (rm
.isGroupsRequest()) {
1116 } catch (UntrustedIdentityException
| IOException e
) {
1117 e
.printStackTrace();
1120 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1122 if (syncMessage
.getGroups().isPresent()) {
1123 File tmpFile
= null;
1125 tmpFile
= IOUtils
.createTempFile();
1126 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1127 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1129 while ((g
= s
.read()) != null) {
1130 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1131 if (syncGroup
== null) {
1132 syncGroup
= new GroupInfo(g
.getId());
1134 if (g
.getName().isPresent()) {
1135 syncGroup
.name
= g
.getName().get();
1137 syncGroup
.members
.addAll(g
.getMembers());
1138 syncGroup
.active
= g
.isActive();
1139 if (g
.getColor().isPresent()) {
1140 syncGroup
.color
= g
.getColor().get();
1143 if (g
.getAvatar().isPresent()) {
1144 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1146 account
.getGroupStore().updateGroup(syncGroup
);
1149 } catch (Exception e
) {
1150 e
.printStackTrace();
1152 if (tmpFile
!= null) {
1154 Files
.delete(tmpFile
.toPath());
1155 } catch (IOException e
) {
1156 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1161 if (syncMessage
.getBlockedList().isPresent()) {
1162 // TODO store list of blocked numbers
1164 if (syncMessage
.getContacts().isPresent()) {
1165 File tmpFile
= null;
1167 tmpFile
= IOUtils
.createTempFile();
1168 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1169 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1170 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1171 if (contactsMessage
.isComplete()) {
1172 account
.getContactStore().clear();
1175 while ((c
= s
.read()) != null) {
1176 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1177 account
.setProfileKey(c
.getProfileKey().get());
1179 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1180 if (contact
== null) {
1181 contact
= new ContactInfo();
1182 contact
.number
= c
.getNumber();
1184 if (c
.getName().isPresent()) {
1185 contact
.name
= c
.getName().get();
1187 if (c
.getColor().isPresent()) {
1188 contact
.color
= c
.getColor().get();
1190 if (c
.getProfileKey().isPresent()) {
1191 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1193 if (c
.getVerified().isPresent()) {
1194 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1195 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1197 if (c
.getExpirationTimer().isPresent()) {
1198 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1199 if (thread
== null) {
1200 thread
= new ThreadInfo();
1201 thread
.id
= c
.getNumber();
1203 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1204 account
.getThreadStore().updateThread(thread
);
1206 if (c
.isBlocked()) {
1207 // TODO store list of blocked numbers
1209 account
.getContactStore().updateContact(contact
);
1211 if (c
.getAvatar().isPresent()) {
1212 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1216 } catch (Exception e
) {
1217 e
.printStackTrace();
1219 if (tmpFile
!= null) {
1221 Files
.delete(tmpFile
.toPath());
1222 } catch (IOException e
) {
1223 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1228 if (syncMessage
.getVerified().isPresent()) {
1229 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1230 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1232 if (syncMessage
.getConfiguration().isPresent()) {
1239 private File
getContactAvatarFile(String number
) {
1240 return new File(avatarsPath
, "contact-" + number
);
1243 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1244 IOUtils
.createPrivateDirectories(avatarsPath
);
1245 if (attachment
.isPointer()) {
1246 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1247 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1249 SignalServiceAttachmentStream stream
= attachment
.asStream();
1250 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1254 private File
getGroupAvatarFile(byte[] groupId
) {
1255 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1258 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1259 IOUtils
.createPrivateDirectories(avatarsPath
);
1260 if (attachment
.isPointer()) {
1261 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1262 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1264 SignalServiceAttachmentStream stream
= attachment
.asStream();
1265 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1269 public File
getAttachmentFile(long attachmentId
) {
1270 return new File(attachmentsPath
, attachmentId
+ "");
1273 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1274 IOUtils
.createPrivateDirectories(attachmentsPath
);
1275 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1278 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1279 if (storePreview
&& pointer
.getPreview().isPresent()) {
1280 File previewFile
= new File(outputFile
+ ".preview");
1281 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1282 byte[] preview
= pointer
.getPreview().get();
1283 output
.write(preview
, 0, preview
.length
);
1284 } catch (FileNotFoundException e
) {
1285 e
.printStackTrace();
1290 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1292 File tmpFile
= IOUtils
.createTempFile();
1293 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1294 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1295 byte[] buffer
= new byte[4096];
1298 while ((read
= input
.read(buffer
)) != -1) {
1299 output
.write(buffer
, 0, read
);
1301 } catch (FileNotFoundException e
) {
1302 e
.printStackTrace();
1307 Files
.delete(tmpFile
.toPath());
1308 } catch (IOException e
) {
1309 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1315 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1316 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1317 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1321 public boolean isRemote() {
1325 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1326 File groupsFile
= IOUtils
.createTempFile();
1329 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1330 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1331 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1332 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1333 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1334 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1335 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1336 Optional
.fromNullable(record.color
), false));
1340 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1341 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1342 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1343 .withStream(groupsFileStream
)
1344 .withContentType("application/octet-stream")
1345 .withLength(groupsFile
.length())
1348 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1353 Files
.delete(groupsFile
.toPath());
1354 } catch (IOException e
) {
1355 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1360 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1361 File contactsFile
= IOUtils
.createTempFile();
1364 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1365 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1366 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1367 VerifiedMessage verifiedMessage
= null;
1368 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1369 if (getIdentities().containsKey(record.number
)) {
1370 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1371 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1372 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1373 currentIdentity
= id
;
1376 if (currentIdentity
!= null) {
1377 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1381 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1382 // TODO store list of blocked numbers
1383 boolean blocked
= false;
1384 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1385 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1386 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1389 if (account
.getProfileKey() != null) {
1390 // Send our own profile key as well
1391 out
.write(new DeviceContact(account
.getUsername(),
1392 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1393 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1394 Optional
.of(account
.getProfileKey()),
1395 false, Optional
.<Integer
>absent()));
1399 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1400 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1401 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1402 .withStream(contactsFileStream
)
1403 .withContentType("application/octet-stream")
1404 .withLength(contactsFile
.length())
1407 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1412 Files
.delete(contactsFile
.toPath());
1413 } catch (IOException e
) {
1414 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1419 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1420 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1421 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1424 public ContactInfo
getContact(String number
) {
1425 return account
.getContactStore().getContact(number
);
1428 public GroupInfo
getGroup(byte[] groupId
) {
1429 return account
.getGroupStore().getGroup(groupId
);
1432 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1433 return account
.getSignalProtocolStore().getIdentities();
1436 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1437 return account
.getSignalProtocolStore().getIdentities(number
);
1441 * Trust this the identity with this fingerprint
1443 * @param name username of the identity
1444 * @param fingerprint Fingerprint
1446 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1447 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1451 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1452 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1456 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1458 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1459 } catch (IOException
| UntrustedIdentityException e
) {
1460 e
.printStackTrace();
1469 * Trust this the identity with this safety number
1471 * @param name username of the identity
1472 * @param safetyNumber Safety number
1474 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1475 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1479 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1480 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1484 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1486 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1487 } catch (IOException
| UntrustedIdentityException e
) {
1488 e
.printStackTrace();
1497 * Trust all keys of this identity without verification
1499 * @param name username of the identity
1501 public boolean trustIdentityAllKeys(String name
) {
1502 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1506 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1507 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1508 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1510 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1511 } catch (IOException
| UntrustedIdentityException e
) {
1512 e
.printStackTrace();
1520 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1521 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1524 public interface ReceiveMessageHandler
{
1526 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);