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());
167 private void createNewIdentity() throws IOException
{
168 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
169 int registrationId
= KeyHelper
.generateRegistrationId(false);
170 if (username
== null) {
171 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
173 byte[] profileKey
= KeyUtils
.createProfileKey();
174 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
179 public boolean isRegistered() {
180 return account
!= null && account
.isRegistered();
183 public void register(boolean voiceVerification
) throws IOException
{
184 if (account
== null) {
187 account
.setPassword(KeyUtils
.createPassword());
188 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, account
.getUsername(), account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
190 if (voiceVerification
)
191 accountManager
.requestVoiceVerificationCode();
193 accountManager
.requestSmsVerificationCode();
195 account
.setRegistered(false);
199 public void updateAccountAttributes() throws IOException
{
200 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
203 public void unregister() throws IOException
{
204 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
205 // If this is the master device, other users can't send messages to this number anymore.
206 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
207 accountManager
.setGcmId(Optional
.<String
>absent());
210 public String
getDeviceLinkUri() throws TimeoutException
, IOException
{
211 if (account
== null) {
214 account
.setPassword(KeyUtils
.createPassword());
215 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
216 String uuid
= accountManager
.getNewDeviceUuid();
218 return Utils
.createDeviceLinkUri(new Utils
.DeviceLinkInfo(uuid
, getIdentity().getPublicKey()));
221 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
222 account
.setSignalingKey(KeyUtils
.createSignalingKey());
223 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
225 username
= ret
.getNumber();
226 // TODO do this check before actually registering
227 if (SignalAccount
.userExists(dataPath
, username
)) {
228 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
231 // Create new account with the synced identity
232 byte[] profileKey
= ret
.getProfileKey();
233 if (profileKey
== null) {
234 profileKey
= KeyUtils
.createProfileKey();
236 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
241 requestSyncContacts();
242 requestSyncBlocked();
243 requestSyncConfiguration();
248 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
249 List
<DeviceInfo
> devices
= accountManager
.getDevices();
250 account
.setMultiDevice(devices
.size() > 1);
254 public void removeLinkedDevices(int deviceId
) throws IOException
{
255 accountManager
.removeDevice(deviceId
);
258 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
259 Utils
.DeviceLinkInfo info
= Utils
.parseDeviceLinkUri(linkUri
);
261 addDevice(info
.deviceIdentifier
, info
.deviceKey
);
264 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
265 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
266 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
268 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
269 account
.setMultiDevice(true);
272 private List
<PreKeyRecord
> generatePreKeys() {
273 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
275 final int offset
= account
.getPreKeyIdOffset();
276 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
277 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
278 ECKeyPair keyPair
= Curve
.generateKeyPair();
279 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
284 account
.addPreKeys(records
);
290 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
292 ECKeyPair keyPair
= Curve
.generateKeyPair();
293 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
294 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
296 account
.addSignedPreKey(record);
300 } catch (InvalidKeyException e
) {
301 throw new AssertionError(e
);
305 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
306 verificationCode
= verificationCode
.replace("-", "");
307 account
.setSignalingKey(KeyUtils
.createSignalingKey());
308 // TODO make unrestricted unidentified access configurable
309 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
311 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
312 account
.setRegistered(true);
313 account
.setRegistrationLockPin(pin
);
319 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
320 accountManager
.setPin(pin
);
321 if (pin
.isPresent()) {
322 account
.setRegistrationLockPin(pin
.get());
324 account
.setRegistrationLockPin(null);
329 private void refreshPreKeys() throws IOException
{
330 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
331 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
332 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
334 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
337 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
338 File file
= getGroupAvatarFile(groupId
);
339 if (!file
.exists()) {
340 return Optional
.absent();
343 return Optional
.of(Utils
.createAttachment(file
));
346 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
347 File file
= getContactAvatarFile(number
);
348 if (!file
.exists()) {
349 return Optional
.absent();
352 return Optional
.of(Utils
.createAttachment(file
));
355 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
356 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
358 throw new GroupNotFoundException(groupId
);
360 for (String member
: g
.members
) {
361 if (member
.equals(this.username
)) {
365 throw new NotAGroupMemberException(groupId
, g
.name
);
368 public List
<GroupInfo
> getGroups() {
369 return account
.getGroupStore().getGroups();
373 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
375 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
376 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
377 if (attachments
!= null) {
378 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
380 if (groupId
!= null) {
381 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
384 messageBuilder
.asGroupMessage(group
);
386 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
387 if (thread
!= null) {
388 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
391 final GroupInfo g
= getGroupForSending(groupId
);
393 // Don't send group message to ourself
394 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
395 membersSend
.remove(this.username
);
396 sendMessageLegacy(messageBuilder
, membersSend
);
399 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
400 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
404 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
405 .asGroupMessage(group
);
407 final GroupInfo g
= getGroupForSending(groupId
);
408 g
.members
.remove(this.username
);
409 account
.getGroupStore().updateGroup(g
);
411 sendMessageLegacy(messageBuilder
, g
.members
);
414 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
416 if (groupId
== null) {
418 g
= new GroupInfo(KeyUtils
.createGroupId());
419 g
.members
.add(username
);
421 g
= getGroupForSending(groupId
);
428 if (members
!= null) {
429 Set
<String
> newMembers
= new HashSet
<>();
430 for (String member
: members
) {
432 member
= Utils
.canonicalizeNumber(member
, username
);
433 } catch (InvalidNumberException e
) {
434 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
435 System
.err
.println("Aborting…");
438 if (g
.members
.contains(member
)) {
441 newMembers
.add(member
);
442 g
.members
.add(member
);
444 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
445 if (contacts
.size() != newMembers
.size()) {
446 // Some of the new members are not registered on Signal
447 for (ContactTokenDetails contact
: contacts
) {
448 newMembers
.remove(contact
.getNumber());
450 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
451 System
.err
.println("Aborting…");
456 if (avatarFile
!= null) {
457 IOUtils
.createPrivateDirectories(avatarsPath
);
458 File aFile
= getGroupAvatarFile(g
.groupId
);
459 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
462 account
.getGroupStore().updateGroup(g
);
464 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
466 // Don't send group message to ourself
467 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
468 membersSend
.remove(this.username
);
469 sendMessageLegacy(messageBuilder
, membersSend
);
473 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
474 if (groupId
== null) {
477 GroupInfo g
= getGroupForSending(groupId
);
479 if (!g
.members
.contains(recipient
)) {
483 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
485 // Send group message only to the recipient who requested it
486 final List
<String
> membersSend
= new ArrayList
<>();
487 membersSend
.add(recipient
);
488 sendMessageLegacy(messageBuilder
, membersSend
);
491 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
492 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
495 .withMembers(new ArrayList
<>(g
.members
));
497 File aFile
= getGroupAvatarFile(g
.groupId
);
498 if (aFile
.exists()) {
500 group
.withAvatar(Utils
.createAttachment(aFile
));
501 } catch (IOException e
) {
502 throw new AttachmentInvalidException(aFile
.toString(), e
);
506 return SignalServiceDataMessage
.newBuilder()
507 .asGroupMessage(group
.build());
510 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
511 if (groupId
== null) {
515 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
518 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
519 .asGroupMessage(group
.build());
521 // Send group info request message to the recipient who sent us a message with this groupId
522 final List
<String
> membersSend
= new ArrayList
<>();
523 membersSend
.add(recipient
);
524 sendMessageLegacy(messageBuilder
, membersSend
);
528 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
529 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
530 List
<String
> recipients
= new ArrayList
<>(1);
531 recipients
.add(recipient
);
532 sendMessage(message
, attachments
, recipients
);
536 public void sendMessage(String messageText
, List
<String
> attachments
,
537 List
<String
> recipients
)
538 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
539 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
540 if (attachments
!= null) {
541 messageBuilder
.withAttachments(Utils
.getSignalServiceAttachments(attachments
));
543 sendMessageLegacy(messageBuilder
, recipients
);
547 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
548 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
549 .asEndSessionMessage();
551 sendMessageLegacy(messageBuilder
, recipients
);
555 public String
getContactName(String number
) {
556 ContactInfo contact
= account
.getContactStore().getContact(number
);
557 if (contact
== null) {
565 public void setContactName(String number
, String name
) {
566 ContactInfo contact
= account
.getContactStore().getContact(number
);
567 if (contact
== null) {
568 contact
= new ContactInfo();
569 contact
.number
= number
;
570 System
.err
.println("Add contact " + number
+ " named " + name
);
572 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
575 account
.getContactStore().updateContact(contact
);
580 public List
<byte[]> getGroupIds() {
581 List
<GroupInfo
> groups
= getGroups();
582 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
583 for (GroupInfo group
: groups
) {
584 ids
.add(group
.groupId
);
590 public String
getGroupName(byte[] groupId
) {
591 GroupInfo group
= getGroup(groupId
);
600 public List
<String
> getGroupMembers(byte[] groupId
) {
601 GroupInfo group
= getGroup(groupId
);
603 return new ArrayList
<>();
605 return new ArrayList
<>(group
.members
);
610 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
611 if (groupId
.length
== 0) {
614 if (name
.isEmpty()) {
617 if (members
.size() == 0) {
620 if (avatar
.isEmpty()) {
623 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
627 * Change the expiration timer for a thread (number of groupId)
629 * @param numberOrGroupId
630 * @param messageExpirationTimer
632 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
633 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
634 thread
.messageExpirationTime
= messageExpirationTimer
;
635 account
.getThreadStore().updateThread(thread
);
638 private void requestSyncGroups() throws IOException
{
639 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
640 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
642 sendSyncMessage(message
);
643 } catch (UntrustedIdentityException e
) {
648 private void requestSyncContacts() throws IOException
{
649 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
650 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
652 sendSyncMessage(message
);
653 } catch (UntrustedIdentityException e
) {
658 private void requestSyncBlocked() throws IOException
{
659 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
660 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
662 sendSyncMessage(message
);
663 } catch (UntrustedIdentityException e
) {
668 private void requestSyncConfiguration() throws IOException
{
669 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
670 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
672 sendSyncMessage(message
);
673 } catch (UntrustedIdentityException e
) {
678 private byte[] getSelfUnidentifiedAccessKey() {
679 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
682 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
687 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
689 return Optional
.absent();
692 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
693 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
694 for (SignalServiceAddress recipient
: recipients
) {
695 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
700 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
702 return Optional
.absent();
705 private void sendSyncMessage(SignalServiceSyncMessage message
)
706 throws IOException
, UntrustedIdentityException
{
707 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
708 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
710 messageSender
.sendMessage(message
, getAccessForSync());
711 } catch (UntrustedIdentityException e
) {
712 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
718 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
720 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
721 throws EncapsulatedExceptions
, IOException
{
722 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
724 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
725 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
726 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
728 for (SendMessageResult result
: results
) {
729 if (result
.isUnregisteredFailure()) {
730 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
731 } else if (result
.isNetworkFailure()) {
732 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
733 } else if (result
.getIdentityFailure() != null) {
734 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
737 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
738 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
742 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
744 Set
<SignalServiceAddress
> recipientsTS
= Utils
.getSignalServiceAddresses(recipients
, username
);
745 if (recipientsTS
== null) {
747 return Collections
.emptyList();
750 SignalServiceDataMessage message
= null;
752 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
753 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
755 message
= messageBuilder
.build();
756 if (message
.getGroupInfo().isPresent()) {
758 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), message
);
759 for (SendMessageResult r
: result
) {
760 if (r
.getIdentityFailure() != null) {
761 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
765 } catch (UntrustedIdentityException e
) {
766 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
767 return Collections
.emptyList();
770 // Send to all individually, so sync messages are sent correctly
771 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
772 for (SignalServiceAddress address
: recipientsTS
) {
773 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
774 if (thread
!= null) {
775 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
777 messageBuilder
.withExpiration(0);
779 message
= messageBuilder
.build();
781 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
783 } catch (UntrustedIdentityException e
) {
784 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
785 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
791 if (message
!= null && message
.isEndSession()) {
792 for (SignalServiceAddress recipient
: recipientsTS
) {
793 handleEndSession(recipient
.getNumber());
800 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
{
801 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), Utils
.getCertificateValidator());
803 return cipher
.decrypt(envelope
);
804 } catch (ProtocolUntrustedIdentityException e
) {
805 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
806 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
811 private void handleEndSession(String source
) {
812 account
.getSignalProtocolStore().deleteAllSessions(source
);
815 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
817 if (message
.getGroupInfo().isPresent()) {
818 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
819 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
820 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
821 switch (groupInfo
.getType()) {
824 group
= new GroupInfo(groupInfo
.getGroupId());
827 if (groupInfo
.getAvatar().isPresent()) {
828 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
829 if (avatar
.isPointer()) {
831 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
832 } catch (IOException
| InvalidMessageException e
) {
833 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
838 if (groupInfo
.getName().isPresent()) {
839 group
.name
= groupInfo
.getName().get();
842 if (groupInfo
.getMembers().isPresent()) {
843 group
.members
.addAll(groupInfo
.getMembers().get());
846 account
.getGroupStore().updateGroup(group
);
851 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
852 } catch (IOException
| EncapsulatedExceptions e
) {
860 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
861 } catch (IOException
| EncapsulatedExceptions e
) {
865 group
.members
.remove(source
);
866 account
.getGroupStore().updateGroup(group
);
872 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
873 } catch (IOException
| EncapsulatedExceptions e
) {
875 } catch (NotAGroupMemberException e
) {
876 // We have left this group, so don't send a group update message
883 threadId
= destination
;
888 if (message
.isEndSession()) {
889 handleEndSession(isSync ? destination
: source
);
891 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
892 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
893 if (thread
== null) {
894 thread
= new ThreadInfo();
895 thread
.id
= threadId
;
897 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
898 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
899 account
.getThreadStore().updateThread(thread
);
902 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
903 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
904 if (attachment
.isPointer()) {
906 retrieveAttachment(attachment
.asPointer());
907 } catch (IOException
| InvalidMessageException e
) {
908 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
913 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
914 if (source
.equals(username
)) {
915 this.account
.setProfileKey(message
.getProfileKey().get());
917 ContactInfo contact
= account
.getContactStore().getContact(source
);
918 if (contact
== null) {
919 contact
= new ContactInfo();
920 contact
.number
= source
;
922 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
926 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
927 final File cachePath
= new File(getMessageCachePath());
928 if (!cachePath
.exists()) {
931 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
932 if (!dir
.isDirectory()) {
936 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
937 if (!fileEntry
.isFile()) {
940 SignalServiceEnvelope envelope
;
942 envelope
= Utils
.loadEnvelope(fileEntry
);
943 if (envelope
== null) {
946 } catch (IOException e
) {
950 SignalServiceContent content
= null;
951 if (!envelope
.isReceipt()) {
953 content
= decryptMessage(envelope
);
954 } catch (Exception e
) {
957 handleMessage(envelope
, content
, ignoreAttachments
);
960 handler
.handleMessage(envelope
, content
, null);
962 Files
.delete(fileEntry
.toPath());
963 } catch (IOException e
) {
964 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
967 // Try to delete directory if empty
972 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
973 retryFailedReceivedMessages(handler
, ignoreAttachments
);
974 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
977 if (messagePipe
== null) {
978 messagePipe
= messageReceiver
.createMessagePipe();
982 SignalServiceEnvelope envelope
;
983 SignalServiceContent content
= null;
984 Exception exception
= null;
985 final long now
= new Date().getTime();
987 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
989 public void onMessage(SignalServiceEnvelope envelope
) {
990 // store message on disk, before acknowledging receipt to the server
992 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
993 Utils
.storeEnvelope(envelope
, cacheFile
);
994 } catch (IOException e
) {
995 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
999 } catch (TimeoutException e
) {
1000 if (returnOnTimeout
)
1003 } catch (InvalidVersionException e
) {
1004 System
.err
.println("Ignoring error: " + e
.getMessage());
1007 if (!envelope
.isReceipt()) {
1009 content
= decryptMessage(envelope
);
1010 } catch (Exception e
) {
1013 handleMessage(envelope
, content
, ignoreAttachments
);
1016 handler
.handleMessage(envelope
, content
, exception
);
1017 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1018 File cacheFile
= null;
1020 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1021 Files
.delete(cacheFile
.toPath());
1022 // Try to delete directory if empty
1023 new File(getMessageCachePath()).delete();
1024 } catch (IOException e
) {
1025 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1030 if (messagePipe
!= null) {
1031 messagePipe
.shutdown();
1037 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1038 if (content
!= null) {
1039 if (content
.getDataMessage().isPresent()) {
1040 SignalServiceDataMessage message
= content
.getDataMessage().get();
1041 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1043 if (content
.getSyncMessage().isPresent()) {
1044 account
.setMultiDevice(true);
1045 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1046 if (syncMessage
.getSent().isPresent()) {
1047 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1048 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1050 if (syncMessage
.getRequest().isPresent()) {
1051 RequestMessage rm
= syncMessage
.getRequest().get();
1052 if (rm
.isContactsRequest()) {
1055 } catch (UntrustedIdentityException
| IOException e
) {
1056 e
.printStackTrace();
1059 if (rm
.isGroupsRequest()) {
1062 } catch (UntrustedIdentityException
| IOException e
) {
1063 e
.printStackTrace();
1066 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1068 if (syncMessage
.getGroups().isPresent()) {
1069 File tmpFile
= null;
1071 tmpFile
= IOUtils
.createTempFile();
1072 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1073 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1075 while ((g
= s
.read()) != null) {
1076 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1077 if (syncGroup
== null) {
1078 syncGroup
= new GroupInfo(g
.getId());
1080 if (g
.getName().isPresent()) {
1081 syncGroup
.name
= g
.getName().get();
1083 syncGroup
.members
.addAll(g
.getMembers());
1084 syncGroup
.active
= g
.isActive();
1085 if (g
.getColor().isPresent()) {
1086 syncGroup
.color
= g
.getColor().get();
1089 if (g
.getAvatar().isPresent()) {
1090 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1092 account
.getGroupStore().updateGroup(syncGroup
);
1095 } catch (Exception e
) {
1096 e
.printStackTrace();
1098 if (tmpFile
!= null) {
1100 Files
.delete(tmpFile
.toPath());
1101 } catch (IOException e
) {
1102 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1107 if (syncMessage
.getBlockedList().isPresent()) {
1108 // TODO store list of blocked numbers
1110 if (syncMessage
.getContacts().isPresent()) {
1111 File tmpFile
= null;
1113 tmpFile
= IOUtils
.createTempFile();
1114 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1115 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1116 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1117 if (contactsMessage
.isComplete()) {
1118 account
.getContactStore().clear();
1121 while ((c
= s
.read()) != null) {
1122 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1123 account
.setProfileKey(c
.getProfileKey().get());
1125 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1126 if (contact
== null) {
1127 contact
= new ContactInfo();
1128 contact
.number
= c
.getNumber();
1130 if (c
.getName().isPresent()) {
1131 contact
.name
= c
.getName().get();
1133 if (c
.getColor().isPresent()) {
1134 contact
.color
= c
.getColor().get();
1136 if (c
.getProfileKey().isPresent()) {
1137 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1139 if (c
.getVerified().isPresent()) {
1140 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1141 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1143 if (c
.getExpirationTimer().isPresent()) {
1144 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1145 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1146 account
.getThreadStore().updateThread(thread
);
1148 if (c
.isBlocked()) {
1149 // TODO store list of blocked numbers
1151 account
.getContactStore().updateContact(contact
);
1153 if (c
.getAvatar().isPresent()) {
1154 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1158 } catch (Exception e
) {
1159 e
.printStackTrace();
1161 if (tmpFile
!= null) {
1163 Files
.delete(tmpFile
.toPath());
1164 } catch (IOException e
) {
1165 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1170 if (syncMessage
.getVerified().isPresent()) {
1171 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1172 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1174 if (syncMessage
.getConfiguration().isPresent()) {
1181 private File
getContactAvatarFile(String number
) {
1182 return new File(avatarsPath
, "contact-" + number
);
1185 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1186 IOUtils
.createPrivateDirectories(avatarsPath
);
1187 if (attachment
.isPointer()) {
1188 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1189 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1191 SignalServiceAttachmentStream stream
= attachment
.asStream();
1192 return Utils
.retrieveAttachment(stream
, getContactAvatarFile(number
));
1196 private File
getGroupAvatarFile(byte[] groupId
) {
1197 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1200 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1201 IOUtils
.createPrivateDirectories(avatarsPath
);
1202 if (attachment
.isPointer()) {
1203 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1204 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1206 SignalServiceAttachmentStream stream
= attachment
.asStream();
1207 return Utils
.retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1211 public File
getAttachmentFile(long attachmentId
) {
1212 return new File(attachmentsPath
, attachmentId
+ "");
1215 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1216 IOUtils
.createPrivateDirectories(attachmentsPath
);
1217 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1220 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1221 if (storePreview
&& pointer
.getPreview().isPresent()) {
1222 File previewFile
= new File(outputFile
+ ".preview");
1223 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1224 byte[] preview
= pointer
.getPreview().get();
1225 output
.write(preview
, 0, preview
.length
);
1226 } catch (FileNotFoundException e
) {
1227 e
.printStackTrace();
1232 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1234 File tmpFile
= IOUtils
.createTempFile();
1235 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1236 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1237 byte[] buffer
= new byte[4096];
1240 while ((read
= input
.read(buffer
)) != -1) {
1241 output
.write(buffer
, 0, read
);
1243 } catch (FileNotFoundException e
) {
1244 e
.printStackTrace();
1249 Files
.delete(tmpFile
.toPath());
1250 } catch (IOException e
) {
1251 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1257 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1258 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1259 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1263 public boolean isRemote() {
1267 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1268 File groupsFile
= IOUtils
.createTempFile();
1271 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1272 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1273 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1274 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1275 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1276 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1277 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1278 Optional
.fromNullable(record.color
), false));
1282 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1283 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1284 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1285 .withStream(groupsFileStream
)
1286 .withContentType("application/octet-stream")
1287 .withLength(groupsFile
.length())
1290 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1295 Files
.delete(groupsFile
.toPath());
1296 } catch (IOException e
) {
1297 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1302 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1303 File contactsFile
= IOUtils
.createTempFile();
1306 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1307 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1308 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1309 VerifiedMessage verifiedMessage
= null;
1310 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1311 if (getIdentities().containsKey(record.number
)) {
1312 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1313 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1314 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1315 currentIdentity
= id
;
1318 if (currentIdentity
!= null) {
1319 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1323 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1324 // TODO store list of blocked numbers
1325 boolean blocked
= false;
1326 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1327 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1328 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1331 if (account
.getProfileKey() != null) {
1332 // Send our own profile key as well
1333 out
.write(new DeviceContact(account
.getUsername(),
1334 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1335 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1336 Optional
.of(account
.getProfileKey()),
1337 false, Optional
.<Integer
>absent()));
1341 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1342 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1343 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1344 .withStream(contactsFileStream
)
1345 .withContentType("application/octet-stream")
1346 .withLength(contactsFile
.length())
1349 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1354 Files
.delete(contactsFile
.toPath());
1355 } catch (IOException e
) {
1356 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1361 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1362 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1363 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1366 public ContactInfo
getContact(String number
) {
1367 return account
.getContactStore().getContact(number
);
1370 public GroupInfo
getGroup(byte[] groupId
) {
1371 return account
.getGroupStore().getGroup(groupId
);
1374 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1375 return account
.getSignalProtocolStore().getIdentities();
1378 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1379 return account
.getSignalProtocolStore().getIdentities(number
);
1383 * Trust this the identity with this fingerprint
1385 * @param name username of the identity
1386 * @param fingerprint Fingerprint
1388 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1389 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1393 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1394 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1398 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1400 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1401 } catch (IOException
| UntrustedIdentityException e
) {
1402 e
.printStackTrace();
1411 * Trust this the identity with this safety number
1413 * @param name username of the identity
1414 * @param safetyNumber Safety number
1416 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1417 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1421 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1422 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1426 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1428 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1429 } catch (IOException
| UntrustedIdentityException e
) {
1430 e
.printStackTrace();
1439 * Trust all keys of this identity without verification
1441 * @param name username of the identity
1443 public boolean trustIdentityAllKeys(String name
) {
1444 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1448 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1449 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1450 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1452 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1453 } catch (IOException
| UntrustedIdentityException e
) {
1454 e
.printStackTrace();
1462 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1463 return Utils
.computeSafetyNumber(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1466 public interface ReceiveMessageHandler
{
1468 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);