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 final StreamDetails streamDetails
= Utils
.createStreamDetailsFromFile(avatar
);
214 accountManager
.setProfileAvatar(account
.getProfileKey(), streamDetails
);
215 streamDetails
.getStream().close();
218 public void removeProfileAvatar() throws IOException
{
219 accountManager
.setProfileAvatar(account
.getProfileKey(), null);
222 public void unregister() throws IOException
{
223 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
224 // If this is the master device, other users can't send messages to this number anymore.
225 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
226 accountManager
.setGcmId(Optional
.<String
>absent());
228 account
.setRegistered(false);
232 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
233 if (account
== null) {
236 account
.setPassword(KeyUtils
.createPassword());
237 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
238 String uuid
= accountManager
.getNewDeviceUuid();
240 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
243 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
244 account
.setSignalingKey(KeyUtils
.createSignalingKey());
245 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
247 username
= ret
.getNumber();
248 // TODO do this check before actually registering
249 if (SignalAccount
.userExists(dataPath
, username
)) {
250 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
253 // Create new account with the synced identity
254 byte[] profileKey
= ret
.getProfileKey();
255 if (profileKey
== null) {
256 profileKey
= KeyUtils
.createProfileKey();
258 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
263 requestSyncContacts();
264 requestSyncBlocked();
265 requestSyncConfiguration();
270 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
271 List
<DeviceInfo
> devices
= accountManager
.getDevices();
272 account
.setMultiDevice(devices
.size() > 1);
277 public void removeLinkedDevices(int deviceId
) throws IOException
{
278 accountManager
.removeDevice(deviceId
);
279 List
<DeviceInfo
> devices
= accountManager
.getDevices();
280 account
.setMultiDevice(devices
.size() > 1);
284 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
285 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
287 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
290 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
291 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
292 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
294 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
295 account
.setMultiDevice(true);
299 private List
<PreKeyRecord
> generatePreKeys() {
300 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
302 final int offset
= account
.getPreKeyIdOffset();
303 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
304 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
305 ECKeyPair keyPair
= Curve
.generateKeyPair();
306 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
311 account
.addPreKeys(records
);
317 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
319 ECKeyPair keyPair
= Curve
.generateKeyPair();
320 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
321 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
323 account
.addSignedPreKey(record);
327 } catch (InvalidKeyException e
) {
328 throw new AssertionError(e
);
332 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
333 verificationCode
= verificationCode
.replace("-", "");
334 account
.setSignalingKey(KeyUtils
.createSignalingKey());
335 // TODO make unrestricted unidentified access configurable
336 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
338 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
339 account
.setRegistered(true);
340 account
.setRegistrationLockPin(pin
);
346 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
347 accountManager
.setPin(pin
);
348 if (pin
.isPresent()) {
349 account
.setRegistrationLockPin(pin
.get());
351 account
.setRegistrationLockPin(null);
356 private void refreshPreKeys() throws IOException
{
357 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
358 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
359 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
361 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
364 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
365 File file
= getGroupAvatarFile(groupId
);
366 if (!file
.exists()) {
367 return Optional
.absent();
370 return Optional
.of(Utils
.createAttachment(file
));
373 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
374 File file
= getContactAvatarFile(number
);
375 if (!file
.exists()) {
376 return Optional
.absent();
379 return Optional
.of(Utils
.createAttachment(file
));
382 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
383 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
385 throw new GroupNotFoundException(groupId
);
387 for (String member
: g
.members
) {
388 if (member
.equals(this.username
)) {
392 throw new NotAGroupMemberException(groupId
, g
.name
);
395 public List
<GroupInfo
> getGroups() {
396 return account
.getGroupStore().getGroups();
400 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
402 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
403 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
404 if (attachments
!= null) {
405 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
407 if (groupId
!= null) {
408 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
411 messageBuilder
.asGroupMessage(group
);
413 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
414 if (thread
!= null) {
415 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
418 final GroupInfo g
= getGroupForSending(groupId
);
420 // Don't send group message to ourself
421 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
422 membersSend
.remove(this.username
);
423 sendMessageLegacy(messageBuilder
, membersSend
);
426 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
427 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
431 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
432 .asGroupMessage(group
);
434 final GroupInfo g
= getGroupForSending(groupId
);
435 g
.members
.remove(this.username
);
436 account
.getGroupStore().updateGroup(g
);
438 sendMessageLegacy(messageBuilder
, g
.members
);
441 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
443 if (groupId
== null) {
445 g
= new GroupInfo(KeyUtils
.createGroupId());
446 g
.members
.add(username
);
448 g
= getGroupForSending(groupId
);
455 if (members
!= null) {
456 Set
<String
> newMembers
= new HashSet
<>();
457 for (String member
: members
) {
459 member
= Utils
.canonicalizeNumber(member
, username
);
460 } catch (InvalidNumberException e
) {
461 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
462 System
.err
.println("Aborting…");
465 if (g
.members
.contains(member
)) {
468 newMembers
.add(member
);
469 g
.members
.add(member
);
471 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
472 if (contacts
.size() != newMembers
.size()) {
473 // Some of the new members are not registered on Signal
474 for (ContactTokenDetails contact
: contacts
) {
475 newMembers
.remove(contact
.getNumber());
477 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
478 System
.err
.println("Aborting…");
483 if (avatarFile
!= null) {
484 IOUtils
.createPrivateDirectories(avatarsPath
);
485 File aFile
= getGroupAvatarFile(g
.groupId
);
486 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
489 account
.getGroupStore().updateGroup(g
);
491 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
493 // Don't send group message to ourself
494 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
495 membersSend
.remove(this.username
);
496 sendMessageLegacy(messageBuilder
, membersSend
);
500 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
501 if (groupId
== null) {
504 GroupInfo g
= getGroupForSending(groupId
);
506 if (!g
.members
.contains(recipient
)) {
510 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
512 // Send group message only to the recipient who requested it
513 final List
<String
> membersSend
= new ArrayList
<>();
514 membersSend
.add(recipient
);
515 sendMessageLegacy(messageBuilder
, membersSend
);
518 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
519 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
522 .withMembers(new ArrayList
<>(g
.members
));
524 File aFile
= getGroupAvatarFile(g
.groupId
);
525 if (aFile
.exists()) {
527 group
.withAvatar(Utils
.createAttachment(aFile
));
528 } catch (IOException e
) {
529 throw new AttachmentInvalidException(aFile
.toString(), e
);
533 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
534 .asGroupMessage(group
.build());
536 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
537 if (thread
!= null) {
538 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
541 return messageBuilder
;
544 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
545 if (groupId
== null) {
549 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
552 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
553 .asGroupMessage(group
.build());
555 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
556 if (thread
!= null) {
557 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
560 // Send group info request message to the recipient who sent us a message with this groupId
561 final List
<String
> membersSend
= new ArrayList
<>();
562 membersSend
.add(recipient
);
563 sendMessageLegacy(messageBuilder
, membersSend
);
567 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
568 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
569 List
<String
> recipients
= new ArrayList
<>(1);
570 recipients
.add(recipient
);
571 sendMessage(message
, attachments
, recipients
);
575 public void sendMessage(String messageText
, List
<String
> attachments
,
576 List
<String
> recipients
)
577 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
578 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
579 if (attachments
!= null) {
580 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
582 messageBuilder
.withProfileKey(account
.getProfileKey());
583 sendMessageLegacy(messageBuilder
, recipients
);
587 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
588 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
589 .asEndSessionMessage();
591 sendMessageLegacy(messageBuilder
, recipients
);
595 public String
getContactName(String number
) {
596 ContactInfo contact
= account
.getContactStore().getContact(number
);
597 if (contact
== null) {
605 public void setContactName(String number
, String name
) {
606 ContactInfo contact
= account
.getContactStore().getContact(number
);
607 if (contact
== null) {
608 contact
= new ContactInfo();
609 contact
.number
= number
;
610 System
.err
.println("Add contact " + number
+ " named " + name
);
612 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
615 account
.getContactStore().updateContact(contact
);
620 public List
<byte[]> getGroupIds() {
621 List
<GroupInfo
> groups
= getGroups();
622 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
623 for (GroupInfo group
: groups
) {
624 ids
.add(group
.groupId
);
630 public String
getGroupName(byte[] groupId
) {
631 GroupInfo group
= getGroup(groupId
);
640 public List
<String
> getGroupMembers(byte[] groupId
) {
641 GroupInfo group
= getGroup(groupId
);
643 return new ArrayList
<>();
645 return new ArrayList
<>(group
.members
);
650 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
651 if (groupId
.length
== 0) {
654 if (name
.isEmpty()) {
657 if (members
.size() == 0) {
660 if (avatar
.isEmpty()) {
663 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
667 * Change the expiration timer for a thread (number of groupId)
669 * @param numberOrGroupId
670 * @param messageExpirationTimer
672 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
673 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
674 thread
.messageExpirationTime
= messageExpirationTimer
;
675 account
.getThreadStore().updateThread(thread
);
678 private void requestSyncGroups() throws IOException
{
679 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
680 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
682 sendSyncMessage(message
);
683 } catch (UntrustedIdentityException e
) {
688 private void requestSyncContacts() throws IOException
{
689 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
690 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
692 sendSyncMessage(message
);
693 } catch (UntrustedIdentityException e
) {
698 private void requestSyncBlocked() throws IOException
{
699 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
700 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
702 sendSyncMessage(message
);
703 } catch (UntrustedIdentityException e
) {
708 private void requestSyncConfiguration() throws IOException
{
709 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
710 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
712 sendSyncMessage(message
);
713 } catch (UntrustedIdentityException e
) {
718 private byte[] getSelfUnidentifiedAccessKey() {
719 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
722 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
727 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
729 return Optional
.absent();
732 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
733 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
734 for (SignalServiceAddress recipient
: recipients
) {
735 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
740 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
742 return Optional
.absent();
745 private void sendSyncMessage(SignalServiceSyncMessage message
)
746 throws IOException
, UntrustedIdentityException
{
747 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
748 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
750 messageSender
.sendMessage(message
, getAccessForSync());
751 } catch (UntrustedIdentityException e
) {
752 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
758 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
760 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
761 throws EncapsulatedExceptions
, IOException
{
762 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
764 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
765 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
766 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
768 for (SendMessageResult result
: results
) {
769 if (result
.isUnregisteredFailure()) {
770 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
771 } else if (result
.isNetworkFailure()) {
772 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
773 } else if (result
.getIdentityFailure() != null) {
774 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
777 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
778 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
782 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
784 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
785 if (recipientsTS
== null) {
787 return Collections
.emptyList();
790 SignalServiceDataMessage message
= null;
792 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
793 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
795 message
= messageBuilder
.build();
796 if (message
.getGroupInfo().isPresent()) {
798 final boolean isRecipientUpdate
= false;
799 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
800 for (SendMessageResult r
: result
) {
801 if (r
.getIdentityFailure() != null) {
802 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
806 } catch (UntrustedIdentityException e
) {
807 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
808 return Collections
.emptyList();
810 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(new SignalServiceAddress(username
))) {
811 SignalServiceAddress recipient
= new SignalServiceAddress(username
);
812 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
813 SentTranscriptMessage transcript
= new SentTranscriptMessage(recipient
.getNumber(),
814 message
.getTimestamp(),
816 message
.getExpiresInSeconds(),
817 Collections
.singletonMap(recipient
.getNumber(), unidentifiedAccess
.isPresent()),
819 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
821 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
823 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
824 } catch (UntrustedIdentityException e
) {
825 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
826 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
830 // Send to all individually, so sync messages are sent correctly
831 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
832 for (SignalServiceAddress address
: recipientsTS
) {
833 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
834 if (thread
!= null) {
835 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
837 messageBuilder
.withExpiration(0);
839 message
= messageBuilder
.build();
841 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
843 } catch (UntrustedIdentityException e
) {
844 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
845 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
851 if (message
!= null && message
.isEndSession()) {
852 for (SignalServiceAddress recipient
: recipientsTS
) {
853 handleEndSession(recipient
.getNumber());
860 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
861 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
863 return cipher
.decrypt(envelope
);
864 } catch (ProtocolUntrustedIdentityException e
) {
865 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
866 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
871 private void handleEndSession(String source
) {
872 account
.getSignalProtocolStore().deleteAllSessions(source
);
875 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
877 if (message
.getGroupInfo().isPresent()) {
878 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
879 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
880 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
881 switch (groupInfo
.getType()) {
884 group
= new GroupInfo(groupInfo
.getGroupId());
887 if (groupInfo
.getAvatar().isPresent()) {
888 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
889 if (avatar
.isPointer()) {
891 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
892 } catch (IOException
| InvalidMessageException e
) {
893 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
898 if (groupInfo
.getName().isPresent()) {
899 group
.name
= groupInfo
.getName().get();
902 if (groupInfo
.getMembers().isPresent()) {
903 group
.members
.addAll(groupInfo
.getMembers().get());
906 account
.getGroupStore().updateGroup(group
);
911 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
912 } catch (IOException
| EncapsulatedExceptions e
) {
920 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
921 } catch (IOException
| EncapsulatedExceptions e
) {
925 group
.members
.remove(source
);
926 account
.getGroupStore().updateGroup(group
);
932 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
933 } catch (IOException
| EncapsulatedExceptions e
) {
935 } catch (NotAGroupMemberException e
) {
936 // We have left this group, so don't send a group update message
943 threadId
= destination
;
948 if (message
.isEndSession()) {
949 handleEndSession(isSync ? destination
: source
);
951 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
952 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
953 if (thread
== null) {
954 thread
= new ThreadInfo();
955 thread
.id
= threadId
;
957 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
958 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
959 account
.getThreadStore().updateThread(thread
);
962 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
963 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
964 if (attachment
.isPointer()) {
966 retrieveAttachment(attachment
.asPointer());
967 } catch (IOException
| InvalidMessageException e
) {
968 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
973 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
974 if (source
.equals(username
)) {
975 this.account
.setProfileKey(message
.getProfileKey().get());
977 ContactInfo contact
= account
.getContactStore().getContact(source
);
978 if (contact
== null) {
979 contact
= new ContactInfo();
980 contact
.number
= source
;
982 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
986 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
987 final File cachePath
= new File(getMessageCachePath());
988 if (!cachePath
.exists()) {
991 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
992 if (!dir
.isDirectory()) {
996 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
997 if (!fileEntry
.isFile()) {
1000 SignalServiceEnvelope envelope
;
1002 envelope
= Utils
.loadEnvelope(fileEntry
);
1003 if (envelope
== null) {
1006 } catch (IOException e
) {
1007 e
.printStackTrace();
1010 SignalServiceContent content
= null;
1011 if (!envelope
.isReceipt()) {
1013 content
= decryptMessage(envelope
);
1014 } catch (Exception e
) {
1017 handleMessage(envelope
, content
, ignoreAttachments
);
1020 handler
.handleMessage(envelope
, content
, null);
1022 Files
.delete(fileEntry
.toPath());
1023 } catch (IOException e
) {
1024 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1027 // Try to delete directory if empty
1032 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1033 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1034 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1037 if (messagePipe
== null) {
1038 messagePipe
= messageReceiver
.createMessagePipe();
1042 SignalServiceEnvelope envelope
;
1043 SignalServiceContent content
= null;
1044 Exception exception
= null;
1045 final long now
= new Date().getTime();
1047 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1049 public void onMessage(SignalServiceEnvelope envelope
) {
1050 // store message on disk, before acknowledging receipt to the server
1052 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1053 Utils
.storeEnvelope(envelope
, cacheFile
);
1054 } catch (IOException e
) {
1055 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1059 } catch (TimeoutException e
) {
1060 if (returnOnTimeout
)
1063 } catch (InvalidVersionException e
) {
1064 System
.err
.println("Ignoring error: " + e
.getMessage());
1067 if (!envelope
.isReceipt()) {
1069 content
= decryptMessage(envelope
);
1070 } catch (Exception e
) {
1073 handleMessage(envelope
, content
, ignoreAttachments
);
1076 handler
.handleMessage(envelope
, content
, exception
);
1077 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1078 File cacheFile
= null;
1080 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1081 Files
.delete(cacheFile
.toPath());
1082 // Try to delete directory if empty
1083 new File(getMessageCachePath()).delete();
1084 } catch (IOException e
) {
1085 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1090 if (messagePipe
!= null) {
1091 messagePipe
.shutdown();
1097 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1098 if (content
!= null) {
1099 if (content
.getDataMessage().isPresent()) {
1100 SignalServiceDataMessage message
= content
.getDataMessage().get();
1101 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1103 if (content
.getSyncMessage().isPresent()) {
1104 account
.setMultiDevice(true);
1105 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1106 if (syncMessage
.getSent().isPresent()) {
1107 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1108 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1110 if (syncMessage
.getRequest().isPresent()) {
1111 RequestMessage rm
= syncMessage
.getRequest().get();
1112 if (rm
.isContactsRequest()) {
1115 } catch (UntrustedIdentityException
| IOException e
) {
1116 e
.printStackTrace();
1119 if (rm
.isGroupsRequest()) {
1122 } catch (UntrustedIdentityException
| IOException e
) {
1123 e
.printStackTrace();
1126 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1128 if (syncMessage
.getGroups().isPresent()) {
1129 File tmpFile
= null;
1131 tmpFile
= IOUtils
.createTempFile();
1132 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1133 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1135 while ((g
= s
.read()) != null) {
1136 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1137 if (syncGroup
== null) {
1138 syncGroup
= new GroupInfo(g
.getId());
1140 if (g
.getName().isPresent()) {
1141 syncGroup
.name
= g
.getName().get();
1143 syncGroup
.members
.addAll(g
.getMembers());
1144 syncGroup
.active
= g
.isActive();
1145 if (g
.getColor().isPresent()) {
1146 syncGroup
.color
= g
.getColor().get();
1149 if (g
.getAvatar().isPresent()) {
1150 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1152 account
.getGroupStore().updateGroup(syncGroup
);
1155 } catch (Exception e
) {
1156 e
.printStackTrace();
1158 if (tmpFile
!= null) {
1160 Files
.delete(tmpFile
.toPath());
1161 } catch (IOException e
) {
1162 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1167 if (syncMessage
.getBlockedList().isPresent()) {
1168 // TODO store list of blocked numbers
1170 if (syncMessage
.getContacts().isPresent()) {
1171 File tmpFile
= null;
1173 tmpFile
= IOUtils
.createTempFile();
1174 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1175 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1176 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1177 if (contactsMessage
.isComplete()) {
1178 account
.getContactStore().clear();
1181 while ((c
= s
.read()) != null) {
1182 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1183 account
.setProfileKey(c
.getProfileKey().get());
1185 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1186 if (contact
== null) {
1187 contact
= new ContactInfo();
1188 contact
.number
= c
.getNumber();
1190 if (c
.getName().isPresent()) {
1191 contact
.name
= c
.getName().get();
1193 if (c
.getColor().isPresent()) {
1194 contact
.color
= c
.getColor().get();
1196 if (c
.getProfileKey().isPresent()) {
1197 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1199 if (c
.getVerified().isPresent()) {
1200 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1201 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1203 if (c
.getExpirationTimer().isPresent()) {
1204 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1205 if (thread
== null) {
1206 thread
= new ThreadInfo();
1207 thread
.id
= c
.getNumber();
1209 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1210 account
.getThreadStore().updateThread(thread
);
1212 if (c
.isBlocked()) {
1213 // TODO store list of blocked numbers
1215 account
.getContactStore().updateContact(contact
);
1217 if (c
.getAvatar().isPresent()) {
1218 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1222 } catch (Exception e
) {
1223 e
.printStackTrace();
1225 if (tmpFile
!= null) {
1227 Files
.delete(tmpFile
.toPath());
1228 } catch (IOException e
) {
1229 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1234 if (syncMessage
.getVerified().isPresent()) {
1235 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1236 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1238 if (syncMessage
.getConfiguration().isPresent()) {
1245 private File
getContactAvatarFile(String number
) {
1246 return new File(avatarsPath
, "contact-" + number
);
1249 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1250 IOUtils
.createPrivateDirectories(avatarsPath
);
1251 if (attachment
.isPointer()) {
1252 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1253 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1255 SignalServiceAttachmentStream stream
= attachment
.asStream();
1256 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1260 private File
getGroupAvatarFile(byte[] groupId
) {
1261 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1264 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1265 IOUtils
.createPrivateDirectories(avatarsPath
);
1266 if (attachment
.isPointer()) {
1267 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1268 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1270 SignalServiceAttachmentStream stream
= attachment
.asStream();
1271 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1275 public File
getAttachmentFile(long attachmentId
) {
1276 return new File(attachmentsPath
, attachmentId
+ "");
1279 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1280 IOUtils
.createPrivateDirectories(attachmentsPath
);
1281 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1284 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1285 if (storePreview
&& pointer
.getPreview().isPresent()) {
1286 File previewFile
= new File(outputFile
+ ".preview");
1287 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1288 byte[] preview
= pointer
.getPreview().get();
1289 output
.write(preview
, 0, preview
.length
);
1290 } catch (FileNotFoundException e
) {
1291 e
.printStackTrace();
1296 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1298 File tmpFile
= IOUtils
.createTempFile();
1299 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1300 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1301 byte[] buffer
= new byte[4096];
1304 while ((read
= input
.read(buffer
)) != -1) {
1305 output
.write(buffer
, 0, read
);
1307 } catch (FileNotFoundException e
) {
1308 e
.printStackTrace();
1313 Files
.delete(tmpFile
.toPath());
1314 } catch (IOException e
) {
1315 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1321 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1322 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1323 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1327 public boolean isRemote() {
1331 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1332 File groupsFile
= IOUtils
.createTempFile();
1335 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1336 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1337 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1338 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1339 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1340 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1341 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1342 Optional
.fromNullable(record.color
), false));
1346 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1347 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1348 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1349 .withStream(groupsFileStream
)
1350 .withContentType("application/octet-stream")
1351 .withLength(groupsFile
.length())
1354 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1359 Files
.delete(groupsFile
.toPath());
1360 } catch (IOException e
) {
1361 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1366 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1367 File contactsFile
= IOUtils
.createTempFile();
1370 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1371 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1372 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1373 VerifiedMessage verifiedMessage
= null;
1374 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1375 if (getIdentities().containsKey(record.number
)) {
1376 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1377 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1378 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1379 currentIdentity
= id
;
1382 if (currentIdentity
!= null) {
1383 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1387 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1388 // TODO store list of blocked numbers
1389 boolean blocked
= false;
1390 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1391 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1392 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1395 if (account
.getProfileKey() != null) {
1396 // Send our own profile key as well
1397 out
.write(new DeviceContact(account
.getUsername(),
1398 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1399 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1400 Optional
.of(account
.getProfileKey()),
1401 false, Optional
.<Integer
>absent()));
1405 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1406 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1407 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1408 .withStream(contactsFileStream
)
1409 .withContentType("application/octet-stream")
1410 .withLength(contactsFile
.length())
1413 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1418 Files
.delete(contactsFile
.toPath());
1419 } catch (IOException e
) {
1420 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1425 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1426 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1427 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1430 public ContactInfo
getContact(String number
) {
1431 return account
.getContactStore().getContact(number
);
1434 public GroupInfo
getGroup(byte[] groupId
) {
1435 return account
.getGroupStore().getGroup(groupId
);
1438 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1439 return account
.getSignalProtocolStore().getIdentities();
1442 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1443 return account
.getSignalProtocolStore().getIdentities(number
);
1447 * Trust this the identity with this fingerprint
1449 * @param name username of the identity
1450 * @param fingerprint Fingerprint
1452 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1453 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1457 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1458 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1462 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1464 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1465 } catch (IOException
| UntrustedIdentityException e
) {
1466 e
.printStackTrace();
1475 * Trust this the identity with this safety number
1477 * @param name username of the identity
1478 * @param safetyNumber Safety number
1480 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1481 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1485 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1486 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1490 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1492 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1493 } catch (IOException
| UntrustedIdentityException e
) {
1494 e
.printStackTrace();
1503 * Trust all keys of this identity without verification
1505 * @param name username of the identity
1507 public boolean trustIdentityAllKeys(String name
) {
1508 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1512 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1513 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1514 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1516 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1517 } catch (IOException
| UntrustedIdentityException e
) {
1518 e
.printStackTrace();
1526 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1527 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1530 public interface ReceiveMessageHandler
{
1532 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);