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
) {
679 ContactInfo contact
= account
.getContactStore().getContact(number
);
680 if (contact
== null) {
688 public void setContactName(String number
, String name
) {
689 ContactInfo contact
= account
.getContactStore().getContact(number
);
690 if (contact
== null) {
691 contact
= new ContactInfo();
692 contact
.number
= number
;
693 System
.err
.println("Add contact " + number
+ " named " + name
);
695 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
698 account
.getContactStore().updateContact(contact
);
703 public List
<byte[]> getGroupIds() {
704 List
<GroupInfo
> groups
= getGroups();
705 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
706 for (GroupInfo group
: groups
) {
707 ids
.add(group
.groupId
);
713 public String
getGroupName(byte[] groupId
) {
714 GroupInfo group
= getGroup(groupId
);
723 public List
<String
> getGroupMembers(byte[] groupId
) {
724 GroupInfo group
= getGroup(groupId
);
726 return new ArrayList
<>();
728 return new ArrayList
<>(group
.members
);
733 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
734 if (groupId
.length
== 0) {
737 if (name
.isEmpty()) {
740 if (members
.size() == 0) {
743 if (avatar
.isEmpty()) {
746 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
750 * Change the expiration timer for a thread (number of groupId)
752 * @param numberOrGroupId
753 * @param messageExpirationTimer
755 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
756 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
757 thread
.messageExpirationTime
= messageExpirationTimer
;
758 account
.getThreadStore().updateThread(thread
);
761 private void requestSyncGroups() throws IOException
{
762 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
763 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
765 sendSyncMessage(message
);
766 } catch (UntrustedIdentityException e
) {
771 private void requestSyncContacts() throws IOException
{
772 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
773 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
775 sendSyncMessage(message
);
776 } catch (UntrustedIdentityException e
) {
781 private void requestSyncBlocked() throws IOException
{
782 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
783 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
785 sendSyncMessage(message
);
786 } catch (UntrustedIdentityException e
) {
791 private void requestSyncConfiguration() throws IOException
{
792 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
793 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
795 sendSyncMessage(message
);
796 } catch (UntrustedIdentityException e
) {
801 private byte[] getSelfUnidentifiedAccessKey() {
802 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
805 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
810 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
812 return Optional
.absent();
815 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
816 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
817 for (SignalServiceAddress recipient
: recipients
) {
818 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
823 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
825 return Optional
.absent();
828 private void sendSyncMessage(SignalServiceSyncMessage message
)
829 throws IOException
, UntrustedIdentityException
{
830 SignalServiceMessageSender messageSender
= getMessageSender();
832 messageSender
.sendMessage(message
, getAccessForSync());
833 } catch (UntrustedIdentityException e
) {
834 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
840 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
842 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
843 throws EncapsulatedExceptions
, IOException
{
844 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
846 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
847 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
848 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
850 for (SendMessageResult result
: results
) {
851 if (result
.isUnregisteredFailure()) {
852 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber().get(), null));
853 } else if (result
.isNetworkFailure()) {
854 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber().get(), null));
855 } else if (result
.getIdentityFailure() != null) {
856 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber().get(), result
.getIdentityFailure().getIdentityKey()));
859 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
860 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
864 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
866 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
867 if (recipientsTS
== null) {
869 return Collections
.emptyList();
872 SignalServiceDataMessage message
= null;
874 SignalServiceMessageSender messageSender
= getMessageSender();
876 message
= messageBuilder
.build();
877 if (message
.getGroupInfo().isPresent()) {
879 final boolean isRecipientUpdate
= false;
880 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
881 for (SendMessageResult r
: result
) {
882 if (r
.getIdentityFailure() != null) {
883 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber().get(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
887 } catch (UntrustedIdentityException e
) {
888 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
889 return Collections
.emptyList();
891 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(getSelfAddress())) {
892 SignalServiceAddress recipient
= getSelfAddress();
893 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
894 SentTranscriptMessage transcript
= new SentTranscriptMessage(Optional
.of(recipient
),
895 message
.getTimestamp(),
897 message
.getExpiresInSeconds(),
898 Collections
.singletonMap(recipient
, unidentifiedAccess
.isPresent()),
900 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
902 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
904 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
905 } catch (UntrustedIdentityException e
) {
906 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
907 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
911 // Send to all individually, so sync messages are sent correctly
912 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
913 for (SignalServiceAddress address
: recipientsTS
) {
914 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber().get());
915 if (thread
!= null) {
916 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
918 messageBuilder
.withExpiration(0);
920 message
= messageBuilder
.build();
922 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
924 } catch (UntrustedIdentityException e
) {
925 account
.getSignalProtocolStore().saveIdentity(e
.getIdentifier(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
926 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
932 if (message
!= null && message
.isEndSession()) {
933 for (SignalServiceAddress recipient
: recipientsTS
) {
934 handleEndSession(recipient
.getNumber().get());
941 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
942 SignalServiceCipher cipher
= new SignalServiceCipher(getSelfAddress(), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
944 return cipher
.decrypt(envelope
);
945 } catch (ProtocolUntrustedIdentityException e
) {
946 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
947 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
952 private void handleEndSession(String source
) {
953 account
.getSignalProtocolStore().deleteAllSessions(source
);
956 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, SignalServiceAddress destination
, boolean ignoreAttachments
) {
958 if (message
.getGroupInfo().isPresent()) {
959 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
960 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
961 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
962 switch (groupInfo
.getType()) {
965 group
= new GroupInfo(groupInfo
.getGroupId());
968 if (groupInfo
.getAvatar().isPresent()) {
969 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
970 if (avatar
.isPointer()) {
972 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
973 } catch (IOException
| InvalidMessageException e
) {
974 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
979 if (groupInfo
.getName().isPresent()) {
980 group
.name
= groupInfo
.getName().get();
983 if (groupInfo
.getMembers().isPresent()) {
984 group
.addMembers(groupInfo
.getMembers().get());
987 account
.getGroupStore().updateGroup(group
);
992 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
993 } catch (IOException
| EncapsulatedExceptions e
) {
1001 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1002 } catch (IOException
| EncapsulatedExceptions e
) {
1003 e
.printStackTrace();
1006 group
.members
.remove(source
);
1007 account
.getGroupStore().updateGroup(group
);
1011 if (group
!= null) {
1013 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
1014 } catch (IOException
| EncapsulatedExceptions e
) {
1015 e
.printStackTrace();
1016 } catch (NotAGroupMemberException e
) {
1017 // We have left this group, so don't send a group update message
1024 threadId
= destination
.getNumber().get();
1029 if (message
.isEndSession()) {
1030 handleEndSession(isSync ? destination
.getNumber().get() : source
);
1032 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1033 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
1034 if (thread
== null) {
1035 thread
= new ThreadInfo();
1036 thread
.id
= threadId
;
1038 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1039 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1040 account
.getThreadStore().updateThread(thread
);
1043 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1044 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1045 if (attachment
.isPointer()) {
1047 retrieveAttachment(attachment
.asPointer());
1048 } catch (IOException
| InvalidMessageException e
) {
1049 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1054 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1055 if (source
.equals(username
)) {
1056 this.account
.setProfileKey(message
.getProfileKey().get());
1058 ContactInfo contact
= account
.getContactStore().getContact(source
);
1059 if (contact
== null) {
1060 contact
= new ContactInfo();
1061 contact
.number
= source
;
1063 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
1065 if (message
.getPreviews().isPresent()) {
1066 final List
<SignalServiceDataMessage
.Preview
> previews
= message
.getPreviews().get();
1067 for (SignalServiceDataMessage
.Preview preview
: previews
) {
1068 if (preview
.getImage().isPresent() && preview
.getImage().get().isPointer()) {
1069 SignalServiceAttachmentPointer attachment
= preview
.getImage().get().asPointer();
1071 retrieveAttachment(attachment
);
1072 } catch (IOException
| InvalidMessageException e
) {
1073 System
.err
.println("Failed to retrieve attachment (" + attachment
.getId() + "): " + e
.getMessage());
1080 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1081 final File cachePath
= new File(getMessageCachePath());
1082 if (!cachePath
.exists()) {
1085 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
1086 if (!dir
.isDirectory()) {
1090 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1091 if (!fileEntry
.isFile()) {
1094 SignalServiceEnvelope envelope
;
1096 envelope
= Utils
.loadEnvelope(fileEntry
);
1097 if (envelope
== null) {
1100 } catch (IOException e
) {
1101 e
.printStackTrace();
1104 SignalServiceContent content
= null;
1105 if (!envelope
.isReceipt()) {
1107 content
= decryptMessage(envelope
);
1108 } catch (Exception e
) {
1111 handleMessage(envelope
, content
, ignoreAttachments
);
1114 handler
.handleMessage(envelope
, content
, null);
1116 Files
.delete(fileEntry
.toPath());
1117 } catch (IOException e
) {
1118 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1121 // Try to delete directory if empty
1126 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1127 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1128 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1131 if (messagePipe
== null) {
1132 messagePipe
= messageReceiver
.createMessagePipe();
1136 SignalServiceEnvelope envelope
;
1137 SignalServiceContent content
= null;
1138 Exception exception
= null;
1139 final long now
= new Date().getTime();
1141 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1143 public void onMessage(SignalServiceEnvelope envelope
) {
1144 // store message on disk, before acknowledging receipt to the server
1146 File cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1147 Utils
.storeEnvelope(envelope
, cacheFile
);
1148 } catch (IOException e
) {
1149 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1153 } catch (TimeoutException e
) {
1154 if (returnOnTimeout
)
1157 } catch (InvalidVersionException e
) {
1158 System
.err
.println("Ignoring error: " + e
.getMessage());
1161 if (!envelope
.isReceipt()) {
1163 content
= decryptMessage(envelope
);
1164 } catch (Exception e
) {
1167 handleMessage(envelope
, content
, ignoreAttachments
);
1170 handler
.handleMessage(envelope
, content
, exception
);
1171 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1172 File cacheFile
= null;
1174 cacheFile
= getMessageCacheFile(envelope
.getSourceE164().get(), now
, envelope
.getTimestamp());
1175 Files
.delete(cacheFile
.toPath());
1176 // Try to delete directory if empty
1177 new File(getMessageCachePath()).delete();
1178 } catch (IOException e
) {
1179 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1184 if (messagePipe
!= null) {
1185 messagePipe
.shutdown();
1191 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1192 if (content
!= null) {
1193 SignalServiceAddress sender
;
1194 if (!envelope
.isUnidentifiedSender() && envelope
.hasSource()) {
1195 sender
= envelope
.getSourceAddress();
1197 sender
= content
.getSender();
1199 if (content
.getDataMessage().isPresent()) {
1200 SignalServiceDataMessage message
= content
.getDataMessage().get();
1201 handleSignalServiceDataMessage(message
, false, sender
.getNumber().get(), getSelfAddress(), ignoreAttachments
);
1203 if (content
.getSyncMessage().isPresent()) {
1204 account
.setMultiDevice(true);
1205 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1206 if (syncMessage
.getSent().isPresent()) {
1207 SentTranscriptMessage message
= syncMessage
.getSent().get();
1208 handleSignalServiceDataMessage(message
.getMessage(), true, sender
.getNumber().get(), message
.getDestination().orNull(), ignoreAttachments
);
1210 if (syncMessage
.getRequest().isPresent()) {
1211 RequestMessage rm
= syncMessage
.getRequest().get();
1212 if (rm
.isContactsRequest()) {
1215 } catch (UntrustedIdentityException
| IOException e
) {
1216 e
.printStackTrace();
1219 if (rm
.isGroupsRequest()) {
1222 } catch (UntrustedIdentityException
| IOException e
) {
1223 e
.printStackTrace();
1226 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1228 if (syncMessage
.getGroups().isPresent()) {
1229 File tmpFile
= null;
1231 tmpFile
= IOUtils
.createTempFile();
1232 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1233 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1235 while ((g
= s
.read()) != null) {
1236 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1237 if (syncGroup
== null) {
1238 syncGroup
= new GroupInfo(g
.getId());
1240 if (g
.getName().isPresent()) {
1241 syncGroup
.name
= g
.getName().get();
1243 syncGroup
.addMembers(g
.getMembers());
1244 syncGroup
.active
= g
.isActive();
1245 if (g
.getColor().isPresent()) {
1246 syncGroup
.color
= g
.getColor().get();
1249 if (g
.getAvatar().isPresent()) {
1250 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1252 account
.getGroupStore().updateGroup(syncGroup
);
1255 } catch (Exception e
) {
1256 e
.printStackTrace();
1258 if (tmpFile
!= null) {
1260 Files
.delete(tmpFile
.toPath());
1261 } catch (IOException e
) {
1262 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1267 if (syncMessage
.getBlockedList().isPresent()) {
1268 // TODO store list of blocked numbers
1270 if (syncMessage
.getContacts().isPresent()) {
1271 File tmpFile
= null;
1273 tmpFile
= IOUtils
.createTempFile();
1274 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1275 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1276 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1277 if (contactsMessage
.isComplete()) {
1278 account
.getContactStore().clear();
1281 while ((c
= s
.read()) != null) {
1282 if (c
.getAddress().matches(account
.getSelfAddress()) && c
.getProfileKey().isPresent()) {
1283 account
.setProfileKey(c
.getProfileKey().get());
1285 ContactInfo contact
= account
.getContactStore().getContact(c
.getAddress().getNumber().get());
1286 if (contact
== null) {
1287 contact
= new ContactInfo();
1288 contact
.number
= c
.getAddress().getNumber().get();
1290 if (c
.getName().isPresent()) {
1291 contact
.name
= c
.getName().get();
1293 if (c
.getColor().isPresent()) {
1294 contact
.color
= c
.getColor().get();
1296 if (c
.getProfileKey().isPresent()) {
1297 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1299 if (c
.getVerified().isPresent()) {
1300 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1301 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1303 if (c
.getExpirationTimer().isPresent()) {
1304 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getAddress().getNumber().get());
1305 if (thread
== null) {
1306 thread
= new ThreadInfo();
1307 thread
.id
= c
.getAddress().getNumber().get();
1309 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1310 account
.getThreadStore().updateThread(thread
);
1312 if (c
.isBlocked()) {
1313 // TODO store list of blocked numbers
1315 account
.getContactStore().updateContact(contact
);
1317 if (c
.getAvatar().isPresent()) {
1318 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1322 } catch (Exception e
) {
1323 e
.printStackTrace();
1325 if (tmpFile
!= null) {
1327 Files
.delete(tmpFile
.toPath());
1328 } catch (IOException e
) {
1329 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1334 if (syncMessage
.getVerified().isPresent()) {
1335 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1336 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination().getNumber().get(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1338 if (syncMessage
.getConfiguration().isPresent()) {
1345 private File
getContactAvatarFile(String number
) {
1346 return new File(avatarsPath
, "contact-" + number
);
1349 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1350 IOUtils
.createPrivateDirectories(avatarsPath
);
1351 if (attachment
.isPointer()) {
1352 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1353 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1355 SignalServiceAttachmentStream stream
= attachment
.asStream();
1356 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1360 private File
getGroupAvatarFile(byte[] groupId
) {
1361 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1364 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1365 IOUtils
.createPrivateDirectories(avatarsPath
);
1366 if (attachment
.isPointer()) {
1367 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1368 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1370 SignalServiceAttachmentStream stream
= attachment
.asStream();
1371 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1375 public File
getAttachmentFile(long attachmentId
) {
1376 return new File(attachmentsPath
, attachmentId
+ "");
1379 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1380 IOUtils
.createPrivateDirectories(attachmentsPath
);
1381 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1384 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1385 if (storePreview
&& pointer
.getPreview().isPresent()) {
1386 File previewFile
= new File(outputFile
+ ".preview");
1387 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1388 byte[] preview
= pointer
.getPreview().get();
1389 output
.write(preview
, 0, preview
.length
);
1390 } catch (FileNotFoundException e
) {
1391 e
.printStackTrace();
1396 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1398 File tmpFile
= IOUtils
.createTempFile();
1399 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1400 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1401 byte[] buffer
= new byte[4096];
1404 while ((read
= input
.read(buffer
)) != -1) {
1405 output
.write(buffer
, 0, read
);
1407 } catch (FileNotFoundException e
) {
1408 e
.printStackTrace();
1413 Files
.delete(tmpFile
.toPath());
1414 } catch (IOException e
) {
1415 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1421 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1422 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1423 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1427 public boolean isRemote() {
1431 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1432 File groupsFile
= IOUtils
.createTempFile();
1435 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1436 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1437 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1438 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1439 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1440 new ArrayList
<>(record.getMembers()), createGroupAvatarAttachment(record.groupId
),
1441 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1442 Optional
.fromNullable(record.color
), false));
1446 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1447 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1448 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1449 .withStream(groupsFileStream
)
1450 .withContentType("application/octet-stream")
1451 .withLength(groupsFile
.length())
1454 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1459 Files
.delete(groupsFile
.toPath());
1460 } catch (IOException e
) {
1461 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1466 public void sendContacts() throws IOException
, UntrustedIdentityException
{
1467 File contactsFile
= IOUtils
.createTempFile();
1470 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1471 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1472 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1473 VerifiedMessage verifiedMessage
= null;
1474 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1475 if (getIdentities().containsKey(record.number
)) {
1476 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1477 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1478 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1479 currentIdentity
= id
;
1482 if (currentIdentity
!= null) {
1483 verifiedMessage
= new VerifiedMessage(record.getAddress(), currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1487 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1488 // TODO store list of blocked numbers
1489 boolean blocked
= false;
1490 out
.write(new DeviceContact(record.getAddress(), Optional
.fromNullable(record.name
),
1491 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1492 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1495 if (account
.getProfileKey() != null) {
1496 // Send our own profile key as well
1497 out
.write(new DeviceContact(account
.getSelfAddress(),
1498 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1499 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1500 Optional
.of(account
.getProfileKey()),
1501 false, Optional
.<Integer
>absent()));
1505 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1506 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1507 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1508 .withStream(contactsFileStream
)
1509 .withContentType("application/octet-stream")
1510 .withLength(contactsFile
.length())
1513 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1518 Files
.delete(contactsFile
.toPath());
1519 } catch (IOException e
) {
1520 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1525 private void sendVerifiedMessage(SignalServiceAddress destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1526 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1527 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1530 public List
<ContactInfo
> getContacts() {
1531 return account
.getContactStore().getContacts();
1534 public ContactInfo
getContact(String number
) {
1535 return account
.getContactStore().getContact(number
);
1538 public GroupInfo
getGroup(byte[] groupId
) {
1539 return account
.getGroupStore().getGroup(groupId
);
1542 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1543 return account
.getSignalProtocolStore().getIdentities();
1546 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1547 return account
.getSignalProtocolStore().getIdentities(number
);
1551 * Trust this the identity with this fingerprint
1553 * @param name username of the identity
1554 * @param fingerprint Fingerprint
1556 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1557 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1561 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1562 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1566 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1568 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1569 } catch (IOException
| UntrustedIdentityException e
) {
1570 e
.printStackTrace();
1579 * Trust this the identity with this safety number
1581 * @param name username of the identity
1582 * @param safetyNumber Safety number
1584 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1585 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1589 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1590 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1594 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1596 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1597 } catch (IOException
| UntrustedIdentityException e
) {
1598 e
.printStackTrace();
1607 * Trust all keys of this identity without verification
1609 * @param name username of the identity
1611 public boolean trustIdentityAllKeys(String name
) {
1612 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1616 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1617 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1618 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1620 sendVerifiedMessage(new SignalServiceAddress(null, name
), id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1621 } catch (IOException
| UntrustedIdentityException e
) {
1622 e
.printStackTrace();
1630 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1631 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1634 public interface ReceiveMessageHandler
{
1636 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);