2 * Copyright (C) 2015 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
;
19 import com
.fasterxml
.jackson
.annotation
.JsonAutoDetect
;
20 import com
.fasterxml
.jackson
.annotation
.PropertyAccessor
;
21 import com
.fasterxml
.jackson
.core
.JsonGenerator
;
22 import com
.fasterxml
.jackson
.core
.JsonParser
;
23 import com
.fasterxml
.jackson
.databind
.DeserializationFeature
;
24 import com
.fasterxml
.jackson
.databind
.JsonNode
;
25 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
26 import com
.fasterxml
.jackson
.databind
.SerializationFeature
;
27 import com
.fasterxml
.jackson
.databind
.node
.ObjectNode
;
28 import org
.apache
.http
.util
.TextUtils
;
29 import org
.asamk
.Signal
;
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
.fingerprint
.Fingerprint
;
35 import org
.whispersystems
.libsignal
.fingerprint
.NumericFingerprintGenerator
;
36 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
37 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
38 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
39 import org
.whispersystems
.libsignal
.util
.Medium
;
40 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
41 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
42 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
43 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
44 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
45 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
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
.TrustStore
;
52 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.*;
53 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
54 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
55 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
59 import java
.net
.URISyntaxException
;
60 import java
.net
.URLDecoder
;
61 import java
.net
.URLEncoder
;
62 import java
.nio
.channels
.Channels
;
63 import java
.nio
.channels
.FileChannel
;
64 import java
.nio
.channels
.FileLock
;
65 import java
.nio
.file
.Files
;
66 import java
.nio
.file
.Path
;
67 import java
.nio
.file
.Paths
;
68 import java
.nio
.file
.StandardCopyOption
;
69 import java
.nio
.file
.attribute
.PosixFilePermission
;
70 import java
.nio
.file
.attribute
.PosixFilePermissions
;
72 import java
.util
.concurrent
.TimeUnit
;
73 import java
.util
.concurrent
.TimeoutException
;
75 import static java
.nio
.file
.attribute
.PosixFilePermission
.*;
77 class Manager
implements Signal
{
78 private final static String URL
= "https://textsecure-service.whispersystems.org";
79 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
81 public final static String PROJECT_NAME
= Manager
.class.getPackage().getImplementationTitle();
82 public final static String PROJECT_VERSION
= Manager
.class.getPackage().getImplementationVersion();
83 private final static String USER_AGENT
= PROJECT_NAME
== null ?
null : PROJECT_NAME
+ " " + PROJECT_VERSION
;
85 private final static int PREKEY_MINIMUM_COUNT
= 20;
86 private static final int PREKEY_BATCH_SIZE
= 100;
88 private final String settingsPath
;
89 private final String dataPath
;
90 private final String attachmentsPath
;
91 private final String avatarsPath
;
93 private FileChannel fileChannel
;
94 private FileLock lock
;
96 private final ObjectMapper jsonProcessor
= new ObjectMapper();
97 private String username
;
98 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
99 private String password
;
100 private String signalingKey
;
101 private int preKeyIdOffset
;
102 private int nextSignedPreKeyId
;
104 private boolean registered
= false;
106 private JsonSignalProtocolStore signalProtocolStore
;
107 private SignalServiceAccountManager accountManager
;
108 private JsonGroupStore groupStore
;
109 private JsonContactsStore contactStore
;
111 public Manager(String username
, String settingsPath
) {
112 this.username
= username
;
113 this.settingsPath
= settingsPath
;
114 this.dataPath
= this.settingsPath
+ "/data";
115 this.attachmentsPath
= this.settingsPath
+ "/attachments";
116 this.avatarsPath
= this.settingsPath
+ "/avatars";
118 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
119 jsonProcessor
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
120 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
121 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
122 jsonProcessor
.disable(JsonParser
.Feature
.AUTO_CLOSE_SOURCE
);
123 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
126 public String
getUsername() {
130 private IdentityKey
getIdentity() {
131 return signalProtocolStore
.getIdentityKeyPair().getPublicKey();
134 public int getDeviceId() {
138 public String
getFileName() {
139 return dataPath
+ "/" + username
;
142 private String
getMessageCachePath() {
143 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
146 private String
getMessageCachePath(String sender
) {
147 return getMessageCachePath() + "/" + sender
.replace("/", "_");
150 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
151 String cachePath
= getMessageCachePath(sender
);
152 createPrivateDirectories(cachePath
);
153 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
156 private static void createPrivateDirectories(String path
) throws IOException
{
157 final Path file
= new File(path
).toPath();
159 Set
<PosixFilePermission
> perms
= EnumSet
.of(OWNER_READ
, OWNER_WRITE
, OWNER_EXECUTE
);
160 Files
.createDirectories(file
, PosixFilePermissions
.asFileAttribute(perms
));
161 } catch (UnsupportedOperationException e
) {
162 Files
.createDirectories(file
);
166 private static void createPrivateFile(String path
) throws IOException
{
167 final Path file
= new File(path
).toPath();
169 Set
<PosixFilePermission
> perms
= EnumSet
.of(OWNER_READ
, OWNER_WRITE
);
170 Files
.createFile(file
, PosixFilePermissions
.asFileAttribute(perms
));
171 } catch (UnsupportedOperationException e
) {
172 Files
.createFile(file
);
176 public boolean userExists() {
177 if (username
== null) {
180 File f
= new File(getFileName());
181 return !(!f
.exists() || f
.isDirectory());
184 public boolean userHasKeys() {
185 return signalProtocolStore
!= null;
188 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
189 JsonNode node
= parent
.get(name
);
191 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
197 private void openFileChannel() throws IOException
{
198 if (fileChannel
!= null)
201 createPrivateDirectories(dataPath
);
202 if (!new File(getFileName()).exists()) {
203 createPrivateFile(getFileName());
205 fileChannel
= new RandomAccessFile(new File(getFileName()), "rw").getChannel();
206 lock
= fileChannel
.tryLock();
208 System
.err
.println("Config file is in use by another instance, waiting…");
209 lock
= fileChannel
.lock();
210 System
.err
.println("Config file lock acquired.");
214 public void init() throws IOException
{
217 migrateLegacyConfigs();
219 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, deviceId
, USER_AGENT
);
221 if (registered
&& accountManager
.getPreKeysCount() < PREKEY_MINIMUM_COUNT
) {
225 } catch (AuthorizationFailedException e
) {
226 System
.err
.println("Authorization failed, was the number registered elsewhere?");
230 private void load() throws IOException
{
232 JsonNode rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
234 JsonNode node
= rootNode
.get("deviceId");
236 deviceId
= node
.asInt();
238 username
= getNotNullNode(rootNode
, "username").asText();
239 password
= getNotNullNode(rootNode
, "password").asText();
240 if (rootNode
.has("signalingKey")) {
241 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
243 if (rootNode
.has("preKeyIdOffset")) {
244 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
248 if (rootNode
.has("nextSignedPreKeyId")) {
249 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
251 nextSignedPreKeyId
= 0;
253 signalProtocolStore
= jsonProcessor
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
254 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
255 JsonNode groupStoreNode
= rootNode
.get("groupStore");
256 if (groupStoreNode
!= null) {
257 groupStore
= jsonProcessor
.convertValue(groupStoreNode
, JsonGroupStore
.class);
259 if (groupStore
== null) {
260 groupStore
= new JsonGroupStore();
263 JsonNode contactStoreNode
= rootNode
.get("contactStore");
264 if (contactStoreNode
!= null) {
265 contactStore
= jsonProcessor
.convertValue(contactStoreNode
, JsonContactsStore
.class);
267 if (contactStore
== null) {
268 contactStore
= new JsonContactsStore();
272 private void migrateLegacyConfigs() {
273 // Copy group avatars that were previously stored in the attachments folder
274 // to the new avatar folder
275 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
276 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
277 File avatarFile
= getGroupAvatarFile(g
.groupId
);
278 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
279 if (!avatarFile
.exists() && attachmentFile
.exists()) {
281 createPrivateDirectories(avatarsPath
);
282 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
283 } catch (Exception e
) {
288 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
293 private void save() {
294 if (username
== null) {
297 ObjectNode rootNode
= jsonProcessor
.createObjectNode();
298 rootNode
.put("username", username
)
299 .put("deviceId", deviceId
)
300 .put("password", password
)
301 .put("signalingKey", signalingKey
)
302 .put("preKeyIdOffset", preKeyIdOffset
)
303 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
304 .put("registered", registered
)
305 .putPOJO("axolotlStore", signalProtocolStore
)
306 .putPOJO("groupStore", groupStore
)
307 .putPOJO("contactStore", contactStore
)
311 fileChannel
.position(0);
312 jsonProcessor
.writeValue(Channels
.newOutputStream(fileChannel
), rootNode
);
313 fileChannel
.truncate(fileChannel
.position());
314 fileChannel
.force(false);
315 } catch (Exception e
) {
316 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
320 public void createNewIdentity() {
321 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
322 int registrationId
= KeyHelper
.generateRegistrationId(false);
323 signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
324 groupStore
= new JsonGroupStore();
329 public boolean isRegistered() {
333 public void register(boolean voiceVerification
) throws IOException
{
334 password
= Util
.getSecret(18);
336 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
338 if (voiceVerification
)
339 accountManager
.requestVoiceVerificationCode();
341 accountManager
.requestSmsVerificationCode();
347 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
348 password
= Util
.getSecret(18);
350 accountManager
= new SignalServiceAccountManager(URL
, TRUST_STORE
, username
, password
, USER_AGENT
);
351 String uuid
= accountManager
.getNewDeviceUuid();
355 return new URI("tsdevice:/?uuid=" + URLEncoder
.encode(uuid
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(signalProtocolStore
.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
356 } catch (URISyntaxException e
) {
362 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
363 signalingKey
= Util
.getSecret(52);
364 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(signalProtocolStore
.getIdentityKeyPair(), signalingKey
, false, true, signalProtocolStore
.getLocalRegistrationId(), deviceName
);
365 deviceId
= ret
.getDeviceId();
366 username
= ret
.getNumber();
367 // TODO do this check before actually registering
369 throw new UserAlreadyExists(username
, getFileName());
371 signalProtocolStore
= new JsonSignalProtocolStore(ret
.getIdentity(), signalProtocolStore
.getLocalRegistrationId());
377 requestSyncContacts();
382 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
383 return accountManager
.getDevices();
386 public void removeLinkedDevices(int deviceId
) throws IOException
{
387 accountManager
.removeDevice(deviceId
);
390 public static Map
<String
, String
> getQueryMap(String query
) {
391 String
[] params
= query
.split("&");
392 Map
<String
, String
> map
= new HashMap
<>();
393 for (String param
: params
) {
396 name
= URLDecoder
.decode(param
.split("=")[0], "utf-8");
397 } catch (UnsupportedEncodingException e
) {
402 value
= URLDecoder
.decode(param
.split("=")[1], "utf-8");
403 } catch (UnsupportedEncodingException e
) {
406 map
.put(name
, value
);
411 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
412 Map
<String
, String
> query
= getQueryMap(linkUri
.getRawQuery());
413 String deviceIdentifier
= query
.get("uuid");
414 String publicKeyEncoded
= query
.get("pub_key");
416 if (TextUtils
.isEmpty(deviceIdentifier
) || TextUtils
.isEmpty(publicKeyEncoded
)) {
417 throw new RuntimeException("Invalid device link uri");
420 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
422 addDevice(deviceIdentifier
, deviceKey
);
425 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
426 IdentityKeyPair identityKeyPair
= signalProtocolStore
.getIdentityKeyPair();
427 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
429 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, verificationCode
);
432 private List
<PreKeyRecord
> generatePreKeys() {
433 List
<PreKeyRecord
> records
= new LinkedList
<>();
435 for (int i
= 0; i
< PREKEY_BATCH_SIZE
; i
++) {
436 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
437 ECKeyPair keyPair
= Curve
.generateKeyPair();
438 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
440 signalProtocolStore
.storePreKey(preKeyId
, record);
444 preKeyIdOffset
= (preKeyIdOffset
+ PREKEY_BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
450 private PreKeyRecord
getOrGenerateLastResortPreKey() {
451 if (signalProtocolStore
.containsPreKey(Medium
.MAX_VALUE
)) {
453 return signalProtocolStore
.loadPreKey(Medium
.MAX_VALUE
);
454 } catch (InvalidKeyIdException e
) {
455 signalProtocolStore
.removePreKey(Medium
.MAX_VALUE
);
459 ECKeyPair keyPair
= Curve
.generateKeyPair();
460 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
462 signalProtocolStore
.storePreKey(Medium
.MAX_VALUE
, record);
468 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
470 ECKeyPair keyPair
= Curve
.generateKeyPair();
471 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
472 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
474 signalProtocolStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
475 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
479 } catch (InvalidKeyException e
) {
480 throw new AssertionError(e
);
484 public void verifyAccount(String verificationCode
) throws IOException
{
485 verificationCode
= verificationCode
.replace("-", "");
486 signalingKey
= Util
.getSecret(52);
487 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, signalProtocolStore
.getLocalRegistrationId(), false, true);
489 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
496 private void refreshPreKeys() throws IOException
{
497 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
498 PreKeyRecord lastResortKey
= getOrGenerateLastResortPreKey();
499 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(signalProtocolStore
.getIdentityKeyPair());
501 accountManager
.setPreKeys(signalProtocolStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
505 private static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
506 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
507 if (attachments
!= null) {
508 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
509 for (String attachment
: attachments
) {
511 SignalServiceAttachments
.add(createAttachment(new File(attachment
)));
512 } catch (IOException e
) {
513 throw new AttachmentInvalidException(attachment
, e
);
517 return SignalServiceAttachments
;
520 private static SignalServiceAttachmentStream
createAttachment(File attachmentFile
) throws IOException
{
521 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
522 final long attachmentSize
= attachmentFile
.length();
523 String mime
= Files
.probeContentType(attachmentFile
.toPath());
525 mime
= "application/octet-stream";
527 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, null);
530 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
531 File file
= getGroupAvatarFile(groupId
);
532 if (!file
.exists()) {
533 return Optional
.absent();
536 return Optional
.of(createAttachment(file
));
539 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
540 File file
= getContactAvatarFile(number
);
541 if (!file
.exists()) {
542 return Optional
.absent();
545 return Optional
.of(createAttachment(file
));
548 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
549 GroupInfo g
= groupStore
.getGroup(groupId
);
551 throw new GroupNotFoundException(groupId
);
553 for (String member
: g
.members
) {
554 if (member
.equals(this.username
)) {
558 throw new NotAGroupMemberException(groupId
, g
.name
);
562 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
564 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
565 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
566 if (attachments
!= null) {
567 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
569 if (groupId
!= null) {
570 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
573 messageBuilder
.asGroupMessage(group
);
575 SignalServiceDataMessage message
= messageBuilder
.build();
577 final GroupInfo g
= getGroupForSending(groupId
);
579 // Don't send group message to ourself
580 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
581 membersSend
.remove(this.username
);
582 sendMessage(message
, membersSend
);
585 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
586 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
590 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
591 .asGroupMessage(group
)
594 final GroupInfo g
= getGroupForSending(groupId
);
595 g
.members
.remove(this.username
);
596 groupStore
.updateGroup(g
);
598 sendMessage(message
, g
.members
);
601 private static String
join(CharSequence separator
, Iterable
<?
extends CharSequence
> list
) {
602 StringBuilder buf
= new StringBuilder();
603 for (CharSequence str
: list
) {
604 if (buf
.length() > 0) {
605 buf
.append(separator
);
610 return buf
.toString();
613 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
615 if (groupId
== null) {
617 g
= new GroupInfo(Util
.getSecretBytes(16));
618 g
.members
.add(username
);
620 g
= getGroupForSending(groupId
);
627 if (members
!= null) {
628 Set
<String
> newMembers
= new HashSet
<>();
629 for (String member
: members
) {
631 member
= canonicalizeNumber(member
);
632 } catch (InvalidNumberException e
) {
633 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
634 System
.err
.println("Aborting…");
637 if (g
.members
.contains(member
)) {
640 newMembers
.add(member
);
641 g
.members
.add(member
);
643 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
644 if (contacts
.size() != newMembers
.size()) {
645 // Some of the new members are not registered on Signal
646 for (ContactTokenDetails contact
: contacts
) {
647 newMembers
.remove(contact
.getNumber());
649 System
.err
.println("Failed to add members " + join(", ", newMembers
) + " to group: Not registered on Signal");
650 System
.err
.println("Aborting…");
655 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
658 .withMembers(new ArrayList
<>(g
.members
));
660 File aFile
= getGroupAvatarFile(g
.groupId
);
661 if (avatarFile
!= null) {
662 createPrivateDirectories(avatarsPath
);
663 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
665 if (aFile
.exists()) {
667 group
.withAvatar(createAttachment(aFile
));
668 } catch (IOException e
) {
669 throw new AttachmentInvalidException(avatarFile
, e
);
673 groupStore
.updateGroup(g
);
675 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
676 .asGroupMessage(group
.build())
679 // Don't send group message to ourself
680 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
681 membersSend
.remove(this.username
);
682 sendMessage(message
, membersSend
);
687 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
688 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
689 List
<String
> recipients
= new ArrayList
<>(1);
690 recipients
.add(recipient
);
691 sendMessage(message
, attachments
, recipients
);
695 public void sendMessage(String messageText
, List
<String
> attachments
,
696 List
<String
> recipients
)
697 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
698 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
699 if (attachments
!= null) {
700 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
702 SignalServiceDataMessage message
= messageBuilder
.build();
704 sendMessage(message
, recipients
);
708 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
709 SignalServiceDataMessage message
= SignalServiceDataMessage
.newBuilder()
710 .asEndSessionMessage()
713 sendMessage(message
, recipients
);
716 private void requestSyncGroups() throws IOException
{
717 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
718 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
720 sendMessage(message
);
721 } catch (UntrustedIdentityException e
) {
726 private void requestSyncContacts() throws IOException
{
727 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
728 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
730 sendMessage(message
);
731 } catch (UntrustedIdentityException e
) {
736 private void sendMessage(SignalServiceSyncMessage message
)
737 throws IOException
, UntrustedIdentityException
{
738 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
739 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
741 messageSender
.sendMessage(message
);
742 } catch (UntrustedIdentityException e
) {
743 signalProtocolStore
.saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
748 private void sendMessage(SignalServiceDataMessage message
, Collection
<String
> recipients
)
749 throws EncapsulatedExceptions
, IOException
{
750 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
751 for (String recipient
: recipients
) {
753 recipientsTS
.add(getPushAddress(recipient
));
754 } catch (InvalidNumberException e
) {
755 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
756 System
.err
.println("Aborting sending.");
763 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(URL
, TRUST_STORE
, username
, password
,
764 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.<SignalServiceMessageSender
.EventListener
>absent());
766 if (message
.getGroupInfo().isPresent()) {
768 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
769 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
770 for (UntrustedIdentityException e
: encapsulatedExceptions
.getUntrustedIdentityExceptions()) {
771 signalProtocolStore
.saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
775 // Send to all individually, so sync messages are sent correctly
776 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
777 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
778 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
779 for (SignalServiceAddress address
: recipientsTS
) {
781 messageSender
.sendMessage(address
, message
);
782 } catch (UntrustedIdentityException e
) {
783 signalProtocolStore
.saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
784 untrustedIdentities
.add(e
);
785 } catch (UnregisteredUserException e
) {
786 unregisteredUsers
.add(e
);
787 } catch (PushNetworkException e
) {
788 networkExceptions
.add(new NetworkFailureException(address
.getNumber(), e
));
791 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
792 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
796 if (message
.isEndSession()) {
797 for (SignalServiceAddress recipient
: recipientsTS
) {
798 handleEndSession(recipient
.getNumber());
805 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws NoSessionException
, LegacyMessageException
, InvalidVersionException
, InvalidMessageException
, DuplicateMessageException
, InvalidKeyException
, InvalidKeyIdException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
806 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
808 return cipher
.decrypt(envelope
);
809 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
810 signalProtocolStore
.saveIdentity(e
.getName(), e
.getUntrustedIdentity(), TrustLevel
.UNTRUSTED
);
815 private void handleEndSession(String source
) {
816 signalProtocolStore
.deleteAllSessions(source
);
819 public interface ReceiveMessageHandler
{
820 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);
823 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
) {
824 if (message
.getGroupInfo().isPresent()) {
825 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
826 switch (groupInfo
.getType()) {
829 group
= groupStore
.getGroup(groupInfo
.getGroupId());
831 group
= new GroupInfo(groupInfo
.getGroupId());
834 if (groupInfo
.getAvatar().isPresent()) {
835 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
836 if (avatar
.isPointer()) {
838 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
839 } catch (IOException
| InvalidMessageException e
) {
840 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
845 if (groupInfo
.getName().isPresent()) {
846 group
.name
= groupInfo
.getName().get();
849 if (groupInfo
.getMembers().isPresent()) {
850 group
.members
.addAll(groupInfo
.getMembers().get());
853 groupStore
.updateGroup(group
);
858 group
= groupStore
.getGroup(groupInfo
.getGroupId());
860 group
.members
.remove(source
);
861 groupStore
.updateGroup(group
);
866 if (message
.isEndSession()) {
867 handleEndSession(isSync ? destination
: source
);
869 if (message
.getAttachments().isPresent()) {
870 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
871 if (attachment
.isPointer()) {
873 retrieveAttachment(attachment
.asPointer());
874 } catch (IOException
| InvalidMessageException e
) {
875 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
882 public void retryFailedReceivedMessages(ReceiveMessageHandler handler
) {
883 final File cachePath
= new File(getMessageCachePath());
884 if (!cachePath
.exists()) {
887 for (final File dir
: cachePath
.listFiles()) {
888 if (!dir
.isDirectory()) {
892 String sender
= dir
.getName();
893 for (final File fileEntry
: dir
.listFiles()) {
894 if (!fileEntry
.isFile()) {
897 SignalServiceEnvelope envelope
;
899 envelope
= loadEnvelope(fileEntry
);
900 if (envelope
== null) {
903 } catch (IOException e
) {
907 SignalServiceContent content
= null;
908 if (!envelope
.isReceipt()) {
910 content
= decryptMessage(envelope
);
911 } catch (Exception e
) {
914 handleMessage(envelope
, content
);
917 handler
.handleMessage(envelope
, content
, null);
923 public void receiveMessages(int timeoutSeconds
, boolean returnOnTimeout
, ReceiveMessageHandler handler
) throws IOException
{
924 retryFailedReceivedMessages(handler
);
925 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
926 SignalServiceMessagePipe messagePipe
= null;
929 messagePipe
= messageReceiver
.createMessagePipe();
932 SignalServiceEnvelope envelope
;
933 SignalServiceContent content
= null;
934 Exception exception
= null;
935 final long now
= new Date().getTime();
937 envelope
= messagePipe
.read(timeoutSeconds
, TimeUnit
.SECONDS
, new SignalServiceMessagePipe
.MessagePipeCallback() {
939 public void onMessage(SignalServiceEnvelope envelope
) {
940 // store message on disk, before acknowledging receipt to the server
942 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
943 storeEnvelope(envelope
, cacheFile
);
944 } catch (IOException e
) {
945 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
949 } catch (TimeoutException e
) {
953 } catch (InvalidVersionException e
) {
954 System
.err
.println("Ignoring error: " + e
.getMessage());
957 if (!envelope
.isReceipt()) {
959 content
= decryptMessage(envelope
);
960 } catch (Exception e
) {
963 handleMessage(envelope
, content
);
966 handler
.handleMessage(envelope
, content
, exception
);
967 if (exception
== null || !(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
969 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
971 } catch (IOException e
) {
978 if (messagePipe
!= null)
979 messagePipe
.shutdown();
983 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
) {
984 if (content
!= null) {
985 if (content
.getDataMessage().isPresent()) {
986 SignalServiceDataMessage message
= content
.getDataMessage().get();
987 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
);
989 if (content
.getSyncMessage().isPresent()) {
990 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
991 if (syncMessage
.getSent().isPresent()) {
992 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
993 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get());
995 if (syncMessage
.getRequest().isPresent()) {
996 RequestMessage rm
= syncMessage
.getRequest().get();
997 if (rm
.isContactsRequest()) {
1000 } catch (UntrustedIdentityException
| IOException e
) {
1001 e
.printStackTrace();
1004 if (rm
.isGroupsRequest()) {
1007 } catch (UntrustedIdentityException
| IOException e
) {
1008 e
.printStackTrace();
1012 if (syncMessage
.getGroups().isPresent()) {
1014 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer()));
1016 while ((g
= s
.read()) != null) {
1017 GroupInfo syncGroup
= groupStore
.getGroup(g
.getId());
1018 if (syncGroup
== null) {
1019 syncGroup
= new GroupInfo(g
.getId());
1021 if (g
.getName().isPresent()) {
1022 syncGroup
.name
= g
.getName().get();
1024 syncGroup
.members
.addAll(g
.getMembers());
1025 syncGroup
.active
= g
.isActive();
1027 if (g
.getAvatar().isPresent()) {
1028 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1030 groupStore
.updateGroup(syncGroup
);
1032 } catch (Exception e
) {
1033 e
.printStackTrace();
1035 if (syncMessage
.getBlockedList().isPresent()) {
1036 // TODO store list of blocked numbers
1039 if (syncMessage
.getContacts().isPresent()) {
1041 DeviceContactsInputStream s
= new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage
.getContacts().get().asPointer()));
1043 while ((c
= s
.read()) != null) {
1044 ContactInfo contact
= new ContactInfo();
1045 contact
.number
= c
.getNumber();
1046 if (c
.getName().isPresent()) {
1047 contact
.name
= c
.getName().get();
1049 if (c
.getColor().isPresent()) {
1050 contact
.color
= c
.getColor().get();
1052 contactStore
.updateContact(contact
);
1054 if (c
.getAvatar().isPresent()) {
1055 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1058 } catch (Exception e
) {
1059 e
.printStackTrace();
1066 private SignalServiceEnvelope
loadEnvelope(File file
) throws IOException
{
1067 try (FileInputStream f
= new FileInputStream(file
)) {
1068 DataInputStream
in = new DataInputStream(f
);
1069 int version
= in.readInt();
1073 int type
= in.readInt();
1074 String source
= in.readUTF();
1075 int sourceDevice
= in.readInt();
1076 String relay
= in.readUTF();
1077 long timestamp
= in.readLong();
1078 byte[] content
= null;
1079 int contentLen
= in.readInt();
1080 if (contentLen
> 0) {
1081 content
= new byte[contentLen
];
1082 in.readFully(content
);
1084 byte[] legacyMessage
= null;
1085 int legacyMessageLen
= in.readInt();
1086 if (legacyMessageLen
> 0) {
1087 legacyMessage
= new byte[legacyMessageLen
];
1088 in.readFully(legacyMessage
);
1090 return new SignalServiceEnvelope(type
, source
, sourceDevice
, relay
, timestamp
, legacyMessage
, content
);
1094 private void storeEnvelope(SignalServiceEnvelope envelope
, File file
) throws IOException
{
1095 try (FileOutputStream f
= new FileOutputStream(file
)) {
1096 DataOutputStream out
= new DataOutputStream(f
);
1097 out
.writeInt(1); // version
1098 out
.writeInt(envelope
.getType());
1099 out
.writeUTF(envelope
.getSource());
1100 out
.writeInt(envelope
.getSourceDevice());
1101 out
.writeUTF(envelope
.getRelay());
1102 out
.writeLong(envelope
.getTimestamp());
1103 if (envelope
.hasContent()) {
1104 out
.writeInt(envelope
.getContent().length
);
1105 out
.write(envelope
.getContent());
1109 if (envelope
.hasLegacyMessage()) {
1110 out
.writeInt(envelope
.getLegacyMessage().length
);
1111 out
.write(envelope
.getLegacyMessage());
1119 public File
getContactAvatarFile(String number
) {
1120 return new File(avatarsPath
, "contact-" + number
);
1123 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1124 createPrivateDirectories(avatarsPath
);
1125 if (attachment
.isPointer()) {
1126 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1127 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1129 SignalServiceAttachmentStream stream
= attachment
.asStream();
1130 return retrieveAttachment(stream
, getContactAvatarFile(number
));
1134 public File
getGroupAvatarFile(byte[] groupId
) {
1135 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1138 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1139 createPrivateDirectories(avatarsPath
);
1140 if (attachment
.isPointer()) {
1141 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1142 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1144 SignalServiceAttachmentStream stream
= attachment
.asStream();
1145 return retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1149 public File
getAttachmentFile(long attachmentId
) {
1150 return new File(attachmentsPath
, attachmentId
+ "");
1153 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1154 createPrivateDirectories(attachmentsPath
);
1155 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1158 private File
retrieveAttachment(SignalServiceAttachmentStream stream
, File outputFile
) throws IOException
, InvalidMessageException
{
1159 InputStream input
= stream
.getInputStream();
1161 OutputStream output
= null;
1163 output
= new FileOutputStream(outputFile
);
1164 byte[] buffer
= new byte[4096];
1167 while ((read
= input
.read(buffer
)) != -1) {
1168 output
.write(buffer
, 0, read
);
1170 } catch (FileNotFoundException e
) {
1171 e
.printStackTrace();
1174 if (output
!= null) {
1181 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1182 if (storePreview
&& pointer
.getPreview().isPresent()) {
1183 File previewFile
= new File(outputFile
+ ".preview");
1184 OutputStream output
= null;
1186 output
= new FileOutputStream(previewFile
);
1187 byte[] preview
= pointer
.getPreview().get();
1188 output
.write(preview
, 0, preview
.length
);
1189 } catch (FileNotFoundException e
) {
1190 e
.printStackTrace();
1193 if (output
!= null) {
1199 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
1201 File tmpFile
= File
.createTempFile("ts_attach_" + pointer
.getId(), ".tmp");
1202 InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
1204 OutputStream output
= null;
1206 output
= new FileOutputStream(outputFile
);
1207 byte[] buffer
= new byte[4096];
1210 while ((read
= input
.read(buffer
)) != -1) {
1211 output
.write(buffer
, 0, read
);
1213 } catch (FileNotFoundException e
) {
1214 e
.printStackTrace();
1217 if (output
!= null) {
1220 if (!tmpFile
.delete()) {
1221 System
.err
.println("Failed to delete temp file: " + tmpFile
);
1227 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1228 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(URL
, TRUST_STORE
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
1229 File file
= File
.createTempFile("ts_tmp", "tmp");
1230 file
.deleteOnExit();
1232 return messageReceiver
.retrieveAttachment(pointer
, file
);
1235 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
1236 String localNumber
= username
;
1237 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
1240 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
1241 String e164number
= canonicalizeNumber(number
);
1242 return new SignalServiceAddress(e164number
);
1246 public boolean isRemote() {
1250 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1251 File groupsFile
= File
.createTempFile("multidevice-group-update", ".tmp");
1254 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(new FileOutputStream(groupsFile
));
1256 for (GroupInfo
record : groupStore
.getGroups()) {
1257 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1258 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1265 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1266 FileInputStream contactsFileStream
= new FileInputStream(groupsFile
);
1267 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1268 .withStream(contactsFileStream
)
1269 .withContentType("application/octet-stream")
1270 .withLength(groupsFile
.length())
1273 sendMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1276 groupsFile
.delete();
1280 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1281 File contactsFile
= File
.createTempFile("multidevice-contact-update", ".tmp");
1284 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(new FileOutputStream(contactsFile
));
1286 for (ContactInfo
record : contactStore
.getContacts()) {
1287 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1288 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
)));
1294 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1295 FileInputStream contactsFileStream
= new FileInputStream(contactsFile
);
1296 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1297 .withStream(contactsFileStream
)
1298 .withContentType("application/octet-stream")
1299 .withLength(contactsFile
.length())
1302 sendMessage(SignalServiceSyncMessage
.forContacts(attachmentStream
));
1305 contactsFile
.delete();
1309 public ContactInfo
getContact(String number
) {
1310 return contactStore
.getContact(number
);
1313 public GroupInfo
getGroup(byte[] groupId
) {
1314 return groupStore
.getGroup(groupId
);
1317 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1318 return signalProtocolStore
.getIdentities();
1321 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1322 return signalProtocolStore
.getIdentities(number
);
1326 * Trust this the identity with this fingerprint
1328 * @param name username of the identity
1329 * @param fingerprint Fingerprint
1331 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1332 List
<JsonIdentityKeyStore
.Identity
> ids
= signalProtocolStore
.getIdentities(name
);
1336 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1337 if (!Arrays
.equals(id
.identityKey
.serialize(), fingerprint
)) {
1341 signalProtocolStore
.saveIdentity(name
, id
.identityKey
, TrustLevel
.TRUSTED_VERIFIED
);
1349 * Trust this the identity with this safety number
1351 * @param name username of the identity
1352 * @param safetyNumber Safety number
1354 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1355 List
<JsonIdentityKeyStore
.Identity
> ids
= signalProtocolStore
.getIdentities(name
);
1359 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1360 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.identityKey
))) {
1364 signalProtocolStore
.saveIdentity(name
, id
.identityKey
, TrustLevel
.TRUSTED_VERIFIED
);
1372 * Trust all keys of this identity without verification
1374 * @param name username of the identity
1376 public boolean trustIdentityAllKeys(String name
) {
1377 List
<JsonIdentityKeyStore
.Identity
> ids
= signalProtocolStore
.getIdentities(name
);
1381 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1382 if (id
.trustLevel
== TrustLevel
.UNTRUSTED
) {
1383 signalProtocolStore
.saveIdentity(name
, id
.identityKey
, TrustLevel
.TRUSTED_UNVERIFIED
);
1390 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1391 Fingerprint fingerprint
= new NumericFingerprintGenerator(5200).createFor(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1392 return fingerprint
.getDisplayableFingerprint().getDisplayText();