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
.guava
.Optional
;
57 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
58 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
59 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
60 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
61 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
62 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
63 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
64 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
65 import org
.whispersystems
.signalservice
.api
.messages
.SendMessageResult
;
66 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachment
;
67 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentPointer
;
68 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceAttachmentStream
;
69 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceContent
;
70 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceDataMessage
;
71 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceEnvelope
;
72 import org
.whispersystems
.signalservice
.api
.messages
.SignalServiceGroup
;
73 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.ContactsMessage
;
74 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContact
;
75 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsInputStream
;
76 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceContactsOutputStream
;
77 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroup
;
78 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsInputStream
;
79 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceGroupsOutputStream
;
80 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.DeviceInfo
;
81 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.RequestMessage
;
82 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SentTranscriptMessage
;
83 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.SignalServiceSyncMessage
;
84 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.VerifiedMessage
;
85 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
86 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
87 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
88 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
89 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
90 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
91 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
92 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
93 import org
.whispersystems
.signalservice
.api
.util
.StreamDetails
;
94 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
95 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
96 import org
.whispersystems
.signalservice
.internal
.push
.UnsupportedDataMessageException
;
97 import org
.whispersystems
.util
.Base64
;
100 import java
.io
.FileInputStream
;
101 import java
.io
.FileNotFoundException
;
102 import java
.io
.FileOutputStream
;
103 import java
.io
.IOException
;
104 import java
.io
.InputStream
;
105 import java
.io
.OutputStream
;
107 import java
.nio
.file
.Files
;
108 import java
.nio
.file
.Paths
;
109 import java
.nio
.file
.StandardCopyOption
;
110 import java
.util
.ArrayList
;
111 import java
.util
.Arrays
;
112 import java
.util
.Collection
;
113 import java
.util
.Collections
;
114 import java
.util
.Date
;
115 import java
.util
.HashSet
;
116 import java
.util
.LinkedList
;
117 import java
.util
.List
;
118 import java
.util
.Locale
;
119 import java
.util
.Map
;
120 import java
.util
.Objects
;
121 import java
.util
.Set
;
122 import java
.util
.concurrent
.TimeUnit
;
123 import java
.util
.concurrent
.TimeoutException
;
125 public class Manager
implements Signal
{
127 private final String settingsPath
;
128 private final String dataPath
;
129 private final String attachmentsPath
;
130 private final String avatarsPath
;
131 private final SleepTimer timer
= new UptimeSleepTimer();
133 private SignalAccount account
;
134 private String username
;
135 private SignalServiceAccountManager accountManager
;
136 private SignalServiceMessagePipe messagePipe
= null;
137 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
139 public Manager(String username
, String settingsPath
) {
140 this.username
= username
;
141 this.settingsPath
= settingsPath
;
142 this.dataPath
= this.settingsPath
+ "/data";
143 this.attachmentsPath
= this.settingsPath
+ "/attachments";
144 this.avatarsPath
= this.settingsPath
+ "/avatars";
148 public String
getUsername() {
152 private SignalServiceAddress
getSelfAddress() {
153 return new SignalServiceAddress(null, username
);
156 private SignalServiceAccountManager
getSignalServiceAccountManager() {
157 return new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, null, account
.getUsername(), account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
160 private IdentityKey
getIdentity() {
161 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
164 public int getDeviceId() {
165 return account
.getDeviceId();
168 private String
getMessageCachePath() {
169 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
172 private String
getMessageCachePath(String sender
) {
173 return getMessageCachePath() + "/" + sender
.replace("/", "_");
176 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
177 String cachePath
= getMessageCachePath(sender
);
178 IOUtils
.createPrivateDirectories(cachePath
);
179 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
182 public boolean userHasKeys() {
183 return account
!= null && account
.getSignalProtocolStore() != null;
186 public void init() throws IOException
{
187 if (!SignalAccount
.userExists(dataPath
, username
)) {
190 account
= SignalAccount
.load(dataPath
, username
);
192 migrateLegacyConfigs();
194 accountManager
= getSignalServiceAccountManager();
196 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
200 } catch (AuthorizationFailedException e
) {
201 System
.err
.println("Authorization failed, was the number registered elsewhere?");
206 private void migrateLegacyConfigs() {
207 // Copy group avatars that were previously stored in the attachments folder
208 // to the new avatar folder
209 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
210 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
211 File avatarFile
= getGroupAvatarFile(g
.groupId
);
212 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
213 if (!avatarFile
.exists() && attachmentFile
.exists()) {
215 IOUtils
.createPrivateDirectories(avatarsPath
);
216 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
217 } catch (Exception e
) {
222 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
225 if (account
.getProfileKey() == null) {
226 // Old config file, creating new profile key
227 account
.setProfileKey(KeyUtils
.createProfileKey());
232 private void createNewIdentity() throws IOException
{
233 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
234 int registrationId
= KeyHelper
.generateRegistrationId(false);
235 if (username
== null) {
236 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
238 byte[] profileKey
= KeyUtils
.createProfileKey();
239 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
244 public boolean isRegistered() {
245 return account
!= null && account
.isRegistered();
248 public void register(boolean voiceVerification
) throws IOException
{
249 if (account
== null) {
252 account
.setPassword(KeyUtils
.createPassword());
253 accountManager
= getSignalServiceAccountManager();
255 if (voiceVerification
) {
256 accountManager
.requestVoiceVerificationCode(Locale
.getDefault(), Optional
.<String
>absent(), Optional
.<String
>absent());
258 accountManager
.requestSmsVerificationCode(false, Optional
.<String
>absent(), Optional
.<String
>absent());
261 account
.setRegistered(false);
265 public void updateAccountAttributes() throws IOException
{
266 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
269 public void setProfileName(String name
) throws IOException
{
270 accountManager
.setProfileName(account
.getProfileKey(), name
);
273 public void setProfileAvatar(File avatar
) throws IOException
{
274 final StreamDetails streamDetails
= Utils
.createStreamDetailsFromFile(avatar
);
275 accountManager
.setProfileAvatar(account
.getProfileKey(), streamDetails
);
276 streamDetails
.getStream().close();
279 public void removeProfileAvatar() throws IOException
{
280 accountManager
.setProfileAvatar(account
.getProfileKey(), null);
283 public void unregister() throws IOException
{
284 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
285 // If this is the master device, other users can't send messages to this number anymore.
286 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
287 accountManager
.setGcmId(Optional
.<String
>absent());
289 account
.setRegistered(false);
293 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
294 if (account
== null) {
297 account
.setPassword(KeyUtils
.createPassword());
298 accountManager
= getSignalServiceAccountManager();
299 String uuid
= accountManager
.getNewDeviceUuid();
301 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
304 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
305 account
.setSignalingKey(KeyUtils
.createSignalingKey());
306 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
308 username
= ret
.getNumber();
309 // TODO do this check before actually registering
310 if (SignalAccount
.userExists(dataPath
, username
)) {
311 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
314 // Create new account with the synced identity
315 byte[] profileKey
= ret
.getProfileKey();
316 if (profileKey
== null) {
317 profileKey
= KeyUtils
.createProfileKey();
319 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
324 requestSyncContacts();
325 requestSyncBlocked();
326 requestSyncConfiguration();
331 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
332 List
<DeviceInfo
> devices
= accountManager
.getDevices();
333 account
.setMultiDevice(devices
.size() > 1);
338 public void removeLinkedDevices(int deviceId
) throws IOException
{
339 accountManager
.removeDevice(deviceId
);
340 List
<DeviceInfo
> devices
= accountManager
.getDevices();
341 account
.setMultiDevice(devices
.size() > 1);
345 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
346 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
348 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
351 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
352 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
353 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
355 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
356 account
.setMultiDevice(true);
360 private List
<PreKeyRecord
> generatePreKeys() {
361 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
363 final int offset
= account
.getPreKeyIdOffset();
364 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
365 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
366 ECKeyPair keyPair
= Curve
.generateKeyPair();
367 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
372 account
.addPreKeys(records
);
378 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
380 ECKeyPair keyPair
= Curve
.generateKeyPair();
381 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
382 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
384 account
.addSignedPreKey(record);
388 } catch (InvalidKeyException e
) {
389 throw new AssertionError(e
);
393 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
394 verificationCode
= verificationCode
.replace("-", "");
395 account
.setSignalingKey(KeyUtils
.createSignalingKey());
396 // TODO make unrestricted unidentified access configurable
397 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
399 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
400 account
.setRegistered(true);
401 account
.setRegistrationLockPin(pin
);
407 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
408 accountManager
.setPin(pin
);
409 if (pin
.isPresent()) {
410 account
.setRegistrationLockPin(pin
.get());
412 account
.setRegistrationLockPin(null);
417 private void refreshPreKeys() throws IOException
{
418 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
419 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
420 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
422 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
425 private SignalServiceMessageReceiver
getMessageReceiver() {
426 return new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
429 private SignalServiceMessageSender
getMessageSender() {
430 return new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, null, username
, account
.getPassword(),
431 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
434 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
435 File file
= getGroupAvatarFile(groupId
);
436 if (!file
.exists()) {
437 return Optional
.absent();
440 return Optional
.of(Utils
.createAttachment(file
));
443 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
444 File file
= getContactAvatarFile(number
);
445 if (!file
.exists()) {
446 return Optional
.absent();
449 return Optional
.of(Utils
.createAttachment(file
));
452 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
453 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
455 throw new GroupNotFoundException(groupId
);
457 for (String member
: g
.members
) {
458 if (member
.equals(this.username
)) {
462 throw new NotAGroupMemberException(groupId
, g
.name
);
465 public List
<GroupInfo
> getGroups() {
466 return account
.getGroupStore().getGroups();
470 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
472 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
473 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
474 if (attachments
!= null) {
475 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
477 if (groupId
!= null) {
478 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
481 messageBuilder
.asGroupMessage(group
);
483 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
484 if (thread
!= null) {
485 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
488 final GroupInfo g
= getGroupForSending(groupId
);
490 // Don't send group message to ourself
491 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
492 membersSend
.remove(this.username
);
493 sendMessageLegacy(messageBuilder
, membersSend
);
496 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
497 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
501 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
502 .asGroupMessage(group
);
504 final GroupInfo g
= getGroupForSending(groupId
);
505 g
.members
.remove(this.username
);
506 account
.getGroupStore().updateGroup(g
);
508 sendMessageLegacy(messageBuilder
, g
.members
);
511 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
513 if (groupId
== null) {
515 g
= new GroupInfo(KeyUtils
.createGroupId());
516 g
.members
.add(username
);
518 g
= getGroupForSending(groupId
);
525 if (members
!= null) {
526 Set
<String
> newMembers
= new HashSet
<>();
527 for (String member
: members
) {
529 member
= Utils
.canonicalizeNumber(member
, username
);
530 } catch (InvalidNumberException e
) {
531 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
532 System
.err
.println("Aborting…");
535 if (g
.members
.contains(member
)) {
538 newMembers
.add(member
);
539 g
.members
.add(member
);
541 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
542 if (contacts
.size() != newMembers
.size()) {
543 // Some of the new members are not registered on Signal
544 for (ContactTokenDetails contact
: contacts
) {
545 newMembers
.remove(contact
.getNumber());
547 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
548 System
.err
.println("Aborting…");
553 if (avatarFile
!= null) {
554 IOUtils
.createPrivateDirectories(avatarsPath
);
555 File aFile
= getGroupAvatarFile(g
.groupId
);
556 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
559 account
.getGroupStore().updateGroup(g
);
561 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
563 // Don't send group message to ourself
564 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
565 membersSend
.remove(this.username
);
566 sendMessageLegacy(messageBuilder
, membersSend
);
570 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
571 if (groupId
== null) {
574 GroupInfo g
= getGroupForSending(groupId
);
576 if (!g
.members
.contains(recipient
)) {
580 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
582 // Send group message only to the recipient who requested it
583 final List
<String
> membersSend
= new ArrayList
<>();
584 membersSend
.add(recipient
);
585 sendMessageLegacy(messageBuilder
, membersSend
);
588 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
589 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
592 .withMembers(new ArrayList
<>(g
.getMembers()));
594 File aFile
= getGroupAvatarFile(g
.groupId
);
595 if (aFile
.exists()) {
597 group
.withAvatar(Utils
.createAttachment(aFile
));
598 } catch (IOException e
) {
599 throw new AttachmentInvalidException(aFile
.toString(), e
);
603 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
604 .asGroupMessage(group
.build());
606 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
607 if (thread
!= null) {
608 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
611 return messageBuilder
;
614 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
615 if (groupId
== null) {
619 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
622 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
623 .asGroupMessage(group
.build());
625 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
626 if (thread
!= null) {
627 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
630 // Send group info request message to the recipient who sent us a message with this groupId
631 final List
<String
> membersSend
= new ArrayList
<>();
632 membersSend
.add(recipient
);
633 sendMessageLegacy(messageBuilder
, membersSend
);
637 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
638 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
639 List
<String
> recipients
= new ArrayList
<>(1);
640 recipients
.add(recipient
);
641 sendMessage(message
, attachments
, recipients
);
645 public void sendMessage(String messageText
, List
<String
> attachments
,
646 List
<String
> recipients
)
647 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
648 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
649 if (attachments
!= null) {
650 List
<SignalServiceAttachment
> attachmentStreams
= Utils
.getSignalServiceAttachments(attachments
);
652 // Upload attachments here, so we only upload once even for multiple recipients
653 SignalServiceMessageSender messageSender
= getMessageSender();
654 List
<SignalServiceAttachment
> attachmentPointers
= new ArrayList
<>(attachmentStreams
.size());
655 for (SignalServiceAttachment attachment
: attachmentStreams
) {
656 if (attachment
.isStream()) {
657 attachmentPointers
.add(messageSender
.uploadAttachment(attachment
.asStream()));
658 } else if (attachment
.isPointer()) {
659 attachmentPointers
.add(attachment
.asPointer());
663 messageBuilder
.withAttachments(attachmentPointers
);
665 messageBuilder
.withProfileKey(account
.getProfileKey());
666 sendMessageLegacy(messageBuilder
, recipients
);
670 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
671 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
672 .asEndSessionMessage();
674 sendMessageLegacy(messageBuilder
, recipients
);
678 public String
getContactName(String number
) throws InvalidNumberException
{
679 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
680 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
681 if (contact
== null) {
689 public void setContactName(String number
, String name
) throws InvalidNumberException
{
690 String canonicalizedNumber
= Utils
.canonicalizeNumber(number
, username
);
691 ContactInfo contact
= account
.getContactStore().getContact(canonicalizedNumber
);
692 if (contact
== null) {
693 contact
= new ContactInfo();
694 contact
.number
= canonicalizedNumber
;
695 System
.err
.println("Add contact " + canonicalizedNumber
+ " named " + name
);
697 System
.err
.println("Updating contact " + canonicalizedNumber
+ " name " + contact
.name
+ " -> " + name
);
700 account
.getContactStore().updateContact(contact
);
705 public List
<byte[]> getGroupIds() {
706 List
<GroupInfo
> groups
= getGroups();
707 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
708 for (GroupInfo group
: groups
) {
709 ids
.add(group
.groupId
);
715 public String
getGroupName(byte[] groupId
) {
716 GroupInfo group
= getGroup(groupId
);
725 public List
<String
> getGroupMembers(byte[] groupId
) {
726 GroupInfo group
= getGroup(groupId
);
728 return new ArrayList
<>();
730 return new ArrayList
<>(group
.members
);
735 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
736 if (groupId
.length
== 0) {
739 if (name
.isEmpty()) {
742 if (members
.size() == 0) {
745 if (avatar
.isEmpty()) {
748 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
752 * Change the expiration timer for a thread (number of groupId)
754 * @param numberOrGroupId
755 * @param messageExpirationTimer
757 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
758 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
759 thread
.messageExpirationTime
= messageExpirationTimer
;
760 account
.getThreadStore().updateThread(thread
);
763 private void requestSyncGroups() throws IOException
{
764 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
765 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
767 sendSyncMessage(message
);
768 } catch (UntrustedIdentityException e
) {
773 private void requestSyncContacts() throws IOException
{
774 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
775 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
777 sendSyncMessage(message
);
778 } catch (UntrustedIdentityException e
) {
783 private void requestSyncBlocked() throws IOException
{
784 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
785 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
787 sendSyncMessage(message
);
788 } catch (UntrustedIdentityException e
) {
793 private void requestSyncConfiguration() throws IOException
{
794 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
795 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
797 sendSyncMessage(message
);
798 } catch (UntrustedIdentityException e
) {
803 private byte[] getSelfUnidentifiedAccessKey() {
804 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
807 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
812 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
814 return Optional
.absent();
817 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
818 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
819 for (SignalServiceAddress recipient
: recipients
) {
820 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
825 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
827 return Optional
.absent();
830 private void sendSyncMessage(SignalServiceSyncMessage message
)
831 throws IOException
, UntrustedIdentityException
{
832 SignalServiceMessageSender messageSender
= getMessageSender();
834 messageSender
.sendMessage(message
, getAccessForSync());
835 } catch (UntrustedIdentityException e
) {
836 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
842 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
844 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
845 throws EncapsulatedExceptions
, IOException
{
846 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
848 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
849 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
850 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
852 for (SendMessageResult result
: results
) {
853 if (result
.isUnregisteredFailure()) {
854 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber().get(), null));
855 } else if (result
.isNetworkFailure()) {
856 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber().get(), null));
857 } else if (result
.getIdentityFailure() != null) {
858 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber().get(), result
.getIdentityFailure().getIdentityKey()));
861 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
862 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
866 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
868 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
869 if (recipientsTS
== null) {
871 return Collections
.emptyList();
874 SignalServiceDataMessage message
= null;
876 SignalServiceMessageSender messageSender
= getMessageSender();
878 message
= messageBuilder
.build();
879 if (message
.getGroupInfo().isPresent()) {
881 final boolean isRecipientUpdate
= false;
882 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
883 for (SendMessageResult r
: result
) {
884 if (r
.getIdentityFailure() != null) {
885 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber().get(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
889 } catch (UntrustedIdentityException e
) {
890 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
891 return Collections
.emptyList();
893 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(getSelfAddress())) {
894 SignalServiceAddress recipient
= getSelfAddress();
895 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
896 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
897 message
.getTimestamp(),
899 message
.getExpiresInSeconds(),
900 Collections
.singletonMap(recipient
, unidentifiedAccess
.isPresent()),
902 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
904 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
906 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
907 } catch (UntrustedIdentityException e
) {
908 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
909 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
913 // Send to all individually, so sync messages are sent correctly
914 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
915 for (SignalServiceAddress address
: recipientsTS
) {
916 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber().get());
917 if (thread
!= null) {
918 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
920 messageBuilder
.withExpiration(0);
922 message
= messageBuilder
.build();
924 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
926 } catch (UntrustedIdentityException e
) {
927 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
928 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
934 if (message
!= null && message
.isEndSession()) {
935 for (SignalServiceAddress recipient
: recipientsTS
) {
936 handleEndSession(recipient
.getNumber().get());
943 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
944 SignalServiceCipher cipher
= new SignalServiceCipher(getSelfAddress(), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
946 return cipher
.decrypt(envelope
);
947 } catch (ProtocolUntrustedIdentityException e
) {
948 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
949 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
954 private void handleEndSession(String source
) {
955 account
.getSignalProtocolStore().deleteAllSessions(source
);
958 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, SignalServiceAddress destination
, boolean ignoreAttachments
) {
960 if (message
.getGroupInfo().isPresent()) {
961 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
962 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
963 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
964 switch (groupInfo
.getType()) {
967 group
= new GroupInfo(groupInfo
.getGroupId());
970 if (groupInfo
.getAvatar().isPresent()) {
971 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
972 if (avatar
.isPointer()) {
974 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
975 } catch (IOException
| InvalidMessageException e
) {
976 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
981 if (groupInfo
.getName().isPresent()) {
982 group
.name
= groupInfo
.getName().get();
985 if (groupInfo
.getMembers().isPresent()) {
986 group
.addMembers(groupInfo
.getMembers().get());
989 account
.getGroupStore().updateGroup(group
);
994 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
995 } catch (IOException
| EncapsulatedExceptions e
) {
1001 if (group
== null) {
1003 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1004 } catch (IOException
| EncapsulatedExceptions e
) {
1005 e
.printStackTrace();
1008 group
.members
.remove(source
);
1009 account
.getGroupStore().updateGroup(group
);
1013 if (group
!= null) {
1015 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
1016 } catch (IOException
| EncapsulatedExceptions e
) {
1017 e
.printStackTrace();
1018 } catch (NotAGroupMemberException e
) {
1019 // We have left this group, so don't send a group update message
1026 threadId
= destination
.getNumber().get();
1031 if (message
.isEndSession()) {
1032 handleEndSession(isSync ? destination
.getNumber().get() : source
);
1034 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1035 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
1036 if (thread
== null) {
1037 thread
= new ThreadInfo();
1038 thread
.id
= threadId
;
1040 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1041 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1042 account
.getThreadStore().updateThread(thread
);
1045 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1046 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1047 if (attachment
.isPointer()) {
1049 retrieveAttachment(attachment
.asPointer());
1050 } catch (IOException
| InvalidMessageException e
) {
1051 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1056 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1057 if (source
.equals(username
)) {
1058 this.account
.setProfileKey(message
.getProfileKey().get());
1060 ContactInfo contact
= account
.getContactStore().getContact(source
);
1061 if (contact
== null) {
1062 contact
= new ContactInfo();
1063 contact
.number
= source
;
1065 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
1067 if (message
.getPreviews().isPresent()) {
1068 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1069 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1070 if (preview
.getImage().isPresent() && preview
.getImage().get().isPointer()) {
1071 SignalServiceAttachmentPointer attachment
= preview
.getImage().get().asPointer();
1073 retrieveAttachment(attachment
);
1074 } catch (IOException
| InvalidMessageException e
) {
1075 System
.err
.println("Failed to retrieve attachment (" + attachment
.getId() + "): " + e
.getMessage());
1082 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1083 final File cachePath
= new File(getMessageCachePath());
1084 if (!cachePath
.exists()) {
1087 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
1088 if (!dir
.isDirectory()) {
1092 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1093 if (!fileEntry
.isFile()) {
1096 SignalServiceEnvelope envelope
;
1098 envelope
= Utils
.loadEnvelope(fileEntry
);
1099 if (envelope
== null) {
1102 } catch (IOException e
) {
1103 e
.printStackTrace();
1106 SignalServiceContent content
= null;
1107 if (!envelope
.isReceipt()) {
1109 content
= decryptMessage(envelope
);
1110 } catch (Exception e
) {
1113 handleMessage(envelope
, content
, ignoreAttachments
);
1116 handler
.handleMessage(envelope
, content
, null);
1118 Files
.delete(fileEntry
.toPath());
1119 } catch (IOException e
) {
1120 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1123 // Try to delete directory if empty
1128 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1129 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1130 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1133 if (messagePipe
== null) {
1134 messagePipe
= messageReceiver
.createMessagePipe();
1138 SignalServiceEnvelope envelope
;
1139 SignalServiceContent content
= null;
1140 Exception exception
= null;
1141 final long now
= new Date().getTime();
1143 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1145 public void onMessage(SignalServiceEnvelope envelope
) {
1146 // store message on disk, before acknowledging receipt to the server
1148 File cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1149 Utils
.storeEnvelope(envelope
, cacheFile
);
1150 } catch (IOException e
) {
1151 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1155 } catch (TimeoutException e
) {
1156 if (returnOnTimeout
)
1159 } catch (InvalidVersionException e
) {
1160 System
.err
.println("Ignoring error: " + e
.getMessage());
1163 if (!envelope
.isReceipt()) {
1165 content
= decryptMessage(envelope
);
1166 } catch (Exception e
) {
1169 handleMessage(envelope
, content
, ignoreAttachments
);
1172 handler
.handleMessage(envelope
, content
, exception
);
1173 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1174 File cacheFile
= null;
1176 cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1177 Files
.delete(cacheFile
.toPath());
1178 // Try to delete directory if empty
1179 new File(getMessageCachePath()).delete();
1180 } catch (IOException e
) {
1181 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1186 if (messagePipe
!= null) {
1187 messagePipe
.shutdown();
1193 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1194 if (content
!= null) {
1195 SignalServiceAddress sender
;
1196 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1197 sender
= envelope
.getSourceAddress();
1199 sender
= content
.getSender();
1201 if (content
.getDataMessage().isPresent()) {
1202 SignalServiceDataMessage message
= content
.getDataMessage().get();
1203 handleSignalServiceDataMessage(message
, false, sender
.getNumber().get(), getSelfAddress(), ignoreAttachments
);
1205 if (content
.getSyncMessage().isPresent()) {
1206 account
.setMultiDevice(true);
1207 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1208 if (syncMessage
.getSent().isPresent()) {
1209 SentTranscriptMessage message
= syncMessage
.getSent().get();
1210 handleSignalServiceDataMessage(message
.getMessage(), true, sender
.getNumber().get(), message
.getDestination().orNull(), ignoreAttachments
);
1212 if (syncMessage
.getRequest().isPresent()) {
1213 RequestMessage rm
= syncMessage
.getRequest().get();
1214 if (rm
.isContactsRequest()) {
1217 } catch (UntrustedIdentityException
| IOException e
) {
1218 e
.printStackTrace();
1221 if (rm
.isGroupsRequest()) {
1224 } catch (UntrustedIdentityException
| IOException e
) {
1225 e
.printStackTrace();
1228 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1230 if (syncMessage
.getGroups().isPresent()) {
1231 File tmpFile
= null;
1233 tmpFile
= IOUtils
.createTempFile();
1234 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1235 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1237 while ((g
= s
.read()) != null) {
1238 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1239 if (syncGroup
== null) {
1240 syncGroup
= new GroupInfo(g
.getId());
1242 if (g
.getName().isPresent()) {
1243 syncGroup
.name
= g
.getName().get();
1245 syncGroup
.addMembers(g
.getMembers());
1246 syncGroup
.active
= g
.isActive();
1247 if (g
.getColor().isPresent()) {
1248 syncGroup
.color
= g
.getColor().get();
1251 if (g
.getAvatar().isPresent()) {
1252 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1254 account
.getGroupStore().updateGroup(syncGroup
);
1257 } catch (Exception e
) {
1258 e
.printStackTrace();
1260 if (tmpFile
!= null) {
1262 Files
.delete(tmpFile
.toPath());
1263 } catch (IOException e
) {
1264 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1269 if (syncMessage
.getBlockedList().isPresent()) {
1270 // TODO store list of blocked numbers
1272 if (syncMessage
.getContacts().isPresent()) {
1273 File tmpFile
= null;
1275 tmpFile
= IOUtils
.createTempFile();
1276 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1277 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1278 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1279 if (contactsMessage
.isComplete()) {
1280 account
.getContactStore().clear();
1283 while ((c
= s
.read()) != null) {
1284 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1285 account
.setProfileKey(c
.getProfileKey().get());
1287 ContactInfo contact
= account
.getContactStore().getContact(c
.getAddress().getNumber().get());
1288 if (contact
== null) {
1289 contact
= new ContactInfo();
1290 contact
.number
= c
.getAddress().getNumber().get();
1292 if (c
.getName().isPresent()) {
1293 contact
.name
= c
.getName().get();
1295 if (c
.getColor().isPresent()) {
1296 contact
.color
= c
.getColor().get();
1298 if (c
.getProfileKey().isPresent()) {
1299 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1301 if (c
.getVerified().isPresent()) {
1302 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1303 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1305 if (c
.getExpirationTimer().isPresent()) {
1306 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getAddress().getNumber().get());
1307 if (thread
== null) {
1308 thread
= new ThreadInfo();
1309 thread
.id
= c
.getAddress().getNumber().get();
1311 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1312 account
.getThreadStore().updateThread(thread
);
1314 if (c
.isBlocked()) {
1315 // TODO store list of blocked numbers
1317 account
.getContactStore().updateContact(contact
);
1319 if (c
.getAvatar().isPresent()) {
1320 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1324 } catch (Exception e
) {
1325 e
.printStackTrace();
1327 if (tmpFile
!= null) {
1329 Files
.delete(tmpFile
.toPath());
1330 } catch (IOException e
) {
1331 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1336 if (syncMessage
.getVerified().isPresent()) {
1337 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1338 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1340 if (syncMessage
.getConfiguration().isPresent()) {
1347 private File
getContactAvatarFile(String number
) {
1348 return new File(avatarsPath
, "contact-" + number
);
1351 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1352 IOUtils
.createPrivateDirectories(avatarsPath
);
1353 if (attachment
.isPointer()) {
1354 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1355 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1357 SignalServiceAttachmentStream stream
= attachment
.asStream();
1358 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1362 private File
getGroupAvatarFile(byte[] groupId
) {
1363 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1366 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1367 IOUtils
.createPrivateDirectories(avatarsPath
);
1368 if (attachment
.isPointer()) {
1369 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1370 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1372 SignalServiceAttachmentStream stream
= attachment
.asStream();
1373 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1377 public File
getAttachmentFile(long attachmentId
) {
1378 return new File(attachmentsPath
, attachmentId
+ "");
1381 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1382 IOUtils
.createPrivateDirectories(attachmentsPath
);
1383 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1386 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1387 if (storePreview
&& pointer
.getPreview().isPresent()) {
1388 File previewFile
= new File(outputFile
+ ".preview");
1389 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1390 byte[] preview
= pointer
.getPreview().get();
1391 output
.write(preview
, 0, preview
.length
);
1392 } catch (FileNotFoundException e
) {
1393 e
.printStackTrace();
1398 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1400 File tmpFile
= IOUtils
.createTempFile();
1401 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1402 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1403 byte[] buffer
= new byte[4096];
1406 while ((read
= input
.read(buffer
)) != -1) {
1407 output
.write(buffer
, 0, read
);
1409 } catch (FileNotFoundException e
) {
1410 e
.printStackTrace();
1415 Files
.delete(tmpFile
.toPath());
1416 } catch (IOException e
) {
1417 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1423 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1424 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1425 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1429 public boolean isRemote() {
1433 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1434 File groupsFile
= IOUtils
.createTempFile();
1437 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1438 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1439 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1440 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1441 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1442 new ArrayList
<>(record.getMembers()), createGroupAvatarAttachment(record.groupId
),
1443 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1444 Optional
.fromNullable(record.color
), false));
1448 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1449 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1450 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1451 .withStream(groupsFileStream
)
1452 .withContentType("application/octet-stream")
1453 .withLength(groupsFile
.length())
1456 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1461 Files
.delete(groupsFile
.toPath());
1462 } catch (IOException e
) {
1463 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1468 public void sendContacts() throws IOException
, UntrustedIdentityException
{
1469 File contactsFile
= IOUtils
.createTempFile();
1472 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1473 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1474 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1475 VerifiedMessage verifiedMessage
= null;
1476 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1477 if (getIdentities().containsKey(record.number
)) {
1478 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1479 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1480 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1481 currentIdentity
= id
;
1484 if (currentIdentity
!= null) {
1485 verifiedMessage
= new VerifiedMessage(record.getAddress(), currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1489 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1490 // TODO store list of blocked numbers
1491 boolean blocked
= false;
1492 out
.write(new DeviceContact(record.getAddress(), Optional
.fromNullable(record.name
),
1493 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1494 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1497 if (account
.getProfileKey() != null) {
1498 // Send our own profile key as well
1499 out
.write(new DeviceContact(account
.getSelfAddress(),
1500 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1501 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1502 Optional
.of(account
.getProfileKey()),
1503 false, Optional
.<Integer
>absent()));
1507 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1508 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1509 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1510 .withStream(contactsFileStream
)
1511 .withContentType("application/octet-stream")
1512 .withLength(contactsFile
.length())
1515 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1520 Files
.delete(contactsFile
.toPath());
1521 } catch (IOException e
) {
1522 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1527 private void sendVerifiedMessage(SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1528 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1529 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1532 public List
<ContactInfo
> getContacts() {
1533 return account
.getContactStore().getContacts();
1536 public ContactInfo
getContact(String number
) {
1537 return account
.getContactStore().getContact(number
);
1540 public GroupInfo
getGroup(byte[] groupId
) {
1541 return account
.getGroupStore().getGroup(groupId
);
1544 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1545 return account
.getSignalProtocolStore().getIdentities();
1548 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1549 return account
.getSignalProtocolStore().getIdentities(number
);
1553 * Trust this the identity with this fingerprint
1555 * @param name username of the identity
1556 * @param fingerprint Fingerprint
1558 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1559 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1563 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1564 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1568 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1570 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1571 } catch (IOException
| UntrustedIdentityException e
) {
1572 e
.printStackTrace();
1581 * Trust this the identity with this safety number
1583 * @param name username of the identity
1584 * @param safetyNumber Safety number
1586 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1587 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1591 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1592 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1596 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1598 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1599 } catch (IOException
| UntrustedIdentityException e
) {
1600 e
.printStackTrace();
1609 * Trust all keys of this identity without verification
1611 * @param name username of the identity
1613 public boolean trustIdentityAllKeys(String name
) {
1614 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1618 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1619 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1620 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1622 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1623 } catch (IOException
| UntrustedIdentityException e
) {
1624 e
.printStackTrace();
1632 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1633 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1636 public interface ReceiveMessageHandler
{
1638 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);