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 Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
418 File file
= getGroupAvatarFile(groupId
);
419 if (!file
.exists()) {
420 return Optional
.absent();
423 return Optional
.of(Utils
.createAttachment(file
));
426 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
427 File file
= getContactAvatarFile(number
);
428 if (!file
.exists()) {
429 return Optional
.absent();
432 return Optional
.of(Utils
.createAttachment(file
));
435 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
436 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
438 throw new GroupNotFoundException(groupId
);
440 for (String member
: g
.members
) {
441 if (member
.equals(this.username
)) {
445 throw new NotAGroupMemberException(groupId
, g
.name
);
448 public List
<GroupInfo
> getGroups() {
449 return account
.getGroupStore().getGroups();
453 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
455 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
456 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
457 if (attachments
!= null) {
458 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
460 if (groupId
!= null) {
461 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
464 messageBuilder
.asGroupMessage(group
);
466 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
467 if (thread
!= null) {
468 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
471 final GroupInfo g
= getGroupForSending(groupId
);
473 // Don't send group message to ourself
474 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
475 membersSend
.remove(this.username
);
476 sendMessageLegacy(messageBuilder
, membersSend
);
479 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
480 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
484 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
485 .asGroupMessage(group
);
487 final GroupInfo g
= getGroupForSending(groupId
);
488 g
.members
.remove(this.username
);
489 account
.getGroupStore().updateGroup(g
);
491 sendMessageLegacy(messageBuilder
, g
.members
);
494 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
496 if (groupId
== null) {
498 g
= new GroupInfo(KeyUtils
.createGroupId());
499 g
.members
.add(username
);
501 g
= getGroupForSending(groupId
);
508 if (members
!= null) {
509 Set
<String
> newMembers
= new HashSet
<>();
510 for (String member
: members
) {
512 member
= Utils
.canonicalizeNumber(member
, username
);
513 } catch (InvalidNumberException e
) {
514 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
515 System
.err
.println("Aborting…");
518 if (g
.members
.contains(member
)) {
521 newMembers
.add(member
);
522 g
.members
.add(member
);
524 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
525 if (contacts
.size() != newMembers
.size()) {
526 // Some of the new members are not registered on Signal
527 for (ContactTokenDetails contact
: contacts
) {
528 newMembers
.remove(contact
.getNumber());
530 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
531 System
.err
.println("Aborting…");
536 if (avatarFile
!= null) {
537 IOUtils
.createPrivateDirectories(avatarsPath
);
538 File aFile
= getGroupAvatarFile(g
.groupId
);
539 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
542 account
.getGroupStore().updateGroup(g
);
544 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
546 // Don't send group message to ourself
547 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
548 membersSend
.remove(this.username
);
549 sendMessageLegacy(messageBuilder
, membersSend
);
553 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
554 if (groupId
== null) {
557 GroupInfo g
= getGroupForSending(groupId
);
559 if (!g
.members
.contains(recipient
)) {
563 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
565 // Send group message only to the recipient who requested it
566 final List
<String
> membersSend
= new ArrayList
<>();
567 membersSend
.add(recipient
);
568 sendMessageLegacy(messageBuilder
, membersSend
);
571 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
572 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
575 .withMembers(new ArrayList
<>(g
.members
));
577 File aFile
= getGroupAvatarFile(g
.groupId
);
578 if (aFile
.exists()) {
580 group
.withAvatar(Utils
.createAttachment(aFile
));
581 } catch (IOException e
) {
582 throw new AttachmentInvalidException(aFile
.toString(), e
);
586 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
587 .asGroupMessage(group
.build());
589 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
590 if (thread
!= null) {
591 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
594 return messageBuilder
;
597 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
598 if (groupId
== null) {
602 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
605 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
606 .asGroupMessage(group
.build());
608 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
609 if (thread
!= null) {
610 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
613 // Send group info request message to the recipient who sent us a message with this groupId
614 final List
<String
> membersSend
= new ArrayList
<>();
615 membersSend
.add(recipient
);
616 sendMessageLegacy(messageBuilder
, membersSend
);
620 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
621 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
622 List
<String
> recipients
= new ArrayList
<>(1);
623 recipients
.add(recipient
);
624 sendMessage(message
, attachments
, recipients
);
628 public void sendMessage(String messageText
, List
<String
> attachments
,
629 List
<String
> recipients
)
630 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
631 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
632 if (attachments
!= null) {
633 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
635 messageBuilder
.withProfileKey(account
.getProfileKey());
636 sendMessageLegacy(messageBuilder
, recipients
);
640 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
641 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
642 .asEndSessionMessage();
644 sendMessageLegacy(messageBuilder
, recipients
);
648 public String
getContactName(String number
) {
649 ContactInfo contact
= account
.getContactStore().getContact(number
);
650 if (contact
== null) {
658 public void setContactName(String number
, String name
) {
659 ContactInfo contact
= account
.getContactStore().getContact(number
);
660 if (contact
== null) {
661 contact
= new ContactInfo();
662 contact
.number
= number
;
663 System
.err
.println("Add contact " + number
+ " named " + name
);
665 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
668 account
.getContactStore().updateContact(contact
);
673 public List
<byte[]> getGroupIds() {
674 List
<GroupInfo
> groups
= getGroups();
675 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
676 for (GroupInfo group
: groups
) {
677 ids
.add(group
.groupId
);
683 public String
getGroupName(byte[] groupId
) {
684 GroupInfo group
= getGroup(groupId
);
693 public List
<String
> getGroupMembers(byte[] groupId
) {
694 GroupInfo group
= getGroup(groupId
);
696 return new ArrayList
<>();
698 return new ArrayList
<>(group
.members
);
703 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
704 if (groupId
.length
== 0) {
707 if (name
.isEmpty()) {
710 if (members
.size() == 0) {
713 if (avatar
.isEmpty()) {
716 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
720 * Change the expiration timer for a thread (number of groupId)
722 * @param numberOrGroupId
723 * @param messageExpirationTimer
725 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
726 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
727 thread
.messageExpirationTime
= messageExpirationTimer
;
728 account
.getThreadStore().updateThread(thread
);
731 private void requestSyncGroups() throws IOException
{
732 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
733 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
735 sendSyncMessage(message
);
736 } catch (UntrustedIdentityException e
) {
741 private void requestSyncContacts() throws IOException
{
742 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
743 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
745 sendSyncMessage(message
);
746 } catch (UntrustedIdentityException e
) {
751 private void requestSyncBlocked() throws IOException
{
752 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
753 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
755 sendSyncMessage(message
);
756 } catch (UntrustedIdentityException e
) {
761 private void requestSyncConfiguration() throws IOException
{
762 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
763 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
765 sendSyncMessage(message
);
766 } catch (UntrustedIdentityException e
) {
771 private byte[] getSelfUnidentifiedAccessKey() {
772 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
775 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
780 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
782 return Optional
.absent();
785 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
786 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
787 for (SignalServiceAddress recipient
: recipients
) {
788 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
793 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
795 return Optional
.absent();
798 private void sendSyncMessage(SignalServiceSyncMessage message
)
799 throws IOException
, UntrustedIdentityException
{
800 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
801 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
803 messageSender
.sendMessage(message
, getAccessForSync());
804 } catch (UntrustedIdentityException e
) {
805 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
811 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
813 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
814 throws EncapsulatedExceptions
, IOException
{
815 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
817 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
818 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
819 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
821 for (SendMessageResult result
: results
) {
822 if (result
.isUnregisteredFailure()) {
823 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
824 } else if (result
.isNetworkFailure()) {
825 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
826 } else if (result
.getIdentityFailure() != null) {
827 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
830 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
831 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
835 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
837 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
838 if (recipientsTS
== null) {
840 return Collections
.emptyList();
843 SignalServiceDataMessage message
= null;
845 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
846 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
848 message
= messageBuilder
.build();
849 if (message
.getGroupInfo().isPresent()) {
851 final boolean isRecipientUpdate
= false;
852 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
853 for (SendMessageResult r
: result
) {
854 if (r
.getIdentityFailure() != null) {
855 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
859 } catch (UntrustedIdentityException e
) {
860 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
861 return Collections
.emptyList();
863 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(new SignalServiceAddress(username
))) {
864 SignalServiceAddress recipient
= new SignalServiceAddress(username
);
865 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
866 SentTranscriptMessage transcript
= new SentTranscriptMessage(recipient
.getNumber(),
867 message
.getTimestamp(),
869 message
.getExpiresInSeconds(),
870 Collections
.singletonMap(recipient
.getNumber(), unidentifiedAccess
.isPresent()),
872 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
874 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
876 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
877 } catch (UntrustedIdentityException e
) {
878 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
879 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
883 // Send to all individually, so sync messages are sent correctly
884 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
885 for (SignalServiceAddress address
: recipientsTS
) {
886 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
887 if (thread
!= null) {
888 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
890 messageBuilder
.withExpiration(0);
892 message
= messageBuilder
.build();
894 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
896 } catch (UntrustedIdentityException e
) {
897 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
898 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
904 if (message
!= null && message
.isEndSession()) {
905 for (SignalServiceAddress recipient
: recipientsTS
) {
906 handleEndSession(recipient
.getNumber());
913 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
914 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
916 return cipher
.decrypt(envelope
);
917 } catch (ProtocolUntrustedIdentityException e
) {
918 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
919 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
924 private void handleEndSession(String source
) {
925 account
.getSignalProtocolStore().deleteAllSessions(source
);
928 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
930 if (message
.getGroupInfo().isPresent()) {
931 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
932 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
933 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
934 switch (groupInfo
.getType()) {
937 group
= new GroupInfo(groupInfo
.getGroupId());
940 if (groupInfo
.getAvatar().isPresent()) {
941 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
942 if (avatar
.isPointer()) {
944 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
945 } catch (IOException
| InvalidMessageException e
) {
946 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
951 if (groupInfo
.getName().isPresent()) {
952 group
.name
= groupInfo
.getName().get();
955 if (groupInfo
.getMembers().isPresent()) {
956 group
.members
.addAll(groupInfo
.getMembers().get());
959 account
.getGroupStore().updateGroup(group
);
964 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
965 } catch (IOException
| EncapsulatedExceptions e
) {
973 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
974 } catch (IOException
| EncapsulatedExceptions e
) {
978 group
.members
.remove(source
);
979 account
.getGroupStore().updateGroup(group
);
985 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
986 } catch (IOException
| EncapsulatedExceptions e
) {
988 } catch (NotAGroupMemberException e
) {
989 // We have left this group, so don't send a group update message
996 threadId
= destination
;
1001 if (message
.isEndSession()) {
1002 handleEndSession(isSync ? destination
: source
);
1004 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1005 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
1006 if (thread
== null) {
1007 thread
= new ThreadInfo();
1008 thread
.id
= threadId
;
1010 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1011 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1012 account
.getThreadStore().updateThread(thread
);
1015 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1016 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1017 if (attachment
.isPointer()) {
1019 retrieveAttachment(attachment
.asPointer());
1020 } catch (IOException
| InvalidMessageException e
) {
1021 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1026 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
1027 if (source
.equals(username
)) {
1028 this.account
.setProfileKey(message
.getProfileKey().get());
1030 ContactInfo contact
= account
.getContactStore().getContact(source
);
1031 if (contact
== null) {
1032 contact
= new ContactInfo();
1033 contact
.number
= source
;
1035 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
1039 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1040 final File cachePath
= new File(getMessageCachePath());
1041 if (!cachePath
.exists()) {
1044 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
1045 if (!dir
.isDirectory()) {
1049 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1050 if (!fileEntry
.isFile()) {
1053 SignalServiceEnvelope envelope
;
1055 envelope
= Utils
.loadEnvelope(fileEntry
);
1056 if (envelope
== null) {
1059 } catch (IOException e
) {
1060 e
.printStackTrace();
1063 SignalServiceContent content
= null;
1064 if (!envelope
.isReceipt()) {
1066 content
= decryptMessage(envelope
);
1067 } catch (Exception e
) {
1070 handleMessage(envelope
, content
, ignoreAttachments
);
1073 handler
.handleMessage(envelope
, content
, null);
1075 Files
.delete(fileEntry
.toPath());
1076 } catch (IOException e
) {
1077 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1080 // Try to delete directory if empty
1085 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1086 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1087 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1090 if (messagePipe
== null) {
1091 messagePipe
= messageReceiver
.createMessagePipe();
1095 SignalServiceEnvelope envelope
;
1096 SignalServiceContent content
= null;
1097 Exception exception
= null;
1098 final long now
= new Date().getTime();
1100 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1102 public void onMessage(SignalServiceEnvelope envelope
) {
1103 // store message on disk, before acknowledging receipt to the server
1105 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1106 Utils
.storeEnvelope(envelope
, cacheFile
);
1107 } catch (IOException e
) {
1108 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1112 } catch (TimeoutException e
) {
1113 if (returnOnTimeout
)
1116 } catch (InvalidVersionException e
) {
1117 System
.err
.println("Ignoring error: " + e
.getMessage());
1120 if (!envelope
.isReceipt()) {
1122 content
= decryptMessage(envelope
);
1123 } catch (Exception e
) {
1126 handleMessage(envelope
, content
, ignoreAttachments
);
1129 handler
.handleMessage(envelope
, content
, exception
);
1130 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1131 File cacheFile
= null;
1133 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1134 Files
.delete(cacheFile
.toPath());
1135 // Try to delete directory if empty
1136 new File(getMessageCachePath()).delete();
1137 } catch (IOException e
) {
1138 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1143 if (messagePipe
!= null) {
1144 messagePipe
.shutdown();
1150 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1151 if (content
!= null) {
1152 if (content
.getDataMessage().isPresent()) {
1153 SignalServiceDataMessage message
= content
.getDataMessage().get();
1154 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1156 if (content
.getSyncMessage().isPresent()) {
1157 account
.setMultiDevice(true);
1158 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1159 if (syncMessage
.getSent().isPresent()) {
1160 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1161 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1163 if (syncMessage
.getRequest().isPresent()) {
1164 RequestMessage rm
= syncMessage
.getRequest().get();
1165 if (rm
.isContactsRequest()) {
1168 } catch (UntrustedIdentityException
| IOException e
) {
1169 e
.printStackTrace();
1172 if (rm
.isGroupsRequest()) {
1175 } catch (UntrustedIdentityException
| IOException e
) {
1176 e
.printStackTrace();
1179 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1181 if (syncMessage
.getGroups().isPresent()) {
1182 File tmpFile
= null;
1184 tmpFile
= IOUtils
.createTempFile();
1185 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1186 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1188 while ((g
= s
.read()) != null) {
1189 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1190 if (syncGroup
== null) {
1191 syncGroup
= new GroupInfo(g
.getId());
1193 if (g
.getName().isPresent()) {
1194 syncGroup
.name
= g
.getName().get();
1196 syncGroup
.members
.addAll(g
.getMembers());
1197 syncGroup
.active
= g
.isActive();
1198 if (g
.getColor().isPresent()) {
1199 syncGroup
.color
= g
.getColor().get();
1202 if (g
.getAvatar().isPresent()) {
1203 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1205 account
.getGroupStore().updateGroup(syncGroup
);
1208 } catch (Exception e
) {
1209 e
.printStackTrace();
1211 if (tmpFile
!= null) {
1213 Files
.delete(tmpFile
.toPath());
1214 } catch (IOException e
) {
1215 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1220 if (syncMessage
.getBlockedList().isPresent()) {
1221 // TODO store list of blocked numbers
1223 if (syncMessage
.getContacts().isPresent()) {
1224 File tmpFile
= null;
1226 tmpFile
= IOUtils
.createTempFile();
1227 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1228 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1229 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1230 if (contactsMessage
.isComplete()) {
1231 account
.getContactStore().clear();
1234 while ((c
= s
.read()) != null) {
1235 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1236 account
.setProfileKey(c
.getProfileKey().get());
1238 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1239 if (contact
== null) {
1240 contact
= new ContactInfo();
1241 contact
.number
= c
.getNumber();
1243 if (c
.getName().isPresent()) {
1244 contact
.name
= c
.getName().get();
1246 if (c
.getColor().isPresent()) {
1247 contact
.color
= c
.getColor().get();
1249 if (c
.getProfileKey().isPresent()) {
1250 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1252 if (c
.getVerified().isPresent()) {
1253 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1254 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1256 if (c
.getExpirationTimer().isPresent()) {
1257 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1258 if (thread
== null) {
1259 thread
= new ThreadInfo();
1260 thread
.id
= c
.getNumber();
1262 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1263 account
.getThreadStore().updateThread(thread
);
1265 if (c
.isBlocked()) {
1266 // TODO store list of blocked numbers
1268 account
.getContactStore().updateContact(contact
);
1270 if (c
.getAvatar().isPresent()) {
1271 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1275 } catch (Exception e
) {
1276 e
.printStackTrace();
1278 if (tmpFile
!= null) {
1280 Files
.delete(tmpFile
.toPath());
1281 } catch (IOException e
) {
1282 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1287 if (syncMessage
.getVerified().isPresent()) {
1288 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1289 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1291 if (syncMessage
.getConfiguration().isPresent()) {
1298 private File
getContactAvatarFile(String number
) {
1299 return new File(avatarsPath
, "contact-" + number
);
1302 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1303 IOUtils
.createPrivateDirectories(avatarsPath
);
1304 if (attachment
.isPointer()) {
1305 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1306 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1308 SignalServiceAttachmentStream stream
= attachment
.asStream();
1309 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1313 private File
getGroupAvatarFile(byte[] groupId
) {
1314 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1317 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1318 IOUtils
.createPrivateDirectories(avatarsPath
);
1319 if (attachment
.isPointer()) {
1320 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1321 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1323 SignalServiceAttachmentStream stream
= attachment
.asStream();
1324 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1328 public File
getAttachmentFile(long attachmentId
) {
1329 return new File(attachmentsPath
, attachmentId
+ "");
1332 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1333 IOUtils
.createPrivateDirectories(attachmentsPath
);
1334 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1337 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1338 if (storePreview
&& pointer
.getPreview().isPresent()) {
1339 File previewFile
= new File(outputFile
+ ".preview");
1340 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1341 byte[] preview
= pointer
.getPreview().get();
1342 output
.write(preview
, 0, preview
.length
);
1343 } catch (FileNotFoundException e
) {
1344 e
.printStackTrace();
1349 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1351 File tmpFile
= IOUtils
.createTempFile();
1352 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1353 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1354 byte[] buffer
= new byte[4096];
1357 while ((read
= input
.read(buffer
)) != -1) {
1358 output
.write(buffer
, 0, read
);
1360 } catch (FileNotFoundException e
) {
1361 e
.printStackTrace();
1366 Files
.delete(tmpFile
.toPath());
1367 } catch (IOException e
) {
1368 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1374 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1375 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1376 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1380 public boolean isRemote() {
1384 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1385 File groupsFile
= IOUtils
.createTempFile();
1388 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1389 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1390 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1391 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1392 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1393 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1394 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1395 Optional
.fromNullable(record.color
), false));
1399 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1400 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1401 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1402 .withStream(groupsFileStream
)
1403 .withContentType("application/octet-stream")
1404 .withLength(groupsFile
.length())
1407 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1412 Files
.delete(groupsFile
.toPath());
1413 } catch (IOException e
) {
1414 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1419 public void sendContacts() throws IOException
, UntrustedIdentityException
{
1420 File contactsFile
= IOUtils
.createTempFile();
1423 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1424 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1425 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1426 VerifiedMessage verifiedMessage
= null;
1427 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1428 if (getIdentities().containsKey(record.number
)) {
1429 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1430 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1431 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1432 currentIdentity
= id
;
1435 if (currentIdentity
!= null) {
1436 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1440 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1441 // TODO store list of blocked numbers
1442 boolean blocked
= false;
1443 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1444 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1445 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1448 if (account
.getProfileKey() != null) {
1449 // Send our own profile key as well
1450 out
.write(new DeviceContact(account
.getUsername(),
1451 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1452 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1453 Optional
.of(account
.getProfileKey()),
1454 false, Optional
.<Integer
>absent()));
1458 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1459 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1460 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1461 .withStream(contactsFileStream
)
1462 .withContentType("application/octet-stream")
1463 .withLength(contactsFile
.length())
1466 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1471 Files
.delete(contactsFile
.toPath());
1472 } catch (IOException e
) {
1473 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1478 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1479 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1480 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1483 public ContactInfo
getContact(String number
) {
1484 return account
.getContactStore().getContact(number
);
1487 public GroupInfo
getGroup(byte[] groupId
) {
1488 return account
.getGroupStore().getGroup(groupId
);
1491 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1492 return account
.getSignalProtocolStore().getIdentities();
1495 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1496 return account
.getSignalProtocolStore().getIdentities(number
);
1500 * Trust this the identity with this fingerprint
1502 * @param name username of the identity
1503 * @param fingerprint Fingerprint
1505 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1506 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1510 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1511 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1515 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1517 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1518 } catch (IOException
| UntrustedIdentityException e
) {
1519 e
.printStackTrace();
1528 * Trust this the identity with this safety number
1530 * @param name username of the identity
1531 * @param safetyNumber Safety number
1533 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1534 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1538 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1539 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1543 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1545 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1546 } catch (IOException
| UntrustedIdentityException e
) {
1547 e
.printStackTrace();
1556 * Trust all keys of this identity without verification
1558 * @param name username of the identity
1560 public boolean trustIdentityAllKeys(String name
) {
1561 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1565 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1566 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1567 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1569 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1570 } catch (IOException
| UntrustedIdentityException e
) {
1571 e
.printStackTrace();
1579 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1580 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1583 public interface ReceiveMessageHandler
{
1585 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);