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(), account
.getRegistrationLock(), 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
, null, 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 if (pin
.isPresent()) {
411 account
.setRegistrationLockPin(pin
.get());
412 throw new RuntimeException("Not implemented anymore, will be replaced with KBS");
414 account
.setRegistrationLockPin(null);
415 accountManager
.removeV1Pin();
420 private void refreshPreKeys() throws IOException
{
421 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
422 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
423 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
425 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
428 private SignalServiceMessageReceiver
getMessageReceiver() {
429 return new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
432 private SignalServiceMessageSender
getMessageSender() {
433 return new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(),
434 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
437 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
438 File file
= getGroupAvatarFile(groupId
);
439 if (!file
.exists()) {
440 return Optional
.absent();
443 return Optional
.of(Utils
.createAttachment(file
));
446 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
447 File file
= getContactAvatarFile(number
);
448 if (!file
.exists()) {
449 return Optional
.absent();
452 return Optional
.of(Utils
.createAttachment(file
));
455 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
456 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
458 throw new GroupNotFoundException(groupId
);
460 for (String member
: g
.members
) {
461 if (member
.equals(this.username
)) {
465 throw new NotAGroupMemberException(groupId
, g
.name
);
468 public List
<GroupInfo
> getGroups() {
469 return account
.getGroupStore().getGroups();
473 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
475 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
476 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
477 if (attachments
!= null) {
478 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
480 if (groupId
!= null) {
481 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
484 messageBuilder
.asGroupMessage(group
);
486 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
487 if (thread
!= null) {
488 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
491 final GroupInfo g
= getGroupForSending(groupId
);
493 // Don't send group message to ourself
494 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
495 membersSend
.remove(this.username
);
496 sendMessageLegacy(messageBuilder
, membersSend
);
499 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
500 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
504 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
505 .asGroupMessage(group
);
507 final GroupInfo g
= getGroupForSending(groupId
);
508 g
.members
.remove(this.username
);
509 account
.getGroupStore().updateGroup(g
);
511 sendMessageLegacy(messageBuilder
, g
.members
);
514 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
516 if (groupId
== null) {
518 g
= new GroupInfo(KeyUtils
.createGroupId());
519 g
.members
.add(username
);
521 g
= getGroupForSending(groupId
);
528 if (members
!= null) {
529 Set
<String
> newMembers
= new HashSet
<>();
530 for (String member
: members
) {
532 member
= Utils
.canonicalizeNumber(member
, username
);
533 } catch (InvalidNumberException e
) {
534 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
535 System
.err
.println("Aborting…");
538 if (g
.members
.contains(member
)) {
541 newMembers
.add(member
);
542 g
.members
.add(member
);
544 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
545 if (contacts
.size() != newMembers
.size()) {
546 // Some of the new members are not registered on Signal
547 for (ContactTokenDetails contact
: contacts
) {
548 newMembers
.remove(contact
.getNumber());
550 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
551 System
.err
.println("Aborting…");
556 if (avatarFile
!= null) {
557 IOUtils
.createPrivateDirectories(avatarsPath
);
558 File aFile
= getGroupAvatarFile(g
.groupId
);
559 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
562 account
.getGroupStore().updateGroup(g
);
564 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
566 // Don't send group message to ourself
567 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
568 membersSend
.remove(this.username
);
569 sendMessageLegacy(messageBuilder
, membersSend
);
573 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
574 if (groupId
== null) {
577 GroupInfo g
= getGroupForSending(groupId
);
579 if (!g
.members
.contains(recipient
)) {
583 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
585 // Send group message only to the recipient who requested it
586 final List
<String
> membersSend
= new ArrayList
<>();
587 membersSend
.add(recipient
);
588 sendMessageLegacy(messageBuilder
, membersSend
);
591 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
592 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
595 .withMembers(new ArrayList
<>(g
.getMembers()));
597 File aFile
= getGroupAvatarFile(g
.groupId
);
598 if (aFile
.exists()) {
600 group
.withAvatar(Utils
.createAttachment(aFile
));
601 } catch (IOException e
) {
602 throw new AttachmentInvalidException(aFile
.toString(), e
);
606 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
607 .asGroupMessage(group
.build());
609 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
610 if (thread
!= null) {
611 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
614 return messageBuilder
;
617 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
618 if (groupId
== null) {
622 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
625 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
626 .asGroupMessage(group
.build());
628 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
629 if (thread
!= null) {
630 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
633 // Send group info request message to the recipient who sent us a message with this groupId
634 final List
<String
> membersSend
= new ArrayList
<>();
635 membersSend
.add(recipient
);
636 sendMessageLegacy(messageBuilder
, membersSend
);
640 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
641 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
642 List
<String
> recipients
= new ArrayList
<>(1);
643 recipients
.add(recipient
);
644 sendMessage(message
, attachments
, recipients
);
648 public void sendMessage(String messageText
, List
<String
> attachments
,
649 List
<String
> recipients
)
650 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
651 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
652 if (attachments
!= null) {
653 List
<SignalServiceAttachment
> attachmentStreams
= Utils
.getSignalServiceAttachments(attachments
);
655 // Upload attachments here, so we only upload once even for multiple recipients
656 SignalServiceMessageSender messageSender
= getMessageSender();
657 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
658 for (SignalServiceAttachment attachment
: attachmentStreams
) {
659 if (attachment
.isStream()) {
660 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
661 } else if (attachment
.isPointer()) {
662 attachmentPointers
.add(attachment
.asPointer());
666 messageBuilder
.withAttachments(attachmentPointers
);
668 messageBuilder
.withProfileKey(account
.getProfileKey());
669 sendMessageLegacy(messageBuilder
, recipients
);
673 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
674 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
675 .asEndSessionMessage();
677 sendMessageLegacy(messageBuilder
, recipients
);
681 public String
getContactName(String number
) throws InvalidNumberException
{
682 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
683 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
684 if (contact
== null) {
692 public void setContactName(String number
, String name
) throws InvalidNumberException
{
693 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
694 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
695 if (contact
== null) {
696 contact
= new ContactInfo();
697 contact
.number
= canonicalizedNumber
;
698 System
.err
.println("Add contact " + canonicalizedNumber
+ " named " + name
);
700 System
.err
.println("Updating contact " + canonicalizedNumber
+ " name " + contact
.name
+ " -> " + name
);
703 account
.getContactStore().updateContact(contact
);
708 public void setContactBlocked(String number
, boolean blocked
) throws InvalidNumberException
{
709 number
= Utils
.canonicalizeNumber(number
, username
);
710 ContactInfo contact
= account
.getContactStore().getContact(number
);
711 if (contact
== null) {
712 contact
= new ContactInfo();
713 contact
.number
= number
;
714 System
.err
.println("Adding and " + (blocked ?
"blocking" : "unblocking") + " contact " + number
);
716 System
.err
.println((blocked ?
"Blocking" : "Unblocking") + " contact " + number
);
718 contact
.blocked
= blocked
;
719 account
.getContactStore().updateContact(contact
);
724 public void setGroupBlocked(final byte[] groupId
, final boolean blocked
) throws GroupNotFoundException
{
725 GroupInfo group
= getGroup(groupId
);
727 throw new GroupNotFoundException(groupId
);
729 System
.err
.println((blocked ?
"Blocking" : "Unblocking") + " group " + Base64
.encodeBytes(groupId
));
730 group
.blocked
= blocked
;
731 account
.getGroupStore().updateGroup(group
);
737 public List
<byte[]> getGroupIds() {
738 List
<GroupInfo
> groups
= getGroups();
739 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
740 for (GroupInfo group
: groups
) {
741 ids
.add(group
.groupId
);
747 public String
getGroupName(byte[] groupId
) {
748 GroupInfo group
= getGroup(groupId
);
757 public List
<String
> getGroupMembers(byte[] groupId
) {
758 GroupInfo group
= getGroup(groupId
);
760 return new ArrayList
<>();
762 return new ArrayList
<>(group
.members
);
767 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
768 if (groupId
.length
== 0) {
771 if (name
.isEmpty()) {
774 if (members
.size() == 0) {
777 if (avatar
.isEmpty()) {
780 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
784 * Change the expiration timer for a thread (number of groupId)
786 * @param numberOrGroupId
787 * @param messageExpirationTimer
789 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
790 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
791 thread
.messageExpirationTime
= messageExpirationTimer
;
792 account
.getThreadStore().updateThread(thread
);
795 private void requestSyncGroups() throws IOException
{
796 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
797 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
799 sendSyncMessage(message
);
800 } catch (UntrustedIdentityException e
) {
805 private void requestSyncContacts() throws IOException
{
806 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
807 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
809 sendSyncMessage(message
);
810 } catch (UntrustedIdentityException e
) {
815 private void requestSyncBlocked() throws IOException
{
816 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
817 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
819 sendSyncMessage(message
);
820 } catch (UntrustedIdentityException e
) {
825 private void requestSyncConfiguration() throws IOException
{
826 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
827 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
829 sendSyncMessage(message
);
830 } catch (UntrustedIdentityException e
) {
835 private byte[] getSelfUnidentifiedAccessKey() {
836 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
839 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
844 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
846 return Optional
.absent();
849 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
850 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
851 for (SignalServiceAddress recipient
: recipients
) {
852 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
857 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
859 return Optional
.absent();
862 private void sendSyncMessage(SignalServiceSyncMessage message
)
863 throws IOException
, UntrustedIdentityException
{
864 SignalServiceMessageSender messageSender
= getMessageSender();
866 messageSender
.sendMessage(message
, getAccessForSync());
867 } catch (UntrustedIdentityException e
) {
868 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
874 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
876 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
877 throws EncapsulatedExceptions
, IOException
{
878 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
880 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
881 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
882 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
884 for (SendMessageResult result
: results
) {
885 if (result
.isUnregisteredFailure()) {
886 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber().get(), null));
887 } else if (result
.isNetworkFailure()) {
888 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber().get(), null));
889 } else if (result
.getIdentityFailure() != null) {
890 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber().get(), result
.getIdentityFailure().getIdentityKey()));
893 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
894 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
898 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
900 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
901 if (recipientsTS
== null) {
903 return Collections
.emptyList();
906 SignalServiceDataMessage message
= null;
908 SignalServiceMessageSender messageSender
= getMessageSender();
910 message
= messageBuilder
.build();
911 if (message
.getGroupInfo().isPresent()) {
913 final boolean isRecipientUpdate
= false;
914 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
915 for (SendMessageResult r
: result
) {
916 if (r
.getIdentityFailure() != null) {
917 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber().get(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
921 } catch (UntrustedIdentityException e
) {
922 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
923 return Collections
.emptyList();
925 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(getSelfAddress())) {
926 SignalServiceAddress recipient
= getSelfAddress();
927 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
928 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
929 message
.getTimestamp(),
931 message
.getExpiresInSeconds(),
932 Collections
.singletonMap(recipient
, unidentifiedAccess
.isPresent()),
934 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
936 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
938 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
939 } catch (UntrustedIdentityException e
) {
940 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
941 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
945 // Send to all individually, so sync messages are sent correctly
946 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
947 for (SignalServiceAddress address
: recipientsTS
) {
948 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber().get());
949 if (thread
!= null) {
950 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
952 messageBuilder
.withExpiration(0);
954 message
= messageBuilder
.build();
956 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
958 } catch (UntrustedIdentityException e
) {
959 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
960 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
966 if (message
!= null && message
.isEndSession()) {
967 for (SignalServiceAddress recipient
: recipientsTS
) {
968 handleEndSession(recipient
.getNumber().get());
975 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
976 SignalServiceCipher cipher
= new SignalServiceCipher(getSelfAddress(), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
978 return cipher
.decrypt(envelope
);
979 } catch (ProtocolUntrustedIdentityException e
) {
980 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
981 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
986 private void handleEndSession(String source
) {
987 account
.getSignalProtocolStore().deleteAllSessions(source
);
990 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, SignalServiceAddress destination
, boolean ignoreAttachments
) {
992 if (message
.getGroupInfo().isPresent()) {
993 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
994 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
995 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
996 switch (groupInfo
.getType()) {
999 group
= new GroupInfo(groupInfo
.getGroupId());
1002 if (groupInfo
.getAvatar().isPresent()) {
1003 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1004 if (avatar
.isPointer()) {
1006 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
1007 } catch (IOException
| InvalidMessageException e
) {
1008 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
1013 if (groupInfo
.getName().isPresent()) {
1014 group
.name
= groupInfo
.getName().get();
1017 if (groupInfo
.getMembers().isPresent()) {
1018 group
.addMembers(groupInfo
.getMembers().get());
1021 account
.getGroupStore().updateGroup(group
);
1024 if (group
== null) {
1026 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1027 } catch (IOException
| EncapsulatedExceptions e
) {
1028 e
.printStackTrace();
1033 if (group
== null) {
1035 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1036 } catch (IOException
| EncapsulatedExceptions e
) {
1037 e
.printStackTrace();
1040 group
.members
.remove(source
);
1041 account
.getGroupStore().updateGroup(group
);
1045 if (group
!= null) {
1047 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
1048 } catch (IOException
| EncapsulatedExceptions e
) {
1049 e
.printStackTrace();
1050 } catch (NotAGroupMemberException e
) {
1051 // We have left this group, so don't send a group update message
1058 threadId
= destination
.getNumber().get();
1063 if (message
.isEndSession()) {
1064 handleEndSession(isSync ? destination
.getNumber().get() : source
);
1066 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1067 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
1068 if (thread
== null) {
1069 thread
= new ThreadInfo();
1070 thread
.id
= threadId
;
1072 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1073 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1074 account
.getThreadStore().updateThread(thread
);
1077 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1078 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1079 if (attachment
.isPointer()) {
1081 retrieveAttachment(attachment
.asPointer());
1082 } catch (IOException
| InvalidMessageException e
) {
1083 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1088 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1089 if (source
.equals(username
)) {
1090 this.account
.setProfileKey(message
.getProfileKey().get());
1092 ContactInfo contact
= account
.getContactStore().getContact(source
);
1093 if (contact
== null) {
1094 contact
= new ContactInfo();
1095 contact
.number
= source
;
1097 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
1099 if (message
.getPreviews().isPresent()) {
1100 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1101 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1102 if (preview
.getImage().isPresent() && preview
.getImage().get().isPointer()) {
1103 SignalServiceAttachmentPointer attachment
= preview
.getImage().get().asPointer();
1105 retrieveAttachment(attachment
);
1106 } catch (IOException
| InvalidMessageException e
) {
1107 System
.err
.println("Failed to retrieve attachment (" + attachment
.getId() + "): " + e
.getMessage());
1114 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1115 final File cachePath
= new File(getMessageCachePath());
1116 if (!cachePath
.exists()) {
1119 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
1120 if (!dir
.isDirectory()) {
1124 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1125 if (!fileEntry
.isFile()) {
1128 SignalServiceEnvelope envelope
;
1130 envelope
= Utils
.loadEnvelope(fileEntry
);
1131 if (envelope
== null) {
1134 } catch (IOException e
) {
1135 e
.printStackTrace();
1138 SignalServiceContent content
= null;
1139 if (!envelope
.isReceipt()) {
1141 content
= decryptMessage(envelope
);
1142 } catch (Exception e
) {
1145 handleMessage(envelope
, content
, ignoreAttachments
);
1148 handler
.handleMessage(envelope
, content
, null);
1150 Files
.delete(fileEntry
.toPath());
1151 } catch (IOException e
) {
1152 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1155 // Try to delete directory if empty
1160 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1161 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1162 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1165 if (messagePipe
== null) {
1166 messagePipe
= messageReceiver
.createMessagePipe();
1170 SignalServiceEnvelope envelope
;
1171 SignalServiceContent content
= null;
1172 Exception exception
= null;
1173 final long now
= new Date().getTime();
1175 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1177 public void onMessage(SignalServiceEnvelope envelope
) {
1178 // store message on disk, before acknowledging receipt to the server
1180 File cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1181 Utils
.storeEnvelope(envelope
, cacheFile
);
1182 } catch (IOException e
) {
1183 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1187 } catch (TimeoutException e
) {
1188 if (returnOnTimeout
)
1191 } catch (InvalidVersionException e
) {
1192 System
.err
.println("Ignoring error: " + e
.getMessage());
1195 if (!envelope
.isReceipt()) {
1197 content
= decryptMessage(envelope
);
1198 } catch (Exception e
) {
1201 handleMessage(envelope
, content
, ignoreAttachments
);
1204 if (!isMessageBlocked(envelope
, content
)) {
1205 handler
.handleMessage(envelope
, content
, exception
);
1207 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1208 File cacheFile
= null;
1210 cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1211 Files
.delete(cacheFile
.toPath());
1212 // Try to delete directory if empty
1213 new File(getMessageCachePath()).delete();
1214 } catch (IOException e
) {
1215 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1220 if (messagePipe
!= null) {
1221 messagePipe
.shutdown();
1227 private boolean isMessageBlocked(SignalServiceEnvelope envelope
, SignalServiceContent content
) {
1228 SignalServiceAddress source
;
1229 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1230 source
= envelope
.getSourceAddress();
1231 } else if (content
!= null) {
1232 source
= content
.getSender();
1236 ContactInfo sourceContact
= getContact(source
.getNumber().get());
1237 if (sourceContact
!= null && sourceContact
.blocked
) {
1241 if (content
!= null && content
.getDataMessage().isPresent()) {
1242 SignalServiceDataMessage message
= content
.getDataMessage().get();
1243 if (message
.getGroupInfo().isPresent()) {
1244 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
1245 GroupInfo group
= getGroup(groupInfo
.getGroupId());
1246 if (groupInfo
.getType() == SignalServiceGroup
.Type
.DELIVER
&& group
!= null && group
.blocked
) {
1254 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1255 if (content
!= null) {
1256 SignalServiceAddress sender
;
1257 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1258 sender
= envelope
.getSourceAddress();
1260 sender
= content
.getSender();
1262 if (content
.getDataMessage().isPresent()) {
1263 SignalServiceDataMessage message
= content
.getDataMessage().get();
1264 handleSignalServiceDataMessage(message
, false, sender
.getNumber().get(), getSelfAddress(), ignoreAttachments
);
1266 if (content
.getSyncMessage().isPresent()) {
1267 account
.setMultiDevice(true);
1268 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1269 if (syncMessage
.getSent().isPresent()) {
1270 SentTranscriptMessage message
= syncMessage
.getSent().get();
1271 handleSignalServiceDataMessage(message
.getMessage(), true, sender
.getNumber().get(), message
.getDestination().orNull(), ignoreAttachments
);
1273 if (syncMessage
.getRequest().isPresent()) {
1274 RequestMessage rm
= syncMessage
.getRequest().get();
1275 if (rm
.isContactsRequest()) {
1278 } catch (UntrustedIdentityException
| IOException e
) {
1279 e
.printStackTrace();
1282 if (rm
.isGroupsRequest()) {
1285 } catch (UntrustedIdentityException
| IOException e
) {
1286 e
.printStackTrace();
1289 if (rm
.isBlockedListRequest()) {
1292 } catch (UntrustedIdentityException
| IOException e
) {
1293 e
.printStackTrace();
1296 // TODO Handle rm.isConfigurationRequest();
1298 if (syncMessage
.getGroups().isPresent()) {
1299 File tmpFile
= null;
1301 tmpFile
= IOUtils
.createTempFile();
1302 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1303 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1305 while ((g
= s
.read()) != null) {
1306 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1307 if (syncGroup
== null) {
1308 syncGroup
= new GroupInfo(g
.getId());
1310 if (g
.getName().isPresent()) {
1311 syncGroup
.name
= g
.getName().get();
1313 syncGroup
.addMembers(g
.getMembers());
1314 syncGroup
.active
= g
.isActive();
1315 syncGroup
.blocked
= g
.isBlocked();
1316 if (g
.getColor().isPresent()) {
1317 syncGroup
.color
= g
.getColor().get();
1320 if (g
.getAvatar().isPresent()) {
1321 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1323 syncGroup
.inboxPosition
= g
.getInboxPosition().orNull();
1324 syncGroup
.archived
= g
.isArchived();
1325 account
.getGroupStore().updateGroup(syncGroup
);
1328 } catch (Exception e
) {
1329 e
.printStackTrace();
1331 if (tmpFile
!= null) {
1333 Files
.delete(tmpFile
.toPath());
1334 } catch (IOException e
) {
1335 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1340 if (syncMessage
.getBlockedList().isPresent()) {
1341 final BlockedListMessage blockedListMessage
= syncMessage
.getBlockedList().get();
1342 for (SignalServiceAddress address
: blockedListMessage
.getAddresses()) {
1343 if (address
.getNumber().isPresent()) {
1345 setContactBlocked(address
.getNumber().get(), true);
1346 } catch (InvalidNumberException e
) {
1347 e
.printStackTrace();
1351 for (byte[] groupId
: blockedListMessage
.getGroupIds()) {
1353 setGroupBlocked(groupId
, true);
1354 } catch (GroupNotFoundException e
) {
1355 System
.err
.println("BlockedListMessage contained groupID that was not found in GroupStore: " + Base64
.encodeBytes(groupId
));
1359 if (syncMessage
.getContacts().isPresent()) {
1360 File tmpFile
= null;
1362 tmpFile
= IOUtils
.createTempFile();
1363 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1364 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1365 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1366 if (contactsMessage
.isComplete()) {
1367 account
.getContactStore().clear();
1370 while ((c
= s
.read()) != null) {
1371 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1372 account
.setProfileKey(c
.getProfileKey().get());
1374 ContactInfo contact
= account
.getContactStore().getContact(c
.getAddress().getNumber().get());
1375 if (contact
== null) {
1376 contact
= new ContactInfo();
1377 contact
.number
= c
.getAddress().getNumber().get();
1379 if (c
.getName().isPresent()) {
1380 contact
.name
= c
.getName().get();
1382 if (c
.getColor().isPresent()) {
1383 contact
.color
= c
.getColor().get();
1385 if (c
.getProfileKey().isPresent()) {
1386 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1388 if (c
.getVerified().isPresent()) {
1389 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1390 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1392 if (c
.getExpirationTimer().isPresent()) {
1393 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getAddress().getNumber().get());
1394 if (thread
== null) {
1395 thread
= new ThreadInfo();
1396 thread
.id
= c
.getAddress().getNumber().get();
1398 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1399 account
.getThreadStore().updateThread(thread
);
1401 contact
.blocked
= c
.isBlocked();
1402 contact
.inboxPosition
= c
.getInboxPosition().orNull();
1403 contact
.archived
= c
.isArchived();
1404 account
.getContactStore().updateContact(contact
);
1406 if (c
.getAvatar().isPresent()) {
1407 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1411 } catch (Exception e
) {
1412 e
.printStackTrace();
1414 if (tmpFile
!= null) {
1416 Files
.delete(tmpFile
.toPath());
1417 } catch (IOException e
) {
1418 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1423 if (syncMessage
.getVerified().isPresent()) {
1424 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1425 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1427 if (syncMessage
.getConfiguration().isPresent()) {
1434 private File
getContactAvatarFile(String number
) {
1435 return new File(avatarsPath
, "contact-" + number
);
1438 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1439 IOUtils
.createPrivateDirectories(avatarsPath
);
1440 if (attachment
.isPointer()) {
1441 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1442 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1444 SignalServiceAttachmentStream stream
= attachment
.asStream();
1445 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1449 private File
getGroupAvatarFile(byte[] groupId
) {
1450 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1453 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1454 IOUtils
.createPrivateDirectories(avatarsPath
);
1455 if (attachment
.isPointer()) {
1456 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1457 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1459 SignalServiceAttachmentStream stream
= attachment
.asStream();
1460 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1464 public File
getAttachmentFile(long attachmentId
) {
1465 return new File(attachmentsPath
, attachmentId
+ "");
1468 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1469 IOUtils
.createPrivateDirectories(attachmentsPath
);
1470 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1473 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1474 if (storePreview
&& pointer
.getPreview().isPresent()) {
1475 File previewFile
= new File(outputFile
+ ".preview");
1476 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1477 byte[] preview
= pointer
.getPreview().get();
1478 output
.write(preview
, 0, preview
.length
);
1479 } catch (FileNotFoundException e
) {
1480 e
.printStackTrace();
1485 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1487 File tmpFile
= IOUtils
.createTempFile();
1488 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1489 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1490 byte[] buffer
= new byte[4096];
1493 while ((read
= input
.read(buffer
)) != -1) {
1494 output
.write(buffer
, 0, read
);
1496 } catch (FileNotFoundException e
) {
1497 e
.printStackTrace();
1502 Files
.delete(tmpFile
.toPath());
1503 } catch (IOException e
) {
1504 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1510 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1511 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1512 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1516 public boolean isRemote() {
1520 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1521 File groupsFile
= IOUtils
.createTempFile();
1524 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1525 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1526 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1527 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1528 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1529 new ArrayList
<>(record.getMembers()), createGroupAvatarAttachment(record.groupId
),
1530 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1531 Optional
.fromNullable(record.color
), record.blocked
, Optional
.fromNullable(record.inboxPosition
), record.archived
));
1535 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1536 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1537 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1538 .withStream(groupsFileStream
)
1539 .withContentType("application/octet-stream")
1540 .withLength(groupsFile
.length())
1543 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1548 Files
.delete(groupsFile
.toPath());
1549 } catch (IOException e
) {
1550 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1555 public void sendContacts() throws IOException
, UntrustedIdentityException
{
1556 File contactsFile
= IOUtils
.createTempFile();
1559 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1560 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1561 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1562 VerifiedMessage verifiedMessage
= null;
1563 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1564 if (getIdentities().containsKey(record.number
)) {
1565 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1566 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1567 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1568 currentIdentity
= id
;
1571 if (currentIdentity
!= null) {
1572 verifiedMessage
= new VerifiedMessage(record.getAddress(), currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1576 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1577 out
.write(new DeviceContact(record.getAddress(), Optional
.fromNullable(record.name
),
1578 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1579 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), record.blocked
,
1580 Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1581 Optional
.fromNullable(record.inboxPosition
), record.archived
));
1584 if (account
.getProfileKey() != null) {
1585 // Send our own profile key as well
1586 out
.write(new DeviceContact(account
.getSelfAddress(),
1587 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1588 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1589 Optional
.of(account
.getProfileKey()),
1590 false, Optional
.<Integer
>absent(), Optional
.<Integer
>absent(), false));
1594 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1595 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1596 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1597 .withStream(contactsFileStream
)
1598 .withContentType("application/octet-stream")
1599 .withLength(contactsFile
.length())
1602 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1607 Files
.delete(contactsFile
.toPath());
1608 } catch (IOException e
) {
1609 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1614 private void sendBlockedList() throws IOException
, UntrustedIdentityException
{
1615 List
<SignalServiceAddress
> addresses
= new ArrayList
<>();
1616 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1617 if (record.blocked
) {
1618 addresses
.add(record.getAddress());
1621 List
<byte[]> groupIds
= new ArrayList
<>();
1622 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1623 if (record.blocked
) {
1624 groupIds
.add(record.groupId
);
1627 sendSyncMessage(SignalServiceSyncMessage
.forBlocked(new BlockedListMessage(addresses
, groupIds
)));
1630 private void sendVerifiedMessage(SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1631 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1632 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1635 public List
<ContactInfo
> getContacts() {
1636 return account
.getContactStore().getContacts();
1639 public ContactInfo
getContact(String number
) {
1640 return account
.getContactStore().getContact(number
);
1643 public GroupInfo
getGroup(byte[] groupId
) {
1644 return account
.getGroupStore().getGroup(groupId
);
1647 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1648 return account
.getSignalProtocolStore().getIdentities();
1651 public Pair
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities(String number
) throws InvalidNumberException
{
1652 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
1653 return new Pair
<>(canonicalizedNumber
, account
.getSignalProtocolStore().getIdentities(canonicalizedNumber
));
1657 * Trust this the identity with this fingerprint
1659 * @param name username of the identity
1660 * @param fingerprint Fingerprint
1662 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1663 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1667 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1668 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1672 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1674 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1675 } catch (IOException
| UntrustedIdentityException e
) {
1676 e
.printStackTrace();
1685 * Trust this the identity with this safety number
1687 * @param name username of the identity
1688 * @param safetyNumber Safety number
1690 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1691 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1695 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1696 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1700 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1702 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1703 } catch (IOException
| UntrustedIdentityException e
) {
1704 e
.printStackTrace();
1713 * Trust all keys of this identity without verification
1715 * @param name username of the identity
1717 public boolean trustIdentityAllKeys(String name
) {
1718 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1722 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1723 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1724 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1726 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1727 } catch (IOException
| UntrustedIdentityException e
) {
1728 e
.printStackTrace();
1736 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1737 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1740 public interface ReceiveMessageHandler
{
1742 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);