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
.UptimeSleepTimer
;
58 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
59 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
63 import java
.nio
.file
.Files
;
64 import java
.nio
.file
.Paths
;
65 import java
.nio
.file
.StandardCopyOption
;
67 import java
.util
.concurrent
.TimeUnit
;
68 import java
.util
.concurrent
.TimeoutException
;
70 public class Manager
implements Signal
{
72 private final String settingsPath
;
73 private final String dataPath
;
74 private final String attachmentsPath
;
75 private final String avatarsPath
;
76 private final SleepTimer timer
= new UptimeSleepTimer();
78 private SignalAccount account
;
79 private String username
;
80 private SignalServiceAccountManager accountManager
;
81 private SignalServiceMessagePipe messagePipe
= null;
82 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
84 public Manager(String username
, String settingsPath
) {
85 this.username
= username
;
86 this.settingsPath
= settingsPath
;
87 this.dataPath
= this.settingsPath
+ "/data";
88 this.attachmentsPath
= this.settingsPath
+ "/attachments";
89 this.avatarsPath
= this.settingsPath
+ "/avatars";
93 public String
getUsername() {
97 private IdentityKey
getIdentity() {
98 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
101 public int getDeviceId() {
102 return account
.getDeviceId();
105 private String
getMessageCachePath() {
106 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
109 private String
getMessageCachePath(String sender
) {
110 return getMessageCachePath() + "/" + sender
.replace("/", "_");
113 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
114 String cachePath
= getMessageCachePath(sender
);
115 IOUtils
.createPrivateDirectories(cachePath
);
116 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
119 public boolean userHasKeys() {
120 return account
!= null && account
.getSignalProtocolStore() != null;
123 public void init() throws IOException
{
124 if (!SignalAccount
.userExists(dataPath
, username
)) {
127 account
= SignalAccount
.load(dataPath
, username
);
129 migrateLegacyConfigs();
131 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
133 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
137 } catch (AuthorizationFailedException e
) {
138 System
.err
.println("Authorization failed, was the number registered elsewhere?");
142 private void migrateLegacyConfigs() {
143 // Copy group avatars that were previously stored in the attachments folder
144 // to the new avatar folder
145 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
146 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
147 File avatarFile
= getGroupAvatarFile(g
.groupId
);
148 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
149 if (!avatarFile
.exists() && attachmentFile
.exists()) {
151 IOUtils
.createPrivateDirectories(avatarsPath
);
152 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
153 } catch (Exception e
) {
158 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
161 if (account
.getProfileKey() == null) {
162 // Old config file, creating new profile key
163 account
.setProfileKey(KeyUtils
.createProfileKey());
168 private void createNewIdentity() throws IOException
{
169 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
170 int registrationId
= KeyHelper
.generateRegistrationId(false);
171 if (username
== null) {
172 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
174 byte[] profileKey
= KeyUtils
.createProfileKey();
175 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
180 public boolean isRegistered() {
181 return account
!= null && account
.isRegistered();
184 public void register(boolean voiceVerification
) throws IOException
{
185 if (account
== null) {
188 account
.setPassword(KeyUtils
.createPassword());
189 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, account
.getUsername(), account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
191 if (voiceVerification
) {
192 accountManager
.requestVoiceVerificationCode(Locale
.getDefault(), Optional
.<String
>absent());
194 accountManager
.requestSmsVerificationCode(false, Optional
.<String
>absent());
197 account
.setRegistered(false);
201 public void updateAccountAttributes() throws IOException
{
202 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
205 public void unregister() throws IOException
{
206 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
207 // If this is the master device, other users can't send messages to this number anymore.
208 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
209 accountManager
.setGcmId(Optional
.<String
>absent());
212 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
213 if (account
== null) {
216 account
.setPassword(KeyUtils
.createPassword());
217 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
218 String uuid
= accountManager
.getNewDeviceUuid();
220 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
223 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
224 account
.setSignalingKey(KeyUtils
.createSignalingKey());
225 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
227 username
= ret
.getNumber();
228 // TODO do this check before actually registering
229 if (SignalAccount
.userExists(dataPath
, username
)) {
230 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
233 // Create new account with the synced identity
234 byte[] profileKey
= ret
.getProfileKey();
235 if (profileKey
== null) {
236 profileKey
= KeyUtils
.createProfileKey();
238 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
243 requestSyncContacts();
244 requestSyncBlocked();
245 requestSyncConfiguration();
250 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
251 List
<DeviceInfo
> devices
= accountManager
.getDevices();
252 account
.setMultiDevice(devices
.size() > 1);
257 public void removeLinkedDevices(int deviceId
) throws IOException
{
258 accountManager
.removeDevice(deviceId
);
259 List
<DeviceInfo
> devices
= accountManager
.getDevices();
260 account
.setMultiDevice(devices
.size() > 1);
264 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
265 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
267 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
270 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
271 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
272 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
274 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
275 account
.setMultiDevice(true);
279 private List
<PreKeyRecord
> generatePreKeys() {
280 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
282 final int offset
= account
.getPreKeyIdOffset();
283 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
284 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
285 ECKeyPair keyPair
= Curve
.generateKeyPair();
286 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
291 account
.addPreKeys(records
);
297 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
299 ECKeyPair keyPair
= Curve
.generateKeyPair();
300 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
301 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
303 account
.addSignedPreKey(record);
307 } catch (InvalidKeyException e
) {
308 throw new AssertionError(e
);
312 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
313 verificationCode
= verificationCode
.replace("-", "");
314 account
.setSignalingKey(KeyUtils
.createSignalingKey());
315 // TODO make unrestricted unidentified access configurable
316 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
318 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
319 account
.setRegistered(true);
320 account
.setRegistrationLockPin(pin
);
326 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
327 accountManager
.setPin(pin
);
328 if (pin
.isPresent()) {
329 account
.setRegistrationLockPin(pin
.get());
331 account
.setRegistrationLockPin(null);
336 private void refreshPreKeys() throws IOException
{
337 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
338 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
339 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
341 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
344 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
345 File file
= getGroupAvatarFile(groupId
);
346 if (!file
.exists()) {
347 return Optional
.absent();
350 return Optional
.of(Utils
.createAttachment(file
));
353 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
354 File file
= getContactAvatarFile(number
);
355 if (!file
.exists()) {
356 return Optional
.absent();
359 return Optional
.of(Utils
.createAttachment(file
));
362 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
363 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
365 throw new GroupNotFoundException(groupId
);
367 for (String member
: g
.members
) {
368 if (member
.equals(this.username
)) {
372 throw new NotAGroupMemberException(groupId
, g
.name
);
375 public List
<GroupInfo
> getGroups() {
376 return account
.getGroupStore().getGroups();
380 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
382 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
383 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
384 if (attachments
!= null) {
385 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
387 if (groupId
!= null) {
388 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
391 messageBuilder
.asGroupMessage(group
);
393 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
394 if (thread
!= null) {
395 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
398 final GroupInfo g
= getGroupForSending(groupId
);
400 // Don't send group message to ourself
401 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
402 membersSend
.remove(this.username
);
403 sendMessageLegacy(messageBuilder
, membersSend
);
406 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
407 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
411 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
412 .asGroupMessage(group
);
414 final GroupInfo g
= getGroupForSending(groupId
);
415 g
.members
.remove(this.username
);
416 account
.getGroupStore().updateGroup(g
);
418 sendMessageLegacy(messageBuilder
, g
.members
);
421 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
423 if (groupId
== null) {
425 g
= new GroupInfo(KeyUtils
.createGroupId());
426 g
.members
.add(username
);
428 g
= getGroupForSending(groupId
);
435 if (members
!= null) {
436 Set
<String
> newMembers
= new HashSet
<>();
437 for (String member
: members
) {
439 member
= Utils
.canonicalizeNumber(member
, username
);
440 } catch (InvalidNumberException e
) {
441 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
442 System
.err
.println("Aborting…");
445 if (g
.members
.contains(member
)) {
448 newMembers
.add(member
);
449 g
.members
.add(member
);
451 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
452 if (contacts
.size() != newMembers
.size()) {
453 // Some of the new members are not registered on Signal
454 for (ContactTokenDetails contact
: contacts
) {
455 newMembers
.remove(contact
.getNumber());
457 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
458 System
.err
.println("Aborting…");
463 if (avatarFile
!= null) {
464 IOUtils
.createPrivateDirectories(avatarsPath
);
465 File aFile
= getGroupAvatarFile(g
.groupId
);
466 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
469 account
.getGroupStore().updateGroup(g
);
471 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
473 // Don't send group message to ourself
474 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
475 membersSend
.remove(this.username
);
476 sendMessageLegacy(messageBuilder
, membersSend
);
480 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
481 if (groupId
== null) {
484 GroupInfo g
= getGroupForSending(groupId
);
486 if (!g
.members
.contains(recipient
)) {
490 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
492 // Send group message only to the recipient who requested it
493 final List
<String
> membersSend
= new ArrayList
<>();
494 membersSend
.add(recipient
);
495 sendMessageLegacy(messageBuilder
, membersSend
);
498 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
499 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
502 .withMembers(new ArrayList
<>(g
.members
));
504 File aFile
= getGroupAvatarFile(g
.groupId
);
505 if (aFile
.exists()) {
507 group
.withAvatar(Utils
.createAttachment(aFile
));
508 } catch (IOException e
) {
509 throw new AttachmentInvalidException(aFile
.toString(), e
);
513 return SignalServiceDataMessage
.newBuilder()
514 .asGroupMessage(group
.build());
517 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
518 if (groupId
== null) {
522 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
525 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
526 .asGroupMessage(group
.build());
528 // Send group info request message to the recipient who sent us a message with this groupId
529 final List
<String
> membersSend
= new ArrayList
<>();
530 membersSend
.add(recipient
);
531 sendMessageLegacy(messageBuilder
, membersSend
);
535 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
536 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
537 List
<String
> recipients
= new ArrayList
<>(1);
538 recipients
.add(recipient
);
539 sendMessage(message
, attachments
, recipients
);
543 public void sendMessage(String messageText
, List
<String
> attachments
,
544 List
<String
> recipients
)
545 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
546 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
547 if (attachments
!= null) {
548 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
550 sendMessageLegacy(messageBuilder
, recipients
);
554 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
555 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
556 .asEndSessionMessage();
558 sendMessageLegacy(messageBuilder
, recipients
);
562 public String
getContactName(String number
) {
563 ContactInfo contact
= account
.getContactStore().getContact(number
);
564 if (contact
== null) {
572 public void setContactName(String number
, String name
) {
573 ContactInfo contact
= account
.getContactStore().getContact(number
);
574 if (contact
== null) {
575 contact
= new ContactInfo();
576 contact
.number
= number
;
577 System
.err
.println("Add contact " + number
+ " named " + name
);
579 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
582 account
.getContactStore().updateContact(contact
);
587 public List
<byte[]> getGroupIds() {
588 List
<GroupInfo
> groups
= getGroups();
589 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
590 for (GroupInfo group
: groups
) {
591 ids
.add(group
.groupId
);
597 public String
getGroupName(byte[] groupId
) {
598 GroupInfo group
= getGroup(groupId
);
607 public List
<String
> getGroupMembers(byte[] groupId
) {
608 GroupInfo group
= getGroup(groupId
);
610 return new ArrayList
<>();
612 return new ArrayList
<>(group
.members
);
617 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
618 if (groupId
.length
== 0) {
621 if (name
.isEmpty()) {
624 if (members
.size() == 0) {
627 if (avatar
.isEmpty()) {
630 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
634 * Change the expiration timer for a thread (number of groupId)
636 * @param numberOrGroupId
637 * @param messageExpirationTimer
639 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
640 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
641 thread
.messageExpirationTime
= messageExpirationTimer
;
642 account
.getThreadStore().updateThread(thread
);
645 private void requestSyncGroups() throws IOException
{
646 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
647 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
649 sendSyncMessage(message
);
650 } catch (UntrustedIdentityException e
) {
655 private void requestSyncContacts() throws IOException
{
656 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
657 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
659 sendSyncMessage(message
);
660 } catch (UntrustedIdentityException e
) {
665 private void requestSyncBlocked() throws IOException
{
666 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
667 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
669 sendSyncMessage(message
);
670 } catch (UntrustedIdentityException e
) {
675 private void requestSyncConfiguration() throws IOException
{
676 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
677 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
679 sendSyncMessage(message
);
680 } catch (UntrustedIdentityException e
) {
685 private byte[] getSelfUnidentifiedAccessKey() {
686 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
689 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
694 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
696 return Optional
.absent();
699 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
700 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
701 for (SignalServiceAddress recipient
: recipients
) {
702 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
707 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
709 return Optional
.absent();
712 private void sendSyncMessage(SignalServiceSyncMessage message
)
713 throws IOException
, UntrustedIdentityException
{
714 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
715 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
717 messageSender
.sendMessage(message
, getAccessForSync());
718 } catch (UntrustedIdentityException e
) {
719 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
725 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
727 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
728 throws EncapsulatedExceptions
, IOException
{
729 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
731 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
732 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
733 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
735 for (SendMessageResult result
: results
) {
736 if (result
.isUnregisteredFailure()) {
737 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
738 } else if (result
.isNetworkFailure()) {
739 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
740 } else if (result
.getIdentityFailure() != null) {
741 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
744 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
745 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
749 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
751 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
752 if (recipientsTS
== null) {
754 return Collections
.emptyList();
757 SignalServiceDataMessage message
= null;
759 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
760 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
762 message
= messageBuilder
.build();
763 if (message
.getGroupInfo().isPresent()) {
765 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), message
);
766 for (SendMessageResult r
: result
) {
767 if (r
.getIdentityFailure() != null) {
768 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
772 } catch (UntrustedIdentityException e
) {
773 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
774 return Collections
.emptyList();
776 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(new SignalServiceAddress(username
))) {
777 SignalServiceAddress recipient
= new SignalServiceAddress(username
);
778 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
779 SentTranscriptMessage transcript
= new SentTranscriptMessage(recipient
.getNumber(),
780 message
.getTimestamp(),
782 message
.getExpiresInSeconds(),
783 Collections
.singletonMap(recipient
.getNumber(), unidentifiedAccess
.isPresent()));
784 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
786 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
788 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
789 } catch (UntrustedIdentityException e
) {
790 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
791 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
795 // Send to all individually, so sync messages are sent correctly
796 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
797 for (SignalServiceAddress address
: recipientsTS
) {
798 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
799 if (thread
!= null) {
800 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
802 messageBuilder
.withExpiration(0);
804 message
= messageBuilder
.build();
806 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
808 } catch (UntrustedIdentityException e
) {
809 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
810 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
816 if (message
!= null && message
.isEndSession()) {
817 for (SignalServiceAddress recipient
: recipientsTS
) {
818 handleEndSession(recipient
.getNumber());
825 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
{
826 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
828 return cipher
.decrypt(envelope
);
829 } catch (ProtocolUntrustedIdentityException e
) {
830 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
831 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
836 private void handleEndSession(String source
) {
837 account
.getSignalProtocolStore().deleteAllSessions(source
);
840 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
842 if (message
.getGroupInfo().isPresent()) {
843 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
844 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
845 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
846 switch (groupInfo
.getType()) {
849 group
= new GroupInfo(groupInfo
.getGroupId());
852 if (groupInfo
.getAvatar().isPresent()) {
853 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
854 if (avatar
.isPointer()) {
856 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
857 } catch (IOException
| InvalidMessageException e
) {
858 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
863 if (groupInfo
.getName().isPresent()) {
864 group
.name
= groupInfo
.getName().get();
867 if (groupInfo
.getMembers().isPresent()) {
868 group
.members
.addAll(groupInfo
.getMembers().get());
871 account
.getGroupStore().updateGroup(group
);
876 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
877 } catch (IOException
| EncapsulatedExceptions e
) {
885 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
886 } catch (IOException
| EncapsulatedExceptions e
) {
890 group
.members
.remove(source
);
891 account
.getGroupStore().updateGroup(group
);
897 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
898 } catch (IOException
| EncapsulatedExceptions e
) {
900 } catch (NotAGroupMemberException e
) {
901 // We have left this group, so don't send a group update message
908 threadId
= destination
;
913 if (message
.isEndSession()) {
914 handleEndSession(isSync ? destination
: source
);
916 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
917 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
918 if (thread
== null) {
919 thread
= new ThreadInfo();
920 thread
.id
= threadId
;
922 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
923 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
924 account
.getThreadStore().updateThread(thread
);
927 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
928 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
929 if (attachment
.isPointer()) {
931 retrieveAttachment(attachment
.asPointer());
932 } catch (IOException
| InvalidMessageException e
) {
933 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
938 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
939 if (source
.equals(username
)) {
940 this.account
.setProfileKey(message
.getProfileKey().get());
942 ContactInfo contact
= account
.getContactStore().getContact(source
);
943 if (contact
== null) {
944 contact
= new ContactInfo();
945 contact
.number
= source
;
947 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
951 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
952 final File cachePath
= new File(getMessageCachePath());
953 if (!cachePath
.exists()) {
956 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
957 if (!dir
.isDirectory()) {
961 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
962 if (!fileEntry
.isFile()) {
965 SignalServiceEnvelope envelope
;
967 envelope
= Utils
.loadEnvelope(fileEntry
);
968 if (envelope
== null) {
971 } catch (IOException e
) {
975 SignalServiceContent content
= null;
976 if (!envelope
.isReceipt()) {
978 content
= decryptMessage(envelope
);
979 } catch (Exception e
) {
982 handleMessage(envelope
, content
, ignoreAttachments
);
985 handler
.handleMessage(envelope
, content
, null);
987 Files
.delete(fileEntry
.toPath());
988 } catch (IOException e
) {
989 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
992 // Try to delete directory if empty
997 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
998 retryFailedReceivedMessages(handler
, ignoreAttachments
);
999 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1002 if (messagePipe
== null) {
1003 messagePipe
= messageReceiver
.createMessagePipe();
1007 SignalServiceEnvelope envelope
;
1008 SignalServiceContent content
= null;
1009 Exception exception
= null;
1010 final long now
= new Date().getTime();
1012 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1014 public void onMessage(SignalServiceEnvelope envelope
) {
1015 // store message on disk, before acknowledging receipt to the server
1017 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1018 Utils
.storeEnvelope(envelope
, cacheFile
);
1019 } catch (IOException e
) {
1020 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1024 } catch (TimeoutException e
) {
1025 if (returnOnTimeout
)
1028 } catch (InvalidVersionException e
) {
1029 System
.err
.println("Ignoring error: " + e
.getMessage());
1032 if (!envelope
.isReceipt()) {
1034 content
= decryptMessage(envelope
);
1035 } catch (Exception e
) {
1038 handleMessage(envelope
, content
, ignoreAttachments
);
1041 handler
.handleMessage(envelope
, content
, exception
);
1042 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1043 File cacheFile
= null;
1045 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1046 Files
.delete(cacheFile
.toPath());
1047 // Try to delete directory if empty
1048 new File(getMessageCachePath()).delete();
1049 } catch (IOException e
) {
1050 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1055 if (messagePipe
!= null) {
1056 messagePipe
.shutdown();
1062 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1063 if (content
!= null) {
1064 if (content
.getDataMessage().isPresent()) {
1065 SignalServiceDataMessage message
= content
.getDataMessage().get();
1066 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1068 if (content
.getSyncMessage().isPresent()) {
1069 account
.setMultiDevice(true);
1070 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1071 if (syncMessage
.getSent().isPresent()) {
1072 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1073 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1075 if (syncMessage
.getRequest().isPresent()) {
1076 RequestMessage rm
= syncMessage
.getRequest().get();
1077 if (rm
.isContactsRequest()) {
1080 } catch (UntrustedIdentityException
| IOException e
) {
1081 e
.printStackTrace();
1084 if (rm
.isGroupsRequest()) {
1087 } catch (UntrustedIdentityException
| IOException e
) {
1088 e
.printStackTrace();
1091 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1093 if (syncMessage
.getGroups().isPresent()) {
1094 File tmpFile
= null;
1096 tmpFile
= IOUtils
.createTempFile();
1097 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1098 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1100 while ((g
= s
.read()) != null) {
1101 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1102 if (syncGroup
== null) {
1103 syncGroup
= new GroupInfo(g
.getId());
1105 if (g
.getName().isPresent()) {
1106 syncGroup
.name
= g
.getName().get();
1108 syncGroup
.members
.addAll(g
.getMembers());
1109 syncGroup
.active
= g
.isActive();
1110 if (g
.getColor().isPresent()) {
1111 syncGroup
.color
= g
.getColor().get();
1114 if (g
.getAvatar().isPresent()) {
1115 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1117 account
.getGroupStore().updateGroup(syncGroup
);
1120 } catch (Exception e
) {
1121 e
.printStackTrace();
1123 if (tmpFile
!= null) {
1125 Files
.delete(tmpFile
.toPath());
1126 } catch (IOException e
) {
1127 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1132 if (syncMessage
.getBlockedList().isPresent()) {
1133 // TODO store list of blocked numbers
1135 if (syncMessage
.getContacts().isPresent()) {
1136 File tmpFile
= null;
1138 tmpFile
= IOUtils
.createTempFile();
1139 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1140 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1141 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1142 if (contactsMessage
.isComplete()) {
1143 account
.getContactStore().clear();
1146 while ((c
= s
.read()) != null) {
1147 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1148 account
.setProfileKey(c
.getProfileKey().get());
1150 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1151 if (contact
== null) {
1152 contact
= new ContactInfo();
1153 contact
.number
= c
.getNumber();
1155 if (c
.getName().isPresent()) {
1156 contact
.name
= c
.getName().get();
1158 if (c
.getColor().isPresent()) {
1159 contact
.color
= c
.getColor().get();
1161 if (c
.getProfileKey().isPresent()) {
1162 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1164 if (c
.getVerified().isPresent()) {
1165 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1166 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1168 if (c
.getExpirationTimer().isPresent()) {
1169 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1170 if (thread
== null) {
1171 thread
= new ThreadInfo();
1172 thread
.id
= c
.getNumber();
1174 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1175 account
.getThreadStore().updateThread(thread
);
1177 if (c
.isBlocked()) {
1178 // TODO store list of blocked numbers
1180 account
.getContactStore().updateContact(contact
);
1182 if (c
.getAvatar().isPresent()) {
1183 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1187 } catch (Exception e
) {
1188 e
.printStackTrace();
1190 if (tmpFile
!= null) {
1192 Files
.delete(tmpFile
.toPath());
1193 } catch (IOException e
) {
1194 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1199 if (syncMessage
.getVerified().isPresent()) {
1200 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1201 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1203 if (syncMessage
.getConfiguration().isPresent()) {
1210 private File
getContactAvatarFile(String number
) {
1211 return new File(avatarsPath
, "contact-" + number
);
1214 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1215 IOUtils
.createPrivateDirectories(avatarsPath
);
1216 if (attachment
.isPointer()) {
1217 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1218 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1220 SignalServiceAttachmentStream stream
= attachment
.asStream();
1221 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1225 private File
getGroupAvatarFile(byte[] groupId
) {
1226 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1229 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1230 IOUtils
.createPrivateDirectories(avatarsPath
);
1231 if (attachment
.isPointer()) {
1232 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1233 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1235 SignalServiceAttachmentStream stream
= attachment
.asStream();
1236 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1240 public File
getAttachmentFile(long attachmentId
) {
1241 return new File(attachmentsPath
, attachmentId
+ "");
1244 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1245 IOUtils
.createPrivateDirectories(attachmentsPath
);
1246 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1249 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1250 if (storePreview
&& pointer
.getPreview().isPresent()) {
1251 File previewFile
= new File(outputFile
+ ".preview");
1252 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1253 byte[] preview
= pointer
.getPreview().get();
1254 output
.write(preview
, 0, preview
.length
);
1255 } catch (FileNotFoundException e
) {
1256 e
.printStackTrace();
1261 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1263 File tmpFile
= IOUtils
.createTempFile();
1264 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1265 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1266 byte[] buffer
= new byte[4096];
1269 while ((read
= input
.read(buffer
)) != -1) {
1270 output
.write(buffer
, 0, read
);
1272 } catch (FileNotFoundException e
) {
1273 e
.printStackTrace();
1278 Files
.delete(tmpFile
.toPath());
1279 } catch (IOException e
) {
1280 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1286 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1287 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1288 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1292 public boolean isRemote() {
1296 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1297 File groupsFile
= IOUtils
.createTempFile();
1300 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1301 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1302 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1303 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1304 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1305 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1306 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1307 Optional
.fromNullable(record.color
), false));
1311 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1312 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1313 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1314 .withStream(groupsFileStream
)
1315 .withContentType("application/octet-stream")
1316 .withLength(groupsFile
.length())
1319 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1324 Files
.delete(groupsFile
.toPath());
1325 } catch (IOException e
) {
1326 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1331 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1332 File contactsFile
= IOUtils
.createTempFile();
1335 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1336 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1337 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1338 VerifiedMessage verifiedMessage
= null;
1339 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1340 if (getIdentities().containsKey(record.number
)) {
1341 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1342 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1343 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1344 currentIdentity
= id
;
1347 if (currentIdentity
!= null) {
1348 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1352 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1353 // TODO store list of blocked numbers
1354 boolean blocked
= false;
1355 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1356 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1357 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1360 if (account
.getProfileKey() != null) {
1361 // Send our own profile key as well
1362 out
.write(new DeviceContact(account
.getUsername(),
1363 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1364 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1365 Optional
.of(account
.getProfileKey()),
1366 false, Optional
.<Integer
>absent()));
1370 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1371 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1372 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1373 .withStream(contactsFileStream
)
1374 .withContentType("application/octet-stream")
1375 .withLength(contactsFile
.length())
1378 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1383 Files
.delete(contactsFile
.toPath());
1384 } catch (IOException e
) {
1385 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1390 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1391 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1392 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1395 public ContactInfo
getContact(String number
) {
1396 return account
.getContactStore().getContact(number
);
1399 public GroupInfo
getGroup(byte[] groupId
) {
1400 return account
.getGroupStore().getGroup(groupId
);
1403 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1404 return account
.getSignalProtocolStore().getIdentities();
1407 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1408 return account
.getSignalProtocolStore().getIdentities(number
);
1412 * Trust this the identity with this fingerprint
1414 * @param name username of the identity
1415 * @param fingerprint Fingerprint
1417 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1418 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1422 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1423 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1427 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1429 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1430 } catch (IOException
| UntrustedIdentityException e
) {
1431 e
.printStackTrace();
1440 * Trust this the identity with this safety number
1442 * @param name username of the identity
1443 * @param safetyNumber Safety number
1445 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1446 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1450 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1451 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1455 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1457 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1458 } catch (IOException
| UntrustedIdentityException e
) {
1459 e
.printStackTrace();
1468 * Trust all keys of this identity without verification
1470 * @param name username of the identity
1472 public boolean trustIdentityAllKeys(String name
) {
1473 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1477 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1478 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1479 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1481 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1482 } catch (IOException
| UntrustedIdentityException e
) {
1483 e
.printStackTrace();
1491 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1492 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1495 public interface ReceiveMessageHandler
{
1497 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);