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
.push
.UnsupportedDataMessageException
;
60 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
64 import java
.nio
.file
.Files
;
65 import java
.nio
.file
.Paths
;
66 import java
.nio
.file
.StandardCopyOption
;
68 import java
.util
.concurrent
.TimeUnit
;
69 import java
.util
.concurrent
.TimeoutException
;
71 public class Manager
implements Signal
{
73 private final String settingsPath
;
74 private final String dataPath
;
75 private final String attachmentsPath
;
76 private final String avatarsPath
;
77 private final SleepTimer timer
= new UptimeSleepTimer();
79 private SignalAccount account
;
80 private String username
;
81 private SignalServiceAccountManager accountManager
;
82 private SignalServiceMessagePipe messagePipe
= null;
83 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
85 public Manager(String username
, String settingsPath
) {
86 this.username
= username
;
87 this.settingsPath
= settingsPath
;
88 this.dataPath
= this.settingsPath
+ "/data";
89 this.attachmentsPath
= this.settingsPath
+ "/attachments";
90 this.avatarsPath
= this.settingsPath
+ "/avatars";
94 public String
getUsername() {
98 private IdentityKey
getIdentity() {
99 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
102 public int getDeviceId() {
103 return account
.getDeviceId();
106 private String
getMessageCachePath() {
107 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
110 private String
getMessageCachePath(String sender
) {
111 return getMessageCachePath() + "/" + sender
.replace("/", "_");
114 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
115 String cachePath
= getMessageCachePath(sender
);
116 IOUtils
.createPrivateDirectories(cachePath
);
117 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
120 public boolean userHasKeys() {
121 return account
!= null && account
.getSignalProtocolStore() != null;
124 public void init() throws IOException
{
125 if (!SignalAccount
.userExists(dataPath
, username
)) {
128 account
= SignalAccount
.load(dataPath
, username
);
130 migrateLegacyConfigs();
132 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
134 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
138 } catch (AuthorizationFailedException e
) {
139 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());
170 private void createNewIdentity() throws IOException
{
171 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
172 int registrationId
= KeyHelper
.generateRegistrationId(false);
173 if (username
== null) {
174 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
176 byte[] profileKey
= KeyUtils
.createProfileKey();
177 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
182 public boolean isRegistered() {
183 return account
!= null && account
.isRegistered();
186 public void register(boolean voiceVerification
) throws IOException
{
187 if (account
== null) {
190 account
.setPassword(KeyUtils
.createPassword());
191 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, account
.getUsername(), account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
193 if (voiceVerification
) {
194 accountManager
.requestVoiceVerificationCode(Locale
.getDefault(), Optional
.<String
>absent(), Optional
.<String
>absent());
196 accountManager
.requestSmsVerificationCode(false, Optional
.<String
>absent(), Optional
.<String
>absent());
199 account
.setRegistered(false);
203 public void updateAccountAttributes() throws IOException
{
204 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
207 public void unregister() throws IOException
{
208 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
209 // If this is the master device, other users can't send messages to this number anymore.
210 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
211 accountManager
.setGcmId(Optional
.<String
>absent());
213 account
.setRegistered(false);
217 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
218 if (account
== null) {
221 account
.setPassword(KeyUtils
.createPassword());
222 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
223 String uuid
= accountManager
.getNewDeviceUuid();
225 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
228 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
229 account
.setSignalingKey(KeyUtils
.createSignalingKey());
230 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
232 username
= ret
.getNumber();
233 // TODO do this check before actually registering
234 if (SignalAccount
.userExists(dataPath
, username
)) {
235 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
238 // Create new account with the synced identity
239 byte[] profileKey
= ret
.getProfileKey();
240 if (profileKey
== null) {
241 profileKey
= KeyUtils
.createProfileKey();
243 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
248 requestSyncContacts();
249 requestSyncBlocked();
250 requestSyncConfiguration();
255 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
256 List
<DeviceInfo
> devices
= accountManager
.getDevices();
257 account
.setMultiDevice(devices
.size() > 1);
262 public void removeLinkedDevices(int deviceId
) throws IOException
{
263 accountManager
.removeDevice(deviceId
);
264 List
<DeviceInfo
> devices
= accountManager
.getDevices();
265 account
.setMultiDevice(devices
.size() > 1);
269 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
270 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
272 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
275 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
276 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
277 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
279 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
280 account
.setMultiDevice(true);
284 private List
<PreKeyRecord
> generatePreKeys() {
285 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
287 final int offset
= account
.getPreKeyIdOffset();
288 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
289 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
290 ECKeyPair keyPair
= Curve
.generateKeyPair();
291 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
296 account
.addPreKeys(records
);
302 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
304 ECKeyPair keyPair
= Curve
.generateKeyPair();
305 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
306 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
308 account
.addSignedPreKey(record);
312 } catch (InvalidKeyException e
) {
313 throw new AssertionError(e
);
317 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
318 verificationCode
= verificationCode
.replace("-", "");
319 account
.setSignalingKey(KeyUtils
.createSignalingKey());
320 // TODO make unrestricted unidentified access configurable
321 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
323 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
324 account
.setRegistered(true);
325 account
.setRegistrationLockPin(pin
);
331 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
332 accountManager
.setPin(pin
);
333 if (pin
.isPresent()) {
334 account
.setRegistrationLockPin(pin
.get());
336 account
.setRegistrationLockPin(null);
341 private void refreshPreKeys() throws IOException
{
342 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
343 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
344 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
346 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
349 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
350 File file
= getGroupAvatarFile(groupId
);
351 if (!file
.exists()) {
352 return Optional
.absent();
355 return Optional
.of(Utils
.createAttachment(file
));
358 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
359 File file
= getContactAvatarFile(number
);
360 if (!file
.exists()) {
361 return Optional
.absent();
364 return Optional
.of(Utils
.createAttachment(file
));
367 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
368 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
370 throw new GroupNotFoundException(groupId
);
372 for (String member
: g
.members
) {
373 if (member
.equals(this.username
)) {
377 throw new NotAGroupMemberException(groupId
, g
.name
);
380 public List
<GroupInfo
> getGroups() {
381 return account
.getGroupStore().getGroups();
385 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
387 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
388 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
389 if (attachments
!= null) {
390 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
392 if (groupId
!= null) {
393 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
396 messageBuilder
.asGroupMessage(group
);
398 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
399 if (thread
!= null) {
400 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
403 final GroupInfo g
= getGroupForSending(groupId
);
405 // Don't send group message to ourself
406 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
407 membersSend
.remove(this.username
);
408 sendMessageLegacy(messageBuilder
, membersSend
);
411 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
412 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
416 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
417 .asGroupMessage(group
);
419 final GroupInfo g
= getGroupForSending(groupId
);
420 g
.members
.remove(this.username
);
421 account
.getGroupStore().updateGroup(g
);
423 sendMessageLegacy(messageBuilder
, g
.members
);
426 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
428 if (groupId
== null) {
430 g
= new GroupInfo(KeyUtils
.createGroupId());
431 g
.members
.add(username
);
433 g
= getGroupForSending(groupId
);
440 if (members
!= null) {
441 Set
<String
> newMembers
= new HashSet
<>();
442 for (String member
: members
) {
444 member
= Utils
.canonicalizeNumber(member
, username
);
445 } catch (InvalidNumberException e
) {
446 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
447 System
.err
.println("Aborting…");
450 if (g
.members
.contains(member
)) {
453 newMembers
.add(member
);
454 g
.members
.add(member
);
456 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
457 if (contacts
.size() != newMembers
.size()) {
458 // Some of the new members are not registered on Signal
459 for (ContactTokenDetails contact
: contacts
) {
460 newMembers
.remove(contact
.getNumber());
462 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
463 System
.err
.println("Aborting…");
468 if (avatarFile
!= null) {
469 IOUtils
.createPrivateDirectories(avatarsPath
);
470 File aFile
= getGroupAvatarFile(g
.groupId
);
471 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
474 account
.getGroupStore().updateGroup(g
);
476 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
478 // Don't send group message to ourself
479 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
480 membersSend
.remove(this.username
);
481 sendMessageLegacy(messageBuilder
, membersSend
);
485 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
486 if (groupId
== null) {
489 GroupInfo g
= getGroupForSending(groupId
);
491 if (!g
.members
.contains(recipient
)) {
495 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
497 // Send group message only to the recipient who requested it
498 final List
<String
> membersSend
= new ArrayList
<>();
499 membersSend
.add(recipient
);
500 sendMessageLegacy(messageBuilder
, membersSend
);
503 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
504 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
507 .withMembers(new ArrayList
<>(g
.members
));
509 File aFile
= getGroupAvatarFile(g
.groupId
);
510 if (aFile
.exists()) {
512 group
.withAvatar(Utils
.createAttachment(aFile
));
513 } catch (IOException e
) {
514 throw new AttachmentInvalidException(aFile
.toString(), e
);
518 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
519 .asGroupMessage(group
.build());
521 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(g
.groupId
));
522 if (thread
!= null) {
523 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
526 return messageBuilder
;
529 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
530 if (groupId
== null) {
534 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
537 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
538 .asGroupMessage(group
.build());
540 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
541 if (thread
!= null) {
542 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
545 // Send group info request message to the recipient who sent us a message with this groupId
546 final List
<String
> membersSend
= new ArrayList
<>();
547 membersSend
.add(recipient
);
548 sendMessageLegacy(messageBuilder
, membersSend
);
552 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
553 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
554 List
<String
> recipients
= new ArrayList
<>(1);
555 recipients
.add(recipient
);
556 sendMessage(message
, attachments
, recipients
);
560 public void sendMessage(String messageText
, List
<String
> attachments
,
561 List
<String
> recipients
)
562 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
563 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
564 if (attachments
!= null) {
565 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
567 sendMessageLegacy(messageBuilder
, recipients
);
571 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
572 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
573 .asEndSessionMessage();
575 sendMessageLegacy(messageBuilder
, recipients
);
579 public String
getContactName(String number
) {
580 ContactInfo contact
= account
.getContactStore().getContact(number
);
581 if (contact
== null) {
589 public void setContactName(String number
, String name
) {
590 ContactInfo contact
= account
.getContactStore().getContact(number
);
591 if (contact
== null) {
592 contact
= new ContactInfo();
593 contact
.number
= number
;
594 System
.err
.println("Add contact " + number
+ " named " + name
);
596 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
599 account
.getContactStore().updateContact(contact
);
604 public List
<byte[]> getGroupIds() {
605 List
<GroupInfo
> groups
= getGroups();
606 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
607 for (GroupInfo group
: groups
) {
608 ids
.add(group
.groupId
);
614 public String
getGroupName(byte[] groupId
) {
615 GroupInfo group
= getGroup(groupId
);
624 public List
<String
> getGroupMembers(byte[] groupId
) {
625 GroupInfo group
= getGroup(groupId
);
627 return new ArrayList
<>();
629 return new ArrayList
<>(group
.members
);
634 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
635 if (groupId
.length
== 0) {
638 if (name
.isEmpty()) {
641 if (members
.size() == 0) {
644 if (avatar
.isEmpty()) {
647 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
651 * Change the expiration timer for a thread (number of groupId)
653 * @param numberOrGroupId
654 * @param messageExpirationTimer
656 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
657 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
658 thread
.messageExpirationTime
= messageExpirationTimer
;
659 account
.getThreadStore().updateThread(thread
);
662 private void requestSyncGroups() throws IOException
{
663 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
664 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
666 sendSyncMessage(message
);
667 } catch (UntrustedIdentityException e
) {
672 private void requestSyncContacts() throws IOException
{
673 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
674 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
676 sendSyncMessage(message
);
677 } catch (UntrustedIdentityException e
) {
682 private void requestSyncBlocked() throws IOException
{
683 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
684 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
686 sendSyncMessage(message
);
687 } catch (UntrustedIdentityException e
) {
692 private void requestSyncConfiguration() throws IOException
{
693 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
694 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
696 sendSyncMessage(message
);
697 } catch (UntrustedIdentityException e
) {
702 private byte[] getSelfUnidentifiedAccessKey() {
703 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
706 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
711 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
713 return Optional
.absent();
716 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
717 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
718 for (SignalServiceAddress recipient
: recipients
) {
719 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
724 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
726 return Optional
.absent();
729 private void sendSyncMessage(SignalServiceSyncMessage message
)
730 throws IOException
, UntrustedIdentityException
{
731 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
732 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
734 messageSender
.sendMessage(message
, getAccessForSync());
735 } catch (UntrustedIdentityException e
) {
736 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
742 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
744 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
745 throws EncapsulatedExceptions
, IOException
{
746 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
748 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
749 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
750 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
752 for (SendMessageResult result
: results
) {
753 if (result
.isUnregisteredFailure()) {
754 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
755 } else if (result
.isNetworkFailure()) {
756 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
757 } else if (result
.getIdentityFailure() != null) {
758 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
761 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
762 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
766 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
768 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
769 if (recipientsTS
== null) {
771 return Collections
.emptyList();
774 SignalServiceDataMessage message
= null;
776 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
777 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
779 message
= messageBuilder
.build();
780 if (message
.getGroupInfo().isPresent()) {
782 final boolean isRecipientUpdate
= true;
783 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), isRecipientUpdate
, message
);
784 for (SendMessageResult r
: result
) {
785 if (r
.getIdentityFailure() != null) {
786 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
790 } catch (UntrustedIdentityException e
) {
791 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
792 return Collections
.emptyList();
794 } else if (recipientsTS
.size() == 1 && recipientsTS
.contains(new SignalServiceAddress(username
))) {
795 SignalServiceAddress recipient
= new SignalServiceAddress(username
);
796 final Optional
<UnidentifiedAccessPair
> unidentifiedAccess
= getAccessFor(recipient
);
797 SentTranscriptMessage transcript
= new SentTranscriptMessage(recipient
.getNumber(),
798 message
.getTimestamp(),
800 message
.getExpiresInSeconds(),
801 Collections
.singletonMap(recipient
.getNumber(), unidentifiedAccess
.isPresent()),
803 SignalServiceSyncMessage syncMessage
= SignalServiceSyncMessage
.forSentTranscript(transcript
);
805 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
807 messageSender
.sendMessage(syncMessage
, unidentifiedAccess
);
808 } catch (UntrustedIdentityException e
) {
809 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
810 results
.add(SendMessageResult
.identityFailure(recipient
, e
.getIdentityKey()));
814 // Send to all individually, so sync messages are sent correctly
815 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
816 for (SignalServiceAddress address
: recipientsTS
) {
817 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
818 if (thread
!= null) {
819 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
821 messageBuilder
.withExpiration(0);
823 message
= messageBuilder
.build();
825 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
827 } catch (UntrustedIdentityException e
) {
828 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
829 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
835 if (message
!= null && message
.isEndSession()) {
836 for (SignalServiceAddress recipient
: recipientsTS
) {
837 handleEndSession(recipient
.getNumber());
844 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
, UnsupportedDataMessageException
{
845 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
847 return cipher
.decrypt(envelope
);
848 } catch (ProtocolUntrustedIdentityException e
) {
849 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
850 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
855 private void handleEndSession(String source
) {
856 account
.getSignalProtocolStore().deleteAllSessions(source
);
859 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
861 if (message
.getGroupInfo().isPresent()) {
862 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
863 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
864 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
865 switch (groupInfo
.getType()) {
868 group
= new GroupInfo(groupInfo
.getGroupId());
871 if (groupInfo
.getAvatar().isPresent()) {
872 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
873 if (avatar
.isPointer()) {
875 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
876 } catch (IOException
| InvalidMessageException e
) {
877 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
882 if (groupInfo
.getName().isPresent()) {
883 group
.name
= groupInfo
.getName().get();
886 if (groupInfo
.getMembers().isPresent()) {
887 group
.members
.addAll(groupInfo
.getMembers().get());
890 account
.getGroupStore().updateGroup(group
);
895 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
896 } catch (IOException
| EncapsulatedExceptions e
) {
904 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
905 } catch (IOException
| EncapsulatedExceptions e
) {
909 group
.members
.remove(source
);
910 account
.getGroupStore().updateGroup(group
);
916 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
917 } catch (IOException
| EncapsulatedExceptions e
) {
919 } catch (NotAGroupMemberException e
) {
920 // We have left this group, so don't send a group update message
927 threadId
= destination
;
932 if (message
.isEndSession()) {
933 handleEndSession(isSync ? destination
: source
);
935 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
936 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
937 if (thread
== null) {
938 thread
= new ThreadInfo();
939 thread
.id
= threadId
;
941 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
942 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
943 account
.getThreadStore().updateThread(thread
);
946 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
947 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
948 if (attachment
.isPointer()) {
950 retrieveAttachment(attachment
.asPointer());
951 } catch (IOException
| InvalidMessageException e
) {
952 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
957 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
958 if (source
.equals(username
)) {
959 this.account
.setProfileKey(message
.getProfileKey().get());
961 ContactInfo contact
= account
.getContactStore().getContact(source
);
962 if (contact
== null) {
963 contact
= new ContactInfo();
964 contact
.number
= source
;
966 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
970 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
971 final File cachePath
= new File(getMessageCachePath());
972 if (!cachePath
.exists()) {
975 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
976 if (!dir
.isDirectory()) {
980 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
981 if (!fileEntry
.isFile()) {
984 SignalServiceEnvelope envelope
;
986 envelope
= Utils
.loadEnvelope(fileEntry
);
987 if (envelope
== null) {
990 } catch (IOException e
) {
994 SignalServiceContent content
= null;
995 if (!envelope
.isReceipt()) {
997 content
= decryptMessage(envelope
);
998 } catch (Exception e
) {
1001 handleMessage(envelope
, content
, ignoreAttachments
);
1004 handler
.handleMessage(envelope
, content
, null);
1006 Files
.delete(fileEntry
.toPath());
1007 } catch (IOException e
) {
1008 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1011 // Try to delete directory if empty
1016 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1017 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1018 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1021 if (messagePipe
== null) {
1022 messagePipe
= messageReceiver
.createMessagePipe();
1026 SignalServiceEnvelope envelope
;
1027 SignalServiceContent content
= null;
1028 Exception exception
= null;
1029 final long now
= new Date().getTime();
1031 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1033 public void onMessage(SignalServiceEnvelope envelope
) {
1034 // store message on disk, before acknowledging receipt to the server
1036 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1037 Utils
.storeEnvelope(envelope
, cacheFile
);
1038 } catch (IOException e
) {
1039 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1043 } catch (TimeoutException e
) {
1044 if (returnOnTimeout
)
1047 } catch (InvalidVersionException e
) {
1048 System
.err
.println("Ignoring error: " + e
.getMessage());
1051 if (!envelope
.isReceipt()) {
1053 content
= decryptMessage(envelope
);
1054 } catch (Exception e
) {
1057 handleMessage(envelope
, content
, ignoreAttachments
);
1060 handler
.handleMessage(envelope
, content
, exception
);
1061 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1062 File cacheFile
= null;
1064 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1065 Files
.delete(cacheFile
.toPath());
1066 // Try to delete directory if empty
1067 new File(getMessageCachePath()).delete();
1068 } catch (IOException e
) {
1069 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1074 if (messagePipe
!= null) {
1075 messagePipe
.shutdown();
1081 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1082 if (content
!= null) {
1083 if (content
.getDataMessage().isPresent()) {
1084 SignalServiceDataMessage message
= content
.getDataMessage().get();
1085 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1087 if (content
.getSyncMessage().isPresent()) {
1088 account
.setMultiDevice(true);
1089 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1090 if (syncMessage
.getSent().isPresent()) {
1091 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1092 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1094 if (syncMessage
.getRequest().isPresent()) {
1095 RequestMessage rm
= syncMessage
.getRequest().get();
1096 if (rm
.isContactsRequest()) {
1099 } catch (UntrustedIdentityException
| IOException e
) {
1100 e
.printStackTrace();
1103 if (rm
.isGroupsRequest()) {
1106 } catch (UntrustedIdentityException
| IOException e
) {
1107 e
.printStackTrace();
1110 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1112 if (syncMessage
.getGroups().isPresent()) {
1113 File tmpFile
= null;
1115 tmpFile
= IOUtils
.createTempFile();
1116 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1117 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1119 while ((g
= s
.read()) != null) {
1120 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1121 if (syncGroup
== null) {
1122 syncGroup
= new GroupInfo(g
.getId());
1124 if (g
.getName().isPresent()) {
1125 syncGroup
.name
= g
.getName().get();
1127 syncGroup
.members
.addAll(g
.getMembers());
1128 syncGroup
.active
= g
.isActive();
1129 if (g
.getColor().isPresent()) {
1130 syncGroup
.color
= g
.getColor().get();
1133 if (g
.getAvatar().isPresent()) {
1134 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1136 account
.getGroupStore().updateGroup(syncGroup
);
1139 } catch (Exception e
) {
1140 e
.printStackTrace();
1142 if (tmpFile
!= null) {
1144 Files
.delete(tmpFile
.toPath());
1145 } catch (IOException e
) {
1146 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1151 if (syncMessage
.getBlockedList().isPresent()) {
1152 // TODO store list of blocked numbers
1154 if (syncMessage
.getContacts().isPresent()) {
1155 File tmpFile
= null;
1157 tmpFile
= IOUtils
.createTempFile();
1158 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1159 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1160 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1161 if (contactsMessage
.isComplete()) {
1162 account
.getContactStore().clear();
1165 while ((c
= s
.read()) != null) {
1166 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1167 account
.setProfileKey(c
.getProfileKey().get());
1169 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1170 if (contact
== null) {
1171 contact
= new ContactInfo();
1172 contact
.number
= c
.getNumber();
1174 if (c
.getName().isPresent()) {
1175 contact
.name
= c
.getName().get();
1177 if (c
.getColor().isPresent()) {
1178 contact
.color
= c
.getColor().get();
1180 if (c
.getProfileKey().isPresent()) {
1181 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1183 if (c
.getVerified().isPresent()) {
1184 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1185 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1187 if (c
.getExpirationTimer().isPresent()) {
1188 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1189 if (thread
== null) {
1190 thread
= new ThreadInfo();
1191 thread
.id
= c
.getNumber();
1193 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1194 account
.getThreadStore().updateThread(thread
);
1196 if (c
.isBlocked()) {
1197 // TODO store list of blocked numbers
1199 account
.getContactStore().updateContact(contact
);
1201 if (c
.getAvatar().isPresent()) {
1202 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1206 } catch (Exception e
) {
1207 e
.printStackTrace();
1209 if (tmpFile
!= null) {
1211 Files
.delete(tmpFile
.toPath());
1212 } catch (IOException e
) {
1213 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1218 if (syncMessage
.getVerified().isPresent()) {
1219 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1220 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1222 if (syncMessage
.getConfiguration().isPresent()) {
1229 private File
getContactAvatarFile(String number
) {
1230 return new File(avatarsPath
, "contact-" + number
);
1233 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1234 IOUtils
.createPrivateDirectories(avatarsPath
);
1235 if (attachment
.isPointer()) {
1236 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1237 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1239 SignalServiceAttachmentStream stream
= attachment
.asStream();
1240 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1244 private File
getGroupAvatarFile(byte[] groupId
) {
1245 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1248 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1249 IOUtils
.createPrivateDirectories(avatarsPath
);
1250 if (attachment
.isPointer()) {
1251 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1252 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1254 SignalServiceAttachmentStream stream
= attachment
.asStream();
1255 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1259 public File
getAttachmentFile(long attachmentId
) {
1260 return new File(attachmentsPath
, attachmentId
+ "");
1263 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1264 IOUtils
.createPrivateDirectories(attachmentsPath
);
1265 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1268 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1269 if (storePreview
&& pointer
.getPreview().isPresent()) {
1270 File previewFile
= new File(outputFile
+ ".preview");
1271 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1272 byte[] preview
= pointer
.getPreview().get();
1273 output
.write(preview
, 0, preview
.length
);
1274 } catch (FileNotFoundException e
) {
1275 e
.printStackTrace();
1280 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1282 File tmpFile
= IOUtils
.createTempFile();
1283 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1284 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1285 byte[] buffer
= new byte[4096];
1288 while ((read
= input
.read(buffer
)) != -1) {
1289 output
.write(buffer
, 0, read
);
1291 } catch (FileNotFoundException e
) {
1292 e
.printStackTrace();
1297 Files
.delete(tmpFile
.toPath());
1298 } catch (IOException e
) {
1299 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1305 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1306 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1307 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1311 public boolean isRemote() {
1315 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1316 File groupsFile
= IOUtils
.createTempFile();
1319 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1320 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1321 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1322 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1323 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1324 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1325 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1326 Optional
.fromNullable(record.color
), false));
1330 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1331 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1332 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1333 .withStream(groupsFileStream
)
1334 .withContentType("application/octet-stream")
1335 .withLength(groupsFile
.length())
1338 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1343 Files
.delete(groupsFile
.toPath());
1344 } catch (IOException e
) {
1345 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1350 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1351 File contactsFile
= IOUtils
.createTempFile();
1354 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1355 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1356 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1357 VerifiedMessage verifiedMessage
= null;
1358 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1359 if (getIdentities().containsKey(record.number
)) {
1360 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1361 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1362 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1363 currentIdentity
= id
;
1366 if (currentIdentity
!= null) {
1367 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1371 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1372 // TODO store list of blocked numbers
1373 boolean blocked
= false;
1374 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1375 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1376 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1379 if (account
.getProfileKey() != null) {
1380 // Send our own profile key as well
1381 out
.write(new DeviceContact(account
.getUsername(),
1382 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1383 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1384 Optional
.of(account
.getProfileKey()),
1385 false, Optional
.<Integer
>absent()));
1389 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1390 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1391 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1392 .withStream(contactsFileStream
)
1393 .withContentType("application/octet-stream")
1394 .withLength(contactsFile
.length())
1397 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1402 Files
.delete(contactsFile
.toPath());
1403 } catch (IOException e
) {
1404 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1409 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1410 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1411 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1414 public ContactInfo
getContact(String number
) {
1415 return account
.getContactStore().getContact(number
);
1418 public GroupInfo
getGroup(byte[] groupId
) {
1419 return account
.getGroupStore().getGroup(groupId
);
1422 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1423 return account
.getSignalProtocolStore().getIdentities();
1426 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1427 return account
.getSignalProtocolStore().getIdentities(number
);
1431 * Trust this the identity with this fingerprint
1433 * @param name username of the identity
1434 * @param fingerprint Fingerprint
1436 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1437 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1441 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1442 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1446 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1448 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1449 } catch (IOException
| UntrustedIdentityException e
) {
1450 e
.printStackTrace();
1459 * Trust this the identity with this safety number
1461 * @param name username of the identity
1462 * @param safetyNumber Safety number
1464 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1465 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1469 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1470 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1474 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1476 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1477 } catch (IOException
| UntrustedIdentityException e
) {
1478 e
.printStackTrace();
1487 * Trust all keys of this identity without verification
1489 * @param name username of the identity
1491 public boolean trustIdentityAllKeys(String name
) {
1492 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1496 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1497 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1498 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1500 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1501 } catch (IOException
| UntrustedIdentityException e
) {
1502 e
.printStackTrace();
1510 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1511 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1514 public interface ReceiveMessageHandler
{
1516 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);