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
.BlockedListMessage
;
75 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
76 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
77 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
78 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
79 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
80 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
81 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
82 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
83 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
84 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
85 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
86 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
87 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
88 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
89 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
90 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
91 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
92 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
93 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
94 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
95 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
96 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
97 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
98 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
99 import org
.whispersystems
.util
.Base64
;
102 import java
.io
.FileInputStream
;
103 import java
.io
.FileNotFoundException
;
104 import java
.io
.FileOutputStream
;
105 import java
.io
.IOException
;
106 import java
.io
.InputStream
;
107 import java
.io
.OutputStream
;
109 import java
.nio
.file
.Files
;
110 import java
.nio
.file
.Paths
;
111 import java
.nio
.file
.StandardCopyOption
;
112 import java
.util
.ArrayList
;
113 import java
.util
.Arrays
;
114 import java
.util
.Collection
;
115 import java
.util
.Collections
;
116 import java
.util
.Date
;
117 import java
.util
.HashSet
;
118 import java
.util
.LinkedList
;
119 import java
.util
.List
;
120 import java
.util
.Locale
;
121 import java
.util
.Map
;
122 import java
.util
.Objects
;
123 import java
.util
.Set
;
124 import java
.util
.concurrent
.TimeUnit
;
125 import java
.util
.concurrent
.TimeoutException
;
127 public class Manager
implements Signal
{
129 private final String settingsPath
;
130 private final String dataPath
;
131 private final String attachmentsPath
;
132 private final String avatarsPath
;
133 private final SleepTimer timer
= new UptimeSleepTimer();
135 private SignalAccount account
;
136 private String username
;
137 private SignalServiceAccountManager accountManager
;
138 private SignalServiceMessagePipe messagePipe
= null;
139 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
141 public Manager(String username
, String settingsPath
) {
142 this.username
= username
;
143 this.settingsPath
= settingsPath
;
144 this.dataPath
= this.settingsPath
+ "/data";
145 this.attachmentsPath
= this.settingsPath
+ "/attachments";
146 this.avatarsPath
= this.settingsPath
+ "/avatars";
150 public String
getUsername() {
154 private SignalServiceAddress
getSelfAddress() {
155 return new SignalServiceAddress(null, username
);
158 private SignalServiceAccountManager
getSignalServiceAccountManager() {
159 return new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, null, account
.getUsername(), account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
162 private IdentityKey
getIdentity() {
163 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
166 public int getDeviceId() {
167 return account
.getDeviceId();
170 private String
getMessageCachePath() {
171 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
174 private String
getMessageCachePath(String sender
) {
175 return getMessageCachePath() + "/" + sender
.replace("/", "_");
178 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
179 String cachePath
= getMessageCachePath(sender
);
180 IOUtils
.createPrivateDirectories(cachePath
);
181 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
184 public boolean userHasKeys() {
185 return account
!= null && account
.getSignalProtocolStore() != null;
188 public void init() throws IOException
{
189 if (!SignalAccount
.userExists(dataPath
, username
)) {
192 account
= SignalAccount
.load(dataPath
, username
);
194 migrateLegacyConfigs();
196 accountManager
= getSignalServiceAccountManager();
198 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
202 } catch (AuthorizationFailedException e
) {
203 System
.err
.println("Authorization failed, was the number registered elsewhere?");
208 private void migrateLegacyConfigs() {
209 // Copy group avatars that were previously stored in the attachments folder
210 // to the new avatar folder
211 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
212 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
213 File avatarFile
= getGroupAvatarFile(g
.groupId
);
214 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
215 if (!avatarFile
.exists() && attachmentFile
.exists()) {
217 IOUtils
.createPrivateDirectories(avatarsPath
);
218 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
219 } catch (Exception e
) {
224 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
227 if (account
.getProfileKey() == null) {
228 // Old config file, creating new profile key
229 account
.setProfileKey(KeyUtils
.createProfileKey());
234 private void createNewIdentity() throws IOException
{
235 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
236 int registrationId
= KeyHelper
.generateRegistrationId(false);
237 if (username
== null) {
238 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
240 byte[] profileKey
= KeyUtils
.createProfileKey();
241 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
246 public boolean isRegistered() {
247 return account
!= null && account
.isRegistered();
250 public void register(boolean voiceVerification
) throws IOException
{
251 if (account
== null) {
254 account
.setPassword(KeyUtils
.createPassword());
255 accountManager
= getSignalServiceAccountManager();
257 if (voiceVerification
) {
258 accountManager
.requestVoiceVerificationCode(Locale
.getDefault(), Optional
.<String
>absent(), Optional
.<String
>absent());
260 accountManager
.requestSmsVerificationCode(false, Optional
.<String
>absent(), Optional
.<String
>absent());
263 account
.setRegistered(false);
267 public void updateAccountAttributes() throws IOException
{
268 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
271 public void setProfileName(String name
) throws IOException
{
272 accountManager
.setProfileName(account
.getProfileKey(), name
);
275 public void setProfileAvatar(File avatar
) throws IOException
{
276 final StreamDetails streamDetails
= Utils
.createStreamDetailsFromFile(avatar
);
277 accountManager
.setProfileAvatar(account
.getProfileKey(), streamDetails
);
278 streamDetails
.getStream().close();
281 public void removeProfileAvatar() throws IOException
{
282 accountManager
.setProfileAvatar(account
.getProfileKey(), null);
285 public void unregister() throws IOException
{
286 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
287 // If this is the master device, other users can't send messages to this number anymore.
288 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
289 accountManager
.setGcmId(Optional
.<String
>absent());
291 account
.setRegistered(false);
295 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
296 if (account
== null) {
299 account
.setPassword(KeyUtils
.createPassword());
300 accountManager
= getSignalServiceAccountManager();
301 String uuid
= accountManager
.getNewDeviceUuid();
303 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
306 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
307 account
.setSignalingKey(KeyUtils
.createSignalingKey());
308 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
310 username
= ret
.getNumber();
311 // TODO do this check before actually registering
312 if (SignalAccount
.userExists(dataPath
, username
)) {
313 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
316 // Create new account with the synced identity
317 byte[] profileKey
= ret
.getProfileKey();
318 if (profileKey
== null) {
319 profileKey
= KeyUtils
.createProfileKey();
321 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
326 requestSyncContacts();
327 requestSyncBlocked();
328 requestSyncConfiguration();
333 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
334 List
<DeviceInfo
> devices
= accountManager
.getDevices();
335 account
.setMultiDevice(devices
.size() > 1);
340 public void removeLinkedDevices(int deviceId
) throws IOException
{
341 accountManager
.removeDevice(deviceId
);
342 List
<DeviceInfo
> devices
= accountManager
.getDevices();
343 account
.setMultiDevice(devices
.size() > 1);
347 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
348 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
350 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
353 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
354 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
355 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
357 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
358 account
.setMultiDevice(true);
362 private List
<PreKeyRecord
> generatePreKeys() {
363 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
365 final int offset
= account
.getPreKeyIdOffset();
366 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
367 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
368 ECKeyPair keyPair
= Curve
.generateKeyPair();
369 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
374 account
.addPreKeys(records
);
380 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
382 ECKeyPair keyPair
= Curve
.generateKeyPair();
383 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
384 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
386 account
.addSignedPreKey(record);
390 } catch (InvalidKeyException e
) {
391 throw new AssertionError(e
);
395 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
396 verificationCode
= verificationCode
.replace("-", "");
397 account
.setSignalingKey(KeyUtils
.createSignalingKey());
398 // TODO make unrestricted unidentified access configurable
399 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
401 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
402 account
.setRegistered(true);
403 account
.setRegistrationLockPin(pin
);
409 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
410 accountManager
.setPin(pin
);
411 if (pin
.isPresent()) {
412 account
.setRegistrationLockPin(pin
.get());
414 account
.setRegistrationLockPin(null);
419 private void refreshPreKeys() throws IOException
{
420 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
421 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
422 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
424 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
427 private SignalServiceMessageReceiver
getMessageReceiver() {
428 return new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
431 private SignalServiceMessageSender
getMessageSender() {
432 return new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(),
433 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
436 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
437 File file
= getGroupAvatarFile(groupId
);
438 if (!file
.exists()) {
439 return Optional
.absent();
442 return Optional
.of(Utils
.createAttachment(file
));
445 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
446 File file
= getContactAvatarFile(number
);
447 if (!file
.exists()) {
448 return Optional
.absent();
451 return Optional
.of(Utils
.createAttachment(file
));
454 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
455 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
457 throw new GroupNotFoundException(groupId
);
459 for (String member
: g
.members
) {
460 if (member
.equals(this.username
)) {
464 throw new NotAGroupMemberException(groupId
, g
.name
);
467 public List
<GroupInfo
> getGroups() {
468 return account
.getGroupStore().getGroups();
472 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
474 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
475 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
476 if (attachments
!= null) {
477 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
479 if (groupId
!= null) {
480 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
483 messageBuilder
.asGroupMessage(group
);
485 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
486 if (thread
!= null) {
487 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
490 final GroupInfo g
= getGroupForSending(groupId
);
492 // Don't send group message to ourself
493 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
494 membersSend
.remove(this.username
);
495 sendMessageLegacy(messageBuilder
, membersSend
);
498 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
499 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
503 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
504 .asGroupMessage(group
);
506 final GroupInfo g
= getGroupForSending(groupId
);
507 g
.members
.remove(this.username
);
508 account
.getGroupStore().updateGroup(g
);
510 sendMessageLegacy(messageBuilder
, g
.members
);
513 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
515 if (groupId
== null) {
517 g
= new GroupInfo(KeyUtils
.createGroupId());
518 g
.members
.add(username
);
520 g
= getGroupForSending(groupId
);
527 if (members
!= null) {
528 Set
<String
> newMembers
= new HashSet
<>();
529 for (String member
: members
) {
531 member
= Utils
.canonicalizeNumber(member
, username
);
532 } catch (InvalidNumberException e
) {
533 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
534 System
.err
.println("Aborting…");
537 if (g
.members
.contains(member
)) {
540 newMembers
.add(member
);
541 g
.members
.add(member
);
543 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
544 if (contacts
.size() != newMembers
.size()) {
545 // Some of the new members are not registered on Signal
546 for (ContactTokenDetails contact
: contacts
) {
547 newMembers
.remove(contact
.getNumber());
549 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
550 System
.err
.println("Aborting…");
555 if (avatarFile
!= null) {
556 IOUtils
.createPrivateDirectories(avatarsPath
);
557 File aFile
= getGroupAvatarFile(g
.groupId
);
558 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
561 account
.getGroupStore().updateGroup(g
);
563 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
565 // Don't send group message to ourself
566 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
567 membersSend
.remove(this.username
);
568 sendMessageLegacy(messageBuilder
, membersSend
);
572 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
573 if (groupId
== null) {
576 GroupInfo g
= getGroupForSending(groupId
);
578 if (!g
.members
.contains(recipient
)) {
582 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
584 // Send group message only to the recipient who requested it
585 final List
<String
> membersSend
= new ArrayList
<>();
586 membersSend
.add(recipient
);
587 sendMessageLegacy(messageBuilder
, membersSend
);
590 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
591 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
594 .withMembers(new ArrayList
<>(g
.getMembers()));
596 File aFile
= getGroupAvatarFile(g
.groupId
);
597 if (aFile
.exists()) {
599 group
.withAvatar(Utils
.createAttachment(aFile
));
600 } catch (IOException e
) {
601 throw new AttachmentInvalidException(aFile
.toString(), e
);
605 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
606 .asGroupMessage(group
.build());
608 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
609 if (thread
!= null) {
610 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
613 return messageBuilder
;
616 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
617 if (groupId
== null) {
621 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
624 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
625 .asGroupMessage(group
.build());
627 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
628 if (thread
!= null) {
629 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
632 // Send group info request message to the recipient who sent us a message with this groupId
633 final List
<String
> membersSend
= new ArrayList
<>();
634 membersSend
.add(recipient
);
635 sendMessageLegacy(messageBuilder
, membersSend
);
639 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
640 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
641 List
<String
> recipients
= new ArrayList
<>(1);
642 recipients
.add(recipient
);
643 sendMessage(message
, attachments
, recipients
);
647 public void sendMessage(String messageText
, List
<String
> attachments
,
648 List
<String
> recipients
)
649 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
650 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
651 if (attachments
!= null) {
652 List
<SignalServiceAttachment
> attachmentStreams
= Utils
.getSignalServiceAttachments(attachments
);
654 // Upload attachments here, so we only upload once even for multiple recipients
655 SignalServiceMessageSender messageSender
= getMessageSender();
656 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
657 for (SignalServiceAttachment attachment
: attachmentStreams
) {
658 if (attachment
.isStream()) {
659 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
660 } else if (attachment
.isPointer()) {
661 attachmentPointers
.add(attachment
.asPointer());
665 messageBuilder
.withAttachments(attachmentPointers
);
667 messageBuilder
.withProfileKey(account
.getProfileKey());
668 sendMessageLegacy(messageBuilder
, recipients
);
672 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
673 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
674 .asEndSessionMessage();
676 sendMessageLegacy(messageBuilder
, recipients
);
680 public String
getContactName(String number
) throws InvalidNumberException
{
681 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
682 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
683 if (contact
== null) {
691 public void setContactName(String number
, String name
) throws InvalidNumberException
{
692 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
693 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
694 if (contact
== null) {
695 contact
= new ContactInfo();
696 contact
.number
= canonicalizedNumber
;
697 System
.err
.println("Add contact " + canonicalizedNumber
+ " named " + name
);
699 System
.err
.println("Updating contact " + canonicalizedNumber
+ " name " + contact
.name
+ " -> " + name
);
702 account
.getContactStore().updateContact(contact
);
707 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
708 number
= Utils
.canonicalizeNumber(number
, username
);
709 ContactInfo contact
= account
.getContactStore().getContact(number
);
710 if (contact
== null) {
711 contact
= new ContactInfo();
712 contact
.number
= number
;
713 System
.err
.println("Adding and " + (blocked ?
"blocking" : "unblocking") + " contact " + number
);
715 System
.err
.println((blocked ?
"Blocking" : "Unblocking") + " contact " + number
);
717 contact
.blocked
= blocked
;
718 account
.getContactStore().updateContact(contact
);
723 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) throws GroupNotFoundException
{
724 GroupInfo group
= getGroup(groupId
);
726 throw new GroupNotFoundException(groupId
);
728 System
.err
.println((blocked ?
"Blocking" : "Unblocking") + " group " + Base64
.encodeBytes(groupId
));
729 group
.blocked
= blocked
;
730 account
.getGroupStore().updateGroup(group
);
736 public List
<byte[]> getGroupIds() {
737 List
<GroupInfo
> groups
= getGroups();
738 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
739 for (GroupInfo group
: groups
) {
740 ids
.add(group
.groupId
);
746 public String
getGroupName(byte[] groupId
) {
747 GroupInfo group
= getGroup(groupId
);
756 public List
<String
> getGroupMembers(byte[] groupId
) {
757 GroupInfo group
= getGroup(groupId
);
759 return new ArrayList
<>();
761 return new ArrayList
<>(group
.members
);
766 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
767 if (groupId
.length
== 0) {
770 if (name
.isEmpty()) {
773 if (members
.size() == 0) {
776 if (avatar
.isEmpty()) {
779 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
783 * Change the expiration timer for a thread (number of groupId)
785 * @param numberOrGroupId
786 * @param messageExpirationTimer
788 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
789 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
790 thread
.messageExpirationTime
= messageExpirationTimer
;
791 account
.getThreadStore().updateThread(thread
);
794 private void requestSyncGroups() throws IOException
{
795 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
796 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
798 sendSyncMessage(message
);
799 } catch (UntrustedIdentityException e
) {
804 private void requestSyncContacts() throws IOException
{
805 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
806 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
808 sendSyncMessage(message
);
809 } catch (UntrustedIdentityException e
) {
814 private void requestSyncBlocked() throws IOException
{
815 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
816 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
818 sendSyncMessage(message
);
819 } catch (UntrustedIdentityException e
) {
824 private void requestSyncConfiguration() throws IOException
{
825 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
826 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
828 sendSyncMessage(message
);
829 } catch (UntrustedIdentityException e
) {
834 private byte[] getSelfUnidentifiedAccessKey() {
835 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
838 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
843 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
845 return Optional
.absent();
848 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
849 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
850 for (SignalServiceAddress recipient
: recipients
) {
851 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
856 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
858 return Optional
.absent();
861 private void sendSyncMessage(SignalServiceSyncMessage message
)
862 throws IOException
, UntrustedIdentityException
{
863 SignalServiceMessageSender messageSender
= getMessageSender();
865 messageSender
.sendMessage(message
, getAccessForSync());
866 } catch (UntrustedIdentityException e
) {
867 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
873 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
875 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
876 throws EncapsulatedExceptions
, IOException
{
877 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
879 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
880 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
881 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
883 for (SendMessageResult result
: results
) {
884 if (result
.isUnregisteredFailure()) {
885 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber().get(), null));
886 } else if (result
.isNetworkFailure()) {
887 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber().get(), null));
888 } else if (result
.getIdentityFailure() != null) {
889 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber().get(), result
.getIdentityFailure().getIdentityKey()));
892 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
893 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
897 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
899 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
900 if (recipientsTS
== null) {
902 return Collections
.emptyList();
905 SignalServiceDataMessage message
= null;
907 SignalServiceMessageSender messageSender
= getMessageSender();
909 message
= messageBuilder
.build();
910 if (message
.getGroupInfo().isPresent()) {
912 final boolean isRecipientUpdate
= false;
913 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
914 for (SendMessageResult r
: result
) {
915 if (r
.getIdentityFailure() != null) {
916 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber().get(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
920 } catch (UntrustedIdentityException e
) {
921 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
922 return Collections
.emptyList();
924 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(getSelfAddress())) {
925 SignalServiceAddress recipient
= getSelfAddress();
926 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
927 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
928 message
.getTimestamp(),
930 message
.getExpiresInSeconds(),
931 Collections
.singletonMap(recipient
, unidentifiedAccess
.isPresent()),
933 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
935 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
937 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
938 } catch (UntrustedIdentityException e
) {
939 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
940 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
944 // Send to all individually, so sync messages are sent correctly
945 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
946 for (SignalServiceAddress address
: recipientsTS
) {
947 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber().get());
948 if (thread
!= null) {
949 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
951 messageBuilder
.withExpiration(0);
953 message
= messageBuilder
.build();
955 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
957 } catch (UntrustedIdentityException e
) {
958 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
959 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
965 if (message
!= null && message
.isEndSession()) {
966 for (SignalServiceAddress recipient
: recipientsTS
) {
967 handleEndSession(recipient
.getNumber().get());
974 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
975 SignalServiceCipher cipher
= new SignalServiceCipher(getSelfAddress(), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
977 return cipher
.decrypt(envelope
);
978 } catch (ProtocolUntrustedIdentityException e
) {
979 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
980 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
985 private void handleEndSession(String source
) {
986 account
.getSignalProtocolStore().deleteAllSessions(source
);
989 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, SignalServiceAddress destination
, boolean ignoreAttachments
) {
991 if (message
.getGroupInfo().isPresent()) {
992 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
993 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
994 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
995 switch (groupInfo
.getType()) {
998 group
= new GroupInfo(groupInfo
.getGroupId());
1001 if (groupInfo
.getAvatar().isPresent()) {
1002 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1003 if (avatar
.isPointer()) {
1005 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
1006 } catch (IOException
| InvalidMessageException e
) {
1007 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
1012 if (groupInfo
.getName().isPresent()) {
1013 group
.name
= groupInfo
.getName().get();
1016 if (groupInfo
.getMembers().isPresent()) {
1017 group
.addMembers(groupInfo
.getMembers().get());
1020 account
.getGroupStore().updateGroup(group
);
1023 if (group
== null) {
1025 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1026 } catch (IOException
| EncapsulatedExceptions e
) {
1027 e
.printStackTrace();
1032 if (group
== null) {
1034 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1035 } catch (IOException
| EncapsulatedExceptions e
) {
1036 e
.printStackTrace();
1039 group
.members
.remove(source
);
1040 account
.getGroupStore().updateGroup(group
);
1044 if (group
!= null) {
1046 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
1047 } catch (IOException
| EncapsulatedExceptions e
) {
1048 e
.printStackTrace();
1049 } catch (NotAGroupMemberException e
) {
1050 // We have left this group, so don't send a group update message
1057 threadId
= destination
.getNumber().get();
1062 if (message
.isEndSession()) {
1063 handleEndSession(isSync ? destination
.getNumber().get() : source
);
1065 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1066 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
1067 if (thread
== null) {
1068 thread
= new ThreadInfo();
1069 thread
.id
= threadId
;
1071 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1072 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1073 account
.getThreadStore().updateThread(thread
);
1076 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1077 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1078 if (attachment
.isPointer()) {
1080 retrieveAttachment(attachment
.asPointer());
1081 } catch (IOException
| InvalidMessageException e
) {
1082 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1087 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1088 if (source
.equals(username
)) {
1089 this.account
.setProfileKey(message
.getProfileKey().get());
1091 ContactInfo contact
= account
.getContactStore().getContact(source
);
1092 if (contact
== null) {
1093 contact
= new ContactInfo();
1094 contact
.number
= source
;
1096 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
1098 if (message
.getPreviews().isPresent()) {
1099 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1100 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1101 if (preview
.getImage().isPresent() && preview
.getImage().get().isPointer()) {
1102 SignalServiceAttachmentPointer attachment
= preview
.getImage().get().asPointer();
1104 retrieveAttachment(attachment
);
1105 } catch (IOException
| InvalidMessageException e
) {
1106 System
.err
.println("Failed to retrieve attachment (" + attachment
.getId() + "): " + e
.getMessage());
1113 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1114 final File cachePath
= new File(getMessageCachePath());
1115 if (!cachePath
.exists()) {
1118 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
1119 if (!dir
.isDirectory()) {
1123 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1124 if (!fileEntry
.isFile()) {
1127 SignalServiceEnvelope envelope
;
1129 envelope
= Utils
.loadEnvelope(fileEntry
);
1130 if (envelope
== null) {
1133 } catch (IOException e
) {
1134 e
.printStackTrace();
1137 SignalServiceContent content
= null;
1138 if (!envelope
.isReceipt()) {
1140 content
= decryptMessage(envelope
);
1141 } catch (Exception e
) {
1144 handleMessage(envelope
, content
, ignoreAttachments
);
1147 handler
.handleMessage(envelope
, content
, null);
1149 Files
.delete(fileEntry
.toPath());
1150 } catch (IOException e
) {
1151 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1154 // Try to delete directory if empty
1159 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1160 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1161 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1164 if (messagePipe
== null) {
1165 messagePipe
= messageReceiver
.createMessagePipe();
1169 SignalServiceEnvelope envelope
;
1170 SignalServiceContent content
= null;
1171 Exception exception
= null;
1172 final long now
= new Date().getTime();
1174 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1176 public void onMessage(SignalServiceEnvelope envelope
) {
1177 // store message on disk, before acknowledging receipt to the server
1179 File cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1180 Utils
.storeEnvelope(envelope
, cacheFile
);
1181 } catch (IOException e
) {
1182 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1186 } catch (TimeoutException e
) {
1187 if (returnOnTimeout
)
1190 } catch (InvalidVersionException e
) {
1191 System
.err
.println("Ignoring error: " + e
.getMessage());
1194 if (!envelope
.isReceipt()) {
1196 content
= decryptMessage(envelope
);
1197 } catch (Exception e
) {
1200 handleMessage(envelope
, content
, ignoreAttachments
);
1203 if (!isMessageBlocked(envelope
, content
)) {
1204 handler
.handleMessage(envelope
, content
, exception
);
1206 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1207 File cacheFile
= null;
1209 cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1210 Files
.delete(cacheFile
.toPath());
1211 // Try to delete directory if empty
1212 new File(getMessageCachePath()).delete();
1213 } catch (IOException e
) {
1214 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1219 if (messagePipe
!= null) {
1220 messagePipe
.shutdown();
1226 private boolean isMessageBlocked(SignalServiceEnvelope envelope
, SignalServiceContent content
) {
1227 SignalServiceAddress source
;
1228 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1229 source
= envelope
.getSourceAddress();
1230 } else if (content
!= null) {
1231 source
= content
.getSender();
1235 ContactInfo sourceContact
= getContact(source
.getNumber().get());
1236 if (sourceContact
!= null && sourceContact
.blocked
) {
1240 if (content
!= null && content
.getDataMessage().isPresent()) {
1241 SignalServiceDataMessage message
= content
.getDataMessage().get();
1242 if (message
.getGroupInfo().isPresent()) {
1243 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1244 GroupInfo group
= getGroup(groupInfo
.getGroupId());
1245 if (groupInfo
.getType() == SignalServiceGroup
.Type
.DELIVER
&& group
!= null && group
.blocked
) {
1253 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1254 if (content
!= null) {
1255 SignalServiceAddress sender
;
1256 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1257 sender
= envelope
.getSourceAddress();
1259 sender
= content
.getSender();
1261 if (content
.getDataMessage().isPresent()) {
1262 SignalServiceDataMessage message
= content
.getDataMessage().get();
1263 handleSignalServiceDataMessage(message
, false, sender
.getNumber().get(), getSelfAddress(), ignoreAttachments
);
1265 if (content
.getSyncMessage().isPresent()) {
1266 account
.setMultiDevice(true);
1267 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1268 if (syncMessage
.getSent().isPresent()) {
1269 SentTranscriptMessage message
= syncMessage
.getSent().get();
1270 handleSignalServiceDataMessage(message
.getMessage(), true, sender
.getNumber().get(), message
.getDestination().orNull(), ignoreAttachments
);
1272 if (syncMessage
.getRequest().isPresent()) {
1273 RequestMessage rm
= syncMessage
.getRequest().get();
1274 if (rm
.isContactsRequest()) {
1277 } catch (UntrustedIdentityException
| IOException e
) {
1278 e
.printStackTrace();
1281 if (rm
.isGroupsRequest()) {
1284 } catch (UntrustedIdentityException
| IOException e
) {
1285 e
.printStackTrace();
1288 if (rm
.isBlockedListRequest()) {
1291 } catch (UntrustedIdentityException
| IOException e
) {
1292 e
.printStackTrace();
1295 // TODO Handle rm.isConfigurationRequest();
1297 if (syncMessage
.getGroups().isPresent()) {
1298 File tmpFile
= null;
1300 tmpFile
= IOUtils
.createTempFile();
1301 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1302 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1304 while ((g
= s
.read()) != null) {
1305 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1306 if (syncGroup
== null) {
1307 syncGroup
= new GroupInfo(g
.getId());
1309 if (g
.getName().isPresent()) {
1310 syncGroup
.name
= g
.getName().get();
1312 syncGroup
.addMembers(g
.getMembers());
1313 syncGroup
.active
= g
.isActive();
1314 syncGroup
.blocked
= g
.isBlocked();
1315 if (g
.getColor().isPresent()) {
1316 syncGroup
.color
= g
.getColor().get();
1319 if (g
.getAvatar().isPresent()) {
1320 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1322 account
.getGroupStore().updateGroup(syncGroup
);
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 groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1337 if (syncMessage
.getBlockedList().isPresent()) {
1338 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1339 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1340 if (address
.getNumber().isPresent()) {
1342 setContactBlocked(address
.getNumber().get(), true);
1343 } catch (InvalidNumberException e
) {
1344 e
.printStackTrace();
1348 for (byte[] groupId
: blockedListMessage
.getGroupIds()) {
1350 setGroupBlocked(groupId
, true);
1351 } catch (GroupNotFoundException e
) {
1352 System
.err
.println("BlockedListMessage contained groupID that was not found in GroupStore: " + Base64
.encodeBytes(groupId
));
1356 if (syncMessage
.getContacts().isPresent()) {
1357 File tmpFile
= null;
1359 tmpFile
= IOUtils
.createTempFile();
1360 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1361 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1362 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1363 if (contactsMessage
.isComplete()) {
1364 account
.getContactStore().clear();
1367 while ((c
= s
.read()) != null) {
1368 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1369 account
.setProfileKey(c
.getProfileKey().get());
1371 ContactInfo contact
= account
.getContactStore().getContact(c
.getAddress().getNumber().get());
1372 if (contact
== null) {
1373 contact
= new ContactInfo();
1374 contact
.number
= c
.getAddress().getNumber().get();
1376 if (c
.getName().isPresent()) {
1377 contact
.name
= c
.getName().get();
1379 if (c
.getColor().isPresent()) {
1380 contact
.color
= c
.getColor().get();
1382 if (c
.getProfileKey().isPresent()) {
1383 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1385 if (c
.getVerified().isPresent()) {
1386 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1387 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1389 if (c
.getExpirationTimer().isPresent()) {
1390 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getAddress().getNumber().get());
1391 if (thread
== null) {
1392 thread
= new ThreadInfo();
1393 thread
.id
= c
.getAddress().getNumber().get();
1395 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1396 account
.getThreadStore().updateThread(thread
);
1398 contact
.blocked
= c
.isBlocked();
1399 account
.getContactStore().updateContact(contact
);
1401 if (c
.getAvatar().isPresent()) {
1402 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1406 } catch (Exception e
) {
1407 e
.printStackTrace();
1409 if (tmpFile
!= null) {
1411 Files
.delete(tmpFile
.toPath());
1412 } catch (IOException e
) {
1413 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1418 if (syncMessage
.getVerified().isPresent()) {
1419 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1420 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1422 if (syncMessage
.getConfiguration().isPresent()) {
1429 private File
getContactAvatarFile(String number
) {
1430 return new File(avatarsPath
, "contact-" + number
);
1433 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1434 IOUtils
.createPrivateDirectories(avatarsPath
);
1435 if (attachment
.isPointer()) {
1436 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1437 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1439 SignalServiceAttachmentStream stream
= attachment
.asStream();
1440 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1444 private File
getGroupAvatarFile(byte[] groupId
) {
1445 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1448 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1449 IOUtils
.createPrivateDirectories(avatarsPath
);
1450 if (attachment
.isPointer()) {
1451 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1452 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1454 SignalServiceAttachmentStream stream
= attachment
.asStream();
1455 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1459 public File
getAttachmentFile(long attachmentId
) {
1460 return new File(attachmentsPath
, attachmentId
+ "");
1463 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1464 IOUtils
.createPrivateDirectories(attachmentsPath
);
1465 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1468 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1469 if (storePreview
&& pointer
.getPreview().isPresent()) {
1470 File previewFile
= new File(outputFile
+ ".preview");
1471 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1472 byte[] preview
= pointer
.getPreview().get();
1473 output
.write(preview
, 0, preview
.length
);
1474 } catch (FileNotFoundException e
) {
1475 e
.printStackTrace();
1480 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1482 File tmpFile
= IOUtils
.createTempFile();
1483 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1484 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1485 byte[] buffer
= new byte[4096];
1488 while ((read
= input
.read(buffer
)) != -1) {
1489 output
.write(buffer
, 0, read
);
1491 } catch (FileNotFoundException e
) {
1492 e
.printStackTrace();
1497 Files
.delete(tmpFile
.toPath());
1498 } catch (IOException e
) {
1499 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1505 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1506 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1507 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1511 public boolean isRemote() {
1515 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1516 File groupsFile
= IOUtils
.createTempFile();
1519 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1520 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1521 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1522 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1523 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1524 new ArrayList
<>(record.getMembers()), createGroupAvatarAttachment(record.groupId
),
1525 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1526 Optional
.fromNullable(record.color
), record.blocked
));
1530 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1531 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1532 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1533 .withStream(groupsFileStream
)
1534 .withContentType("application/octet-stream")
1535 .withLength(groupsFile
.length())
1538 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1543 Files
.delete(groupsFile
.toPath());
1544 } catch (IOException e
) {
1545 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1550 public void sendContacts() throws IOException
, UntrustedIdentityException
{
1551 File contactsFile
= IOUtils
.createTempFile();
1554 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1555 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1556 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1557 VerifiedMessage verifiedMessage
= null;
1558 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1559 if (getIdentities().containsKey(record.number
)) {
1560 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1561 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1562 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1563 currentIdentity
= id
;
1566 if (currentIdentity
!= null) {
1567 verifiedMessage
= new VerifiedMessage(record.getAddress(), currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1571 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1572 out
.write(new DeviceContact(record.getAddress(), Optional
.fromNullable(record.name
),
1573 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1574 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), record.blocked
,
1575 Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1578 if (account
.getProfileKey() != null) {
1579 // Send our own profile key as well
1580 out
.write(new DeviceContact(account
.getSelfAddress(),
1581 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1582 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1583 Optional
.of(account
.getProfileKey()),
1584 false, Optional
.<Integer
>absent()));
1588 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1589 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1590 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1591 .withStream(contactsFileStream
)
1592 .withContentType("application/octet-stream")
1593 .withLength(contactsFile
.length())
1596 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1601 Files
.delete(contactsFile
.toPath());
1602 } catch (IOException e
) {
1603 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1608 private void sendBlockedList() throws IOException
, UntrustedIdentityException
{
1609 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
1610 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1611 if (record.blocked
) {
1612 addresses
.add(record.getAddress());
1615 List
<byte[]> groupIds
= new ArrayList
<>();
1616 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1617 if (record.blocked
) {
1618 groupIds
.add(record.groupId
);
1621 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
1624 private void sendVerifiedMessage(SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1625 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1626 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1629 public List
<ContactInfo
> getContacts() {
1630 return account
.getContactStore().getContacts();
1633 public ContactInfo
getContact(String number
) {
1634 return account
.getContactStore().getContact(number
);
1637 public GroupInfo
getGroup(byte[] groupId
) {
1638 return account
.getGroupStore().getGroup(groupId
);
1641 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1642 return account
.getSignalProtocolStore().getIdentities();
1645 public Pair
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities(String number
) throws InvalidNumberException
{
1646 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
1647 return new Pair
<>(canonicalizedNumber
, account
.getSignalProtocolStore().getIdentities(canonicalizedNumber
));
1651 * Trust this the identity with this fingerprint
1653 * @param name username of the identity
1654 * @param fingerprint Fingerprint
1656 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1657 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1661 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1662 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1666 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1668 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1669 } catch (IOException
| UntrustedIdentityException e
) {
1670 e
.printStackTrace();
1679 * Trust this the identity with this safety number
1681 * @param name username of the identity
1682 * @param safetyNumber Safety number
1684 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1685 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1689 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1690 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1694 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1696 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1697 } catch (IOException
| UntrustedIdentityException e
) {
1698 e
.printStackTrace();
1707 * Trust all keys of this identity without verification
1709 * @param name username of the identity
1711 public boolean trustIdentityAllKeys(String name
) {
1712 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1716 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1717 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1718 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1720 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1721 } catch (IOException
| UntrustedIdentityException e
) {
1722 e
.printStackTrace();
1730 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1731 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1734 public interface ReceiveMessageHandler
{
1736 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);