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
.push
.UnsupportedDataMessageException
;
60 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
64 import java
.nio
.file
.Files
;
65 import java
.nio
.file
.Paths
;
66 import java
.nio
.file
.StandardCopyOption
;
68 import java
.util
.concurrent
.TimeUnit
;
69 import java
.util
.concurrent
.TimeoutException
;
71 public class Manager
implements Signal
{
73 private final String settingsPath
;
74 private final String dataPath
;
75 private final String attachmentsPath
;
76 private final String avatarsPath
;
77 private final SleepTimer timer
= new UptimeSleepTimer();
79 private SignalAccount account
;
80 private String username
;
81 private SignalServiceAccountManager accountManager
;
82 private SignalServiceMessagePipe messagePipe
= null;
83 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
85 public Manager(String username
, String settingsPath
) {
86 this.username
= username
;
87 this.settingsPath
= settingsPath
;
88 this.dataPath
= this.settingsPath
+ "/data";
89 this.attachmentsPath
= this.settingsPath
+ "/attachments";
90 this.avatarsPath
= this.settingsPath
+ "/avatars";
94 public String
getUsername() {
98 private IdentityKey
getIdentity() {
99 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
102 public int getDeviceId() {
103 return account
.getDeviceId();
106 private String
getMessageCachePath() {
107 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
110 private String
getMessageCachePath(String sender
) {
111 return getMessageCachePath() + "/" + sender
.replace("/", "_");
114 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
115 String cachePath
= getMessageCachePath(sender
);
116 IOUtils
.createPrivateDirectories(cachePath
);
117 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
120 public boolean userHasKeys() {
121 return account
!= null && account
.getSignalProtocolStore() != null;
124 public void init() throws IOException
{
125 if (!SignalAccount
.userExists(dataPath
, username
)) {
128 account
= SignalAccount
.load(dataPath
, username
);
130 migrateLegacyConfigs();
132 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
134 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
138 } catch (AuthorizationFailedException e
) {
139 System
.err
.println("Authorization failed, was the number registered elsewhere?");
143 private void migrateLegacyConfigs() {
144 // Copy group avatars that were previously stored in the attachments folder
145 // to the new avatar folder
146 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
147 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
148 File avatarFile
= getGroupAvatarFile(g
.groupId
);
149 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
150 if (!avatarFile
.exists() && attachmentFile
.exists()) {
152 IOUtils
.createPrivateDirectories(avatarsPath
);
153 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
154 } catch (Exception e
) {
159 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
162 if (account
.getProfileKey() == null) {
163 // Old config file, creating new profile key
164 account
.setProfileKey(KeyUtils
.createProfileKey());
169 private void createNewIdentity() throws IOException
{
170 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
171 int registrationId
= KeyHelper
.generateRegistrationId(false);
172 if (username
== null) {
173 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
175 byte[] profileKey
= KeyUtils
.createProfileKey();
176 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
181 public boolean isRegistered() {
182 return account
!= null && account
.isRegistered();
185 public void register(boolean voiceVerification
) throws IOException
{
186 if (account
== null) {
189 account
.setPassword(KeyUtils
.createPassword());
190 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, account
.getUsername(), account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
192 if (voiceVerification
) {
193 accountManager
.requestVoiceVerificationCode(Locale
.getDefault(), Optional
.<String
>absent(), Optional
.<String
>absent());
195 accountManager
.requestSmsVerificationCode(false, Optional
.<String
>absent(), Optional
.<String
>absent());
198 account
.setRegistered(false);
202 public void updateAccountAttributes() throws IOException
{
203 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
206 public void unregister() throws IOException
{
207 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
208 // If this is the master device, other users can't send messages to this number anymore.
209 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
210 accountManager
.setGcmId(Optional
.<String
>absent());
213 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
214 if (account
== null) {
217 account
.setPassword(KeyUtils
.createPassword());
218 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
219 String uuid
= accountManager
.getNewDeviceUuid();
221 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
224 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
225 account
.setSignalingKey(KeyUtils
.createSignalingKey());
226 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
228 username
= ret
.getNumber();
229 // TODO do this check before actually registering
230 if (SignalAccount
.userExists(dataPath
, username
)) {
231 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
234 // Create new account with the synced identity
235 byte[] profileKey
= ret
.getProfileKey();
236 if (profileKey
== null) {
237 profileKey
= KeyUtils
.createProfileKey();
239 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
244 requestSyncContacts();
245 requestSyncBlocked();
246 requestSyncConfiguration();
251 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
252 List
<DeviceInfo
> devices
= accountManager
.getDevices();
253 account
.setMultiDevice(devices
.size() > 1);
258 public void removeLinkedDevices(int deviceId
) throws IOException
{
259 accountManager
.removeDevice(deviceId
);
260 List
<DeviceInfo
> devices
= accountManager
.getDevices();
261 account
.setMultiDevice(devices
.size() > 1);
265 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
266 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
268 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
271 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
272 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
273 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
275 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
276 account
.setMultiDevice(true);
280 private List
<PreKeyRecord
> generatePreKeys() {
281 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
283 final int offset
= account
.getPreKeyIdOffset();
284 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
285 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
286 ECKeyPair keyPair
= Curve
.generateKeyPair();
287 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
292 account
.addPreKeys(records
);
298 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
300 ECKeyPair keyPair
= Curve
.generateKeyPair();
301 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
302 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
304 account
.addSignedPreKey(record);
308 } catch (InvalidKeyException e
) {
309 throw new AssertionError(e
);
313 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
314 verificationCode
= verificationCode
.replace("-", "");
315 account
.setSignalingKey(KeyUtils
.createSignalingKey());
316 // TODO make unrestricted unidentified access configurable
317 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
319 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
320 account
.setRegistered(true);
321 account
.setRegistrationLockPin(pin
);
327 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
328 accountManager
.setPin(pin
);
329 if (pin
.isPresent()) {
330 account
.setRegistrationLockPin(pin
.get());
332 account
.setRegistrationLockPin(null);
337 private void refreshPreKeys() throws IOException
{
338 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
339 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
340 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
342 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
345 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
346 File file
= getGroupAvatarFile(groupId
);
347 if (!file
.exists()) {
348 return Optional
.absent();
351 return Optional
.of(Utils
.createAttachment(file
));
354 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
355 File file
= getContactAvatarFile(number
);
356 if (!file
.exists()) {
357 return Optional
.absent();
360 return Optional
.of(Utils
.createAttachment(file
));
363 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
364 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
366 throw new GroupNotFoundException(groupId
);
368 for (String member
: g
.members
) {
369 if (member
.equals(this.username
)) {
373 throw new NotAGroupMemberException(groupId
, g
.name
);
376 public List
<GroupInfo
> getGroups() {
377 return account
.getGroupStore().getGroups();
381 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
383 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
384 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
385 if (attachments
!= null) {
386 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
388 if (groupId
!= null) {
389 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
392 messageBuilder
.asGroupMessage(group
);
394 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
395 if (thread
!= null) {
396 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
399 final GroupInfo g
= getGroupForSending(groupId
);
401 // Don't send group message to ourself
402 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
403 membersSend
.remove(this.username
);
404 sendMessageLegacy(messageBuilder
, membersSend
);
407 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
408 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
412 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
413 .asGroupMessage(group
);
415 final GroupInfo g
= getGroupForSending(groupId
);
416 g
.members
.remove(this.username
);
417 account
.getGroupStore().updateGroup(g
);
419 sendMessageLegacy(messageBuilder
, g
.members
);
422 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
424 if (groupId
== null) {
426 g
= new GroupInfo(KeyUtils
.createGroupId());
427 g
.members
.add(username
);
429 g
= getGroupForSending(groupId
);
436 if (members
!= null) {
437 Set
<String
> newMembers
= new HashSet
<>();
438 for (String member
: members
) {
440 member
= Utils
.canonicalizeNumber(member
, username
);
441 } catch (InvalidNumberException e
) {
442 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
443 System
.err
.println("Aborting…");
446 if (g
.members
.contains(member
)) {
449 newMembers
.add(member
);
450 g
.members
.add(member
);
452 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
453 if (contacts
.size() != newMembers
.size()) {
454 // Some of the new members are not registered on Signal
455 for (ContactTokenDetails contact
: contacts
) {
456 newMembers
.remove(contact
.getNumber());
458 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
459 System
.err
.println("Aborting…");
464 if (avatarFile
!= null) {
465 IOUtils
.createPrivateDirectories(avatarsPath
);
466 File aFile
= getGroupAvatarFile(g
.groupId
);
467 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
470 account
.getGroupStore().updateGroup(g
);
472 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
474 // Don't send group message to ourself
475 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
476 membersSend
.remove(this.username
);
477 sendMessageLegacy(messageBuilder
, membersSend
);
481 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
482 if (groupId
== null) {
485 GroupInfo g
= getGroupForSending(groupId
);
487 if (!g
.members
.contains(recipient
)) {
491 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
493 // Send group message only to the recipient who requested it
494 final List
<String
> membersSend
= new ArrayList
<>();
495 membersSend
.add(recipient
);
496 sendMessageLegacy(messageBuilder
, membersSend
);
499 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
500 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
503 .withMembers(new ArrayList
<>(g
.members
));
505 File aFile
= getGroupAvatarFile(g
.groupId
);
506 if (aFile
.exists()) {
508 group
.withAvatar(Utils
.createAttachment(aFile
));
509 } catch (IOException e
) {
510 throw new AttachmentInvalidException(aFile
.toString(), e
);
514 return SignalServiceDataMessage
.newBuilder()
515 .asGroupMessage(group
.build());
518 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
519 if (groupId
== null) {
523 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
526 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
527 .asGroupMessage(group
.build());
529 // Send group info request message to the recipient who sent us a message with this groupId
530 final List
<String
> membersSend
= new ArrayList
<>();
531 membersSend
.add(recipient
);
532 sendMessageLegacy(messageBuilder
, membersSend
);
536 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
537 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
538 List
<String
> recipients
= new ArrayList
<>(1);
539 recipients
.add(recipient
);
540 sendMessage(message
, attachments
, recipients
);
544 public void sendMessage(String messageText
, List
<String
> attachments
,
545 List
<String
> recipients
)
546 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
547 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
548 if (attachments
!= null) {
549 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
551 sendMessageLegacy(messageBuilder
, recipients
);
555 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
556 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
557 .asEndSessionMessage();
559 sendMessageLegacy(messageBuilder
, recipients
);
563 public String
getContactName(String number
) {
564 ContactInfo contact
= account
.getContactStore().getContact(number
);
565 if (contact
== null) {
573 public void setContactName(String number
, String name
) {
574 ContactInfo contact
= account
.getContactStore().getContact(number
);
575 if (contact
== null) {
576 contact
= new ContactInfo();
577 contact
.number
= number
;
578 System
.err
.println("Add contact " + number
+ " named " + name
);
580 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
583 account
.getContactStore().updateContact(contact
);
588 public List
<byte[]> getGroupIds() {
589 List
<GroupInfo
> groups
= getGroups();
590 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
591 for (GroupInfo group
: groups
) {
592 ids
.add(group
.groupId
);
598 public String
getGroupName(byte[] groupId
) {
599 GroupInfo group
= getGroup(groupId
);
608 public List
<String
> getGroupMembers(byte[] groupId
) {
609 GroupInfo group
= getGroup(groupId
);
611 return new ArrayList
<>();
613 return new ArrayList
<>(group
.members
);
618 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
619 if (groupId
.length
== 0) {
622 if (name
.isEmpty()) {
625 if (members
.size() == 0) {
628 if (avatar
.isEmpty()) {
631 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
635 * Change the expiration timer for a thread (number of groupId)
637 * @param numberOrGroupId
638 * @param messageExpirationTimer
640 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
641 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
642 thread
.messageExpirationTime
= messageExpirationTimer
;
643 account
.getThreadStore().updateThread(thread
);
646 private void requestSyncGroups() throws IOException
{
647 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
648 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
650 sendSyncMessage(message
);
651 } catch (UntrustedIdentityException e
) {
656 private void requestSyncContacts() throws IOException
{
657 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
658 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
660 sendSyncMessage(message
);
661 } catch (UntrustedIdentityException e
) {
666 private void requestSyncBlocked() throws IOException
{
667 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
668 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
670 sendSyncMessage(message
);
671 } catch (UntrustedIdentityException e
) {
676 private void requestSyncConfiguration() throws IOException
{
677 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
678 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
680 sendSyncMessage(message
);
681 } catch (UntrustedIdentityException e
) {
686 private byte[] getSelfUnidentifiedAccessKey() {
687 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
690 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
695 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
697 return Optional
.absent();
700 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
701 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
702 for (SignalServiceAddress recipient
: recipients
) {
703 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
708 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
710 return Optional
.absent();
713 private void sendSyncMessage(SignalServiceSyncMessage message
)
714 throws IOException
, UntrustedIdentityException
{
715 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
716 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
718 messageSender
.sendMessage(message
, getAccessForSync());
719 } catch (UntrustedIdentityException e
) {
720 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
726 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
728 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
729 throws EncapsulatedExceptions
, IOException
{
730 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
732 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
733 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
734 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
736 for (SendMessageResult result
: results
) {
737 if (result
.isUnregisteredFailure()) {
738 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
739 } else if (result
.isNetworkFailure()) {
740 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
741 } else if (result
.getIdentityFailure() != null) {
742 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
745 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
746 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
750 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
752 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
753 if (recipientsTS
== null) {
755 return Collections
.emptyList();
758 SignalServiceDataMessage message
= null;
760 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
761 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
763 message
= messageBuilder
.build();
764 if (message
.getGroupInfo().isPresent()) {
766 final boolean isRecipientUpdate
= true;
767 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
768 for (SendMessageResult r
: result
) {
769 if (r
.getIdentityFailure() != null) {
770 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
774 } catch (UntrustedIdentityException e
) {
775 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
776 return Collections
.emptyList();
778 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(new SignalServiceAddress(username
))) {
779 SignalServiceAddress recipient
= new SignalServiceAddress(username
);
780 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
781 SentTranscriptMessage transcript
= new SentTranscriptMessage(recipient
.getNumber(),
782 message
.getTimestamp(),
784 message
.getExpiresInSeconds(),
785 Collections
.singletonMap(recipient
.getNumber(), unidentifiedAccess
.isPresent()),
787 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
789 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
791 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
792 } catch (UntrustedIdentityException e
) {
793 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
794 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
798 // Send to all individually, so sync messages are sent correctly
799 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
800 for (SignalServiceAddress address
: recipientsTS
) {
801 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
802 if (thread
!= null) {
803 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
805 messageBuilder
.withExpiration(0);
807 message
= messageBuilder
.build();
809 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
811 } catch (UntrustedIdentityException e
) {
812 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
813 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
819 if (message
!= null && message
.isEndSession()) {
820 for (SignalServiceAddress recipient
: recipientsTS
) {
821 handleEndSession(recipient
.getNumber());
828 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
829 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
831 return cipher
.decrypt(envelope
);
832 } catch (ProtocolUntrustedIdentityException e
) {
833 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
834 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
839 private void handleEndSession(String source
) {
840 account
.getSignalProtocolStore().deleteAllSessions(source
);
843 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
845 if (message
.getGroupInfo().isPresent()) {
846 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
847 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
848 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
849 switch (groupInfo
.getType()) {
852 group
= new GroupInfo(groupInfo
.getGroupId());
855 if (groupInfo
.getAvatar().isPresent()) {
856 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
857 if (avatar
.isPointer()) {
859 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
860 } catch (IOException
| InvalidMessageException e
) {
861 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
866 if (groupInfo
.getName().isPresent()) {
867 group
.name
= groupInfo
.getName().get();
870 if (groupInfo
.getMembers().isPresent()) {
871 group
.members
.addAll(groupInfo
.getMembers().get());
874 account
.getGroupStore().updateGroup(group
);
879 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
880 } catch (IOException
| EncapsulatedExceptions e
) {
888 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
889 } catch (IOException
| EncapsulatedExceptions e
) {
893 group
.members
.remove(source
);
894 account
.getGroupStore().updateGroup(group
);
900 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
901 } catch (IOException
| EncapsulatedExceptions e
) {
903 } catch (NotAGroupMemberException e
) {
904 // We have left this group, so don't send a group update message
911 threadId
= destination
;
916 if (message
.isEndSession()) {
917 handleEndSession(isSync ? destination
: source
);
919 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
920 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
921 if (thread
== null) {
922 thread
= new ThreadInfo();
923 thread
.id
= threadId
;
925 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
926 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
927 account
.getThreadStore().updateThread(thread
);
930 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
931 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
932 if (attachment
.isPointer()) {
934 retrieveAttachment(attachment
.asPointer());
935 } catch (IOException
| InvalidMessageException e
) {
936 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
941 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
942 if (source
.equals(username
)) {
943 this.account
.setProfileKey(message
.getProfileKey().get());
945 ContactInfo contact
= account
.getContactStore().getContact(source
);
946 if (contact
== null) {
947 contact
= new ContactInfo();
948 contact
.number
= source
;
950 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
954 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
955 final File cachePath
= new File(getMessageCachePath());
956 if (!cachePath
.exists()) {
959 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
960 if (!dir
.isDirectory()) {
964 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
965 if (!fileEntry
.isFile()) {
968 SignalServiceEnvelope envelope
;
970 envelope
= Utils
.loadEnvelope(fileEntry
);
971 if (envelope
== null) {
974 } catch (IOException e
) {
978 SignalServiceContent content
= null;
979 if (!envelope
.isReceipt()) {
981 content
= decryptMessage(envelope
);
982 } catch (Exception e
) {
985 handleMessage(envelope
, content
, ignoreAttachments
);
988 handler
.handleMessage(envelope
, content
, null);
990 Files
.delete(fileEntry
.toPath());
991 } catch (IOException e
) {
992 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
995 // Try to delete directory if empty
1000 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1001 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1002 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1005 if (messagePipe
== null) {
1006 messagePipe
= messageReceiver
.createMessagePipe();
1010 SignalServiceEnvelope envelope
;
1011 SignalServiceContent content
= null;
1012 Exception exception
= null;
1013 final long now
= new Date().getTime();
1015 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1017 public void onMessage(SignalServiceEnvelope envelope
) {
1018 // store message on disk, before acknowledging receipt to the server
1020 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1021 Utils
.storeEnvelope(envelope
, cacheFile
);
1022 } catch (IOException e
) {
1023 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1027 } catch (TimeoutException e
) {
1028 if (returnOnTimeout
)
1031 } catch (InvalidVersionException e
) {
1032 System
.err
.println("Ignoring error: " + e
.getMessage());
1035 if (!envelope
.isReceipt()) {
1037 content
= decryptMessage(envelope
);
1038 } catch (Exception e
) {
1041 handleMessage(envelope
, content
, ignoreAttachments
);
1044 handler
.handleMessage(envelope
, content
, exception
);
1045 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1046 File cacheFile
= null;
1048 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1049 Files
.delete(cacheFile
.toPath());
1050 // Try to delete directory if empty
1051 new File(getMessageCachePath()).delete();
1052 } catch (IOException e
) {
1053 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1058 if (messagePipe
!= null) {
1059 messagePipe
.shutdown();
1065 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1066 if (content
!= null) {
1067 if (content
.getDataMessage().isPresent()) {
1068 SignalServiceDataMessage message
= content
.getDataMessage().get();
1069 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1071 if (content
.getSyncMessage().isPresent()) {
1072 account
.setMultiDevice(true);
1073 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1074 if (syncMessage
.getSent().isPresent()) {
1075 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1076 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1078 if (syncMessage
.getRequest().isPresent()) {
1079 RequestMessage rm
= syncMessage
.getRequest().get();
1080 if (rm
.isContactsRequest()) {
1083 } catch (UntrustedIdentityException
| IOException e
) {
1084 e
.printStackTrace();
1087 if (rm
.isGroupsRequest()) {
1090 } catch (UntrustedIdentityException
| IOException e
) {
1091 e
.printStackTrace();
1094 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1096 if (syncMessage
.getGroups().isPresent()) {
1097 File tmpFile
= null;
1099 tmpFile
= IOUtils
.createTempFile();
1100 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1101 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1103 while ((g
= s
.read()) != null) {
1104 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1105 if (syncGroup
== null) {
1106 syncGroup
= new GroupInfo(g
.getId());
1108 if (g
.getName().isPresent()) {
1109 syncGroup
.name
= g
.getName().get();
1111 syncGroup
.members
.addAll(g
.getMembers());
1112 syncGroup
.active
= g
.isActive();
1113 if (g
.getColor().isPresent()) {
1114 syncGroup
.color
= g
.getColor().get();
1117 if (g
.getAvatar().isPresent()) {
1118 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1120 account
.getGroupStore().updateGroup(syncGroup
);
1123 } catch (Exception e
) {
1124 e
.printStackTrace();
1126 if (tmpFile
!= null) {
1128 Files
.delete(tmpFile
.toPath());
1129 } catch (IOException e
) {
1130 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1135 if (syncMessage
.getBlockedList().isPresent()) {
1136 // TODO store list of blocked numbers
1138 if (syncMessage
.getContacts().isPresent()) {
1139 File tmpFile
= null;
1141 tmpFile
= IOUtils
.createTempFile();
1142 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1143 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1144 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1145 if (contactsMessage
.isComplete()) {
1146 account
.getContactStore().clear();
1149 while ((c
= s
.read()) != null) {
1150 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1151 account
.setProfileKey(c
.getProfileKey().get());
1153 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1154 if (contact
== null) {
1155 contact
= new ContactInfo();
1156 contact
.number
= c
.getNumber();
1158 if (c
.getName().isPresent()) {
1159 contact
.name
= c
.getName().get();
1161 if (c
.getColor().isPresent()) {
1162 contact
.color
= c
.getColor().get();
1164 if (c
.getProfileKey().isPresent()) {
1165 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1167 if (c
.getVerified().isPresent()) {
1168 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1169 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1171 if (c
.getExpirationTimer().isPresent()) {
1172 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1173 if (thread
== null) {
1174 thread
= new ThreadInfo();
1175 thread
.id
= c
.getNumber();
1177 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1178 account
.getThreadStore().updateThread(thread
);
1180 if (c
.isBlocked()) {
1181 // TODO store list of blocked numbers
1183 account
.getContactStore().updateContact(contact
);
1185 if (c
.getAvatar().isPresent()) {
1186 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1190 } catch (Exception e
) {
1191 e
.printStackTrace();
1193 if (tmpFile
!= null) {
1195 Files
.delete(tmpFile
.toPath());
1196 } catch (IOException e
) {
1197 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1202 if (syncMessage
.getVerified().isPresent()) {
1203 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1204 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1206 if (syncMessage
.getConfiguration().isPresent()) {
1213 private File
getContactAvatarFile(String number
) {
1214 return new File(avatarsPath
, "contact-" + number
);
1217 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1218 IOUtils
.createPrivateDirectories(avatarsPath
);
1219 if (attachment
.isPointer()) {
1220 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1221 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1223 SignalServiceAttachmentStream stream
= attachment
.asStream();
1224 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1228 private File
getGroupAvatarFile(byte[] groupId
) {
1229 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1232 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1233 IOUtils
.createPrivateDirectories(avatarsPath
);
1234 if (attachment
.isPointer()) {
1235 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1236 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1238 SignalServiceAttachmentStream stream
= attachment
.asStream();
1239 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1243 public File
getAttachmentFile(long attachmentId
) {
1244 return new File(attachmentsPath
, attachmentId
+ "");
1247 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1248 IOUtils
.createPrivateDirectories(attachmentsPath
);
1249 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1252 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1253 if (storePreview
&& pointer
.getPreview().isPresent()) {
1254 File previewFile
= new File(outputFile
+ ".preview");
1255 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1256 byte[] preview
= pointer
.getPreview().get();
1257 output
.write(preview
, 0, preview
.length
);
1258 } catch (FileNotFoundException e
) {
1259 e
.printStackTrace();
1264 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1266 File tmpFile
= IOUtils
.createTempFile();
1267 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1268 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1269 byte[] buffer
= new byte[4096];
1272 while ((read
= input
.read(buffer
)) != -1) {
1273 output
.write(buffer
, 0, read
);
1275 } catch (FileNotFoundException e
) {
1276 e
.printStackTrace();
1281 Files
.delete(tmpFile
.toPath());
1282 } catch (IOException e
) {
1283 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1289 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1290 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1291 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1295 public boolean isRemote() {
1299 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1300 File groupsFile
= IOUtils
.createTempFile();
1303 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1304 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1305 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1306 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1307 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1308 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1309 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1310 Optional
.fromNullable(record.color
), false));
1314 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1315 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1316 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1317 .withStream(groupsFileStream
)
1318 .withContentType("application/octet-stream")
1319 .withLength(groupsFile
.length())
1322 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1327 Files
.delete(groupsFile
.toPath());
1328 } catch (IOException e
) {
1329 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1334 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1335 File contactsFile
= IOUtils
.createTempFile();
1338 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1339 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1340 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1341 VerifiedMessage verifiedMessage
= null;
1342 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1343 if (getIdentities().containsKey(record.number
)) {
1344 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1345 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1346 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1347 currentIdentity
= id
;
1350 if (currentIdentity
!= null) {
1351 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1355 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1356 // TODO store list of blocked numbers
1357 boolean blocked
= false;
1358 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1359 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1360 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1363 if (account
.getProfileKey() != null) {
1364 // Send our own profile key as well
1365 out
.write(new DeviceContact(account
.getUsername(),
1366 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1367 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1368 Optional
.of(account
.getProfileKey()),
1369 false, Optional
.<Integer
>absent()));
1373 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1374 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1375 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1376 .withStream(contactsFileStream
)
1377 .withContentType("application/octet-stream")
1378 .withLength(contactsFile
.length())
1381 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1386 Files
.delete(contactsFile
.toPath());
1387 } catch (IOException e
) {
1388 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1393 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1394 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1395 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1398 public ContactInfo
getContact(String number
) {
1399 return account
.getContactStore().getContact(number
);
1402 public GroupInfo
getGroup(byte[] groupId
) {
1403 return account
.getGroupStore().getGroup(groupId
);
1406 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1407 return account
.getSignalProtocolStore().getIdentities();
1410 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1411 return account
.getSignalProtocolStore().getIdentities(number
);
1415 * Trust this the identity with this fingerprint
1417 * @param name username of the identity
1418 * @param fingerprint Fingerprint
1420 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1421 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1425 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1426 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1430 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1432 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1433 } catch (IOException
| UntrustedIdentityException e
) {
1434 e
.printStackTrace();
1443 * Trust this the identity with this safety number
1445 * @param name username of the identity
1446 * @param safetyNumber Safety number
1448 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1449 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1453 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1454 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1458 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1460 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1461 } catch (IOException
| UntrustedIdentityException e
) {
1462 e
.printStackTrace();
1471 * Trust all keys of this identity without verification
1473 * @param name username of the identity
1475 public boolean trustIdentityAllKeys(String name
) {
1476 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1480 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1481 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1482 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1484 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1485 } catch (IOException
| UntrustedIdentityException e
) {
1486 e
.printStackTrace();
1494 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1495 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1498 public interface ReceiveMessageHandler
{
1500 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);