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
;
76 private final SleepTimer timer
= new UptimeSleepTimer();
78 private SignalAccount account
;
79 private String username
;
80 private SignalServiceAccountManager accountManager
;
81 private SignalServiceMessagePipe messagePipe
= null;
82 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
84 public Manager(String username
, String settingsPath
) {
85 this.username
= username
;
86 this.settingsPath
= settingsPath
;
87 this.dataPath
= this.settingsPath
+ "/data";
88 this.attachmentsPath
= this.settingsPath
+ "/attachments";
89 this.avatarsPath
= this.settingsPath
+ "/avatars";
93 public String
getUsername() {
97 private IdentityKey
getIdentity() {
98 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
101 public int getDeviceId() {
102 return account
.getDeviceId();
105 private String
getMessageCachePath() {
106 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
109 private String
getMessageCachePath(String sender
) {
110 return getMessageCachePath() + "/" + sender
.replace("/", "_");
113 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
114 String cachePath
= getMessageCachePath(sender
);
115 IOUtils
.createPrivateDirectories(cachePath
);
116 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
119 public boolean userHasKeys() {
120 return account
!= null && account
.getSignalProtocolStore() != null;
123 public void init() throws IOException
{
124 if (!SignalAccount
.userExists(dataPath
, username
)) {
127 account
= SignalAccount
.load(dataPath
, username
);
129 migrateLegacyConfigs();
131 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
133 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
137 } catch (AuthorizationFailedException e
) {
138 System
.err
.println("Authorization failed, was the number registered elsewhere?");
142 private void migrateLegacyConfigs() {
143 // Copy group avatars that were previously stored in the attachments folder
144 // to the new avatar folder
145 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
146 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
147 File avatarFile
= getGroupAvatarFile(g
.groupId
);
148 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
149 if (!avatarFile
.exists() && attachmentFile
.exists()) {
151 IOUtils
.createPrivateDirectories(avatarsPath
);
152 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
153 } catch (Exception e
) {
158 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
161 if (account
.getProfileKey() == null) {
162 // Old config file, creating new profile key
163 account
.setProfileKey(KeyUtils
.createProfileKey());
168 private void createNewIdentity() throws IOException
{
169 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
170 int registrationId
= KeyHelper
.generateRegistrationId(false);
171 if (username
== null) {
172 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
174 byte[] profileKey
= KeyUtils
.createProfileKey();
175 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
180 public boolean isRegistered() {
181 return account
!= null && account
.isRegistered();
184 public void register(boolean voiceVerification
) throws IOException
{
185 if (account
== null) {
188 account
.setPassword(KeyUtils
.createPassword());
189 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, account
.getUsername(), account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
191 if (voiceVerification
)
192 accountManager
.requestVoiceVerificationCode();
194 accountManager
.requestSmsVerificationCode();
196 account
.setRegistered(false);
200 public void updateAccountAttributes() throws IOException
{
201 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
204 public void unregister() throws IOException
{
205 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
206 // If this is the master device, other users can't send messages to this number anymore.
207 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
208 accountManager
.setGcmId(Optional
.<String
>absent());
211 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
212 if (account
== null) {
215 account
.setPassword(KeyUtils
.createPassword());
216 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
217 String uuid
= accountManager
.getNewDeviceUuid();
219 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
222 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
223 account
.setSignalingKey(KeyUtils
.createSignalingKey());
224 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
226 username
= ret
.getNumber();
227 // TODO do this check before actually registering
228 if (SignalAccount
.userExists(dataPath
, username
)) {
229 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
232 // Create new account with the synced identity
233 byte[] profileKey
= ret
.getProfileKey();
234 if (profileKey
== null) {
235 profileKey
= KeyUtils
.createProfileKey();
237 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
242 requestSyncContacts();
243 requestSyncBlocked();
244 requestSyncConfiguration();
249 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
250 List
<DeviceInfo
> devices
= accountManager
.getDevices();
251 account
.setMultiDevice(devices
.size() > 1);
256 public void removeLinkedDevices(int deviceId
) throws IOException
{
257 accountManager
.removeDevice(deviceId
);
258 List
<DeviceInfo
> devices
= accountManager
.getDevices();
259 account
.setMultiDevice(devices
.size() > 1);
263 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
264 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
266 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
269 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
270 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
271 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
273 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
274 account
.setMultiDevice(true);
278 private List
<PreKeyRecord
> generatePreKeys() {
279 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
281 final int offset
= account
.getPreKeyIdOffset();
282 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
283 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
284 ECKeyPair keyPair
= Curve
.generateKeyPair();
285 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
290 account
.addPreKeys(records
);
296 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
298 ECKeyPair keyPair
= Curve
.generateKeyPair();
299 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
300 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
302 account
.addSignedPreKey(record);
306 } catch (InvalidKeyException e
) {
307 throw new AssertionError(e
);
311 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
312 verificationCode
= verificationCode
.replace("-", "");
313 account
.setSignalingKey(KeyUtils
.createSignalingKey());
314 // TODO make unrestricted unidentified access configurable
315 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
317 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
318 account
.setRegistered(true);
319 account
.setRegistrationLockPin(pin
);
325 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
326 accountManager
.setPin(pin
);
327 if (pin
.isPresent()) {
328 account
.setRegistrationLockPin(pin
.get());
330 account
.setRegistrationLockPin(null);
335 private void refreshPreKeys() throws IOException
{
336 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
337 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
338 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
340 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
343 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
344 File file
= getGroupAvatarFile(groupId
);
345 if (!file
.exists()) {
346 return Optional
.absent();
349 return Optional
.of(Utils
.createAttachment(file
));
352 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
353 File file
= getContactAvatarFile(number
);
354 if (!file
.exists()) {
355 return Optional
.absent();
358 return Optional
.of(Utils
.createAttachment(file
));
361 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
362 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
364 throw new GroupNotFoundException(groupId
);
366 for (String member
: g
.members
) {
367 if (member
.equals(this.username
)) {
371 throw new NotAGroupMemberException(groupId
, g
.name
);
374 public List
<GroupInfo
> getGroups() {
375 return account
.getGroupStore().getGroups();
379 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
381 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
382 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
383 if (attachments
!= null) {
384 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
386 if (groupId
!= null) {
387 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
390 messageBuilder
.asGroupMessage(group
);
392 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
393 if (thread
!= null) {
394 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
397 final GroupInfo g
= getGroupForSending(groupId
);
399 // Don't send group message to ourself
400 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
401 membersSend
.remove(this.username
);
402 sendMessageLegacy(messageBuilder
, membersSend
);
405 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
406 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
410 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
411 .asGroupMessage(group
);
413 final GroupInfo g
= getGroupForSending(groupId
);
414 g
.members
.remove(this.username
);
415 account
.getGroupStore().updateGroup(g
);
417 sendMessageLegacy(messageBuilder
, g
.members
);
420 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
422 if (groupId
== null) {
424 g
= new GroupInfo(KeyUtils
.createGroupId());
425 g
.members
.add(username
);
427 g
= getGroupForSending(groupId
);
434 if (members
!= null) {
435 Set
<String
> newMembers
= new HashSet
<>();
436 for (String member
: members
) {
438 member
= Utils
.canonicalizeNumber(member
, username
);
439 } catch (InvalidNumberException e
) {
440 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
441 System
.err
.println("Aborting…");
444 if (g
.members
.contains(member
)) {
447 newMembers
.add(member
);
448 g
.members
.add(member
);
450 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
451 if (contacts
.size() != newMembers
.size()) {
452 // Some of the new members are not registered on Signal
453 for (ContactTokenDetails contact
: contacts
) {
454 newMembers
.remove(contact
.getNumber());
456 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
457 System
.err
.println("Aborting…");
462 if (avatarFile
!= null) {
463 IOUtils
.createPrivateDirectories(avatarsPath
);
464 File aFile
= getGroupAvatarFile(g
.groupId
);
465 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
468 account
.getGroupStore().updateGroup(g
);
470 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
472 // Don't send group message to ourself
473 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
474 membersSend
.remove(this.username
);
475 sendMessageLegacy(messageBuilder
, membersSend
);
479 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
480 if (groupId
== null) {
483 GroupInfo g
= getGroupForSending(groupId
);
485 if (!g
.members
.contains(recipient
)) {
489 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
491 // Send group message only to the recipient who requested it
492 final List
<String
> membersSend
= new ArrayList
<>();
493 membersSend
.add(recipient
);
494 sendMessageLegacy(messageBuilder
, membersSend
);
497 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
498 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
501 .withMembers(new ArrayList
<>(g
.members
));
503 File aFile
= getGroupAvatarFile(g
.groupId
);
504 if (aFile
.exists()) {
506 group
.withAvatar(Utils
.createAttachment(aFile
));
507 } catch (IOException e
) {
508 throw new AttachmentInvalidException(aFile
.toString(), e
);
512 return SignalServiceDataMessage
.newBuilder()
513 .asGroupMessage(group
.build());
516 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
517 if (groupId
== null) {
521 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
524 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
525 .asGroupMessage(group
.build());
527 // Send group info request message to the recipient who sent us a message with this groupId
528 final List
<String
> membersSend
= new ArrayList
<>();
529 membersSend
.add(recipient
);
530 sendMessageLegacy(messageBuilder
, membersSend
);
534 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
535 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
536 List
<String
> recipients
= new ArrayList
<>(1);
537 recipients
.add(recipient
);
538 sendMessage(message
, attachments
, recipients
);
542 public void sendMessage(String messageText
, List
<String
> attachments
,
543 List
<String
> recipients
)
544 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
545 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
546 if (attachments
!= null) {
547 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
549 sendMessageLegacy(messageBuilder
, recipients
);
553 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
554 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
555 .asEndSessionMessage();
557 sendMessageLegacy(messageBuilder
, recipients
);
561 public String
getContactName(String number
) {
562 ContactInfo contact
= account
.getContactStore().getContact(number
);
563 if (contact
== null) {
571 public void setContactName(String number
, String name
) {
572 ContactInfo contact
= account
.getContactStore().getContact(number
);
573 if (contact
== null) {
574 contact
= new ContactInfo();
575 contact
.number
= number
;
576 System
.err
.println("Add contact " + number
+ " named " + name
);
578 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
581 account
.getContactStore().updateContact(contact
);
586 public List
<byte[]> getGroupIds() {
587 List
<GroupInfo
> groups
= getGroups();
588 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
589 for (GroupInfo group
: groups
) {
590 ids
.add(group
.groupId
);
596 public String
getGroupName(byte[] groupId
) {
597 GroupInfo group
= getGroup(groupId
);
606 public List
<String
> getGroupMembers(byte[] groupId
) {
607 GroupInfo group
= getGroup(groupId
);
609 return new ArrayList
<>();
611 return new ArrayList
<>(group
.members
);
616 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
617 if (groupId
.length
== 0) {
620 if (name
.isEmpty()) {
623 if (members
.size() == 0) {
626 if (avatar
.isEmpty()) {
629 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
633 * Change the expiration timer for a thread (number of groupId)
635 * @param numberOrGroupId
636 * @param messageExpirationTimer
638 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
639 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
640 thread
.messageExpirationTime
= messageExpirationTimer
;
641 account
.getThreadStore().updateThread(thread
);
644 private void requestSyncGroups() throws IOException
{
645 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
646 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
648 sendSyncMessage(message
);
649 } catch (UntrustedIdentityException e
) {
654 private void requestSyncContacts() throws IOException
{
655 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
656 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
658 sendSyncMessage(message
);
659 } catch (UntrustedIdentityException e
) {
664 private void requestSyncBlocked() throws IOException
{
665 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
666 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
668 sendSyncMessage(message
);
669 } catch (UntrustedIdentityException e
) {
674 private void requestSyncConfiguration() throws IOException
{
675 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
676 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
678 sendSyncMessage(message
);
679 } catch (UntrustedIdentityException e
) {
684 private byte[] getSelfUnidentifiedAccessKey() {
685 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
688 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
693 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
695 return Optional
.absent();
698 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
699 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
700 for (SignalServiceAddress recipient
: recipients
) {
701 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
706 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
708 return Optional
.absent();
711 private void sendSyncMessage(SignalServiceSyncMessage message
)
712 throws IOException
, UntrustedIdentityException
{
713 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
714 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
716 messageSender
.sendMessage(message
, getAccessForSync());
717 } catch (UntrustedIdentityException e
) {
718 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
724 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
726 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
727 throws EncapsulatedExceptions
, IOException
{
728 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
730 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
731 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
732 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
734 for (SendMessageResult result
: results
) {
735 if (result
.isUnregisteredFailure()) {
736 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
737 } else if (result
.isNetworkFailure()) {
738 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
739 } else if (result
.getIdentityFailure() != null) {
740 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
743 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
744 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
748 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
750 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
751 if (recipientsTS
== null) {
753 return Collections
.emptyList();
756 SignalServiceDataMessage message
= null;
758 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
759 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
761 message
= messageBuilder
.build();
762 if (message
.getGroupInfo().isPresent()) {
764 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), message
);
765 for (SendMessageResult r
: result
) {
766 if (r
.getIdentityFailure() != null) {
767 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
771 } catch (UntrustedIdentityException e
) {
772 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
773 return Collections
.emptyList();
776 // Send to all individually, so sync messages are sent correctly
777 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
778 for (SignalServiceAddress address
: recipientsTS
) {
779 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
780 if (thread
!= null) {
781 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
783 messageBuilder
.withExpiration(0);
785 message
= messageBuilder
.build();
787 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
789 } catch (UntrustedIdentityException e
) {
790 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
791 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
797 if (message
!= null && message
.isEndSession()) {
798 for (SignalServiceAddress recipient
: recipientsTS
) {
799 handleEndSession(recipient
.getNumber());
806 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
{
807 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
809 return cipher
.decrypt(envelope
);
810 } catch (ProtocolUntrustedIdentityException e
) {
811 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
812 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
817 private void handleEndSession(String source
) {
818 account
.getSignalProtocolStore().deleteAllSessions(source
);
821 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
823 if (message
.getGroupInfo().isPresent()) {
824 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
825 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
826 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
827 switch (groupInfo
.getType()) {
830 group
= new GroupInfo(groupInfo
.getGroupId());
833 if (groupInfo
.getAvatar().isPresent()) {
834 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
835 if (avatar
.isPointer()) {
837 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
838 } catch (IOException
| InvalidMessageException e
) {
839 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
844 if (groupInfo
.getName().isPresent()) {
845 group
.name
= groupInfo
.getName().get();
848 if (groupInfo
.getMembers().isPresent()) {
849 group
.members
.addAll(groupInfo
.getMembers().get());
852 account
.getGroupStore().updateGroup(group
);
857 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
858 } catch (IOException
| EncapsulatedExceptions e
) {
866 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
867 } catch (IOException
| EncapsulatedExceptions e
) {
871 group
.members
.remove(source
);
872 account
.getGroupStore().updateGroup(group
);
878 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
879 } catch (IOException
| EncapsulatedExceptions e
) {
881 } catch (NotAGroupMemberException e
) {
882 // We have left this group, so don't send a group update message
889 threadId
= destination
;
894 if (message
.isEndSession()) {
895 handleEndSession(isSync ? destination
: source
);
897 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
898 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
899 if (thread
== null) {
900 thread
= new ThreadInfo();
901 thread
.id
= threadId
;
903 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
904 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
905 account
.getThreadStore().updateThread(thread
);
908 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
909 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
910 if (attachment
.isPointer()) {
912 retrieveAttachment(attachment
.asPointer());
913 } catch (IOException
| InvalidMessageException e
) {
914 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
919 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
920 if (source
.equals(username
)) {
921 this.account
.setProfileKey(message
.getProfileKey().get());
923 ContactInfo contact
= account
.getContactStore().getContact(source
);
924 if (contact
== null) {
925 contact
= new ContactInfo();
926 contact
.number
= source
;
928 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
932 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
933 final File cachePath
= new File(getMessageCachePath());
934 if (!cachePath
.exists()) {
937 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
938 if (!dir
.isDirectory()) {
942 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
943 if (!fileEntry
.isFile()) {
946 SignalServiceEnvelope envelope
;
948 envelope
= Utils
.loadEnvelope(fileEntry
);
949 if (envelope
== null) {
952 } catch (IOException e
) {
956 SignalServiceContent content
= null;
957 if (!envelope
.isReceipt()) {
959 content
= decryptMessage(envelope
);
960 } catch (Exception e
) {
963 handleMessage(envelope
, content
, ignoreAttachments
);
966 handler
.handleMessage(envelope
, content
, null);
968 Files
.delete(fileEntry
.toPath());
969 } catch (IOException e
) {
970 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
973 // Try to delete directory if empty
978 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
979 retryFailedReceivedMessages(handler
, ignoreAttachments
);
980 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
983 if (messagePipe
== null) {
984 messagePipe
= messageReceiver
.createMessagePipe();
988 SignalServiceEnvelope envelope
;
989 SignalServiceContent content
= null;
990 Exception exception
= null;
991 final long now
= new Date().getTime();
993 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
995 public void onMessage(SignalServiceEnvelope envelope
) {
996 // store message on disk, before acknowledging receipt to the server
998 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
999 Utils
.storeEnvelope(envelope
, cacheFile
);
1000 } catch (IOException e
) {
1001 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1005 } catch (TimeoutException e
) {
1006 if (returnOnTimeout
)
1009 } catch (InvalidVersionException e
) {
1010 System
.err
.println("Ignoring error: " + e
.getMessage());
1013 if (!envelope
.isReceipt()) {
1015 content
= decryptMessage(envelope
);
1016 } catch (Exception e
) {
1019 handleMessage(envelope
, content
, ignoreAttachments
);
1022 handler
.handleMessage(envelope
, content
, exception
);
1023 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1024 File cacheFile
= null;
1026 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1027 Files
.delete(cacheFile
.toPath());
1028 // Try to delete directory if empty
1029 new File(getMessageCachePath()).delete();
1030 } catch (IOException e
) {
1031 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1036 if (messagePipe
!= null) {
1037 messagePipe
.shutdown();
1043 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1044 if (content
!= null) {
1045 if (content
.getDataMessage().isPresent()) {
1046 SignalServiceDataMessage message
= content
.getDataMessage().get();
1047 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1049 if (content
.getSyncMessage().isPresent()) {
1050 account
.setMultiDevice(true);
1051 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1052 if (syncMessage
.getSent().isPresent()) {
1053 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1054 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1056 if (syncMessage
.getRequest().isPresent()) {
1057 RequestMessage rm
= syncMessage
.getRequest().get();
1058 if (rm
.isContactsRequest()) {
1061 } catch (UntrustedIdentityException
| IOException e
) {
1062 e
.printStackTrace();
1065 if (rm
.isGroupsRequest()) {
1068 } catch (UntrustedIdentityException
| IOException e
) {
1069 e
.printStackTrace();
1072 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1074 if (syncMessage
.getGroups().isPresent()) {
1075 File tmpFile
= null;
1077 tmpFile
= IOUtils
.createTempFile();
1078 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1079 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1081 while ((g
= s
.read()) != null) {
1082 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1083 if (syncGroup
== null) {
1084 syncGroup
= new GroupInfo(g
.getId());
1086 if (g
.getName().isPresent()) {
1087 syncGroup
.name
= g
.getName().get();
1089 syncGroup
.members
.addAll(g
.getMembers());
1090 syncGroup
.active
= g
.isActive();
1091 if (g
.getColor().isPresent()) {
1092 syncGroup
.color
= g
.getColor().get();
1095 if (g
.getAvatar().isPresent()) {
1096 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1098 account
.getGroupStore().updateGroup(syncGroup
);
1101 } catch (Exception e
) {
1102 e
.printStackTrace();
1104 if (tmpFile
!= null) {
1106 Files
.delete(tmpFile
.toPath());
1107 } catch (IOException e
) {
1108 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1113 if (syncMessage
.getBlockedList().isPresent()) {
1114 // TODO store list of blocked numbers
1116 if (syncMessage
.getContacts().isPresent()) {
1117 File tmpFile
= null;
1119 tmpFile
= IOUtils
.createTempFile();
1120 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1121 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1122 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1123 if (contactsMessage
.isComplete()) {
1124 account
.getContactStore().clear();
1127 while ((c
= s
.read()) != null) {
1128 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1129 account
.setProfileKey(c
.getProfileKey().get());
1131 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1132 if (contact
== null) {
1133 contact
= new ContactInfo();
1134 contact
.number
= c
.getNumber();
1136 if (c
.getName().isPresent()) {
1137 contact
.name
= c
.getName().get();
1139 if (c
.getColor().isPresent()) {
1140 contact
.color
= c
.getColor().get();
1142 if (c
.getProfileKey().isPresent()) {
1143 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1145 if (c
.getVerified().isPresent()) {
1146 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1147 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1149 if (c
.getExpirationTimer().isPresent()) {
1150 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1151 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1152 account
.getThreadStore().updateThread(thread
);
1154 if (c
.isBlocked()) {
1155 // TODO store list of blocked numbers
1157 account
.getContactStore().updateContact(contact
);
1159 if (c
.getAvatar().isPresent()) {
1160 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1164 } catch (Exception e
) {
1165 e
.printStackTrace();
1167 if (tmpFile
!= null) {
1169 Files
.delete(tmpFile
.toPath());
1170 } catch (IOException e
) {
1171 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1176 if (syncMessage
.getVerified().isPresent()) {
1177 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1178 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1180 if (syncMessage
.getConfiguration().isPresent()) {
1187 private File
getContactAvatarFile(String number
) {
1188 return new File(avatarsPath
, "contact-" + number
);
1191 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1192 IOUtils
.createPrivateDirectories(avatarsPath
);
1193 if (attachment
.isPointer()) {
1194 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1195 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1197 SignalServiceAttachmentStream stream
= attachment
.asStream();
1198 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1202 private File
getGroupAvatarFile(byte[] groupId
) {
1203 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1206 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1207 IOUtils
.createPrivateDirectories(avatarsPath
);
1208 if (attachment
.isPointer()) {
1209 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1210 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1212 SignalServiceAttachmentStream stream
= attachment
.asStream();
1213 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1217 public File
getAttachmentFile(long attachmentId
) {
1218 return new File(attachmentsPath
, attachmentId
+ "");
1221 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1222 IOUtils
.createPrivateDirectories(attachmentsPath
);
1223 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1226 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1227 if (storePreview
&& pointer
.getPreview().isPresent()) {
1228 File previewFile
= new File(outputFile
+ ".preview");
1229 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1230 byte[] preview
= pointer
.getPreview().get();
1231 output
.write(preview
, 0, preview
.length
);
1232 } catch (FileNotFoundException e
) {
1233 e
.printStackTrace();
1238 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1240 File tmpFile
= IOUtils
.createTempFile();
1241 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1242 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1243 byte[] buffer
= new byte[4096];
1246 while ((read
= input
.read(buffer
)) != -1) {
1247 output
.write(buffer
, 0, read
);
1249 } catch (FileNotFoundException e
) {
1250 e
.printStackTrace();
1255 Files
.delete(tmpFile
.toPath());
1256 } catch (IOException e
) {
1257 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1263 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1264 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1265 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1269 public boolean isRemote() {
1273 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1274 File groupsFile
= IOUtils
.createTempFile();
1277 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1278 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1279 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1280 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1281 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1282 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1283 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1284 Optional
.fromNullable(record.color
), false));
1288 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1289 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1290 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1291 .withStream(groupsFileStream
)
1292 .withContentType("application/octet-stream")
1293 .withLength(groupsFile
.length())
1296 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1301 Files
.delete(groupsFile
.toPath());
1302 } catch (IOException e
) {
1303 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1308 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1309 File contactsFile
= IOUtils
.createTempFile();
1312 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1313 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1314 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1315 VerifiedMessage verifiedMessage
= null;
1316 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1317 if (getIdentities().containsKey(record.number
)) {
1318 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1319 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1320 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1321 currentIdentity
= id
;
1324 if (currentIdentity
!= null) {
1325 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1329 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1330 // TODO store list of blocked numbers
1331 boolean blocked
= false;
1332 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1333 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1334 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1337 if (account
.getProfileKey() != null) {
1338 // Send our own profile key as well
1339 out
.write(new DeviceContact(account
.getUsername(),
1340 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1341 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1342 Optional
.of(account
.getProfileKey()),
1343 false, Optional
.<Integer
>absent()));
1347 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1348 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1349 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1350 .withStream(contactsFileStream
)
1351 .withContentType("application/octet-stream")
1352 .withLength(contactsFile
.length())
1355 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1360 Files
.delete(contactsFile
.toPath());
1361 } catch (IOException e
) {
1362 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1367 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1368 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1369 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1372 public ContactInfo
getContact(String number
) {
1373 return account
.getContactStore().getContact(number
);
1376 public GroupInfo
getGroup(byte[] groupId
) {
1377 return account
.getGroupStore().getGroup(groupId
);
1380 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1381 return account
.getSignalProtocolStore().getIdentities();
1384 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1385 return account
.getSignalProtocolStore().getIdentities(number
);
1389 * Trust this the identity with this fingerprint
1391 * @param name username of the identity
1392 * @param fingerprint Fingerprint
1394 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1395 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1399 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1400 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1404 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1406 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1407 } catch (IOException
| UntrustedIdentityException e
) {
1408 e
.printStackTrace();
1417 * Trust this the identity with this safety number
1419 * @param name username of the identity
1420 * @param safetyNumber Safety number
1422 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1423 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1427 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1428 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1432 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1434 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1435 } catch (IOException
| UntrustedIdentityException e
) {
1436 e
.printStackTrace();
1445 * Trust all keys of this identity without verification
1447 * @param name username of the identity
1449 public boolean trustIdentityAllKeys(String name
) {
1450 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1454 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1455 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1456 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1458 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1459 } catch (IOException
| UntrustedIdentityException e
) {
1460 e
.printStackTrace();
1468 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1469 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1472 public interface ReceiveMessageHandler
{
1474 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);