2 Copyright (C) 2015-2020 AsamK and contributors
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
.AttachmentInvalidException
;
21 import org
.asamk
.signal
.GroupNotFoundException
;
22 import org
.asamk
.signal
.NotAGroupMemberException
;
23 import org
.asamk
.signal
.TrustLevel
;
24 import org
.asamk
.signal
.UserAlreadyExists
;
25 import org
.asamk
.signal
.storage
.SignalAccount
;
26 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
27 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
28 import org
.asamk
.signal
.storage
.groups
.JsonGroupStore
;
29 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
30 import org
.asamk
.signal
.storage
.threads
.ThreadInfo
;
31 import org
.asamk
.signal
.util
.IOUtils
;
32 import org
.asamk
.signal
.util
.Util
;
33 import org
.signal
.libsignal
.metadata
.InvalidMetadataMessageException
;
34 import org
.signal
.libsignal
.metadata
.InvalidMetadataVersionException
;
35 import org
.signal
.libsignal
.metadata
.ProtocolDuplicateMessageException
;
36 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyException
;
37 import org
.signal
.libsignal
.metadata
.ProtocolInvalidKeyIdException
;
38 import org
.signal
.libsignal
.metadata
.ProtocolInvalidMessageException
;
39 import org
.signal
.libsignal
.metadata
.ProtocolInvalidVersionException
;
40 import org
.signal
.libsignal
.metadata
.ProtocolLegacyMessageException
;
41 import org
.signal
.libsignal
.metadata
.ProtocolNoSessionException
;
42 import org
.signal
.libsignal
.metadata
.ProtocolUntrustedIdentityException
;
43 import org
.signal
.libsignal
.metadata
.SelfSendException
;
44 import org
.whispersystems
.libsignal
.IdentityKey
;
45 import org
.whispersystems
.libsignal
.IdentityKeyPair
;
46 import org
.whispersystems
.libsignal
.InvalidKeyException
;
47 import org
.whispersystems
.libsignal
.InvalidMessageException
;
48 import org
.whispersystems
.libsignal
.InvalidVersionException
;
49 import org
.whispersystems
.libsignal
.ecc
.Curve
;
50 import org
.whispersystems
.libsignal
.ecc
.ECKeyPair
;
51 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
52 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
53 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
54 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
55 import org
.whispersystems
.libsignal
.util
.Medium
;
56 import org
.whispersystems
.libsignal
.util
.Pair
;
57 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
58 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
59 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
60 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
61 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
62 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
63 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
64 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
65 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
66 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
70 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
71 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
72 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
73 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
74 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
75 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
76 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
77 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
78 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
79 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
80 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
81 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
82 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
83 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
84 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
85 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
86 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
87 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
88 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
89 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
90 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
91 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
92 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
93 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
94 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
95 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
96 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
97 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
98 import org
.whispersystems
.util
.Base64
;
101 import java
.io
.FileInputStream
;
102 import java
.io
.FileNotFoundException
;
103 import java
.io
.FileOutputStream
;
104 import java
.io
.IOException
;
105 import java
.io
.InputStream
;
106 import java
.io
.OutputStream
;
108 import java
.nio
.file
.Files
;
109 import java
.nio
.file
.Paths
;
110 import java
.nio
.file
.StandardCopyOption
;
111 import java
.util
.ArrayList
;
112 import java
.util
.Arrays
;
113 import java
.util
.Collection
;
114 import java
.util
.Collections
;
115 import java
.util
.Date
;
116 import java
.util
.HashSet
;
117 import java
.util
.LinkedList
;
118 import java
.util
.List
;
119 import java
.util
.Locale
;
120 import java
.util
.Map
;
121 import java
.util
.Objects
;
122 import java
.util
.Set
;
123 import java
.util
.concurrent
.TimeUnit
;
124 import java
.util
.concurrent
.TimeoutException
;
126 public class Manager
implements Signal
{
128 private final String settingsPath
;
129 private final String dataPath
;
130 private final String attachmentsPath
;
131 private final String avatarsPath
;
132 private final SleepTimer timer
= new UptimeSleepTimer();
134 private SignalAccount account
;
135 private String username
;
136 private SignalServiceAccountManager accountManager
;
137 private SignalServiceMessagePipe messagePipe
= null;
138 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
140 public Manager(String username
, String settingsPath
) {
141 this.username
= username
;
142 this.settingsPath
= settingsPath
;
143 this.dataPath
= this.settingsPath
+ "/data";
144 this.attachmentsPath
= this.settingsPath
+ "/attachments";
145 this.avatarsPath
= this.settingsPath
+ "/avatars";
149 public String
getUsername() {
153 private SignalServiceAddress
getSelfAddress() {
154 return new SignalServiceAddress(null, username
);
157 private SignalServiceAccountManager
getSignalServiceAccountManager() {
158 return new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, null, account
.getUsername(), account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
161 private IdentityKey
getIdentity() {
162 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
165 public int getDeviceId() {
166 return account
.getDeviceId();
169 private String
getMessageCachePath() {
170 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
173 private String
getMessageCachePath(String sender
) {
174 return getMessageCachePath() + "/" + sender
.replace("/", "_");
177 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
178 String cachePath
= getMessageCachePath(sender
);
179 IOUtils
.createPrivateDirectories(cachePath
);
180 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
183 public boolean userHasKeys() {
184 return account
!= null && account
.getSignalProtocolStore() != null;
187 public void init() throws IOException
{
188 if (!SignalAccount
.userExists(dataPath
, username
)) {
191 account
= SignalAccount
.load(dataPath
, username
);
193 migrateLegacyConfigs();
195 accountManager
= getSignalServiceAccountManager();
197 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
201 } catch (AuthorizationFailedException e
) {
202 System
.err
.println("Authorization failed, was the number registered elsewhere?");
207 private void migrateLegacyConfigs() {
208 // Copy group avatars that were previously stored in the attachments folder
209 // to the new avatar folder
210 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
211 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
212 File avatarFile
= getGroupAvatarFile(g
.groupId
);
213 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
214 if (!avatarFile
.exists() && attachmentFile
.exists()) {
216 IOUtils
.createPrivateDirectories(avatarsPath
);
217 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
218 } catch (Exception e
) {
223 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
226 if (account
.getProfileKey() == null) {
227 // Old config file, creating new profile key
228 account
.setProfileKey(KeyUtils
.createProfileKey());
233 private void createNewIdentity() throws IOException
{
234 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
235 int registrationId
= KeyHelper
.generateRegistrationId(false);
236 if (username
== null) {
237 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
239 byte[] profileKey
= KeyUtils
.createProfileKey();
240 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
245 public boolean isRegistered() {
246 return account
!= null && account
.isRegistered();
249 public void register(boolean voiceVerification
) throws IOException
{
250 if (account
== null) {
253 account
.setPassword(KeyUtils
.createPassword());
254 accountManager
= getSignalServiceAccountManager();
256 if (voiceVerification
) {
257 accountManager
.requestVoiceVerificationCode(Locale
.getDefault(), Optional
.<String
>absent(), Optional
.<String
>absent());
259 accountManager
.requestSmsVerificationCode(false, Optional
.<String
>absent(), Optional
.<String
>absent());
262 account
.setRegistered(false);
266 public void updateAccountAttributes() throws IOException
{
267 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
270 public void setProfileName(String name
) throws IOException
{
271 accountManager
.setProfileName(account
.getProfileKey(), name
);
274 public void setProfileAvatar(File avatar
) throws IOException
{
275 final StreamDetails streamDetails
= Utils
.createStreamDetailsFromFile(avatar
);
276 accountManager
.setProfileAvatar(account
.getProfileKey(), streamDetails
);
277 streamDetails
.getStream().close();
280 public void removeProfileAvatar() throws IOException
{
281 accountManager
.setProfileAvatar(account
.getProfileKey(), null);
284 public void unregister() throws IOException
{
285 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
286 // If this is the master device, other users can't send messages to this number anymore.
287 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
288 accountManager
.setGcmId(Optional
.<String
>absent());
290 account
.setRegistered(false);
294 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
295 if (account
== null) {
298 account
.setPassword(KeyUtils
.createPassword());
299 accountManager
= getSignalServiceAccountManager();
300 String uuid
= accountManager
.getNewDeviceUuid();
302 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
305 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
306 account
.setSignalingKey(KeyUtils
.createSignalingKey());
307 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
309 username
= ret
.getNumber();
310 // TODO do this check before actually registering
311 if (SignalAccount
.userExists(dataPath
, username
)) {
312 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
315 // Create new account with the synced identity
316 byte[] profileKey
= ret
.getProfileKey();
317 if (profileKey
== null) {
318 profileKey
= KeyUtils
.createProfileKey();
320 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
325 requestSyncContacts();
326 requestSyncBlocked();
327 requestSyncConfiguration();
332 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
333 List
<DeviceInfo
> devices
= accountManager
.getDevices();
334 account
.setMultiDevice(devices
.size() > 1);
339 public void removeLinkedDevices(int deviceId
) throws IOException
{
340 accountManager
.removeDevice(deviceId
);
341 List
<DeviceInfo
> devices
= accountManager
.getDevices();
342 account
.setMultiDevice(devices
.size() > 1);
346 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
347 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
349 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
352 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
353 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
354 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
356 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
357 account
.setMultiDevice(true);
361 private List
<PreKeyRecord
> generatePreKeys() {
362 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
364 final int offset
= account
.getPreKeyIdOffset();
365 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
366 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
367 ECKeyPair keyPair
= Curve
.generateKeyPair();
368 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
373 account
.addPreKeys(records
);
379 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
381 ECKeyPair keyPair
= Curve
.generateKeyPair();
382 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
383 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
385 account
.addSignedPreKey(record);
389 } catch (InvalidKeyException e
) {
390 throw new AssertionError(e
);
394 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
395 verificationCode
= verificationCode
.replace("-", "");
396 account
.setSignalingKey(KeyUtils
.createSignalingKey());
397 // TODO make unrestricted unidentified access configurable
398 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
400 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
401 account
.setRegistered(true);
402 account
.setRegistrationLockPin(pin
);
408 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
409 accountManager
.setPin(pin
);
410 if (pin
.isPresent()) {
411 account
.setRegistrationLockPin(pin
.get());
413 account
.setRegistrationLockPin(null);
418 private void refreshPreKeys() throws IOException
{
419 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
420 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
421 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
423 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
426 private SignalServiceMessageReceiver
getMessageReceiver() {
427 return new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
430 private SignalServiceMessageSender
getMessageSender() {
431 return new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(),
432 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
435 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
436 File file
= getGroupAvatarFile(groupId
);
437 if (!file
.exists()) {
438 return Optional
.absent();
441 return Optional
.of(Utils
.createAttachment(file
));
444 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
445 File file
= getContactAvatarFile(number
);
446 if (!file
.exists()) {
447 return Optional
.absent();
450 return Optional
.of(Utils
.createAttachment(file
));
453 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
454 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
456 throw new GroupNotFoundException(groupId
);
458 for (String member
: g
.members
) {
459 if (member
.equals(this.username
)) {
463 throw new NotAGroupMemberException(groupId
, g
.name
);
466 public List
<GroupInfo
> getGroups() {
467 return account
.getGroupStore().getGroups();
471 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
473 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
474 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
475 if (attachments
!= null) {
476 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
478 if (groupId
!= null) {
479 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
482 messageBuilder
.asGroupMessage(group
);
484 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
485 if (thread
!= null) {
486 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
489 final GroupInfo g
= getGroupForSending(groupId
);
491 // Don't send group message to ourself
492 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
493 membersSend
.remove(this.username
);
494 sendMessageLegacy(messageBuilder
, membersSend
);
497 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
498 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
502 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
503 .asGroupMessage(group
);
505 final GroupInfo g
= getGroupForSending(groupId
);
506 g
.members
.remove(this.username
);
507 account
.getGroupStore().updateGroup(g
);
509 sendMessageLegacy(messageBuilder
, g
.members
);
512 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
514 if (groupId
== null) {
516 g
= new GroupInfo(KeyUtils
.createGroupId());
517 g
.members
.add(username
);
519 g
= getGroupForSending(groupId
);
526 if (members
!= null) {
527 Set
<String
> newMembers
= new HashSet
<>();
528 for (String member
: members
) {
530 member
= Utils
.canonicalizeNumber(member
, username
);
531 } catch (InvalidNumberException e
) {
532 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
533 System
.err
.println("Aborting…");
536 if (g
.members
.contains(member
)) {
539 newMembers
.add(member
);
540 g
.members
.add(member
);
542 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
543 if (contacts
.size() != newMembers
.size()) {
544 // Some of the new members are not registered on Signal
545 for (ContactTokenDetails contact
: contacts
) {
546 newMembers
.remove(contact
.getNumber());
548 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
549 System
.err
.println("Aborting…");
554 if (avatarFile
!= null) {
555 IOUtils
.createPrivateDirectories(avatarsPath
);
556 File aFile
= getGroupAvatarFile(g
.groupId
);
557 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
560 account
.getGroupStore().updateGroup(g
);
562 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
564 // Don't send group message to ourself
565 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
566 membersSend
.remove(this.username
);
567 sendMessageLegacy(messageBuilder
, membersSend
);
571 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
572 if (groupId
== null) {
575 GroupInfo g
= getGroupForSending(groupId
);
577 if (!g
.members
.contains(recipient
)) {
581 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
583 // Send group message only to the recipient who requested it
584 final List
<String
> membersSend
= new ArrayList
<>();
585 membersSend
.add(recipient
);
586 sendMessageLegacy(messageBuilder
, membersSend
);
589 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
590 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
593 .withMembers(new ArrayList
<>(g
.getMembers()));
595 File aFile
= getGroupAvatarFile(g
.groupId
);
596 if (aFile
.exists()) {
598 group
.withAvatar(Utils
.createAttachment(aFile
));
599 } catch (IOException e
) {
600 throw new AttachmentInvalidException(aFile
.toString(), e
);
604 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
605 .asGroupMessage(group
.build());
607 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
608 if (thread
!= null) {
609 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
612 return messageBuilder
;
615 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
616 if (groupId
== null) {
620 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
623 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
624 .asGroupMessage(group
.build());
626 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
627 if (thread
!= null) {
628 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
631 // Send group info request message to the recipient who sent us a message with this groupId
632 final List
<String
> membersSend
= new ArrayList
<>();
633 membersSend
.add(recipient
);
634 sendMessageLegacy(messageBuilder
, membersSend
);
638 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
639 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
640 List
<String
> recipients
= new ArrayList
<>(1);
641 recipients
.add(recipient
);
642 sendMessage(message
, attachments
, recipients
);
646 public void sendMessage(String messageText
, List
<String
> attachments
,
647 List
<String
> recipients
)
648 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
649 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
650 if (attachments
!= null) {
651 List
<SignalServiceAttachment
> attachmentStreams
= Utils
.getSignalServiceAttachments(attachments
);
653 // Upload attachments here, so we only upload once even for multiple recipients
654 SignalServiceMessageSender messageSender
= getMessageSender();
655 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
656 for (SignalServiceAttachment attachment
: attachmentStreams
) {
657 if (attachment
.isStream()) {
658 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
659 } else if (attachment
.isPointer()) {
660 attachmentPointers
.add(attachment
.asPointer());
664 messageBuilder
.withAttachments(attachmentPointers
);
666 messageBuilder
.withProfileKey(account
.getProfileKey());
667 sendMessageLegacy(messageBuilder
, recipients
);
671 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
672 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
673 .asEndSessionMessage();
675 sendMessageLegacy(messageBuilder
, recipients
);
679 public String
getContactName(String number
) throws InvalidNumberException
{
680 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
681 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
682 if (contact
== null) {
690 public void setContactName(String number
, String name
) throws InvalidNumberException
{
691 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
692 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
693 if (contact
== null) {
694 contact
= new ContactInfo();
695 contact
.number
= canonicalizedNumber
;
696 System
.err
.println("Add contact " + canonicalizedNumber
+ " named " + name
);
698 System
.err
.println("Updating contact " + canonicalizedNumber
+ " name " + contact
.name
+ " -> " + name
);
701 account
.getContactStore().updateContact(contact
);
706 public List
<byte[]> getGroupIds() {
707 List
<GroupInfo
> groups
= getGroups();
708 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
709 for (GroupInfo group
: groups
) {
710 ids
.add(group
.groupId
);
716 public String
getGroupName(byte[] groupId
) {
717 GroupInfo group
= getGroup(groupId
);
726 public List
<String
> getGroupMembers(byte[] groupId
) {
727 GroupInfo group
= getGroup(groupId
);
729 return new ArrayList
<>();
731 return new ArrayList
<>(group
.members
);
736 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
737 if (groupId
.length
== 0) {
740 if (name
.isEmpty()) {
743 if (members
.size() == 0) {
746 if (avatar
.isEmpty()) {
749 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
753 * Change the expiration timer for a thread (number of groupId)
755 * @param numberOrGroupId
756 * @param messageExpirationTimer
758 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
759 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
760 thread
.messageExpirationTime
= messageExpirationTimer
;
761 account
.getThreadStore().updateThread(thread
);
764 private void requestSyncGroups() throws IOException
{
765 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
766 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
768 sendSyncMessage(message
);
769 } catch (UntrustedIdentityException e
) {
774 private void requestSyncContacts() throws IOException
{
775 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
776 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
778 sendSyncMessage(message
);
779 } catch (UntrustedIdentityException e
) {
784 private void requestSyncBlocked() throws IOException
{
785 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
786 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
788 sendSyncMessage(message
);
789 } catch (UntrustedIdentityException e
) {
794 private void requestSyncConfiguration() throws IOException
{
795 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
796 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
798 sendSyncMessage(message
);
799 } catch (UntrustedIdentityException e
) {
804 private byte[] getSelfUnidentifiedAccessKey() {
805 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
808 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
813 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
815 return Optional
.absent();
818 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
819 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
820 for (SignalServiceAddress recipient
: recipients
) {
821 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
826 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
828 return Optional
.absent();
831 private void sendSyncMessage(SignalServiceSyncMessage message
)
832 throws IOException
, UntrustedIdentityException
{
833 SignalServiceMessageSender messageSender
= getMessageSender();
835 messageSender
.sendMessage(message
, getAccessForSync());
836 } catch (UntrustedIdentityException e
) {
837 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
843 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
845 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
846 throws EncapsulatedExceptions
, IOException
{
847 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
849 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
850 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
851 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
853 for (SendMessageResult result
: results
) {
854 if (result
.isUnregisteredFailure()) {
855 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber().get(), null));
856 } else if (result
.isNetworkFailure()) {
857 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber().get(), null));
858 } else if (result
.getIdentityFailure() != null) {
859 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber().get(), result
.getIdentityFailure().getIdentityKey()));
862 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
863 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
867 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
869 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
870 if (recipientsTS
== null) {
872 return Collections
.emptyList();
875 SignalServiceDataMessage message
= null;
877 SignalServiceMessageSender messageSender
= getMessageSender();
879 message
= messageBuilder
.build();
880 if (message
.getGroupInfo().isPresent()) {
882 final boolean isRecipientUpdate
= false;
883 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
884 for (SendMessageResult r
: result
) {
885 if (r
.getIdentityFailure() != null) {
886 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber().get(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
890 } catch (UntrustedIdentityException e
) {
891 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
892 return Collections
.emptyList();
894 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(getSelfAddress())) {
895 SignalServiceAddress recipient
= getSelfAddress();
896 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
897 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
898 message
.getTimestamp(),
900 message
.getExpiresInSeconds(),
901 Collections
.singletonMap(recipient
, unidentifiedAccess
.isPresent()),
903 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
905 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
907 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
908 } catch (UntrustedIdentityException e
) {
909 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
910 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
914 // Send to all individually, so sync messages are sent correctly
915 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
916 for (SignalServiceAddress address
: recipientsTS
) {
917 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber().get());
918 if (thread
!= null) {
919 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
921 messageBuilder
.withExpiration(0);
923 message
= messageBuilder
.build();
925 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
927 } catch (UntrustedIdentityException e
) {
928 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
929 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
935 if (message
!= null && message
.isEndSession()) {
936 for (SignalServiceAddress recipient
: recipientsTS
) {
937 handleEndSession(recipient
.getNumber().get());
944 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
945 SignalServiceCipher cipher
= new SignalServiceCipher(getSelfAddress(), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
947 return cipher
.decrypt(envelope
);
948 } catch (ProtocolUntrustedIdentityException e
) {
949 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
950 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
955 private void handleEndSession(String source
) {
956 account
.getSignalProtocolStore().deleteAllSessions(source
);
959 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, SignalServiceAddress destination
, boolean ignoreAttachments
) {
961 if (message
.getGroupInfo().isPresent()) {
962 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
963 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
964 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
965 switch (groupInfo
.getType()) {
968 group
= new GroupInfo(groupInfo
.getGroupId());
971 if (groupInfo
.getAvatar().isPresent()) {
972 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
973 if (avatar
.isPointer()) {
975 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
976 } catch (IOException
| InvalidMessageException e
) {
977 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
982 if (groupInfo
.getName().isPresent()) {
983 group
.name
= groupInfo
.getName().get();
986 if (groupInfo
.getMembers().isPresent()) {
987 group
.addMembers(groupInfo
.getMembers().get());
990 account
.getGroupStore().updateGroup(group
);
995 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
996 } catch (IOException
| EncapsulatedExceptions e
) {
1002 if (group
== null) {
1004 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1005 } catch (IOException
| EncapsulatedExceptions e
) {
1006 e
.printStackTrace();
1009 group
.members
.remove(source
);
1010 account
.getGroupStore().updateGroup(group
);
1014 if (group
!= null) {
1016 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
1017 } catch (IOException
| EncapsulatedExceptions e
) {
1018 e
.printStackTrace();
1019 } catch (NotAGroupMemberException e
) {
1020 // We have left this group, so don't send a group update message
1027 threadId
= destination
.getNumber().get();
1032 if (message
.isEndSession()) {
1033 handleEndSession(isSync ? destination
.getNumber().get() : source
);
1035 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1036 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
1037 if (thread
== null) {
1038 thread
= new ThreadInfo();
1039 thread
.id
= threadId
;
1041 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1042 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1043 account
.getThreadStore().updateThread(thread
);
1046 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1047 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1048 if (attachment
.isPointer()) {
1050 retrieveAttachment(attachment
.asPointer());
1051 } catch (IOException
| InvalidMessageException e
) {
1052 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1057 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1058 if (source
.equals(username
)) {
1059 this.account
.setProfileKey(message
.getProfileKey().get());
1061 ContactInfo contact
= account
.getContactStore().getContact(source
);
1062 if (contact
== null) {
1063 contact
= new ContactInfo();
1064 contact
.number
= source
;
1066 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
1068 if (message
.getPreviews().isPresent()) {
1069 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1070 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1071 if (preview
.getImage().isPresent() && preview
.getImage().get().isPointer()) {
1072 SignalServiceAttachmentPointer attachment
= preview
.getImage().get().asPointer();
1074 retrieveAttachment(attachment
);
1075 } catch (IOException
| InvalidMessageException e
) {
1076 System
.err
.println("Failed to retrieve attachment (" + attachment
.getId() + "): " + e
.getMessage());
1083 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1084 final File cachePath
= new File(getMessageCachePath());
1085 if (!cachePath
.exists()) {
1088 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
1089 if (!dir
.isDirectory()) {
1093 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1094 if (!fileEntry
.isFile()) {
1097 SignalServiceEnvelope envelope
;
1099 envelope
= Utils
.loadEnvelope(fileEntry
);
1100 if (envelope
== null) {
1103 } catch (IOException e
) {
1104 e
.printStackTrace();
1107 SignalServiceContent content
= null;
1108 if (!envelope
.isReceipt()) {
1110 content
= decryptMessage(envelope
);
1111 } catch (Exception e
) {
1114 handleMessage(envelope
, content
, ignoreAttachments
);
1117 handler
.handleMessage(envelope
, content
, null);
1119 Files
.delete(fileEntry
.toPath());
1120 } catch (IOException e
) {
1121 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1124 // Try to delete directory if empty
1129 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1130 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1131 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1134 if (messagePipe
== null) {
1135 messagePipe
= messageReceiver
.createMessagePipe();
1139 SignalServiceEnvelope envelope
;
1140 SignalServiceContent content
= null;
1141 Exception exception
= null;
1142 final long now
= new Date().getTime();
1144 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1146 public void onMessage(SignalServiceEnvelope envelope
) {
1147 // store message on disk, before acknowledging receipt to the server
1149 File cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1150 Utils
.storeEnvelope(envelope
, cacheFile
);
1151 } catch (IOException e
) {
1152 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1156 } catch (TimeoutException e
) {
1157 if (returnOnTimeout
)
1160 } catch (InvalidVersionException e
) {
1161 System
.err
.println("Ignoring error: " + e
.getMessage());
1164 if (!envelope
.isReceipt()) {
1166 content
= decryptMessage(envelope
);
1167 } catch (Exception e
) {
1170 handleMessage(envelope
, content
, ignoreAttachments
);
1173 handler
.handleMessage(envelope
, content
, exception
);
1174 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1175 File cacheFile
= null;
1177 cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1178 Files
.delete(cacheFile
.toPath());
1179 // Try to delete directory if empty
1180 new File(getMessageCachePath()).delete();
1181 } catch (IOException e
) {
1182 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1187 if (messagePipe
!= null) {
1188 messagePipe
.shutdown();
1194 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1195 if (content
!= null) {
1196 SignalServiceAddress sender
;
1197 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1198 sender
= envelope
.getSourceAddress();
1200 sender
= content
.getSender();
1202 if (content
.getDataMessage().isPresent()) {
1203 SignalServiceDataMessage message
= content
.getDataMessage().get();
1204 handleSignalServiceDataMessage(message
, false, sender
.getNumber().get(), getSelfAddress(), ignoreAttachments
);
1206 if (content
.getSyncMessage().isPresent()) {
1207 account
.setMultiDevice(true);
1208 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1209 if (syncMessage
.getSent().isPresent()) {
1210 SentTranscriptMessage message
= syncMessage
.getSent().get();
1211 handleSignalServiceDataMessage(message
.getMessage(), true, sender
.getNumber().get(), message
.getDestination().orNull(), ignoreAttachments
);
1213 if (syncMessage
.getRequest().isPresent()) {
1214 RequestMessage rm
= syncMessage
.getRequest().get();
1215 if (rm
.isContactsRequest()) {
1218 } catch (UntrustedIdentityException
| IOException e
) {
1219 e
.printStackTrace();
1222 if (rm
.isGroupsRequest()) {
1225 } catch (UntrustedIdentityException
| IOException e
) {
1226 e
.printStackTrace();
1229 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1231 if (syncMessage
.getGroups().isPresent()) {
1232 File tmpFile
= null;
1234 tmpFile
= IOUtils
.createTempFile();
1235 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1236 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1238 while ((g
= s
.read()) != null) {
1239 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1240 if (syncGroup
== null) {
1241 syncGroup
= new GroupInfo(g
.getId());
1243 if (g
.getName().isPresent()) {
1244 syncGroup
.name
= g
.getName().get();
1246 syncGroup
.addMembers(g
.getMembers());
1247 syncGroup
.active
= g
.isActive();
1248 if (g
.getColor().isPresent()) {
1249 syncGroup
.color
= g
.getColor().get();
1252 if (g
.getAvatar().isPresent()) {
1253 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1255 account
.getGroupStore().updateGroup(syncGroup
);
1258 } catch (Exception e
) {
1259 e
.printStackTrace();
1261 if (tmpFile
!= null) {
1263 Files
.delete(tmpFile
.toPath());
1264 } catch (IOException e
) {
1265 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1270 if (syncMessage
.getBlockedList().isPresent()) {
1271 // TODO store list of blocked numbers
1273 if (syncMessage
.getContacts().isPresent()) {
1274 File tmpFile
= null;
1276 tmpFile
= IOUtils
.createTempFile();
1277 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1278 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1279 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1280 if (contactsMessage
.isComplete()) {
1281 account
.getContactStore().clear();
1284 while ((c
= s
.read()) != null) {
1285 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1286 account
.setProfileKey(c
.getProfileKey().get());
1288 ContactInfo contact
= account
.getContactStore().getContact(c
.getAddress().getNumber().get());
1289 if (contact
== null) {
1290 contact
= new ContactInfo();
1291 contact
.number
= c
.getAddress().getNumber().get();
1293 if (c
.getName().isPresent()) {
1294 contact
.name
= c
.getName().get();
1296 if (c
.getColor().isPresent()) {
1297 contact
.color
= c
.getColor().get();
1299 if (c
.getProfileKey().isPresent()) {
1300 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1302 if (c
.getVerified().isPresent()) {
1303 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1304 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1306 if (c
.getExpirationTimer().isPresent()) {
1307 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getAddress().getNumber().get());
1308 if (thread
== null) {
1309 thread
= new ThreadInfo();
1310 thread
.id
= c
.getAddress().getNumber().get();
1312 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1313 account
.getThreadStore().updateThread(thread
);
1315 if (c
.isBlocked()) {
1316 // TODO store list of blocked numbers
1318 account
.getContactStore().updateContact(contact
);
1320 if (c
.getAvatar().isPresent()) {
1321 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1325 } catch (Exception e
) {
1326 e
.printStackTrace();
1328 if (tmpFile
!= null) {
1330 Files
.delete(tmpFile
.toPath());
1331 } catch (IOException e
) {
1332 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1337 if (syncMessage
.getVerified().isPresent()) {
1338 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1339 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1341 if (syncMessage
.getConfiguration().isPresent()) {
1348 private File
getContactAvatarFile(String number
) {
1349 return new File(avatarsPath
, "contact-" + number
);
1352 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1353 IOUtils
.createPrivateDirectories(avatarsPath
);
1354 if (attachment
.isPointer()) {
1355 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1356 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1358 SignalServiceAttachmentStream stream
= attachment
.asStream();
1359 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1363 private File
getGroupAvatarFile(byte[] groupId
) {
1364 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1367 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1368 IOUtils
.createPrivateDirectories(avatarsPath
);
1369 if (attachment
.isPointer()) {
1370 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1371 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1373 SignalServiceAttachmentStream stream
= attachment
.asStream();
1374 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1378 public File
getAttachmentFile(long attachmentId
) {
1379 return new File(attachmentsPath
, attachmentId
+ "");
1382 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1383 IOUtils
.createPrivateDirectories(attachmentsPath
);
1384 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1387 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1388 if (storePreview
&& pointer
.getPreview().isPresent()) {
1389 File previewFile
= new File(outputFile
+ ".preview");
1390 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1391 byte[] preview
= pointer
.getPreview().get();
1392 output
.write(preview
, 0, preview
.length
);
1393 } catch (FileNotFoundException e
) {
1394 e
.printStackTrace();
1399 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1401 File tmpFile
= IOUtils
.createTempFile();
1402 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1403 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1404 byte[] buffer
= new byte[4096];
1407 while ((read
= input
.read(buffer
)) != -1) {
1408 output
.write(buffer
, 0, read
);
1410 } catch (FileNotFoundException e
) {
1411 e
.printStackTrace();
1416 Files
.delete(tmpFile
.toPath());
1417 } catch (IOException e
) {
1418 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1424 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1425 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1426 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1430 public boolean isRemote() {
1434 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1435 File groupsFile
= IOUtils
.createTempFile();
1438 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1439 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1440 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1441 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1442 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1443 new ArrayList
<>(record.getMembers()), createGroupAvatarAttachment(record.groupId
),
1444 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1445 Optional
.fromNullable(record.color
), false));
1449 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1450 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1451 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1452 .withStream(groupsFileStream
)
1453 .withContentType("application/octet-stream")
1454 .withLength(groupsFile
.length())
1457 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1462 Files
.delete(groupsFile
.toPath());
1463 } catch (IOException e
) {
1464 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1469 public void sendContacts() throws IOException
, UntrustedIdentityException
{
1470 File contactsFile
= IOUtils
.createTempFile();
1473 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1474 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1475 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1476 VerifiedMessage verifiedMessage
= null;
1477 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1478 if (getIdentities().containsKey(record.number
)) {
1479 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1480 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1481 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1482 currentIdentity
= id
;
1485 if (currentIdentity
!= null) {
1486 verifiedMessage
= new VerifiedMessage(record.getAddress(), currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1490 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1491 // TODO store list of blocked numbers
1492 boolean blocked
= false;
1493 out
.write(new DeviceContact(record.getAddress(), Optional
.fromNullable(record.name
),
1494 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1495 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1498 if (account
.getProfileKey() != null) {
1499 // Send our own profile key as well
1500 out
.write(new DeviceContact(account
.getSelfAddress(),
1501 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1502 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1503 Optional
.of(account
.getProfileKey()),
1504 false, Optional
.<Integer
>absent()));
1508 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1509 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1510 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1511 .withStream(contactsFileStream
)
1512 .withContentType("application/octet-stream")
1513 .withLength(contactsFile
.length())
1516 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1521 Files
.delete(contactsFile
.toPath());
1522 } catch (IOException e
) {
1523 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1528 private void sendVerifiedMessage(SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1529 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1530 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1533 public List
<ContactInfo
> getContacts() {
1534 return account
.getContactStore().getContacts();
1537 public ContactInfo
getContact(String number
) {
1538 return account
.getContactStore().getContact(number
);
1541 public GroupInfo
getGroup(byte[] groupId
) {
1542 return account
.getGroupStore().getGroup(groupId
);
1545 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1546 return account
.getSignalProtocolStore().getIdentities();
1549 public Pair
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities(String number
) throws InvalidNumberException
{
1550 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
1551 return new Pair
<>(canonicalizedNumber
, account
.getSignalProtocolStore().getIdentities(canonicalizedNumber
));
1555 * Trust this the identity with this fingerprint
1557 * @param name username of the identity
1558 * @param fingerprint Fingerprint
1560 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1561 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1565 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1566 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1570 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1572 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1573 } catch (IOException
| UntrustedIdentityException e
) {
1574 e
.printStackTrace();
1583 * Trust this the identity with this safety number
1585 * @param name username of the identity
1586 * @param safetyNumber Safety number
1588 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1589 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1593 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1594 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1598 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1600 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1601 } catch (IOException
| UntrustedIdentityException e
) {
1602 e
.printStackTrace();
1611 * Trust all keys of this identity without verification
1613 * @param name username of the identity
1615 public boolean trustIdentityAllKeys(String name
) {
1616 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1620 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1621 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1622 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1624 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1625 } catch (IOException
| UntrustedIdentityException e
) {
1626 e
.printStackTrace();
1634 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1635 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1638 public interface ReceiveMessageHandler
{
1640 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);