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 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
652 messageBuilder
.withProfileKey(account
.getProfileKey());
653 sendMessageLegacy(messageBuilder
, recipients
);
657 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
658 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
659 .asEndSessionMessage();
661 sendMessageLegacy(messageBuilder
, recipients
);
665 public String
getContactName(String number
) {
666 ContactInfo contact
= account
.getContactStore().getContact(number
);
667 if (contact
== null) {
675 public void setContactName(String number
, String name
) {
676 ContactInfo contact
= account
.getContactStore().getContact(number
);
677 if (contact
== null) {
678 contact
= new ContactInfo();
679 contact
.number
= number
;
680 System
.err
.println("Add contact " + number
+ " named " + name
);
682 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
685 account
.getContactStore().updateContact(contact
);
690 public List
<byte[]> getGroupIds() {
691 List
<GroupInfo
> groups
= getGroups();
692 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
693 for (GroupInfo group
: groups
) {
694 ids
.add(group
.groupId
);
700 public String
getGroupName(byte[] groupId
) {
701 GroupInfo group
= getGroup(groupId
);
710 public List
<String
> getGroupMembers(byte[] groupId
) {
711 GroupInfo group
= getGroup(groupId
);
713 return new ArrayList
<>();
715 return new ArrayList
<>(group
.members
);
720 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
721 if (groupId
.length
== 0) {
724 if (name
.isEmpty()) {
727 if (members
.size() == 0) {
730 if (avatar
.isEmpty()) {
733 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
737 * Change the expiration timer for a thread (number of groupId)
739 * @param numberOrGroupId
740 * @param messageExpirationTimer
742 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
743 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
744 thread
.messageExpirationTime
= messageExpirationTimer
;
745 account
.getThreadStore().updateThread(thread
);
748 private void requestSyncGroups() throws IOException
{
749 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
750 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
752 sendSyncMessage(message
);
753 } catch (UntrustedIdentityException e
) {
758 private void requestSyncContacts() throws IOException
{
759 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
760 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
762 sendSyncMessage(message
);
763 } catch (UntrustedIdentityException e
) {
768 private void requestSyncBlocked() throws IOException
{
769 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
770 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
772 sendSyncMessage(message
);
773 } catch (UntrustedIdentityException e
) {
778 private void requestSyncConfiguration() throws IOException
{
779 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
780 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
782 sendSyncMessage(message
);
783 } catch (UntrustedIdentityException e
) {
788 private byte[] getSelfUnidentifiedAccessKey() {
789 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
792 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
797 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
799 return Optional
.absent();
802 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
803 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
804 for (SignalServiceAddress recipient
: recipients
) {
805 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
810 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
812 return Optional
.absent();
815 private void sendSyncMessage(SignalServiceSyncMessage message
)
816 throws IOException
, UntrustedIdentityException
{
817 SignalServiceMessageSender messageSender
= getMessageSender();
819 messageSender
.sendMessage(message
, getAccessForSync());
820 } catch (UntrustedIdentityException e
) {
821 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
827 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
829 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
830 throws EncapsulatedExceptions
, IOException
{
831 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
833 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
834 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
835 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
837 for (SendMessageResult result
: results
) {
838 if (result
.isUnregisteredFailure()) {
839 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber().get(), null));
840 } else if (result
.isNetworkFailure()) {
841 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber().get(), null));
842 } else if (result
.getIdentityFailure() != null) {
843 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber().get(), result
.getIdentityFailure().getIdentityKey()));
846 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
847 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
851 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
853 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
854 if (recipientsTS
== null) {
856 return Collections
.emptyList();
859 SignalServiceDataMessage message
= null;
861 SignalServiceMessageSender messageSender
= getMessageSender();
863 message
= messageBuilder
.build();
864 if (message
.getGroupInfo().isPresent()) {
866 final boolean isRecipientUpdate
= false;
867 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
868 for (SendMessageResult r
: result
) {
869 if (r
.getIdentityFailure() != null) {
870 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber().get(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
874 } catch (UntrustedIdentityException e
) {
875 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
876 return Collections
.emptyList();
878 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(getSelfAddress())) {
879 SignalServiceAddress recipient
= getSelfAddress();
880 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
881 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
882 message
.getTimestamp(),
884 message
.getExpiresInSeconds(),
885 Collections
.singletonMap(recipient
, unidentifiedAccess
.isPresent()),
887 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
889 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
891 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
892 } catch (UntrustedIdentityException e
) {
893 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
894 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
898 // Send to all individually, so sync messages are sent correctly
899 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
900 for (SignalServiceAddress address
: recipientsTS
) {
901 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber().get());
902 if (thread
!= null) {
903 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
905 messageBuilder
.withExpiration(0);
907 message
= messageBuilder
.build();
909 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
911 } catch (UntrustedIdentityException e
) {
912 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
913 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
919 if (message
!= null && message
.isEndSession()) {
920 for (SignalServiceAddress recipient
: recipientsTS
) {
921 handleEndSession(recipient
.getNumber().get());
928 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
929 SignalServiceCipher cipher
= new SignalServiceCipher(getSelfAddress(), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
931 return cipher
.decrypt(envelope
);
932 } catch (ProtocolUntrustedIdentityException e
) {
933 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
934 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
939 private void handleEndSession(String source
) {
940 account
.getSignalProtocolStore().deleteAllSessions(source
);
943 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, SignalServiceAddress destination
, boolean ignoreAttachments
) {
945 if (message
.getGroupInfo().isPresent()) {
946 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
947 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
948 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
949 switch (groupInfo
.getType()) {
952 group
= new GroupInfo(groupInfo
.getGroupId());
955 if (groupInfo
.getAvatar().isPresent()) {
956 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
957 if (avatar
.isPointer()) {
959 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
960 } catch (IOException
| InvalidMessageException e
) {
961 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
966 if (groupInfo
.getName().isPresent()) {
967 group
.name
= groupInfo
.getName().get();
970 if (groupInfo
.getMembers().isPresent()) {
971 group
.addMembers(groupInfo
.getMembers().get());
974 account
.getGroupStore().updateGroup(group
);
979 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
980 } catch (IOException
| EncapsulatedExceptions e
) {
988 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
989 } catch (IOException
| EncapsulatedExceptions e
) {
993 group
.members
.remove(source
);
994 account
.getGroupStore().updateGroup(group
);
1000 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
1001 } catch (IOException
| EncapsulatedExceptions e
) {
1002 e
.printStackTrace();
1003 } catch (NotAGroupMemberException e
) {
1004 // We have left this group, so don't send a group update message
1011 threadId
= destination
.getNumber().get();
1016 if (message
.isEndSession()) {
1017 handleEndSession(isSync ? destination
.getNumber().get() : source
);
1019 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1020 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
1021 if (thread
== null) {
1022 thread
= new ThreadInfo();
1023 thread
.id
= threadId
;
1025 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1026 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1027 account
.getThreadStore().updateThread(thread
);
1030 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1031 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1032 if (attachment
.isPointer()) {
1034 retrieveAttachment(attachment
.asPointer());
1035 } catch (IOException
| InvalidMessageException e
) {
1036 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1041 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1042 if (source
.equals(username
)) {
1043 this.account
.setProfileKey(message
.getProfileKey().get());
1045 ContactInfo contact
= account
.getContactStore().getContact(source
);
1046 if (contact
== null) {
1047 contact
= new ContactInfo();
1048 contact
.number
= source
;
1050 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
1052 if (message
.getPreviews().isPresent()) {
1053 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1054 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1055 if (preview
.getImage().isPresent() && preview
.getImage().get().isPointer()) {
1056 SignalServiceAttachmentPointer attachment
= preview
.getImage().get().asPointer();
1058 retrieveAttachment(attachment
);
1059 } catch (IOException
| InvalidMessageException e
) {
1060 System
.err
.println("Failed to retrieve attachment (" + attachment
.getId() + "): " + e
.getMessage());
1067 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1068 final File cachePath
= new File(getMessageCachePath());
1069 if (!cachePath
.exists()) {
1072 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
1073 if (!dir
.isDirectory()) {
1077 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1078 if (!fileEntry
.isFile()) {
1081 SignalServiceEnvelope envelope
;
1083 envelope
= Utils
.loadEnvelope(fileEntry
);
1084 if (envelope
== null) {
1087 } catch (IOException e
) {
1088 e
.printStackTrace();
1091 SignalServiceContent content
= null;
1092 if (!envelope
.isReceipt()) {
1094 content
= decryptMessage(envelope
);
1095 } catch (Exception e
) {
1098 handleMessage(envelope
, content
, ignoreAttachments
);
1101 handler
.handleMessage(envelope
, content
, null);
1103 Files
.delete(fileEntry
.toPath());
1104 } catch (IOException e
) {
1105 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1108 // Try to delete directory if empty
1113 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1114 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1115 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1118 if (messagePipe
== null) {
1119 messagePipe
= messageReceiver
.createMessagePipe();
1123 SignalServiceEnvelope envelope
;
1124 SignalServiceContent content
= null;
1125 Exception exception
= null;
1126 final long now
= new Date().getTime();
1128 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1130 public void onMessage(SignalServiceEnvelope envelope
) {
1131 // store message on disk, before acknowledging receipt to the server
1133 File cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1134 Utils
.storeEnvelope(envelope
, cacheFile
);
1135 } catch (IOException e
) {
1136 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1140 } catch (TimeoutException e
) {
1141 if (returnOnTimeout
)
1144 } catch (InvalidVersionException e
) {
1145 System
.err
.println("Ignoring error: " + e
.getMessage());
1148 if (!envelope
.isReceipt()) {
1150 content
= decryptMessage(envelope
);
1151 } catch (Exception e
) {
1154 handleMessage(envelope
, content
, ignoreAttachments
);
1157 handler
.handleMessage(envelope
, content
, exception
);
1158 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1159 File cacheFile
= null;
1161 cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1162 Files
.delete(cacheFile
.toPath());
1163 // Try to delete directory if empty
1164 new File(getMessageCachePath()).delete();
1165 } catch (IOException e
) {
1166 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1171 if (messagePipe
!= null) {
1172 messagePipe
.shutdown();
1178 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1179 if (content
!= null) {
1180 SignalServiceAddress sender
;
1181 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1182 sender
= envelope
.getSourceAddress();
1184 sender
= content
.getSender();
1186 if (content
.getDataMessage().isPresent()) {
1187 SignalServiceDataMessage message
= content
.getDataMessage().get();
1188 handleSignalServiceDataMessage(message
, false, sender
.getNumber().get(), getSelfAddress(), ignoreAttachments
);
1190 if (content
.getSyncMessage().isPresent()) {
1191 account
.setMultiDevice(true);
1192 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1193 if (syncMessage
.getSent().isPresent()) {
1194 SentTranscriptMessage message
= syncMessage
.getSent().get();
1195 handleSignalServiceDataMessage(message
.getMessage(), true, sender
.getNumber().get(), message
.getDestination().orNull(), ignoreAttachments
);
1197 if (syncMessage
.getRequest().isPresent()) {
1198 RequestMessage rm
= syncMessage
.getRequest().get();
1199 if (rm
.isContactsRequest()) {
1202 } catch (UntrustedIdentityException
| IOException e
) {
1203 e
.printStackTrace();
1206 if (rm
.isGroupsRequest()) {
1209 } catch (UntrustedIdentityException
| IOException e
) {
1210 e
.printStackTrace();
1213 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1215 if (syncMessage
.getGroups().isPresent()) {
1216 File tmpFile
= null;
1218 tmpFile
= IOUtils
.createTempFile();
1219 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1220 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1222 while ((g
= s
.read()) != null) {
1223 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1224 if (syncGroup
== null) {
1225 syncGroup
= new GroupInfo(g
.getId());
1227 if (g
.getName().isPresent()) {
1228 syncGroup
.name
= g
.getName().get();
1230 syncGroup
.addMembers(g
.getMembers());
1231 syncGroup
.active
= g
.isActive();
1232 if (g
.getColor().isPresent()) {
1233 syncGroup
.color
= g
.getColor().get();
1236 if (g
.getAvatar().isPresent()) {
1237 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1239 account
.getGroupStore().updateGroup(syncGroup
);
1242 } catch (Exception e
) {
1243 e
.printStackTrace();
1245 if (tmpFile
!= null) {
1247 Files
.delete(tmpFile
.toPath());
1248 } catch (IOException e
) {
1249 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1254 if (syncMessage
.getBlockedList().isPresent()) {
1255 // TODO store list of blocked numbers
1257 if (syncMessage
.getContacts().isPresent()) {
1258 File tmpFile
= null;
1260 tmpFile
= IOUtils
.createTempFile();
1261 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1262 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1263 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1264 if (contactsMessage
.isComplete()) {
1265 account
.getContactStore().clear();
1268 while ((c
= s
.read()) != null) {
1269 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1270 account
.setProfileKey(c
.getProfileKey().get());
1272 ContactInfo contact
= account
.getContactStore().getContact(c
.getAddress().getNumber().get());
1273 if (contact
== null) {
1274 contact
= new ContactInfo();
1275 contact
.number
= c
.getAddress().getNumber().get();
1277 if (c
.getName().isPresent()) {
1278 contact
.name
= c
.getName().get();
1280 if (c
.getColor().isPresent()) {
1281 contact
.color
= c
.getColor().get();
1283 if (c
.getProfileKey().isPresent()) {
1284 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1286 if (c
.getVerified().isPresent()) {
1287 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1288 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1290 if (c
.getExpirationTimer().isPresent()) {
1291 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getAddress().getNumber().get());
1292 if (thread
== null) {
1293 thread
= new ThreadInfo();
1294 thread
.id
= c
.getAddress().getNumber().get();
1296 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1297 account
.getThreadStore().updateThread(thread
);
1299 if (c
.isBlocked()) {
1300 // TODO store list of blocked numbers
1302 account
.getContactStore().updateContact(contact
);
1304 if (c
.getAvatar().isPresent()) {
1305 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1309 } catch (Exception e
) {
1310 e
.printStackTrace();
1312 if (tmpFile
!= null) {
1314 Files
.delete(tmpFile
.toPath());
1315 } catch (IOException e
) {
1316 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1321 if (syncMessage
.getVerified().isPresent()) {
1322 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1323 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1325 if (syncMessage
.getConfiguration().isPresent()) {
1332 private File
getContactAvatarFile(String number
) {
1333 return new File(avatarsPath
, "contact-" + number
);
1336 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1337 IOUtils
.createPrivateDirectories(avatarsPath
);
1338 if (attachment
.isPointer()) {
1339 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1340 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1342 SignalServiceAttachmentStream stream
= attachment
.asStream();
1343 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1347 private File
getGroupAvatarFile(byte[] groupId
) {
1348 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1351 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1352 IOUtils
.createPrivateDirectories(avatarsPath
);
1353 if (attachment
.isPointer()) {
1354 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1355 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1357 SignalServiceAttachmentStream stream
= attachment
.asStream();
1358 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1362 public File
getAttachmentFile(long attachmentId
) {
1363 return new File(attachmentsPath
, attachmentId
+ "");
1366 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1367 IOUtils
.createPrivateDirectories(attachmentsPath
);
1368 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1371 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1372 if (storePreview
&& pointer
.getPreview().isPresent()) {
1373 File previewFile
= new File(outputFile
+ ".preview");
1374 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1375 byte[] preview
= pointer
.getPreview().get();
1376 output
.write(preview
, 0, preview
.length
);
1377 } catch (FileNotFoundException e
) {
1378 e
.printStackTrace();
1383 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1385 File tmpFile
= IOUtils
.createTempFile();
1386 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1387 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1388 byte[] buffer
= new byte[4096];
1391 while ((read
= input
.read(buffer
)) != -1) {
1392 output
.write(buffer
, 0, read
);
1394 } catch (FileNotFoundException e
) {
1395 e
.printStackTrace();
1400 Files
.delete(tmpFile
.toPath());
1401 } catch (IOException e
) {
1402 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1408 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1409 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1410 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1414 public boolean isRemote() {
1418 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1419 File groupsFile
= IOUtils
.createTempFile();
1422 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1423 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1424 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1425 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1426 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1427 new ArrayList
<>(record.getMembers()), createGroupAvatarAttachment(record.groupId
),
1428 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1429 Optional
.fromNullable(record.color
), false));
1433 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1434 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1435 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1436 .withStream(groupsFileStream
)
1437 .withContentType("application/octet-stream")
1438 .withLength(groupsFile
.length())
1441 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1446 Files
.delete(groupsFile
.toPath());
1447 } catch (IOException e
) {
1448 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1453 public void sendContacts() throws IOException
, UntrustedIdentityException
{
1454 File contactsFile
= IOUtils
.createTempFile();
1457 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1458 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1459 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1460 VerifiedMessage verifiedMessage
= null;
1461 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1462 if (getIdentities().containsKey(record.number
)) {
1463 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1464 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1465 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1466 currentIdentity
= id
;
1469 if (currentIdentity
!= null) {
1470 verifiedMessage
= new VerifiedMessage(record.getAddress(), currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1474 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1475 // TODO store list of blocked numbers
1476 boolean blocked
= false;
1477 out
.write(new DeviceContact(record.getAddress(), Optional
.fromNullable(record.name
),
1478 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1479 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1482 if (account
.getProfileKey() != null) {
1483 // Send our own profile key as well
1484 out
.write(new DeviceContact(account
.getSelfAddress(),
1485 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1486 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1487 Optional
.of(account
.getProfileKey()),
1488 false, Optional
.<Integer
>absent()));
1492 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1493 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1494 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1495 .withStream(contactsFileStream
)
1496 .withContentType("application/octet-stream")
1497 .withLength(contactsFile
.length())
1500 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1505 Files
.delete(contactsFile
.toPath());
1506 } catch (IOException e
) {
1507 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1512 private void sendVerifiedMessage(SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1513 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1514 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1517 public List
<ContactInfo
> getContacts() {
1518 return account
.getContactStore().getContacts();
1521 public ContactInfo
getContact(String number
) {
1522 return account
.getContactStore().getContact(number
);
1525 public GroupInfo
getGroup(byte[] groupId
) {
1526 return account
.getGroupStore().getGroup(groupId
);
1529 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1530 return account
.getSignalProtocolStore().getIdentities();
1533 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1534 return account
.getSignalProtocolStore().getIdentities(number
);
1538 * Trust this the identity with this fingerprint
1540 * @param name username of the identity
1541 * @param fingerprint Fingerprint
1543 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1544 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1548 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1549 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1553 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1555 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1556 } catch (IOException
| UntrustedIdentityException e
) {
1557 e
.printStackTrace();
1566 * Trust this the identity with this safety number
1568 * @param name username of the identity
1569 * @param safetyNumber Safety number
1571 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1572 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1576 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1577 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1581 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1583 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1584 } catch (IOException
| UntrustedIdentityException e
) {
1585 e
.printStackTrace();
1594 * Trust all keys of this identity without verification
1596 * @param name username of the identity
1598 public boolean trustIdentityAllKeys(String name
) {
1599 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1603 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1604 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1605 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1607 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1608 } catch (IOException
| UntrustedIdentityException e
) {
1609 e
.printStackTrace();
1617 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1618 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1621 public interface ReceiveMessageHandler
{
1623 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);