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
.*;
21 import org
.asamk
.signal
.storage
.SignalAccount
;
22 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
23 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
24 import org
.asamk
.signal
.storage
.groups
.JsonGroupStore
;
25 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
26 import org
.asamk
.signal
.storage
.threads
.ThreadInfo
;
27 import org
.asamk
.signal
.util
.IOUtils
;
28 import org
.asamk
.signal
.util
.Util
;
29 import org
.signal
.libsignal
.metadata
.*;
30 import org
.whispersystems
.libsignal
.*;
31 import org
.whispersystems
.libsignal
.ecc
.Curve
;
32 import org
.whispersystems
.libsignal
.ecc
.ECKeyPair
;
33 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
34 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
35 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
36 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
37 import org
.whispersystems
.libsignal
.util
.Medium
;
38 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
39 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
40 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
41 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
42 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
43 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
44 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
45 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
46 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
47 import org
.whispersystems
.signalservice
.api
.messages
.*;
48 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
49 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
50 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
51 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
52 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
53 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
54 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
55 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
56 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
57 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
58 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
59 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
63 import java
.nio
.file
.Files
;
64 import java
.nio
.file
.Paths
;
65 import java
.nio
.file
.StandardCopyOption
;
67 import java
.util
.concurrent
.TimeUnit
;
68 import java
.util
.concurrent
.TimeoutException
;
70 public class Manager
implements Signal
{
72 private final String settingsPath
;
73 private final String dataPath
;
74 private final String attachmentsPath
;
75 private final String avatarsPath
;
77 private SignalAccount account
;
79 private String username
;
80 private SignalServiceAccountManager accountManager
;
81 private SignalServiceMessagePipe messagePipe
= null;
82 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
84 private SleepTimer timer
= new UptimeSleepTimer();
86 public Manager(String username
, String settingsPath
) {
87 this.username
= username
;
88 this.settingsPath
= settingsPath
;
89 this.dataPath
= this.settingsPath
+ "/data";
90 this.attachmentsPath
= this.settingsPath
+ "/attachments";
91 this.avatarsPath
= this.settingsPath
+ "/avatars";
95 public String
getUsername() {
99 private IdentityKey
getIdentity() {
100 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
103 public int getDeviceId() {
104 return account
.getDeviceId();
107 private String
getMessageCachePath() {
108 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
111 private String
getMessageCachePath(String sender
) {
112 return getMessageCachePath() + "/" + sender
.replace("/", "_");
115 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
116 String cachePath
= getMessageCachePath(sender
);
117 IOUtils
.createPrivateDirectories(cachePath
);
118 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
121 public boolean userHasKeys() {
122 return account
!= null && account
.getSignalProtocolStore() != null;
125 public void init() throws IOException
{
126 if (!SignalAccount
.userExists(dataPath
, username
)) {
129 account
= SignalAccount
.load(dataPath
, username
);
131 migrateLegacyConfigs();
133 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
135 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
139 } catch (AuthorizationFailedException e
) {
140 System
.err
.println("Authorization failed, was the number registered elsewhere?");
144 private void migrateLegacyConfigs() {
145 // Copy group avatars that were previously stored in the attachments folder
146 // to the new avatar folder
147 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
148 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
149 File avatarFile
= getGroupAvatarFile(g
.groupId
);
150 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
151 if (!avatarFile
.exists() && attachmentFile
.exists()) {
153 IOUtils
.createPrivateDirectories(avatarsPath
);
154 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
155 } catch (Exception e
) {
160 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
163 if (account
.getProfileKey() == null) {
164 // Old config file, creating new profile key
165 account
.setProfileKey(KeyUtils
.createProfileKey());
169 private void createNewIdentity() throws IOException
{
170 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
171 int registrationId
= KeyHelper
.generateRegistrationId(false);
172 if (username
== null) {
173 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
175 byte[] profileKey
= KeyUtils
.createProfileKey();
176 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
181 public boolean isRegistered() {
182 return account
!= null && account
.isRegistered();
185 public void register(boolean voiceVerification
) throws IOException
{
186 if (account
== null) {
189 account
.setPassword(KeyUtils
.createPassword());
190 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, account
.getUsername(), account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
192 if (voiceVerification
)
193 accountManager
.requestVoiceVerificationCode();
195 accountManager
.requestSmsVerificationCode();
197 account
.setRegistered(false);
201 public void updateAccountAttributes() throws IOException
{
202 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
205 public void unregister() throws IOException
{
206 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
207 // If this is the master device, other users can't send messages to this number anymore.
208 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
209 accountManager
.setGcmId(Optional
.<String
>absent());
212 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
213 if (account
== null) {
216 account
.setPassword(KeyUtils
.createPassword());
217 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
218 String uuid
= accountManager
.getNewDeviceUuid();
220 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
223 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
224 account
.setSignalingKey(KeyUtils
.createSignalingKey());
225 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
227 username
= ret
.getNumber();
228 // TODO do this check before actually registering
229 if (SignalAccount
.userExists(dataPath
, username
)) {
230 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
233 // Create new account with the synced identity
234 byte[] profileKey
= ret
.getProfileKey();
235 if (profileKey
== null) {
236 profileKey
= KeyUtils
.createProfileKey();
238 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
243 requestSyncContacts();
244 requestSyncBlocked();
245 requestSyncConfiguration();
250 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
251 List
<DeviceInfo
> devices
= accountManager
.getDevices();
252 account
.setMultiDevice(devices
.size() > 1);
256 public void removeLinkedDevices(int deviceId
) throws IOException
{
257 accountManager
.removeDevice(deviceId
);
260 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
261 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
263 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
266 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
267 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
268 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
270 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
271 account
.setMultiDevice(true);
274 private List
<PreKeyRecord
> generatePreKeys() {
275 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
277 final int offset
= account
.getPreKeyIdOffset();
278 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
279 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
280 ECKeyPair keyPair
= Curve
.generateKeyPair();
281 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
286 account
.addPreKeys(records
);
292 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
294 ECKeyPair keyPair
= Curve
.generateKeyPair();
295 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
296 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
298 account
.addSignedPreKey(record);
302 } catch (InvalidKeyException e
) {
303 throw new AssertionError(e
);
307 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
308 verificationCode
= verificationCode
.replace("-", "");
309 account
.setSignalingKey(KeyUtils
.createSignalingKey());
310 // TODO make unrestricted unidentified access configurable
311 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
313 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
314 account
.setRegistered(true);
315 account
.setRegistrationLockPin(pin
);
321 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
322 accountManager
.setPin(pin
);
323 if (pin
.isPresent()) {
324 account
.setRegistrationLockPin(pin
.get());
326 account
.setRegistrationLockPin(null);
331 private void refreshPreKeys() throws IOException
{
332 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
333 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
334 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
336 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
339 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
340 File file
= getGroupAvatarFile(groupId
);
341 if (!file
.exists()) {
342 return Optional
.absent();
345 return Optional
.of(Utils
.createAttachment(file
));
348 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
349 File file
= getContactAvatarFile(number
);
350 if (!file
.exists()) {
351 return Optional
.absent();
354 return Optional
.of(Utils
.createAttachment(file
));
357 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
358 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
360 throw new GroupNotFoundException(groupId
);
362 for (String member
: g
.members
) {
363 if (member
.equals(this.username
)) {
367 throw new NotAGroupMemberException(groupId
, g
.name
);
370 public List
<GroupInfo
> getGroups() {
371 return account
.getGroupStore().getGroups();
375 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
377 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
378 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
379 if (attachments
!= null) {
380 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
382 if (groupId
!= null) {
383 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
386 messageBuilder
.asGroupMessage(group
);
388 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
389 if (thread
!= null) {
390 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
393 final GroupInfo g
= getGroupForSending(groupId
);
395 // Don't send group message to ourself
396 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
397 membersSend
.remove(this.username
);
398 sendMessageLegacy(messageBuilder
, membersSend
);
401 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
402 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
406 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
407 .asGroupMessage(group
);
409 final GroupInfo g
= getGroupForSending(groupId
);
410 g
.members
.remove(this.username
);
411 account
.getGroupStore().updateGroup(g
);
413 sendMessageLegacy(messageBuilder
, g
.members
);
416 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
418 if (groupId
== null) {
420 g
= new GroupInfo(KeyUtils
.createGroupId());
421 g
.members
.add(username
);
423 g
= getGroupForSending(groupId
);
430 if (members
!= null) {
431 Set
<String
> newMembers
= new HashSet
<>();
432 for (String member
: members
) {
434 member
= Utils
.canonicalizeNumber(member
, username
);
435 } catch (InvalidNumberException e
) {
436 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
437 System
.err
.println("Aborting…");
440 if (g
.members
.contains(member
)) {
443 newMembers
.add(member
);
444 g
.members
.add(member
);
446 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
447 if (contacts
.size() != newMembers
.size()) {
448 // Some of the new members are not registered on Signal
449 for (ContactTokenDetails contact
: contacts
) {
450 newMembers
.remove(contact
.getNumber());
452 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
453 System
.err
.println("Aborting…");
458 if (avatarFile
!= null) {
459 IOUtils
.createPrivateDirectories(avatarsPath
);
460 File aFile
= getGroupAvatarFile(g
.groupId
);
461 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
464 account
.getGroupStore().updateGroup(g
);
466 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
468 // Don't send group message to ourself
469 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
470 membersSend
.remove(this.username
);
471 sendMessageLegacy(messageBuilder
, membersSend
);
475 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
476 if (groupId
== null) {
479 GroupInfo g
= getGroupForSending(groupId
);
481 if (!g
.members
.contains(recipient
)) {
485 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
487 // Send group message only to the recipient who requested it
488 final List
<String
> membersSend
= new ArrayList
<>();
489 membersSend
.add(recipient
);
490 sendMessageLegacy(messageBuilder
, membersSend
);
493 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
494 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
497 .withMembers(new ArrayList
<>(g
.members
));
499 File aFile
= getGroupAvatarFile(g
.groupId
);
500 if (aFile
.exists()) {
502 group
.withAvatar(Utils
.createAttachment(aFile
));
503 } catch (IOException e
) {
504 throw new AttachmentInvalidException(aFile
.toString(), e
);
508 return SignalServiceDataMessage
.newBuilder()
509 .asGroupMessage(group
.build());
512 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
513 if (groupId
== null) {
517 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
520 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
521 .asGroupMessage(group
.build());
523 // Send group info request message to the recipient who sent us a message with this groupId
524 final List
<String
> membersSend
= new ArrayList
<>();
525 membersSend
.add(recipient
);
526 sendMessageLegacy(messageBuilder
, membersSend
);
530 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
531 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
532 List
<String
> recipients
= new ArrayList
<>(1);
533 recipients
.add(recipient
);
534 sendMessage(message
, attachments
, recipients
);
538 public void sendMessage(String messageText
, List
<String
> attachments
,
539 List
<String
> recipients
)
540 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
541 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
542 if (attachments
!= null) {
543 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
545 sendMessageLegacy(messageBuilder
, recipients
);
549 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
550 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
551 .asEndSessionMessage();
553 sendMessageLegacy(messageBuilder
, recipients
);
557 public String
getContactName(String number
) {
558 ContactInfo contact
= account
.getContactStore().getContact(number
);
559 if (contact
== null) {
567 public void setContactName(String number
, String name
) {
568 ContactInfo contact
= account
.getContactStore().getContact(number
);
569 if (contact
== null) {
570 contact
= new ContactInfo();
571 contact
.number
= number
;
572 System
.err
.println("Add contact " + number
+ " named " + name
);
574 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
577 account
.getContactStore().updateContact(contact
);
582 public List
<byte[]> getGroupIds() {
583 List
<GroupInfo
> groups
= getGroups();
584 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
585 for (GroupInfo group
: groups
) {
586 ids
.add(group
.groupId
);
592 public String
getGroupName(byte[] groupId
) {
593 GroupInfo group
= getGroup(groupId
);
602 public List
<String
> getGroupMembers(byte[] groupId
) {
603 GroupInfo group
= getGroup(groupId
);
605 return new ArrayList
<>();
607 return new ArrayList
<>(group
.members
);
612 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
613 if (groupId
.length
== 0) {
616 if (name
.isEmpty()) {
619 if (members
.size() == 0) {
622 if (avatar
.isEmpty()) {
625 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
629 * Change the expiration timer for a thread (number of groupId)
631 * @param numberOrGroupId
632 * @param messageExpirationTimer
634 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
635 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
636 thread
.messageExpirationTime
= messageExpirationTimer
;
637 account
.getThreadStore().updateThread(thread
);
640 private void requestSyncGroups() throws IOException
{
641 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
642 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
644 sendSyncMessage(message
);
645 } catch (UntrustedIdentityException e
) {
650 private void requestSyncContacts() throws IOException
{
651 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
652 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
654 sendSyncMessage(message
);
655 } catch (UntrustedIdentityException e
) {
660 private void requestSyncBlocked() throws IOException
{
661 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
662 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
664 sendSyncMessage(message
);
665 } catch (UntrustedIdentityException e
) {
670 private void requestSyncConfiguration() throws IOException
{
671 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
672 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
674 sendSyncMessage(message
);
675 } catch (UntrustedIdentityException e
) {
680 private byte[] getSelfUnidentifiedAccessKey() {
681 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
684 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
689 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
691 return Optional
.absent();
694 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
695 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
696 for (SignalServiceAddress recipient
: recipients
) {
697 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
702 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
704 return Optional
.absent();
707 private void sendSyncMessage(SignalServiceSyncMessage message
)
708 throws IOException
, UntrustedIdentityException
{
709 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
710 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
712 messageSender
.sendMessage(message
, getAccessForSync());
713 } catch (UntrustedIdentityException e
) {
714 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
720 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
722 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
723 throws EncapsulatedExceptions
, IOException
{
724 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
726 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
727 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
728 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
730 for (SendMessageResult result
: results
) {
731 if (result
.isUnregisteredFailure()) {
732 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
733 } else if (result
.isNetworkFailure()) {
734 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
735 } else if (result
.getIdentityFailure() != null) {
736 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
739 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
740 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
744 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
746 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
747 if (recipientsTS
== null) {
749 return Collections
.emptyList();
752 SignalServiceDataMessage message
= null;
754 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
755 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
757 message
= messageBuilder
.build();
758 if (message
.getGroupInfo().isPresent()) {
760 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), message
);
761 for (SendMessageResult r
: result
) {
762 if (r
.getIdentityFailure() != null) {
763 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
767 } catch (UntrustedIdentityException e
) {
768 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
769 return Collections
.emptyList();
772 // Send to all individually, so sync messages are sent correctly
773 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
774 for (SignalServiceAddress address
: recipientsTS
) {
775 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
776 if (thread
!= null) {
777 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
779 messageBuilder
.withExpiration(0);
781 message
= messageBuilder
.build();
783 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
785 } catch (UntrustedIdentityException e
) {
786 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
787 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
793 if (message
!= null && message
.isEndSession()) {
794 for (SignalServiceAddress recipient
: recipientsTS
) {
795 handleEndSession(recipient
.getNumber());
802 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
{
803 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
805 return cipher
.decrypt(envelope
);
806 } catch (ProtocolUntrustedIdentityException e
) {
807 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
808 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
813 private void handleEndSession(String source
) {
814 account
.getSignalProtocolStore().deleteAllSessions(source
);
817 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
819 if (message
.getGroupInfo().isPresent()) {
820 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
821 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
822 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
823 switch (groupInfo
.getType()) {
826 group
= new GroupInfo(groupInfo
.getGroupId());
829 if (groupInfo
.getAvatar().isPresent()) {
830 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
831 if (avatar
.isPointer()) {
833 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
834 } catch (IOException
| InvalidMessageException e
) {
835 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
840 if (groupInfo
.getName().isPresent()) {
841 group
.name
= groupInfo
.getName().get();
844 if (groupInfo
.getMembers().isPresent()) {
845 group
.members
.addAll(groupInfo
.getMembers().get());
848 account
.getGroupStore().updateGroup(group
);
853 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
854 } catch (IOException
| EncapsulatedExceptions e
) {
862 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
863 } catch (IOException
| EncapsulatedExceptions e
) {
867 group
.members
.remove(source
);
868 account
.getGroupStore().updateGroup(group
);
874 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
875 } catch (IOException
| EncapsulatedExceptions e
) {
877 } catch (NotAGroupMemberException e
) {
878 // We have left this group, so don't send a group update message
885 threadId
= destination
;
890 if (message
.isEndSession()) {
891 handleEndSession(isSync ? destination
: source
);
893 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
894 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
895 if (thread
== null) {
896 thread
= new ThreadInfo();
897 thread
.id
= threadId
;
899 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
900 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
901 account
.getThreadStore().updateThread(thread
);
904 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
905 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
906 if (attachment
.isPointer()) {
908 retrieveAttachment(attachment
.asPointer());
909 } catch (IOException
| InvalidMessageException e
) {
910 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
915 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
916 if (source
.equals(username
)) {
917 this.account
.setProfileKey(message
.getProfileKey().get());
919 ContactInfo contact
= account
.getContactStore().getContact(source
);
920 if (contact
== null) {
921 contact
= new ContactInfo();
922 contact
.number
= source
;
924 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
928 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
929 final File cachePath
= new File(getMessageCachePath());
930 if (!cachePath
.exists()) {
933 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
934 if (!dir
.isDirectory()) {
938 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
939 if (!fileEntry
.isFile()) {
942 SignalServiceEnvelope envelope
;
944 envelope
= Utils
.loadEnvelope(fileEntry
);
945 if (envelope
== null) {
948 } catch (IOException e
) {
952 SignalServiceContent content
= null;
953 if (!envelope
.isReceipt()) {
955 content
= decryptMessage(envelope
);
956 } catch (Exception e
) {
959 handleMessage(envelope
, content
, ignoreAttachments
);
962 handler
.handleMessage(envelope
, content
, null);
964 Files
.delete(fileEntry
.toPath());
965 } catch (IOException e
) {
966 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
969 // Try to delete directory if empty
974 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
975 retryFailedReceivedMessages(handler
, ignoreAttachments
);
976 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
979 if (messagePipe
== null) {
980 messagePipe
= messageReceiver
.createMessagePipe();
984 SignalServiceEnvelope envelope
;
985 SignalServiceContent content
= null;
986 Exception exception
= null;
987 final long now
= new Date().getTime();
989 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
991 public void onMessage(SignalServiceEnvelope envelope
) {
992 // store message on disk, before acknowledging receipt to the server
994 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
995 Utils
.storeEnvelope(envelope
, cacheFile
);
996 } catch (IOException e
) {
997 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1001 } catch (TimeoutException e
) {
1002 if (returnOnTimeout
)
1005 } catch (InvalidVersionException e
) {
1006 System
.err
.println("Ignoring error: " + e
.getMessage());
1009 if (!envelope
.isReceipt()) {
1011 content
= decryptMessage(envelope
);
1012 } catch (Exception e
) {
1015 handleMessage(envelope
, content
, ignoreAttachments
);
1018 handler
.handleMessage(envelope
, content
, exception
);
1019 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1020 File cacheFile
= null;
1022 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1023 Files
.delete(cacheFile
.toPath());
1024 // Try to delete directory if empty
1025 new File(getMessageCachePath()).delete();
1026 } catch (IOException e
) {
1027 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1032 if (messagePipe
!= null) {
1033 messagePipe
.shutdown();
1039 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1040 if (content
!= null) {
1041 if (content
.getDataMessage().isPresent()) {
1042 SignalServiceDataMessage message
= content
.getDataMessage().get();
1043 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1045 if (content
.getSyncMessage().isPresent()) {
1046 account
.setMultiDevice(true);
1047 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1048 if (syncMessage
.getSent().isPresent()) {
1049 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1050 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1052 if (syncMessage
.getRequest().isPresent()) {
1053 RequestMessage rm
= syncMessage
.getRequest().get();
1054 if (rm
.isContactsRequest()) {
1057 } catch (UntrustedIdentityException
| IOException e
) {
1058 e
.printStackTrace();
1061 if (rm
.isGroupsRequest()) {
1064 } catch (UntrustedIdentityException
| IOException e
) {
1065 e
.printStackTrace();
1068 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1070 if (syncMessage
.getGroups().isPresent()) {
1071 File tmpFile
= null;
1073 tmpFile
= IOUtils
.createTempFile();
1074 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1075 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1077 while ((g
= s
.read()) != null) {
1078 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1079 if (syncGroup
== null) {
1080 syncGroup
= new GroupInfo(g
.getId());
1082 if (g
.getName().isPresent()) {
1083 syncGroup
.name
= g
.getName().get();
1085 syncGroup
.members
.addAll(g
.getMembers());
1086 syncGroup
.active
= g
.isActive();
1087 if (g
.getColor().isPresent()) {
1088 syncGroup
.color
= g
.getColor().get();
1091 if (g
.getAvatar().isPresent()) {
1092 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1094 account
.getGroupStore().updateGroup(syncGroup
);
1097 } catch (Exception e
) {
1098 e
.printStackTrace();
1100 if (tmpFile
!= null) {
1102 Files
.delete(tmpFile
.toPath());
1103 } catch (IOException e
) {
1104 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1109 if (syncMessage
.getBlockedList().isPresent()) {
1110 // TODO store list of blocked numbers
1112 if (syncMessage
.getContacts().isPresent()) {
1113 File tmpFile
= null;
1115 tmpFile
= IOUtils
.createTempFile();
1116 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1117 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1118 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1119 if (contactsMessage
.isComplete()) {
1120 account
.getContactStore().clear();
1123 while ((c
= s
.read()) != null) {
1124 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1125 account
.setProfileKey(c
.getProfileKey().get());
1127 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1128 if (contact
== null) {
1129 contact
= new ContactInfo();
1130 contact
.number
= c
.getNumber();
1132 if (c
.getName().isPresent()) {
1133 contact
.name
= c
.getName().get();
1135 if (c
.getColor().isPresent()) {
1136 contact
.color
= c
.getColor().get();
1138 if (c
.getProfileKey().isPresent()) {
1139 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1141 if (c
.getVerified().isPresent()) {
1142 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1143 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1145 if (c
.getExpirationTimer().isPresent()) {
1146 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1147 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1148 account
.getThreadStore().updateThread(thread
);
1150 if (c
.isBlocked()) {
1151 // TODO store list of blocked numbers
1153 account
.getContactStore().updateContact(contact
);
1155 if (c
.getAvatar().isPresent()) {
1156 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1160 } catch (Exception e
) {
1161 e
.printStackTrace();
1163 if (tmpFile
!= null) {
1165 Files
.delete(tmpFile
.toPath());
1166 } catch (IOException e
) {
1167 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1172 if (syncMessage
.getVerified().isPresent()) {
1173 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1174 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1176 if (syncMessage
.getConfiguration().isPresent()) {
1183 private File
getContactAvatarFile(String number
) {
1184 return new File(avatarsPath
, "contact-" + number
);
1187 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1188 IOUtils
.createPrivateDirectories(avatarsPath
);
1189 if (attachment
.isPointer()) {
1190 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1191 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1193 SignalServiceAttachmentStream stream
= attachment
.asStream();
1194 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1198 private File
getGroupAvatarFile(byte[] groupId
) {
1199 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1202 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1203 IOUtils
.createPrivateDirectories(avatarsPath
);
1204 if (attachment
.isPointer()) {
1205 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1206 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1208 SignalServiceAttachmentStream stream
= attachment
.asStream();
1209 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1213 public File
getAttachmentFile(long attachmentId
) {
1214 return new File(attachmentsPath
, attachmentId
+ "");
1217 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1218 IOUtils
.createPrivateDirectories(attachmentsPath
);
1219 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1222 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1223 if (storePreview
&& pointer
.getPreview().isPresent()) {
1224 File previewFile
= new File(outputFile
+ ".preview");
1225 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1226 byte[] preview
= pointer
.getPreview().get();
1227 output
.write(preview
, 0, preview
.length
);
1228 } catch (FileNotFoundException e
) {
1229 e
.printStackTrace();
1234 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1236 File tmpFile
= IOUtils
.createTempFile();
1237 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1238 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1239 byte[] buffer
= new byte[4096];
1242 while ((read
= input
.read(buffer
)) != -1) {
1243 output
.write(buffer
, 0, read
);
1245 } catch (FileNotFoundException e
) {
1246 e
.printStackTrace();
1251 Files
.delete(tmpFile
.toPath());
1252 } catch (IOException e
) {
1253 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1259 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1260 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1261 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1265 public boolean isRemote() {
1269 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1270 File groupsFile
= IOUtils
.createTempFile();
1273 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1274 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1275 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1276 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1277 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1278 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1279 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1280 Optional
.fromNullable(record.color
), false));
1284 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1285 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1286 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1287 .withStream(groupsFileStream
)
1288 .withContentType("application/octet-stream")
1289 .withLength(groupsFile
.length())
1292 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1297 Files
.delete(groupsFile
.toPath());
1298 } catch (IOException e
) {
1299 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1304 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1305 File contactsFile
= IOUtils
.createTempFile();
1308 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1309 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1310 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1311 VerifiedMessage verifiedMessage
= null;
1312 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1313 if (getIdentities().containsKey(record.number
)) {
1314 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1315 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1316 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1317 currentIdentity
= id
;
1320 if (currentIdentity
!= null) {
1321 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1325 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1326 // TODO store list of blocked numbers
1327 boolean blocked
= false;
1328 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1329 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1330 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1333 if (account
.getProfileKey() != null) {
1334 // Send our own profile key as well
1335 out
.write(new DeviceContact(account
.getUsername(),
1336 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1337 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1338 Optional
.of(account
.getProfileKey()),
1339 false, Optional
.<Integer
>absent()));
1343 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1344 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1345 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1346 .withStream(contactsFileStream
)
1347 .withContentType("application/octet-stream")
1348 .withLength(contactsFile
.length())
1351 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1356 Files
.delete(contactsFile
.toPath());
1357 } catch (IOException e
) {
1358 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1363 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1364 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1365 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1368 public ContactInfo
getContact(String number
) {
1369 return account
.getContactStore().getContact(number
);
1372 public GroupInfo
getGroup(byte[] groupId
) {
1373 return account
.getGroupStore().getGroup(groupId
);
1376 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1377 return account
.getSignalProtocolStore().getIdentities();
1380 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1381 return account
.getSignalProtocolStore().getIdentities(number
);
1385 * Trust this the identity with this fingerprint
1387 * @param name username of the identity
1388 * @param fingerprint Fingerprint
1390 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1391 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1395 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1396 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1400 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1402 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1403 } catch (IOException
| UntrustedIdentityException e
) {
1404 e
.printStackTrace();
1413 * Trust this the identity with this safety number
1415 * @param name username of the identity
1416 * @param safetyNumber Safety number
1418 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1419 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1423 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1424 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1428 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1430 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1431 } catch (IOException
| UntrustedIdentityException e
) {
1432 e
.printStackTrace();
1441 * Trust all keys of this identity without verification
1443 * @param name username of the identity
1445 public boolean trustIdentityAllKeys(String name
) {
1446 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1450 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1451 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1452 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1454 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1455 } catch (IOException
| UntrustedIdentityException e
) {
1456 e
.printStackTrace();
1464 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1465 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1468 public interface ReceiveMessageHandler
{
1470 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);