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
.apache
.http
.util
.TextUtils
;
20 import org
.asamk
.Signal
;
21 import org
.asamk
.signal
.*;
22 import org
.asamk
.signal
.storage
.SignalAccount
;
23 import org
.asamk
.signal
.storage
.contacts
.ContactInfo
;
24 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
25 import org
.asamk
.signal
.storage
.groups
.JsonGroupStore
;
26 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
27 import org
.asamk
.signal
.storage
.threads
.ThreadInfo
;
28 import org
.asamk
.signal
.util
.IOUtils
;
29 import org
.asamk
.signal
.util
.Util
;
30 import org
.signal
.libsignal
.metadata
.*;
31 import org
.signal
.libsignal
.metadata
.certificate
.CertificateValidator
;
32 import org
.whispersystems
.libsignal
.*;
33 import org
.whispersystems
.libsignal
.ecc
.Curve
;
34 import org
.whispersystems
.libsignal
.ecc
.ECKeyPair
;
35 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
36 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
37 import org
.whispersystems
.libsignal
.fingerprint
.NumericFingerprintGenerator
;
38 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
39 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
40 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
41 import org
.whispersystems
.libsignal
.util
.Medium
;
42 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
43 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
44 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
45 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
46 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
47 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
48 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccess
;
49 import org
.whispersystems
.signalservice
.api
.crypto
.UnidentifiedAccessPair
;
50 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
51 import org
.whispersystems
.signalservice
.api
.messages
.*;
52 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
53 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
54 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
55 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
56 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.EncapsulatedExceptions
;
57 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NetworkFailureException
;
58 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
59 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
60 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
61 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
62 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
63 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
64 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
68 import java
.net
.URISyntaxException
;
69 import java
.net
.URLEncoder
;
70 import java
.nio
.file
.Files
;
71 import java
.nio
.file
.Paths
;
72 import java
.nio
.file
.StandardCopyOption
;
74 import java
.util
.concurrent
.TimeUnit
;
75 import java
.util
.concurrent
.TimeoutException
;
77 public class Manager
implements Signal
{
79 private final String settingsPath
;
80 private final String dataPath
;
81 private final String attachmentsPath
;
82 private final String avatarsPath
;
84 private SignalAccount account
;
86 private String username
;
87 private SignalServiceAccountManager accountManager
;
88 private SignalServiceMessagePipe messagePipe
= null;
89 private SignalServiceMessagePipe unidentifiedMessagePipe
= null;
91 private SleepTimer timer
= new UptimeSleepTimer();
93 public Manager(String username
, String settingsPath
) {
94 this.username
= username
;
95 this.settingsPath
= settingsPath
;
96 this.dataPath
= this.settingsPath
+ "/data";
97 this.attachmentsPath
= this.settingsPath
+ "/attachments";
98 this.avatarsPath
= this.settingsPath
+ "/avatars";
102 private static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
103 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
104 if (attachments
!= null) {
105 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
106 for (String attachment
: attachments
) {
108 SignalServiceAttachments
.add(createAttachment(new File(attachment
)));
109 } catch (IOException e
) {
110 throw new AttachmentInvalidException(attachment
, e
);
114 return SignalServiceAttachments
;
117 private static SignalServiceAttachmentStream
createAttachment(File attachmentFile
) throws IOException
{
118 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
119 final long attachmentSize
= attachmentFile
.length();
120 String mime
= Files
.probeContentType(attachmentFile
.toPath());
122 mime
= "application/octet-stream";
124 // TODO mabybe add a parameter to set the voiceNote, preview, width, height and caption option
125 Optional
<byte[]> preview
= Optional
.absent();
126 Optional
<String
> caption
= Optional
.absent();
127 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, Optional
.of(attachmentFile
.getName()), false, preview
, 0, 0, caption
, null);
130 private static CertificateValidator
getCertificateValidator() {
132 ECPublicKey unidentifiedSenderTrustRoot
= Curve
.decodePoint(Base64
.decode(BaseConfig
.UNIDENTIFIED_SENDER_TRUST_ROOT
), 0);
133 return new CertificateValidator(unidentifiedSenderTrustRoot
);
134 } catch (InvalidKeyException
| IOException e
) {
135 throw new AssertionError(e
);
139 public String
getUsername() {
143 private IdentityKey
getIdentity() {
144 return account
.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
147 public int getDeviceId() {
148 return account
.getDeviceId();
151 private String
getMessageCachePath() {
152 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
155 private String
getMessageCachePath(String sender
) {
156 return getMessageCachePath() + "/" + sender
.replace("/", "_");
159 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
160 String cachePath
= getMessageCachePath(sender
);
161 IOUtils
.createPrivateDirectories(cachePath
);
162 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
165 public boolean userHasKeys() {
166 return account
.getSignalProtocolStore() != null;
169 public void init() throws IOException
{
170 if (!SignalAccount
.userExists(dataPath
, username
)) {
173 account
= SignalAccount
.load(dataPath
, username
);
175 migrateLegacyConfigs();
177 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), BaseConfig
.USER_AGENT
, timer
);
179 if (account
.isRegistered() && accountManager
.getPreKeysCount() < BaseConfig
.PREKEY_MINIMUM_COUNT
) {
183 } catch (AuthorizationFailedException e
) {
184 System
.err
.println("Authorization failed, was the number registered elsewhere?");
188 private void migrateLegacyConfigs() {
189 // Copy group avatars that were previously stored in the attachments folder
190 // to the new avatar folder
191 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
192 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
193 File avatarFile
= getGroupAvatarFile(g
.groupId
);
194 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
195 if (!avatarFile
.exists() && attachmentFile
.exists()) {
197 IOUtils
.createPrivateDirectories(avatarsPath
);
198 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
199 } catch (Exception e
) {
204 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
207 if (account
.getProfileKey() == null) {
208 // Old config file, creating new profile key
209 account
.setProfileKey(KeyUtils
.createProfileKey());
213 private void createNewIdentity() throws IOException
{
214 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
215 int registrationId
= KeyHelper
.generateRegistrationId(false);
216 if (username
== null) {
217 account
= SignalAccount
.createTemporaryAccount(identityKey
, registrationId
);
219 byte[] profileKey
= KeyUtils
.createProfileKey();
220 account
= SignalAccount
.create(dataPath
, username
, identityKey
, registrationId
, profileKey
);
225 public boolean isRegistered() {
226 return account
!= null && account
.isRegistered();
229 public void register(boolean voiceVerification
) throws IOException
{
230 if (account
== null) {
233 account
.setPassword(KeyUtils
.createPassword());
234 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, account
.getUsername(), account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
236 if (voiceVerification
)
237 accountManager
.requestVoiceVerificationCode();
239 accountManager
.requestSmsVerificationCode();
241 account
.setRegistered(false);
245 public void updateAccountAttributes() throws IOException
{
246 accountManager
.setAccountAttributes(account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, account
.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
249 public void unregister() throws IOException
{
250 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
251 // If this is the master device, other users can't send messages to this number anymore.
252 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
253 accountManager
.setGcmId(Optional
.<String
>absent());
256 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
257 if (account
== null) {
260 account
.setPassword(KeyUtils
.createPassword());
261 accountManager
= new SignalServiceAccountManager(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), BaseConfig
.USER_AGENT
, timer
);
262 String uuid
= accountManager
.getNewDeviceUuid();
265 return new URI("tsdevice:/?uuid=" + URLEncoder
.encode(uuid
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(getIdentity().serialize()), "utf-8"));
266 } catch (URISyntaxException e
) {
272 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
273 account
.setSignalingKey(KeyUtils
.createSignalingKey());
274 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(account
.getSignalProtocolStore().getIdentityKeyPair(), account
.getSignalingKey(), false, true, account
.getSignalProtocolStore().getLocalRegistrationId(), deviceName
);
276 username
= ret
.getNumber();
277 // TODO do this check before actually registering
278 if (SignalAccount
.userExists(dataPath
, username
)) {
279 throw new UserAlreadyExists(username
, SignalAccount
.getFileName(dataPath
, username
));
282 // Create new account with the synced identity
283 byte[] profileKey
= ret
.getProfileKey();
284 if (profileKey
== null) {
285 profileKey
= KeyUtils
.createProfileKey();
287 account
= SignalAccount
.createLinkedAccount(dataPath
, username
, account
.getPassword(), ret
.getDeviceId(), ret
.getIdentity(), account
.getSignalProtocolStore().getLocalRegistrationId(), account
.getSignalingKey(), profileKey
);
292 requestSyncContacts();
297 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
298 List
<DeviceInfo
> devices
= accountManager
.getDevices();
299 account
.setMultiDevice(devices
.size() > 1);
303 public void removeLinkedDevices(int deviceId
) throws IOException
{
304 accountManager
.removeDevice(deviceId
);
307 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
308 Map
<String
, String
> query
= Util
.getQueryMap(linkUri
.getRawQuery());
309 String deviceIdentifier
= query
.get("uuid");
310 String publicKeyEncoded
= query
.get("pub_key");
312 if (TextUtils
.isEmpty(deviceIdentifier
) || TextUtils
.isEmpty(publicKeyEncoded
)) {
313 throw new RuntimeException("Invalid device link uri");
316 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
318 addDevice(deviceIdentifier
, deviceKey
);
321 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
322 IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
323 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
325 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.of(account
.getProfileKey()), verificationCode
);
326 account
.setMultiDevice(true);
329 private List
<PreKeyRecord
> generatePreKeys() {
330 List
<PreKeyRecord
> records
= new ArrayList
<>(BaseConfig
.PREKEY_BATCH_SIZE
);
332 final int offset
= account
.getPreKeyIdOffset();
333 for (int i
= 0; i
< BaseConfig
.PREKEY_BATCH_SIZE
; i
++) {
334 int preKeyId
= (offset
+ i
) % Medium
.MAX_VALUE
;
335 ECKeyPair keyPair
= Curve
.generateKeyPair();
336 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
341 account
.addPreKeys(records
);
347 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
349 ECKeyPair keyPair
= Curve
.generateKeyPair();
350 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
351 SignedPreKeyRecord
record = new SignedPreKeyRecord(account
.getNextSignedPreKeyId(), System
.currentTimeMillis(), keyPair
, signature
);
353 account
.addSignedPreKey(record);
357 } catch (InvalidKeyException e
) {
358 throw new AssertionError(e
);
362 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
363 verificationCode
= verificationCode
.replace("-", "");
364 account
.setSignalingKey(KeyUtils
.createSignalingKey());
365 accountManager
.verifyAccountWithCode(verificationCode
, account
.getSignalingKey(), account
.getSignalProtocolStore().getLocalRegistrationId(), true, pin
, getSelfUnidentifiedAccessKey(), false);
367 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
368 account
.setRegistered(true);
369 account
.setRegistrationLockPin(pin
);
375 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
376 accountManager
.setPin(pin
);
377 if (pin
.isPresent()) {
378 account
.setRegistrationLockPin(pin
.get());
380 account
.setRegistrationLockPin(null);
384 private void refreshPreKeys() throws IOException
{
385 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
386 final IdentityKeyPair identityKeyPair
= account
.getSignalProtocolStore().getIdentityKeyPair();
387 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(identityKeyPair
);
389 accountManager
.setPreKeys(getIdentity(), signedPreKeyRecord
, oneTimePreKeys
);
392 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
393 File file
= getGroupAvatarFile(groupId
);
394 if (!file
.exists()) {
395 return Optional
.absent();
398 return Optional
.of(createAttachment(file
));
401 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
402 File file
= getContactAvatarFile(number
);
403 if (!file
.exists()) {
404 return Optional
.absent();
407 return Optional
.of(createAttachment(file
));
410 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
411 GroupInfo g
= account
.getGroupStore().getGroup(groupId
);
413 throw new GroupNotFoundException(groupId
);
415 for (String member
: g
.members
) {
416 if (member
.equals(this.username
)) {
420 throw new NotAGroupMemberException(groupId
, g
.name
);
423 public List
<GroupInfo
> getGroups() {
424 return account
.getGroupStore().getGroups();
428 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
430 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
431 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
432 if (attachments
!= null) {
433 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
435 if (groupId
!= null) {
436 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
439 messageBuilder
.asGroupMessage(group
);
441 ThreadInfo thread
= account
.getThreadStore().getThread(Base64
.encodeBytes(groupId
));
442 if (thread
!= null) {
443 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
446 final GroupInfo g
= getGroupForSending(groupId
);
448 // Don't send group message to ourself
449 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
450 membersSend
.remove(this.username
);
451 sendMessageLegacy(messageBuilder
, membersSend
);
454 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
455 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
459 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
460 .asGroupMessage(group
);
462 final GroupInfo g
= getGroupForSending(groupId
);
463 g
.members
.remove(this.username
);
464 account
.getGroupStore().updateGroup(g
);
466 sendMessageLegacy(messageBuilder
, g
.members
);
469 private byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
471 if (groupId
== null) {
473 g
= new GroupInfo(KeyUtils
.createGroupId());
474 g
.members
.add(username
);
476 g
= getGroupForSending(groupId
);
483 if (members
!= null) {
484 Set
<String
> newMembers
= new HashSet
<>();
485 for (String member
: members
) {
487 member
= canonicalizeNumber(member
);
488 } catch (InvalidNumberException e
) {
489 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
490 System
.err
.println("Aborting…");
493 if (g
.members
.contains(member
)) {
496 newMembers
.add(member
);
497 g
.members
.add(member
);
499 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
500 if (contacts
.size() != newMembers
.size()) {
501 // Some of the new members are not registered on Signal
502 for (ContactTokenDetails contact
: contacts
) {
503 newMembers
.remove(contact
.getNumber());
505 System
.err
.println("Failed to add members " + Util
.join(", ", newMembers
) + " to group: Not registered on Signal");
506 System
.err
.println("Aborting…");
511 if (avatarFile
!= null) {
512 IOUtils
.createPrivateDirectories(avatarsPath
);
513 File aFile
= getGroupAvatarFile(g
.groupId
);
514 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
517 account
.getGroupStore().updateGroup(g
);
519 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
521 // Don't send group message to ourself
522 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
523 membersSend
.remove(this.username
);
524 sendMessageLegacy(messageBuilder
, membersSend
);
528 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
529 if (groupId
== null) {
532 GroupInfo g
= getGroupForSending(groupId
);
534 if (!g
.members
.contains(recipient
)) {
538 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
540 // Send group message only to the recipient who requested it
541 final List
<String
> membersSend
= new ArrayList
<>();
542 membersSend
.add(recipient
);
543 sendMessageLegacy(messageBuilder
, membersSend
);
546 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
547 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
550 .withMembers(new ArrayList
<>(g
.members
));
552 File aFile
= getGroupAvatarFile(g
.groupId
);
553 if (aFile
.exists()) {
555 group
.withAvatar(createAttachment(aFile
));
556 } catch (IOException e
) {
557 throw new AttachmentInvalidException(aFile
.toString(), e
);
561 return SignalServiceDataMessage
.newBuilder()
562 .asGroupMessage(group
.build());
565 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
566 if (groupId
== null) {
570 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
573 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
574 .asGroupMessage(group
.build());
576 // Send group info request message to the recipient who sent us a message with this groupId
577 final List
<String
> membersSend
= new ArrayList
<>();
578 membersSend
.add(recipient
);
579 sendMessageLegacy(messageBuilder
, membersSend
);
583 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
584 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
585 List
<String
> recipients
= new ArrayList
<>(1);
586 recipients
.add(recipient
);
587 sendMessage(message
, attachments
, recipients
);
591 public void sendMessage(String messageText
, List
<String
> attachments
,
592 List
<String
> recipients
)
593 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
594 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
595 if (attachments
!= null) {
596 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
598 sendMessageLegacy(messageBuilder
, recipients
);
602 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
603 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
604 .asEndSessionMessage();
606 sendMessageLegacy(messageBuilder
, recipients
);
610 public String
getContactName(String number
) {
611 ContactInfo contact
= account
.getContactStore().getContact(number
);
612 if (contact
== null) {
620 public void setContactName(String number
, String name
) {
621 ContactInfo contact
= account
.getContactStore().getContact(number
);
622 if (contact
== null) {
623 contact
= new ContactInfo();
624 contact
.number
= number
;
625 System
.err
.println("Add contact " + number
+ " named " + name
);
627 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
630 account
.getContactStore().updateContact(contact
);
635 public List
<byte[]> getGroupIds() {
636 List
<GroupInfo
> groups
= getGroups();
637 List
<byte[]> ids
= new ArrayList
<>(groups
.size());
638 for (GroupInfo group
: groups
) {
639 ids
.add(group
.groupId
);
645 public String
getGroupName(byte[] groupId
) {
646 GroupInfo group
= getGroup(groupId
);
655 public List
<String
> getGroupMembers(byte[] groupId
) {
656 GroupInfo group
= getGroup(groupId
);
658 return new ArrayList
<>();
660 return new ArrayList
<>(group
.members
);
665 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
666 if (groupId
.length
== 0) {
669 if (name
.isEmpty()) {
672 if (members
.size() == 0) {
675 if (avatar
.isEmpty()) {
678 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
682 * Change the expiration timer for a thread (number of groupId)
684 * @param numberOrGroupId
685 * @param messageExpirationTimer
687 public void setExpirationTimer(String numberOrGroupId
, int messageExpirationTimer
) {
688 ThreadInfo thread
= account
.getThreadStore().getThread(numberOrGroupId
);
689 thread
.messageExpirationTime
= messageExpirationTimer
;
690 account
.getThreadStore().updateThread(thread
);
693 private void requestSyncGroups() throws IOException
{
694 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
695 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
697 sendSyncMessage(message
);
698 } catch (UntrustedIdentityException e
) {
703 private void requestSyncContacts() throws IOException
{
704 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
705 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
707 sendSyncMessage(message
);
708 } catch (UntrustedIdentityException e
) {
713 private void requestSyncBlocked() throws IOException
{
714 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.BLOCKED
).build();
715 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
717 sendSyncMessage(message
);
718 } catch (UntrustedIdentityException e
) {
723 private void requestSyncConfiguration() throws IOException
{
724 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONFIGURATION
).build();
725 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
727 sendSyncMessage(message
);
728 } catch (UntrustedIdentityException e
) {
733 private byte[] getSelfUnidentifiedAccessKey() {
734 return UnidentifiedAccess
.deriveAccessKeyFrom(account
.getProfileKey());
737 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient
) {
742 private Optional
<UnidentifiedAccessPair
> getAccessForSync() {
744 return Optional
.absent();
747 private List
<Optional
<UnidentifiedAccessPair
>> getAccessFor(Collection
<SignalServiceAddress
> recipients
) {
748 List
<Optional
<UnidentifiedAccessPair
>> result
= new ArrayList
<>(recipients
.size());
749 for (SignalServiceAddress recipient
: recipients
) {
750 result
.add(Optional
.<UnidentifiedAccessPair
>absent());
755 private Optional
<UnidentifiedAccessPair
> getAccessFor(SignalServiceAddress recipient
) {
757 return Optional
.absent();
760 private void sendSyncMessage(SignalServiceSyncMessage message
)
761 throws IOException
, UntrustedIdentityException
{
762 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
763 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
765 messageSender
.sendMessage(message
, getAccessForSync());
766 } catch (UntrustedIdentityException e
) {
767 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
773 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
775 private void sendMessageLegacy(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
776 throws EncapsulatedExceptions
, IOException
{
777 List
<SendMessageResult
> results
= sendMessage(messageBuilder
, recipients
);
779 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
780 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
781 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
783 for (SendMessageResult result
: results
) {
784 if (result
.isUnregisteredFailure()) {
785 unregisteredUsers
.add(new UnregisteredUserException(result
.getAddress().getNumber(), null));
786 } else if (result
.isNetworkFailure()) {
787 networkExceptions
.add(new NetworkFailureException(result
.getAddress().getNumber(), null));
788 } else if (result
.getIdentityFailure() != null) {
789 untrustedIdentities
.add(new UntrustedIdentityException("Untrusted", result
.getAddress().getNumber(), result
.getIdentityFailure().getIdentityKey()));
792 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
793 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
797 private List
<SendMessageResult
> sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
799 Set
<SignalServiceAddress
> recipientsTS
= getSignalServiceAddresses(recipients
);
800 if (recipientsTS
== null) return Collections
.emptyList();
802 SignalServiceDataMessage message
= null;
804 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(),
805 account
.getDeviceId(), account
.getSignalProtocolStore(), BaseConfig
.USER_AGENT
, account
.isMultiDevice(), Optional
.fromNullable(messagePipe
), Optional
.fromNullable(unidentifiedMessagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
807 message
= messageBuilder
.build();
808 if (message
.getGroupInfo().isPresent()) {
810 List
<SendMessageResult
> result
= messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), getAccessFor(recipientsTS
), message
);
811 for (SendMessageResult r
: result
) {
812 if (r
.getIdentityFailure() != null) {
813 account
.getSignalProtocolStore().saveIdentity(r
.getAddress().getNumber(), r
.getIdentityFailure().getIdentityKey(), TrustLevel
.UNTRUSTED
);
817 } catch (UntrustedIdentityException e
) {
818 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
819 return Collections
.emptyList();
822 // Send to all individually, so sync messages are sent correctly
823 List
<SendMessageResult
> results
= new ArrayList
<>(recipientsTS
.size());
824 for (SignalServiceAddress address
: recipientsTS
) {
825 ThreadInfo thread
= account
.getThreadStore().getThread(address
.getNumber());
826 if (thread
!= null) {
827 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
829 messageBuilder
.withExpiration(0);
831 message
= messageBuilder
.build();
833 SendMessageResult result
= messageSender
.sendMessage(address
, getAccessFor(address
), message
);
835 } catch (UntrustedIdentityException e
) {
836 account
.getSignalProtocolStore().saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
837 results
.add(SendMessageResult
.identityFailure(address
, e
.getIdentityKey()));
843 if (message
!= null && message
.isEndSession()) {
844 for (SignalServiceAddress recipient
: recipientsTS
) {
845 handleEndSession(recipient
.getNumber());
852 private Set
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> recipients
) {
853 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
854 for (String recipient
: recipients
) {
856 recipientsTS
.add(getPushAddress(recipient
));
857 } catch (InvalidNumberException e
) {
858 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
859 System
.err
.println("Aborting sending.");
867 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws InvalidMetadataMessageException
, ProtocolInvalidMessageException
, ProtocolDuplicateMessageException
, ProtocolLegacyMessageException
, ProtocolInvalidKeyIdException
, InvalidMetadataVersionException
, ProtocolInvalidVersionException
, ProtocolNoSessionException
, ProtocolInvalidKeyException
, ProtocolUntrustedIdentityException
, SelfSendException
{
868 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), account
.getSignalProtocolStore(), getCertificateValidator());
870 return cipher
.decrypt(envelope
);
871 } catch (ProtocolUntrustedIdentityException e
) {
872 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
873 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
878 private void handleEndSession(String source
) {
879 account
.getSignalProtocolStore().deleteAllSessions(source
);
882 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
884 if (message
.getGroupInfo().isPresent()) {
885 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
886 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
887 GroupInfo group
= account
.getGroupStore().getGroup(groupInfo
.getGroupId());
888 switch (groupInfo
.getType()) {
891 group
= new GroupInfo(groupInfo
.getGroupId());
894 if (groupInfo
.getAvatar().isPresent()) {
895 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
896 if (avatar
.isPointer()) {
898 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
899 } catch (IOException
| InvalidMessageException e
) {
900 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
905 if (groupInfo
.getName().isPresent()) {
906 group
.name
= groupInfo
.getName().get();
909 if (groupInfo
.getMembers().isPresent()) {
910 group
.members
.addAll(groupInfo
.getMembers().get());
913 account
.getGroupStore().updateGroup(group
);
918 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
919 } catch (IOException
| EncapsulatedExceptions e
) {
927 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
928 } catch (IOException
| EncapsulatedExceptions e
) {
932 group
.members
.remove(source
);
933 account
.getGroupStore().updateGroup(group
);
939 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
940 } catch (IOException
| EncapsulatedExceptions e
) {
942 } catch (NotAGroupMemberException e
) {
943 // We have left this group, so don't send a group update message
950 threadId
= destination
;
955 if (message
.isEndSession()) {
956 handleEndSession(isSync ? destination
: source
);
958 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
959 ThreadInfo thread
= account
.getThreadStore().getThread(threadId
);
960 if (thread
== null) {
961 thread
= new ThreadInfo();
962 thread
.id
= threadId
;
964 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
965 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
966 account
.getThreadStore().updateThread(thread
);
969 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
970 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
971 if (attachment
.isPointer()) {
973 retrieveAttachment(attachment
.asPointer());
974 } catch (IOException
| InvalidMessageException e
) {
975 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
980 if (message
.getProfileKey().isPresent() && message
.getProfileKey().get().length
== 32) {
981 ContactInfo contact
= account
.getContactStore().getContact(source
);
982 if (contact
== null) {
983 contact
= new ContactInfo();
984 contact
.number
= source
;
986 contact
.profileKey
= Base64
.encodeBytes(message
.getProfileKey().get());
990 private void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
991 final File cachePath
= new File(getMessageCachePath());
992 if (!cachePath
.exists()) {
995 for (final File dir
: Objects
.requireNonNull(cachePath
.listFiles())) {
996 if (!dir
.isDirectory()) {
1000 for (final File fileEntry
: Objects
.requireNonNull(dir
.listFiles())) {
1001 if (!fileEntry
.isFile()) {
1004 SignalServiceEnvelope envelope
;
1006 envelope
= loadEnvelope(fileEntry
);
1007 if (envelope
== null) {
1010 } catch (IOException e
) {
1011 e
.printStackTrace();
1014 SignalServiceContent content
= null;
1015 if (!envelope
.isReceipt()) {
1017 content
= decryptMessage(envelope
);
1018 } catch (Exception e
) {
1021 handleMessage(envelope
, content
, ignoreAttachments
);
1024 handler
.handleMessage(envelope
, content
, null);
1026 Files
.delete(fileEntry
.toPath());
1027 } catch (IOException e
) {
1028 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1031 // Try to delete directory if empty
1036 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1037 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1038 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1041 if (messagePipe
== null) {
1042 messagePipe
= messageReceiver
.createMessagePipe();
1046 SignalServiceEnvelope envelope
;
1047 SignalServiceContent content
= null;
1048 Exception exception
= null;
1049 final long now
= new Date().getTime();
1051 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1053 public void onMessage(SignalServiceEnvelope envelope
) {
1054 // store message on disk, before acknowledging receipt to the server
1056 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1057 storeEnvelope(envelope
, cacheFile
);
1058 } catch (IOException e
) {
1059 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1063 } catch (TimeoutException e
) {
1064 if (returnOnTimeout
)
1067 } catch (InvalidVersionException e
) {
1068 System
.err
.println("Ignoring error: " + e
.getMessage());
1071 if (!envelope
.isReceipt()) {
1073 content
= decryptMessage(envelope
);
1074 } catch (Exception e
) {
1077 handleMessage(envelope
, content
, ignoreAttachments
);
1080 handler
.handleMessage(envelope
, content
, exception
);
1081 if (!(exception
instanceof ProtocolUntrustedIdentityException
)) {
1082 File cacheFile
= null;
1084 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1085 Files
.delete(cacheFile
.toPath());
1086 // Try to delete directory if empty
1087 new File(getMessageCachePath()).delete();
1088 } catch (IOException e
) {
1089 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1094 if (messagePipe
!= null) {
1095 messagePipe
.shutdown();
1101 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1102 if (content
!= null) {
1103 if (content
.getDataMessage().isPresent()) {
1104 SignalServiceDataMessage message
= content
.getDataMessage().get();
1105 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1107 if (content
.getSyncMessage().isPresent()) {
1108 account
.setMultiDevice(true);
1109 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1110 if (syncMessage
.getSent().isPresent()) {
1111 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1112 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1114 if (syncMessage
.getRequest().isPresent()) {
1115 RequestMessage rm
= syncMessage
.getRequest().get();
1116 if (rm
.isContactsRequest()) {
1119 } catch (UntrustedIdentityException
| IOException e
) {
1120 e
.printStackTrace();
1123 if (rm
.isGroupsRequest()) {
1126 } catch (UntrustedIdentityException
| IOException e
) {
1127 e
.printStackTrace();
1130 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1132 if (syncMessage
.getGroups().isPresent()) {
1133 File tmpFile
= null;
1135 tmpFile
= IOUtils
.createTempFile();
1136 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1137 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1139 while ((g
= s
.read()) != null) {
1140 GroupInfo syncGroup
= account
.getGroupStore().getGroup(g
.getId());
1141 if (syncGroup
== null) {
1142 syncGroup
= new GroupInfo(g
.getId());
1144 if (g
.getName().isPresent()) {
1145 syncGroup
.name
= g
.getName().get();
1147 syncGroup
.members
.addAll(g
.getMembers());
1148 syncGroup
.active
= g
.isActive();
1149 if (g
.getColor().isPresent()) {
1150 syncGroup
.color
= g
.getColor().get();
1153 if (g
.getAvatar().isPresent()) {
1154 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1156 account
.getGroupStore().updateGroup(syncGroup
);
1159 } catch (Exception e
) {
1160 e
.printStackTrace();
1162 if (tmpFile
!= null) {
1164 Files
.delete(tmpFile
.toPath());
1165 } catch (IOException e
) {
1166 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1171 if (syncMessage
.getBlockedList().isPresent()) {
1172 // TODO store list of blocked numbers
1174 if (syncMessage
.getContacts().isPresent()) {
1175 File tmpFile
= null;
1177 tmpFile
= IOUtils
.createTempFile();
1178 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1179 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1180 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1181 if (contactsMessage
.isComplete()) {
1182 account
.getContactStore().clear();
1185 while ((c
= s
.read()) != null) {
1186 if (c
.getNumber().equals(account
.getUsername()) && c
.getProfileKey().isPresent()) {
1187 account
.setProfileKey(c
.getProfileKey().get());
1189 ContactInfo contact
= account
.getContactStore().getContact(c
.getNumber());
1190 if (contact
== null) {
1191 contact
= new ContactInfo();
1192 contact
.number
= c
.getNumber();
1194 if (c
.getName().isPresent()) {
1195 contact
.name
= c
.getName().get();
1197 if (c
.getColor().isPresent()) {
1198 contact
.color
= c
.getColor().get();
1200 if (c
.getProfileKey().isPresent()) {
1201 contact
.profileKey
= Base64
.encodeBytes(c
.getProfileKey().get());
1203 if (c
.getVerified().isPresent()) {
1204 final VerifiedMessage verifiedMessage
= c
.getVerified().get();
1205 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1207 if (c
.getExpirationTimer().isPresent()) {
1208 ThreadInfo thread
= account
.getThreadStore().getThread(c
.getNumber());
1209 thread
.messageExpirationTime
= c
.getExpirationTimer().get();
1210 account
.getThreadStore().updateThread(thread
);
1212 if (c
.isBlocked()) {
1213 // TODO store list of blocked numbers
1215 account
.getContactStore().updateContact(contact
);
1217 if (c
.getAvatar().isPresent()) {
1218 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1222 } catch (Exception e
) {
1223 e
.printStackTrace();
1225 if (tmpFile
!= null) {
1227 Files
.delete(tmpFile
.toPath());
1228 } catch (IOException e
) {
1229 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1234 if (syncMessage
.getVerified().isPresent()) {
1235 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1236 account
.getSignalProtocolStore().saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1238 if (syncMessage
.getConfiguration().isPresent()) {
1245 private SignalServiceEnvelope
loadEnvelope(File file
) throws IOException
{
1246 try (FileInputStream f
= new FileInputStream(file
)) {
1247 DataInputStream
in = new DataInputStream(f
);
1248 int version
= in.readInt();
1252 int type
= in.readInt();
1253 String source
= in.readUTF();
1254 int sourceDevice
= in.readInt();
1256 // read legacy relay field
1259 long timestamp
= in.readLong();
1260 byte[] content
= null;
1261 int contentLen
= in.readInt();
1262 if (contentLen
> 0) {
1263 content
= new byte[contentLen
];
1264 in.readFully(content
);
1266 byte[] legacyMessage
= null;
1267 int legacyMessageLen
= in.readInt();
1268 if (legacyMessageLen
> 0) {
1269 legacyMessage
= new byte[legacyMessageLen
];
1270 in.readFully(legacyMessage
);
1272 long serverTimestamp
= 0;
1275 serverTimestamp
= in.readLong();
1276 uuid
= in.readUTF();
1277 if ("".equals(uuid
)) {
1281 return new SignalServiceEnvelope(type
, source
, sourceDevice
, timestamp
, legacyMessage
, content
, serverTimestamp
, uuid
);
1285 private void storeEnvelope(SignalServiceEnvelope envelope
, File file
) throws IOException
{
1286 try (FileOutputStream f
= new FileOutputStream(file
)) {
1287 try (DataOutputStream out
= new DataOutputStream(f
)) {
1288 out
.writeInt(2); // version
1289 out
.writeInt(envelope
.getType());
1290 out
.writeUTF(envelope
.getSource());
1291 out
.writeInt(envelope
.getSourceDevice());
1292 out
.writeLong(envelope
.getTimestamp());
1293 if (envelope
.hasContent()) {
1294 out
.writeInt(envelope
.getContent().length
);
1295 out
.write(envelope
.getContent());
1299 if (envelope
.hasLegacyMessage()) {
1300 out
.writeInt(envelope
.getLegacyMessage().length
);
1301 out
.write(envelope
.getLegacyMessage());
1305 out
.writeLong(envelope
.getServerTimestamp());
1306 String uuid
= envelope
.getUuid();
1307 out
.writeUTF(uuid
== null ?
"" : uuid
);
1312 private File
getContactAvatarFile(String number
) {
1313 return new File(avatarsPath
, "contact-" + number
);
1316 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1317 IOUtils
.createPrivateDirectories(avatarsPath
);
1318 if (attachment
.isPointer()) {
1319 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1320 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1322 SignalServiceAttachmentStream stream
= attachment
.asStream();
1323 return retrieveAttachment(stream
, getContactAvatarFile(number
));
1327 private File
getGroupAvatarFile(byte[] groupId
) {
1328 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1331 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1332 IOUtils
.createPrivateDirectories(avatarsPath
);
1333 if (attachment
.isPointer()) {
1334 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1335 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1337 SignalServiceAttachmentStream stream
= attachment
.asStream();
1338 return retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1342 public File
getAttachmentFile(long attachmentId
) {
1343 return new File(attachmentsPath
, attachmentId
+ "");
1346 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1347 IOUtils
.createPrivateDirectories(attachmentsPath
);
1348 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1351 private File
retrieveAttachment(SignalServiceAttachmentStream stream
, File outputFile
) throws IOException
{
1352 InputStream input
= stream
.getInputStream();
1354 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1355 byte[] buffer
= new byte[4096];
1358 while ((read
= input
.read(buffer
)) != -1) {
1359 output
.write(buffer
, 0, read
);
1361 } catch (FileNotFoundException e
) {
1362 e
.printStackTrace();
1368 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1369 if (storePreview
&& pointer
.getPreview().isPresent()) {
1370 File previewFile
= new File(outputFile
+ ".preview");
1371 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1372 byte[] preview
= pointer
.getPreview().get();
1373 output
.write(preview
, 0, preview
.length
);
1374 } catch (FileNotFoundException e
) {
1375 e
.printStackTrace();
1380 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1382 File tmpFile
= IOUtils
.createTempFile();
1383 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
)) {
1384 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1385 byte[] buffer
= new byte[4096];
1388 while ((read
= input
.read(buffer
)) != -1) {
1389 output
.write(buffer
, 0, read
);
1391 } catch (FileNotFoundException e
) {
1392 e
.printStackTrace();
1397 Files
.delete(tmpFile
.toPath());
1398 } catch (IOException e
) {
1399 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1405 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1406 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(BaseConfig
.serviceConfiguration
, username
, account
.getPassword(), account
.getDeviceId(), account
.getSignalingKey(), BaseConfig
.USER_AGENT
, null, timer
);
1407 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, BaseConfig
.MAX_ATTACHMENT_SIZE
);
1410 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
1411 String localNumber
= username
;
1412 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
1415 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
1416 String e164number
= canonicalizeNumber(number
);
1417 return new SignalServiceAddress(e164number
);
1421 public boolean isRemote() {
1425 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1426 File groupsFile
= IOUtils
.createTempFile();
1429 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1430 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1431 for (GroupInfo
record : account
.getGroupStore().getGroups()) {
1432 ThreadInfo info
= account
.getThreadStore().getThread(Base64
.encodeBytes(record.groupId
));
1433 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1434 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1435 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1436 Optional
.fromNullable(record.color
), false));
1440 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1441 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1442 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1443 .withStream(groupsFileStream
)
1444 .withContentType("application/octet-stream")
1445 .withLength(groupsFile
.length())
1448 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1453 Files
.delete(groupsFile
.toPath());
1454 } catch (IOException e
) {
1455 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1460 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1461 File contactsFile
= IOUtils
.createTempFile();
1464 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1465 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1466 for (ContactInfo
record : account
.getContactStore().getContacts()) {
1467 VerifiedMessage verifiedMessage
= null;
1468 ThreadInfo info
= account
.getThreadStore().getThread(record.number
);
1469 if (getIdentities().containsKey(record.number
)) {
1470 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1471 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1472 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1473 currentIdentity
= id
;
1476 if (currentIdentity
!= null) {
1477 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1481 byte[] profileKey
= record.profileKey
== null ?
null : Base64
.decode(record.profileKey
);
1482 // TODO store list of blocked numbers
1483 boolean blocked
= false;
1484 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1485 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1486 Optional
.fromNullable(verifiedMessage
), Optional
.fromNullable(profileKey
), blocked
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1489 if (account
.getProfileKey() != null) {
1490 // Send our own profile key as well
1491 out
.write(new DeviceContact(account
.getUsername(),
1492 Optional
.<String
>absent(), Optional
.<SignalServiceAttachmentStream
>absent(),
1493 Optional
.<String
>absent(), Optional
.<VerifiedMessage
>absent(),
1494 Optional
.of(account
.getProfileKey()),
1495 false, Optional
.<Integer
>absent()));
1499 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1500 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1501 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1502 .withStream(contactsFileStream
)
1503 .withContentType("application/octet-stream")
1504 .withLength(contactsFile
.length())
1507 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1512 Files
.delete(contactsFile
.toPath());
1513 } catch (IOException e
) {
1514 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1519 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1520 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1521 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1524 public ContactInfo
getContact(String number
) {
1525 return account
.getContactStore().getContact(number
);
1528 public GroupInfo
getGroup(byte[] groupId
) {
1529 return account
.getGroupStore().getGroup(groupId
);
1532 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1533 return account
.getSignalProtocolStore().getIdentities();
1536 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1537 return account
.getSignalProtocolStore().getIdentities(number
);
1541 * Trust this the identity with this fingerprint
1543 * @param name username of the identity
1544 * @param fingerprint Fingerprint
1546 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1547 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1551 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1552 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1556 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1558 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1559 } catch (IOException
| UntrustedIdentityException e
) {
1560 e
.printStackTrace();
1569 * Trust this the identity with this safety number
1571 * @param name username of the identity
1572 * @param safetyNumber Safety number
1574 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1575 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1579 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1580 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1584 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1586 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1587 } catch (IOException
| UntrustedIdentityException e
) {
1588 e
.printStackTrace();
1597 * Trust all keys of this identity without verification
1599 * @param name username of the identity
1601 public boolean trustIdentityAllKeys(String name
) {
1602 List
<JsonIdentityKeyStore
.Identity
> ids
= account
.getSignalProtocolStore().getIdentities(name
);
1606 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1607 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1608 account
.getSignalProtocolStore().saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1610 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1611 } catch (IOException
| UntrustedIdentityException e
) {
1612 e
.printStackTrace();
1620 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1621 Fingerprint fingerprint
= new NumericFingerprintGenerator(5200).createFor(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1622 return fingerprint
.getDisplayableFingerprint().getDisplayText();
1625 public interface ReceiveMessageHandler
{
1627 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);