2 Copyright (C) 2015-2018 AsamK
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
.signalservice
.internal
.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 IdentityKey
getIdentity() {
153 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
156 public int getDeviceId() {
157 return account
.getDeviceId();
160 private String
getMessageCachePath() {
161 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
164 private String
getMessageCachePath(String sender
) {
165 return getMessageCachePath() + "/" + sender
.replace("/", "_");
168 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
169 String cachePath
= getMessageCachePath(sender
);
170 IOUtils
.createPrivateDirectories(cachePath
);
171 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
174 public boolean userHasKeys() {
175 return account
!= null && account
.getSignalProtocolStore() != null;
178 public void init() throws IOException
{
179 if (!SignalAccount
.userExists(dataPath
, username
)) {
182 account
= SignalAccount
.load(dataPath
, username
);
184 migrateLegacyConfigs();
186 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
188 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
192 } catch (AuthorizationFailedException e
) {
193 System
.err
.println("Authorization failed, was the number registered elsewhere?");
198 private void migrateLegacyConfigs() {
199 // Copy group avatars that were previously stored in the attachments folder
200 // to the new avatar folder
201 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
202 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
203 File avatarFile
= getGroupAvatarFile(g
.groupId
);
204 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
205 if (!avatarFile
.exists() && attachmentFile
.exists()) {
207 IOUtils
.createPrivateDirectories(avatarsPath
);
208 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
209 } catch (Exception e
) {
214 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
217 if (account
.getProfileKey() == null) {
218 // Old config file, creating new profile key
219 account
.setProfileKey(KeyUtils
.createProfileKey());
224 private void createNewIdentity() throws IOException
{
225 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
226 int registrationId
= KeyHelper
.generateRegistrationId(false);
227 if (username
== null) {
228 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
230 byte[] profileKey
= KeyUtils
.createProfileKey();
231 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
236 public boolean isRegistered() {
237 return account
!= null && account
.isRegistered();
240 public void register(boolean voiceVerification
) throws IOException
{
241 if (account
== null) {
244 account
.setPassword(KeyUtils
.createPassword());
245 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, account
.getUsername(), account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
247 if (voiceVerification
) {
248 accountManager
.requestVoiceVerificationCode(Locale
.getDefault(), Optional
.<String
>absent(), Optional
.<String
>absent());
250 accountManager
.requestSmsVerificationCode(false, Optional
.<String
>absent(), Optional
.<String
>absent());
253 account
.setRegistered(false);
257 public void updateAccountAttributes() throws IOException
{
258 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
261 public void setProfileName(String name
) throws IOException
{
262 accountManager
.setProfileName(account
.getProfileKey(), name
);
265 public void setProfileAvatar(File avatar
) throws IOException
{
266 final StreamDetails streamDetails
= Utils
.createStreamDetailsFromFile(avatar
);
267 accountManager
.setProfileAvatar(account
.getProfileKey(), streamDetails
);
268 streamDetails
.getStream().close();
271 public void removeProfileAvatar() throws IOException
{
272 accountManager
.setProfileAvatar(account
.getProfileKey(), null);
275 public void unregister() throws IOException
{
276 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
277 // If this is the master device, other users can't send messages to this number anymore.
278 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
279 accountManager
.setGcmId(Optional
.<String
>absent());
281 account
.setRegistered(false);
285 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
286 if (account
== null) {
289 account
.setPassword(KeyUtils
.createPassword());
290 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
291 String uuid
= accountManager
.getNewDeviceUuid();
293 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
296 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
297 account
.setSignalingKey(KeyUtils
.createSignalingKey());
298 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
300 username
= ret
.getNumber();
301 // TODO do this check before actually registering
302 if (SignalAccount
.userExists(dataPath
, username
)) {
303 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
306 // Create new account with the synced identity
307 byte[] profileKey
= ret
.getProfileKey();
308 if (profileKey
== null) {
309 profileKey
= KeyUtils
.createProfileKey();
311 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
316 requestSyncContacts();
317 requestSyncBlocked();
318 requestSyncConfiguration();
323 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
324 List
<DeviceInfo
> devices
= accountManager
.getDevices();
325 account
.setMultiDevice(devices
.size() > 1);
330 public void removeLinkedDevices(int deviceId
) throws IOException
{
331 accountManager
.removeDevice(deviceId
);
332 List
<DeviceInfo
> devices
= accountManager
.getDevices();
333 account
.setMultiDevice(devices
.size() > 1);
337 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
338 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
340 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
343 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
344 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
345 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
347 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
348 account
.setMultiDevice(true);
352 private List
<PreKeyRecord
> generatePreKeys() {
353 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
355 final int offset
= account
.getPreKeyIdOffset();
356 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
357 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
358 ECKeyPair keyPair
= Curve
.generateKeyPair();
359 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
364 account
.addPreKeys(records
);
370 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
372 ECKeyPair keyPair
= Curve
.generateKeyPair();
373 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
374 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
376 account
.addSignedPreKey(record);
380 } catch (InvalidKeyException e
) {
381 throw new AssertionError(e
);
385 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
386 verificationCode
= verificationCode
.replace("-", "");
387 account
.setSignalingKey(KeyUtils
.createSignalingKey());
388 // TODO make unrestricted unidentified access configurable
389 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
391 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
392 account
.setRegistered(true);
393 account
.setRegistrationLockPin(pin
);
399 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
400 accountManager
.setPin(pin
);
401 if (pin
.isPresent()) {
402 account
.setRegistrationLockPin(pin
.get());
404 account
.setRegistrationLockPin(null);
409 private void refreshPreKeys() throws IOException
{
410 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
411 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
412 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
414 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
417 private SignalServiceMessageReceiver
getMessageReceiver() {
418 return new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
421 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
422 File file
= getGroupAvatarFile(groupId
);
423 if (!file
.exists()) {
424 return Optional
.absent();
427 return Optional
.of(Utils
.createAttachment(file
));
430 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
431 File file
= getContactAvatarFile(number
);
432 if (!file
.exists()) {
433 return Optional
.absent();
436 return Optional
.of(Utils
.createAttachment(file
));
439 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
440 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
442 throw new GroupNotFoundException(groupId
);
444 for (String member
: g
.members
) {
445 if (member
.equals(this.username
)) {
449 throw new NotAGroupMemberException(groupId
, g
.name
);
452 public List
<GroupInfo
> getGroups() {
453 return account
.getGroupStore().getGroups();
457 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
459 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
460 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
461 if (attachments
!= null) {
462 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
464 if (groupId
!= null) {
465 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
468 messageBuilder
.asGroupMessage(group
);
470 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
471 if (thread
!= null) {
472 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
475 final GroupInfo g
= getGroupForSending(groupId
);
477 // Don't send group message to ourself
478 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
479 membersSend
.remove(this.username
);
480 sendMessageLegacy(messageBuilder
, membersSend
);
483 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
484 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
488 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
489 .asGroupMessage(group
);
491 final GroupInfo g
= getGroupForSending(groupId
);
492 g
.members
.remove(this.username
);
493 account
.getGroupStore().updateGroup(g
);
495 sendMessageLegacy(messageBuilder
, g
.members
);
498 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
500 if (groupId
== null) {
502 g
= new GroupInfo(KeyUtils
.createGroupId());
503 g
.members
.add(username
);
505 g
= getGroupForSending(groupId
);
512 if (members
!= null) {
513 Set
<String
> newMembers
= new HashSet
<>();
514 for (String member
: members
) {
516 member
= Utils
.canonicalizeNumber(member
, username
);
517 } catch (InvalidNumberException e
) {
518 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
519 System
.err
.println("Aborting…");
522 if (g
.members
.contains(member
)) {
525 newMembers
.add(member
);
526 g
.members
.add(member
);
528 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
529 if (contacts
.size() != newMembers
.size()) {
530 // Some of the new members are not registered on Signal
531 for (ContactTokenDetails contact
: contacts
) {
532 newMembers
.remove(contact
.getNumber());
534 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
535 System
.err
.println("Aborting…");
540 if (avatarFile
!= null) {
541 IOUtils
.createPrivateDirectories(avatarsPath
);
542 File aFile
= getGroupAvatarFile(g
.groupId
);
543 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
546 account
.getGroupStore().updateGroup(g
);
548 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
550 // Don't send group message to ourself
551 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
552 membersSend
.remove(this.username
);
553 sendMessageLegacy(messageBuilder
, membersSend
);
557 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
558 if (groupId
== null) {
561 GroupInfo g
= getGroupForSending(groupId
);
563 if (!g
.members
.contains(recipient
)) {
567 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
569 // Send group message only to the recipient who requested it
570 final List
<String
> membersSend
= new ArrayList
<>();
571 membersSend
.add(recipient
);
572 sendMessageLegacy(messageBuilder
, membersSend
);
575 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
576 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
579 .withMembers(new ArrayList
<>(g
.members
));
581 File aFile
= getGroupAvatarFile(g
.groupId
);
582 if (aFile
.exists()) {
584 group
.withAvatar(Utils
.createAttachment(aFile
));
585 } catch (IOException e
) {
586 throw new AttachmentInvalidException(aFile
.toString(), e
);
590 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
591 .asGroupMessage(group
.build());
593 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
594 if (thread
!= null) {
595 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
598 return messageBuilder
;
601 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
602 if (groupId
== null) {
606 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
609 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
610 .asGroupMessage(group
.build());
612 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
613 if (thread
!= null) {
614 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
617 // Send group info request message to the recipient who sent us a message with this groupId
618 final List
<String
> membersSend
= new ArrayList
<>();
619 membersSend
.add(recipient
);
620 sendMessageLegacy(messageBuilder
, membersSend
);
624 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
625 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
626 List
<String
> recipients
= new ArrayList
<>(1);
627 recipients
.add(recipient
);
628 sendMessage(message
, attachments
, recipients
);
632 public void sendMessage(String messageText
, List
<String
> attachments
,
633 List
<String
> recipients
)
634 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
635 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
636 if (attachments
!= null) {
637 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
639 messageBuilder
.withProfileKey(account
.getProfileKey());
640 sendMessageLegacy(messageBuilder
, recipients
);
644 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
645 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
646 .asEndSessionMessage();
648 sendMessageLegacy(messageBuilder
, recipients
);
652 public String
getContactName(String number
) {
653 ContactInfo contact
= account
.getContactStore().getContact(number
);
654 if (contact
== null) {
662 public void setContactName(String number
, String name
) {
663 ContactInfo contact
= account
.getContactStore().getContact(number
);
664 if (contact
== null) {
665 contact
= new ContactInfo();
666 contact
.number
= number
;
667 System
.err
.println("Add contact " + number
+ " named " + name
);
669 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
672 account
.getContactStore().updateContact(contact
);
677 public List
<byte[]> getGroupIds() {
678 List
<GroupInfo
> groups
= getGroups();
679 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
680 for (GroupInfo group
: groups
) {
681 ids
.add(group
.groupId
);
687 public String
getGroupName(byte[] groupId
) {
688 GroupInfo group
= getGroup(groupId
);
697 public List
<String
> getGroupMembers(byte[] groupId
) {
698 GroupInfo group
= getGroup(groupId
);
700 return new ArrayList
<>();
702 return new ArrayList
<>(group
.members
);
707 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
708 if (groupId
.length
== 0) {
711 if (name
.isEmpty()) {
714 if (members
.size() == 0) {
717 if (avatar
.isEmpty()) {
720 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
724 * Change the expiration timer for a thread (number of groupId)
726 * @param numberOrGroupId
727 * @param messageExpirationTimer
729 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
730 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
731 thread
.messageExpirationTime
= messageExpirationTimer
;
732 account
.getThreadStore().updateThread(thread
);
735 private void requestSyncGroups() throws IOException
{
736 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
737 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
739 sendSyncMessage(message
);
740 } catch (UntrustedIdentityException e
) {
745 private void requestSyncContacts() throws IOException
{
746 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
747 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
749 sendSyncMessage(message
);
750 } catch (UntrustedIdentityException e
) {
755 private void requestSyncBlocked() throws IOException
{
756 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
757 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
759 sendSyncMessage(message
);
760 } catch (UntrustedIdentityException e
) {
765 private void requestSyncConfiguration() throws IOException
{
766 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
767 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
769 sendSyncMessage(message
);
770 } catch (UntrustedIdentityException e
) {
775 private byte[] getSelfUnidentifiedAccessKey() {
776 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
779 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
784 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
786 return Optional
.absent();
789 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
790 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
791 for (SignalServiceAddress recipient
: recipients
) {
792 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
797 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
799 return Optional
.absent();
802 private void sendSyncMessage(SignalServiceSyncMessage message
)
803 throws IOException
, UntrustedIdentityException
{
804 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
805 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
807 messageSender
.sendMessage(message
, getAccessForSync());
808 } catch (UntrustedIdentityException e
) {
809 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
815 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
817 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
818 throws EncapsulatedExceptions
, IOException
{
819 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
821 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
822 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
823 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
825 for (SendMessageResult result
: results
) {
826 if (result
.isUnregisteredFailure()) {
827 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
828 } else if (result
.isNetworkFailure()) {
829 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
830 } else if (result
.getIdentityFailure() != null) {
831 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
834 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
835 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
839 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
841 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
842 if (recipientsTS
== null) {
844 return Collections
.emptyList();
847 SignalServiceDataMessage message
= null;
849 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
850 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
852 message
= messageBuilder
.build();
853 if (message
.getGroupInfo().isPresent()) {
855 final boolean isRecipientUpdate
= false;
856 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
857 for (SendMessageResult r
: result
) {
858 if (r
.getIdentityFailure() != null) {
859 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
863 } catch (UntrustedIdentityException e
) {
864 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
865 return Collections
.emptyList();
867 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(new SignalServiceAddress(username
))) {
868 SignalServiceAddress recipient
= new SignalServiceAddress(username
);
869 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
870 SentTranscriptMessage transcript
= new SentTranscriptMessage(recipient
.getNumber(),
871 message
.getTimestamp(),
873 message
.getExpiresInSeconds(),
874 Collections
.singletonMap(recipient
.getNumber(), unidentifiedAccess
.isPresent()),
876 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
878 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
880 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
881 } catch (UntrustedIdentityException e
) {
882 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
883 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
887 // Send to all individually, so sync messages are sent correctly
888 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
889 for (SignalServiceAddress address
: recipientsTS
) {
890 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
891 if (thread
!= null) {
892 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
894 messageBuilder
.withExpiration(0);
896 message
= messageBuilder
.build();
898 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
900 } catch (UntrustedIdentityException e
) {
901 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
902 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
908 if (message
!= null && message
.isEndSession()) {
909 for (SignalServiceAddress recipient
: recipientsTS
) {
910 handleEndSession(recipient
.getNumber());
917 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
918 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
920 return cipher
.decrypt(envelope
);
921 } catch (ProtocolUntrustedIdentityException e
) {
922 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
923 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
928 private void handleEndSession(String source
) {
929 account
.getSignalProtocolStore().deleteAllSessions(source
);
932 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
934 if (message
.getGroupInfo().isPresent()) {
935 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
936 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
937 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
938 switch (groupInfo
.getType()) {
941 group
= new GroupInfo(groupInfo
.getGroupId());
944 if (groupInfo
.getAvatar().isPresent()) {
945 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
946 if (avatar
.isPointer()) {
948 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
949 } catch (IOException
| InvalidMessageException e
) {
950 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
955 if (groupInfo
.getName().isPresent()) {
956 group
.name
= groupInfo
.getName().get();
959 if (groupInfo
.getMembers().isPresent()) {
960 group
.members
.addAll(groupInfo
.getMembers().get());
963 account
.getGroupStore().updateGroup(group
);
968 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
969 } catch (IOException
| EncapsulatedExceptions e
) {
977 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
978 } catch (IOException
| EncapsulatedExceptions e
) {
982 group
.members
.remove(source
);
983 account
.getGroupStore().updateGroup(group
);
989 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
990 } catch (IOException
| EncapsulatedExceptions e
) {
992 } catch (NotAGroupMemberException e
) {
993 // We have left this group, so don't send a group update message
1000 threadId
= destination
;
1005 if (message
.isEndSession()) {
1006 handleEndSession(isSync ? destination
: source
);
1008 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1009 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
1010 if (thread
== null) {
1011 thread
= new ThreadInfo();
1012 thread
.id
= threadId
;
1014 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1015 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1016 account
.getThreadStore().updateThread(thread
);
1019 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1020 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1021 if (attachment
.isPointer()) {
1023 retrieveAttachment(attachment
.asPointer());
1024 } catch (IOException
| InvalidMessageException e
) {
1025 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1030 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1031 if (source
.equals(username
)) {
1032 this.account
.setProfileKey(message
.getProfileKey().get());
1034 ContactInfo contact
= account
.getContactStore().getContact(source
);
1035 if (contact
== null) {
1036 contact
= new ContactInfo();
1037 contact
.number
= source
;
1039 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
1043 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1044 final File cachePath
= new File(getMessageCachePath());
1045 if (!cachePath
.exists()) {
1048 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
1049 if (!dir
.isDirectory()) {
1053 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1054 if (!fileEntry
.isFile()) {
1057 SignalServiceEnvelope envelope
;
1059 envelope
= Utils
.loadEnvelope(fileEntry
);
1060 if (envelope
== null) {
1063 } catch (IOException e
) {
1064 e
.printStackTrace();
1067 SignalServiceContent content
= null;
1068 if (!envelope
.isReceipt()) {
1070 content
= decryptMessage(envelope
);
1071 } catch (Exception e
) {
1074 handleMessage(envelope
, content
, ignoreAttachments
);
1077 handler
.handleMessage(envelope
, content
, null);
1079 Files
.delete(fileEntry
.toPath());
1080 } catch (IOException e
) {
1081 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1084 // Try to delete directory if empty
1089 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1090 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1091 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1094 if (messagePipe
== null) {
1095 messagePipe
= messageReceiver
.createMessagePipe();
1099 SignalServiceEnvelope envelope
;
1100 SignalServiceContent content
= null;
1101 Exception exception
= null;
1102 final long now
= new Date().getTime();
1104 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1106 public void onMessage(SignalServiceEnvelope envelope
) {
1107 // store message on disk, before acknowledging receipt to the server
1109 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1110 Utils
.storeEnvelope(envelope
, cacheFile
);
1111 } catch (IOException e
) {
1112 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1116 } catch (TimeoutException e
) {
1117 if (returnOnTimeout
)
1120 } catch (InvalidVersionException e
) {
1121 System
.err
.println("Ignoring error: " + e
.getMessage());
1124 if (!envelope
.isReceipt()) {
1126 content
= decryptMessage(envelope
);
1127 } catch (Exception e
) {
1130 handleMessage(envelope
, content
, ignoreAttachments
);
1133 handler
.handleMessage(envelope
, content
, exception
);
1134 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1135 File cacheFile
= null;
1137 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1138 Files
.delete(cacheFile
.toPath());
1139 // Try to delete directory if empty
1140 new File(getMessageCachePath()).delete();
1141 } catch (IOException e
) {
1142 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1147 if (messagePipe
!= null) {
1148 messagePipe
.shutdown();
1154 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1155 if (content
!= null) {
1156 if (content
.getDataMessage().isPresent()) {
1157 SignalServiceDataMessage message
= content
.getDataMessage().get();
1158 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1160 if (content
.getSyncMessage().isPresent()) {
1161 account
.setMultiDevice(true);
1162 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1163 if (syncMessage
.getSent().isPresent()) {
1164 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1165 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1167 if (syncMessage
.getRequest().isPresent()) {
1168 RequestMessage rm
= syncMessage
.getRequest().get();
1169 if (rm
.isContactsRequest()) {
1172 } catch (UntrustedIdentityException
| IOException e
) {
1173 e
.printStackTrace();
1176 if (rm
.isGroupsRequest()) {
1179 } catch (UntrustedIdentityException
| IOException e
) {
1180 e
.printStackTrace();
1183 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1185 if (syncMessage
.getGroups().isPresent()) {
1186 File tmpFile
= null;
1188 tmpFile
= IOUtils
.createTempFile();
1189 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1190 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1192 while ((g
= s
.read()) != null) {
1193 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1194 if (syncGroup
== null) {
1195 syncGroup
= new GroupInfo(g
.getId());
1197 if (g
.getName().isPresent()) {
1198 syncGroup
.name
= g
.getName().get();
1200 syncGroup
.members
.addAll(g
.getMembers());
1201 syncGroup
.active
= g
.isActive();
1202 if (g
.getColor().isPresent()) {
1203 syncGroup
.color
= g
.getColor().get();
1206 if (g
.getAvatar().isPresent()) {
1207 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1209 account
.getGroupStore().updateGroup(syncGroup
);
1212 } catch (Exception e
) {
1213 e
.printStackTrace();
1215 if (tmpFile
!= null) {
1217 Files
.delete(tmpFile
.toPath());
1218 } catch (IOException e
) {
1219 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1224 if (syncMessage
.getBlockedList().isPresent()) {
1225 // TODO store list of blocked numbers
1227 if (syncMessage
.getContacts().isPresent()) {
1228 File tmpFile
= null;
1230 tmpFile
= IOUtils
.createTempFile();
1231 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1232 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1233 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1234 if (contactsMessage
.isComplete()) {
1235 account
.getContactStore().clear();
1238 while ((c
= s
.read()) != null) {
1239 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1240 account
.setProfileKey(c
.getProfileKey().get());
1242 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1243 if (contact
== null) {
1244 contact
= new ContactInfo();
1245 contact
.number
= c
.getNumber();
1247 if (c
.getName().isPresent()) {
1248 contact
.name
= c
.getName().get();
1250 if (c
.getColor().isPresent()) {
1251 contact
.color
= c
.getColor().get();
1253 if (c
.getProfileKey().isPresent()) {
1254 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1256 if (c
.getVerified().isPresent()) {
1257 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1258 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1260 if (c
.getExpirationTimer().isPresent()) {
1261 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1262 if (thread
== null) {
1263 thread
= new ThreadInfo();
1264 thread
.id
= c
.getNumber();
1266 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1267 account
.getThreadStore().updateThread(thread
);
1269 if (c
.isBlocked()) {
1270 // TODO store list of blocked numbers
1272 account
.getContactStore().updateContact(contact
);
1274 if (c
.getAvatar().isPresent()) {
1275 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1279 } catch (Exception e
) {
1280 e
.printStackTrace();
1282 if (tmpFile
!= null) {
1284 Files
.delete(tmpFile
.toPath());
1285 } catch (IOException e
) {
1286 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1291 if (syncMessage
.getVerified().isPresent()) {
1292 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1293 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1295 if (syncMessage
.getConfiguration().isPresent()) {
1302 private File
getContactAvatarFile(String number
) {
1303 return new File(avatarsPath
, "contact-" + number
);
1306 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1307 IOUtils
.createPrivateDirectories(avatarsPath
);
1308 if (attachment
.isPointer()) {
1309 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1310 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1312 SignalServiceAttachmentStream stream
= attachment
.asStream();
1313 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1317 private File
getGroupAvatarFile(byte[] groupId
) {
1318 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1321 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1322 IOUtils
.createPrivateDirectories(avatarsPath
);
1323 if (attachment
.isPointer()) {
1324 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1325 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1327 SignalServiceAttachmentStream stream
= attachment
.asStream();
1328 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1332 public File
getAttachmentFile(long attachmentId
) {
1333 return new File(attachmentsPath
, attachmentId
+ "");
1336 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1337 IOUtils
.createPrivateDirectories(attachmentsPath
);
1338 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1341 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1342 if (storePreview
&& pointer
.getPreview().isPresent()) {
1343 File previewFile
= new File(outputFile
+ ".preview");
1344 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1345 byte[] preview
= pointer
.getPreview().get();
1346 output
.write(preview
, 0, preview
.length
);
1347 } catch (FileNotFoundException e
) {
1348 e
.printStackTrace();
1353 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1355 File tmpFile
= IOUtils
.createTempFile();
1356 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1357 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1358 byte[] buffer
= new byte[4096];
1361 while ((read
= input
.read(buffer
)) != -1) {
1362 output
.write(buffer
, 0, read
);
1364 } catch (FileNotFoundException e
) {
1365 e
.printStackTrace();
1370 Files
.delete(tmpFile
.toPath());
1371 } catch (IOException e
) {
1372 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1378 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1379 final SignalServiceMessageReceiver messageReceiver
= getMessageReceiver();
1380 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1384 public boolean isRemote() {
1388 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1389 File groupsFile
= IOUtils
.createTempFile();
1392 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1393 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1394 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1395 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1396 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1397 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1398 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1399 Optional
.fromNullable(record.color
), false));
1403 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1404 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1405 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1406 .withStream(groupsFileStream
)
1407 .withContentType("application/octet-stream")
1408 .withLength(groupsFile
.length())
1411 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1416 Files
.delete(groupsFile
.toPath());
1417 } catch (IOException e
) {
1418 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1423 public void sendContacts() throws IOException
, UntrustedIdentityException
{
1424 File contactsFile
= IOUtils
.createTempFile();
1427 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1428 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1429 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1430 VerifiedMessage verifiedMessage
= null;
1431 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1432 if (getIdentities().containsKey(record.number
)) {
1433 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1434 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1435 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1436 currentIdentity
= id
;
1439 if (currentIdentity
!= null) {
1440 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1444 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1445 // TODO store list of blocked numbers
1446 boolean blocked
= false;
1447 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1448 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1449 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1452 if (account
.getProfileKey() != null) {
1453 // Send our own profile key as well
1454 out
.write(new DeviceContact(account
.getUsername(),
1455 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1456 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1457 Optional
.of(account
.getProfileKey()),
1458 false, Optional
.<Integer
>absent()));
1462 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1463 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1464 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1465 .withStream(contactsFileStream
)
1466 .withContentType("application/octet-stream")
1467 .withLength(contactsFile
.length())
1470 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1475 Files
.delete(contactsFile
.toPath());
1476 } catch (IOException e
) {
1477 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1482 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1483 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1484 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1487 public List
<ContactInfo
> getContacts() {
1488 return account
.getContactStore().getContacts();
1491 public ContactInfo
getContact(String number
) {
1492 return account
.getContactStore().getContact(number
);
1495 public GroupInfo
getGroup(byte[] groupId
) {
1496 return account
.getGroupStore().getGroup(groupId
);
1499 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1500 return account
.getSignalProtocolStore().getIdentities();
1503 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1504 return account
.getSignalProtocolStore().getIdentities(number
);
1508 * Trust this the identity with this fingerprint
1510 * @param name username of the identity
1511 * @param fingerprint Fingerprint
1513 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1514 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1518 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1519 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1523 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1525 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1526 } catch (IOException
| UntrustedIdentityException e
) {
1527 e
.printStackTrace();
1536 * Trust this the identity with this safety number
1538 * @param name username of the identity
1539 * @param safetyNumber Safety number
1541 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1542 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1546 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1547 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1551 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1553 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1554 } catch (IOException
| UntrustedIdentityException e
) {
1555 e
.printStackTrace();
1564 * Trust all keys of this identity without verification
1566 * @param name username of the identity
1568 public boolean trustIdentityAllKeys(String name
) {
1569 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1573 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1574 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1575 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1577 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1578 } catch (IOException
| UntrustedIdentityException e
) {
1579 e
.printStackTrace();
1587 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1588 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1591 public interface ReceiveMessageHandler
{
1593 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);