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();
777 // Send to all individually, so sync messages are sent correctly
778 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
779 for (SignalServiceAddress address
: recipientsTS
) {
780 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
781 if (thread
!= null) {
782 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
784 messageBuilder
.withExpiration(0);
786 message
= messageBuilder
.build();
788 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
790 } catch (UntrustedIdentityException e
) {
791 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
792 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
798 if (message
!= null && message
.isEndSession()) {
799 for (SignalServiceAddress recipient
: recipientsTS
) {
800 handleEndSession(recipient
.getNumber());
807 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
{
808 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
810 return cipher
.decrypt(envelope
);
811 } catch (ProtocolUntrustedIdentityException e
) {
812 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
813 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
818 private void handleEndSession(String source
) {
819 account
.getSignalProtocolStore().deleteAllSessions(source
);
822 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
824 if (message
.getGroupInfo().isPresent()) {
825 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
826 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
827 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
828 switch (groupInfo
.getType()) {
831 group
= new GroupInfo(groupInfo
.getGroupId());
834 if (groupInfo
.getAvatar().isPresent()) {
835 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
836 if (avatar
.isPointer()) {
838 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
839 } catch (IOException
| InvalidMessageException e
) {
840 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
845 if (groupInfo
.getName().isPresent()) {
846 group
.name
= groupInfo
.getName().get();
849 if (groupInfo
.getMembers().isPresent()) {
850 group
.members
.addAll(groupInfo
.getMembers().get());
853 account
.getGroupStore().updateGroup(group
);
858 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
859 } catch (IOException
| EncapsulatedExceptions e
) {
867 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
868 } catch (IOException
| EncapsulatedExceptions e
) {
872 group
.members
.remove(source
);
873 account
.getGroupStore().updateGroup(group
);
879 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
880 } catch (IOException
| EncapsulatedExceptions e
) {
882 } catch (NotAGroupMemberException e
) {
883 // We have left this group, so don't send a group update message
890 threadId
= destination
;
895 if (message
.isEndSession()) {
896 handleEndSession(isSync ? destination
: source
);
898 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
899 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
900 if (thread
== null) {
901 thread
= new ThreadInfo();
902 thread
.id
= threadId
;
904 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
905 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
906 account
.getThreadStore().updateThread(thread
);
909 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
910 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
911 if (attachment
.isPointer()) {
913 retrieveAttachment(attachment
.asPointer());
914 } catch (IOException
| InvalidMessageException e
) {
915 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
920 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
921 if (source
.equals(username
)) {
922 this.account
.setProfileKey(message
.getProfileKey().get());
924 ContactInfo contact
= account
.getContactStore().getContact(source
);
925 if (contact
== null) {
926 contact
= new ContactInfo();
927 contact
.number
= source
;
929 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
933 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
934 final File cachePath
= new File(getMessageCachePath());
935 if (!cachePath
.exists()) {
938 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
939 if (!dir
.isDirectory()) {
943 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
944 if (!fileEntry
.isFile()) {
947 SignalServiceEnvelope envelope
;
949 envelope
= Utils
.loadEnvelope(fileEntry
);
950 if (envelope
== null) {
953 } catch (IOException e
) {
957 SignalServiceContent content
= null;
958 if (!envelope
.isReceipt()) {
960 content
= decryptMessage(envelope
);
961 } catch (Exception e
) {
964 handleMessage(envelope
, content
, ignoreAttachments
);
967 handler
.handleMessage(envelope
, content
, null);
969 Files
.delete(fileEntry
.toPath());
970 } catch (IOException e
) {
971 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
974 // Try to delete directory if empty
979 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
980 retryFailedReceivedMessages(handler
, ignoreAttachments
);
981 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
984 if (messagePipe
== null) {
985 messagePipe
= messageReceiver
.createMessagePipe();
989 SignalServiceEnvelope envelope
;
990 SignalServiceContent content
= null;
991 Exception exception
= null;
992 final long now
= new Date().getTime();
994 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
996 public void onMessage(SignalServiceEnvelope envelope
) {
997 // store message on disk, before acknowledging receipt to the server
999 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1000 Utils
.storeEnvelope(envelope
, cacheFile
);
1001 } catch (IOException e
) {
1002 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1006 } catch (TimeoutException e
) {
1007 if (returnOnTimeout
)
1010 } catch (InvalidVersionException e
) {
1011 System
.err
.println("Ignoring error: " + e
.getMessage());
1014 if (!envelope
.isReceipt()) {
1016 content
= decryptMessage(envelope
);
1017 } catch (Exception e
) {
1020 handleMessage(envelope
, content
, ignoreAttachments
);
1023 handler
.handleMessage(envelope
, content
, exception
);
1024 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1025 File cacheFile
= null;
1027 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1028 Files
.delete(cacheFile
.toPath());
1029 // Try to delete directory if empty
1030 new File(getMessageCachePath()).delete();
1031 } catch (IOException e
) {
1032 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1037 if (messagePipe
!= null) {
1038 messagePipe
.shutdown();
1044 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1045 if (content
!= null) {
1046 if (content
.getDataMessage().isPresent()) {
1047 SignalServiceDataMessage message
= content
.getDataMessage().get();
1048 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1050 if (content
.getSyncMessage().isPresent()) {
1051 account
.setMultiDevice(true);
1052 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1053 if (syncMessage
.getSent().isPresent()) {
1054 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1055 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1057 if (syncMessage
.getRequest().isPresent()) {
1058 RequestMessage rm
= syncMessage
.getRequest().get();
1059 if (rm
.isContactsRequest()) {
1062 } catch (UntrustedIdentityException
| IOException e
) {
1063 e
.printStackTrace();
1066 if (rm
.isGroupsRequest()) {
1069 } catch (UntrustedIdentityException
| IOException e
) {
1070 e
.printStackTrace();
1073 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1075 if (syncMessage
.getGroups().isPresent()) {
1076 File tmpFile
= null;
1078 tmpFile
= IOUtils
.createTempFile();
1079 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1080 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1082 while ((g
= s
.read()) != null) {
1083 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1084 if (syncGroup
== null) {
1085 syncGroup
= new GroupInfo(g
.getId());
1087 if (g
.getName().isPresent()) {
1088 syncGroup
.name
= g
.getName().get();
1090 syncGroup
.members
.addAll(g
.getMembers());
1091 syncGroup
.active
= g
.isActive();
1092 if (g
.getColor().isPresent()) {
1093 syncGroup
.color
= g
.getColor().get();
1096 if (g
.getAvatar().isPresent()) {
1097 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1099 account
.getGroupStore().updateGroup(syncGroup
);
1102 } catch (Exception e
) {
1103 e
.printStackTrace();
1105 if (tmpFile
!= null) {
1107 Files
.delete(tmpFile
.toPath());
1108 } catch (IOException e
) {
1109 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1114 if (syncMessage
.getBlockedList().isPresent()) {
1115 // TODO store list of blocked numbers
1117 if (syncMessage
.getContacts().isPresent()) {
1118 File tmpFile
= null;
1120 tmpFile
= IOUtils
.createTempFile();
1121 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1122 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1123 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1124 if (contactsMessage
.isComplete()) {
1125 account
.getContactStore().clear();
1128 while ((c
= s
.read()) != null) {
1129 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1130 account
.setProfileKey(c
.getProfileKey().get());
1132 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1133 if (contact
== null) {
1134 contact
= new ContactInfo();
1135 contact
.number
= c
.getNumber();
1137 if (c
.getName().isPresent()) {
1138 contact
.name
= c
.getName().get();
1140 if (c
.getColor().isPresent()) {
1141 contact
.color
= c
.getColor().get();
1143 if (c
.getProfileKey().isPresent()) {
1144 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1146 if (c
.getVerified().isPresent()) {
1147 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1148 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1150 if (c
.getExpirationTimer().isPresent()) {
1151 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1152 if (thread
== null) {
1153 thread
= new ThreadInfo();
1154 thread
.id
= c
.getNumber();
1156 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1157 account
.getThreadStore().updateThread(thread
);
1159 if (c
.isBlocked()) {
1160 // TODO store list of blocked numbers
1162 account
.getContactStore().updateContact(contact
);
1164 if (c
.getAvatar().isPresent()) {
1165 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1169 } catch (Exception e
) {
1170 e
.printStackTrace();
1172 if (tmpFile
!= null) {
1174 Files
.delete(tmpFile
.toPath());
1175 } catch (IOException e
) {
1176 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1181 if (syncMessage
.getVerified().isPresent()) {
1182 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1183 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1185 if (syncMessage
.getConfiguration().isPresent()) {
1192 private File
getContactAvatarFile(String number
) {
1193 return new File(avatarsPath
, "contact-" + number
);
1196 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1197 IOUtils
.createPrivateDirectories(avatarsPath
);
1198 if (attachment
.isPointer()) {
1199 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1200 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1202 SignalServiceAttachmentStream stream
= attachment
.asStream();
1203 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1207 private File
getGroupAvatarFile(byte[] groupId
) {
1208 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1211 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1212 IOUtils
.createPrivateDirectories(avatarsPath
);
1213 if (attachment
.isPointer()) {
1214 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1215 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1217 SignalServiceAttachmentStream stream
= attachment
.asStream();
1218 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1222 public File
getAttachmentFile(long attachmentId
) {
1223 return new File(attachmentsPath
, attachmentId
+ "");
1226 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1227 IOUtils
.createPrivateDirectories(attachmentsPath
);
1228 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1231 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1232 if (storePreview
&& pointer
.getPreview().isPresent()) {
1233 File previewFile
= new File(outputFile
+ ".preview");
1234 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1235 byte[] preview
= pointer
.getPreview().get();
1236 output
.write(preview
, 0, preview
.length
);
1237 } catch (FileNotFoundException e
) {
1238 e
.printStackTrace();
1243 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1245 File tmpFile
= IOUtils
.createTempFile();
1246 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1247 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1248 byte[] buffer
= new byte[4096];
1251 while ((read
= input
.read(buffer
)) != -1) {
1252 output
.write(buffer
, 0, read
);
1254 } catch (FileNotFoundException e
) {
1255 e
.printStackTrace();
1260 Files
.delete(tmpFile
.toPath());
1261 } catch (IOException e
) {
1262 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1268 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1269 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1270 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1274 public boolean isRemote() {
1278 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1279 File groupsFile
= IOUtils
.createTempFile();
1282 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1283 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1284 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1285 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1286 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1287 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1288 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1289 Optional
.fromNullable(record.color
), false));
1293 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1294 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1295 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1296 .withStream(groupsFileStream
)
1297 .withContentType("application/octet-stream")
1298 .withLength(groupsFile
.length())
1301 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1306 Files
.delete(groupsFile
.toPath());
1307 } catch (IOException e
) {
1308 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1313 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1314 File contactsFile
= IOUtils
.createTempFile();
1317 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1318 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1319 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1320 VerifiedMessage verifiedMessage
= null;
1321 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1322 if (getIdentities().containsKey(record.number
)) {
1323 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1324 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1325 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1326 currentIdentity
= id
;
1329 if (currentIdentity
!= null) {
1330 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1334 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1335 // TODO store list of blocked numbers
1336 boolean blocked
= false;
1337 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1338 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1339 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1342 if (account
.getProfileKey() != null) {
1343 // Send our own profile key as well
1344 out
.write(new DeviceContact(account
.getUsername(),
1345 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1346 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1347 Optional
.of(account
.getProfileKey()),
1348 false, Optional
.<Integer
>absent()));
1352 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1353 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1354 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1355 .withStream(contactsFileStream
)
1356 .withContentType("application/octet-stream")
1357 .withLength(contactsFile
.length())
1360 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1365 Files
.delete(contactsFile
.toPath());
1366 } catch (IOException e
) {
1367 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1372 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1373 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1374 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1377 public ContactInfo
getContact(String number
) {
1378 return account
.getContactStore().getContact(number
);
1381 public GroupInfo
getGroup(byte[] groupId
) {
1382 return account
.getGroupStore().getGroup(groupId
);
1385 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1386 return account
.getSignalProtocolStore().getIdentities();
1389 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1390 return account
.getSignalProtocolStore().getIdentities(number
);
1394 * Trust this the identity with this fingerprint
1396 * @param name username of the identity
1397 * @param fingerprint Fingerprint
1399 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1400 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1404 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1405 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1409 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1411 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1412 } catch (IOException
| UntrustedIdentityException e
) {
1413 e
.printStackTrace();
1422 * Trust this the identity with this safety number
1424 * @param name username of the identity
1425 * @param safetyNumber Safety number
1427 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1428 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1432 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1433 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1437 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1439 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1440 } catch (IOException
| UntrustedIdentityException e
) {
1441 e
.printStackTrace();
1450 * Trust all keys of this identity without verification
1452 * @param name username of the identity
1454 public boolean trustIdentityAllKeys(String name
) {
1455 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1459 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1460 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1461 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1463 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1464 } catch (IOException
| UntrustedIdentityException e
) {
1465 e
.printStackTrace();
1473 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1474 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1477 public interface ReceiveMessageHandler
{
1479 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);