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
.asamk
.signal
.storage
.contacts
.ContactInfo
;
31 import org
.asamk
.signal
.storage
.contacts
.JsonContactsStore
;
32 import org
.asamk
.signal
.storage
.groups
.GroupInfo
;
33 import org
.asamk
.signal
.storage
.groups
.JsonGroupStore
;
34 import org
.asamk
.signal
.storage
.protocol
.JsonIdentityKeyStore
;
35 import org
.asamk
.signal
.storage
.protocol
.JsonSignalProtocolStore
;
36 import org
.asamk
.signal
.storage
.threads
.JsonThreadStore
;
37 import org
.asamk
.signal
.storage
.threads
.ThreadInfo
;
38 import org
.asamk
.signal
.util
.Base64
;
39 import org
.asamk
.signal
.util
.Util
;
40 import org
.whispersystems
.libsignal
.*;
41 import org
.whispersystems
.libsignal
.ecc
.Curve
;
42 import org
.whispersystems
.libsignal
.ecc
.ECKeyPair
;
43 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
44 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
45 import org
.whispersystems
.libsignal
.fingerprint
.NumericFingerprintGenerator
;
46 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
47 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
48 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
49 import org
.whispersystems
.libsignal
.util
.Medium
;
50 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
51 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
52 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
53 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
54 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
55 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
56 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
57 import org
.whispersystems
.signalservice
.api
.messages
.*;
58 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
59 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
60 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
61 import org
.whispersystems
.signalservice
.api
.push
.TrustStore
;
62 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.*;
63 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
64 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
65 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
66 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceUrl
;
70 import java
.net
.URISyntaxException
;
71 import java
.net
.URLDecoder
;
72 import java
.net
.URLEncoder
;
73 import java
.nio
.channels
.Channels
;
74 import java
.nio
.channels
.FileChannel
;
75 import java
.nio
.channels
.FileLock
;
76 import java
.nio
.file
.Files
;
77 import java
.nio
.file
.Path
;
78 import java
.nio
.file
.Paths
;
79 import java
.nio
.file
.StandardCopyOption
;
80 import java
.nio
.file
.attribute
.PosixFilePermission
;
81 import java
.nio
.file
.attribute
.PosixFilePermissions
;
83 import java
.util
.concurrent
.TimeUnit
;
84 import java
.util
.concurrent
.TimeoutException
;
86 import static java
.nio
.file
.attribute
.PosixFilePermission
.*;
88 class Manager
implements Signal
{
89 private final static String URL
= "https://textsecure-service.whispersystems.org";
90 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
91 private final static SignalServiceUrl
[] serviceUrls
= new SignalServiceUrl
[]{new SignalServiceUrl(URL
, TRUST_STORE
)};
93 public final static String PROJECT_NAME
= Manager
.class.getPackage().getImplementationTitle();
94 public final static String PROJECT_VERSION
= Manager
.class.getPackage().getImplementationVersion();
95 private final static String USER_AGENT
= PROJECT_NAME
== null ?
null : PROJECT_NAME
+ " " + PROJECT_VERSION
;
97 private final static int PREKEY_MINIMUM_COUNT
= 20;
98 private static final int PREKEY_BATCH_SIZE
= 100;
100 private final String settingsPath
;
101 private final String dataPath
;
102 private final String attachmentsPath
;
103 private final String avatarsPath
;
105 private FileChannel fileChannel
;
106 private FileLock lock
;
108 private final ObjectMapper jsonProcessor
= new ObjectMapper();
109 private String username
;
110 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
111 private String password
;
112 private String signalingKey
;
113 private int preKeyIdOffset
;
114 private int nextSignedPreKeyId
;
116 private boolean registered
= false;
118 private JsonSignalProtocolStore signalProtocolStore
;
119 private SignalServiceAccountManager accountManager
;
120 private JsonGroupStore groupStore
;
121 private JsonContactsStore contactStore
;
122 private JsonThreadStore threadStore
;
123 private SignalServiceMessagePipe messagePipe
= null;
125 public Manager(String username
, String settingsPath
) {
126 this.username
= username
;
127 this.settingsPath
= settingsPath
;
128 this.dataPath
= this.settingsPath
+ "/data";
129 this.attachmentsPath
= this.settingsPath
+ "/attachments";
130 this.avatarsPath
= this.settingsPath
+ "/avatars";
132 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
133 jsonProcessor
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
134 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
135 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
136 jsonProcessor
.disable(JsonParser
.Feature
.AUTO_CLOSE_SOURCE
);
137 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
140 public String
getUsername() {
144 private IdentityKey
getIdentity() {
145 return signalProtocolStore
.getIdentityKeyPair().getPublicKey();
148 public int getDeviceId() {
152 public String
getFileName() {
153 return dataPath
+ "/" + username
;
156 private String
getMessageCachePath() {
157 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
160 private String
getMessageCachePath(String sender
) {
161 return getMessageCachePath() + "/" + sender
.replace("/", "_");
164 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
165 String cachePath
= getMessageCachePath(sender
);
166 createPrivateDirectories(cachePath
);
167 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
170 private static void createPrivateDirectories(String path
) throws IOException
{
171 final Path file
= new File(path
).toPath();
173 Set
<PosixFilePermission
> perms
= EnumSet
.of(OWNER_READ
, OWNER_WRITE
, OWNER_EXECUTE
);
174 Files
.createDirectories(file
, PosixFilePermissions
.asFileAttribute(perms
));
175 } catch (UnsupportedOperationException e
) {
176 Files
.createDirectories(file
);
180 private static void createPrivateFile(String path
) throws IOException
{
181 final Path file
= new File(path
).toPath();
183 Set
<PosixFilePermission
> perms
= EnumSet
.of(OWNER_READ
, OWNER_WRITE
);
184 Files
.createFile(file
, PosixFilePermissions
.asFileAttribute(perms
));
185 } catch (UnsupportedOperationException e
) {
186 Files
.createFile(file
);
190 public boolean userExists() {
191 if (username
== null) {
194 File f
= new File(getFileName());
195 return !(!f
.exists() || f
.isDirectory());
198 public boolean userHasKeys() {
199 return signalProtocolStore
!= null;
202 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
203 JsonNode node
= parent
.get(name
);
205 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
211 private void openFileChannel() throws IOException
{
212 if (fileChannel
!= null)
215 createPrivateDirectories(dataPath
);
216 if (!new File(getFileName()).exists()) {
217 createPrivateFile(getFileName());
219 fileChannel
= new RandomAccessFile(new File(getFileName()), "rw").getChannel();
220 lock
= fileChannel
.tryLock();
222 System
.err
.println("Config file is in use by another instance, waiting…");
223 lock
= fileChannel
.lock();
224 System
.err
.println("Config file lock acquired.");
228 public void init() throws IOException
{
231 migrateLegacyConfigs();
233 accountManager
= new SignalServiceAccountManager(serviceUrls
, username
, password
, deviceId
, USER_AGENT
);
235 if (registered
&& accountManager
.getPreKeysCount() < PREKEY_MINIMUM_COUNT
) {
239 } catch (AuthorizationFailedException e
) {
240 System
.err
.println("Authorization failed, was the number registered elsewhere?");
244 private void load() throws IOException
{
246 JsonNode rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
248 JsonNode node
= rootNode
.get("deviceId");
250 deviceId
= node
.asInt();
252 username
= getNotNullNode(rootNode
, "username").asText();
253 password
= getNotNullNode(rootNode
, "password").asText();
254 if (rootNode
.has("signalingKey")) {
255 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
257 if (rootNode
.has("preKeyIdOffset")) {
258 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
262 if (rootNode
.has("nextSignedPreKeyId")) {
263 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
265 nextSignedPreKeyId
= 0;
267 signalProtocolStore
= jsonProcessor
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
268 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
269 JsonNode groupStoreNode
= rootNode
.get("groupStore");
270 if (groupStoreNode
!= null) {
271 groupStore
= jsonProcessor
.convertValue(groupStoreNode
, JsonGroupStore
.class);
273 if (groupStore
== null) {
274 groupStore
= new JsonGroupStore();
277 JsonNode contactStoreNode
= rootNode
.get("contactStore");
278 if (contactStoreNode
!= null) {
279 contactStore
= jsonProcessor
.convertValue(contactStoreNode
, JsonContactsStore
.class);
281 if (contactStore
== null) {
282 contactStore
= new JsonContactsStore();
284 JsonNode threadStoreNode
= rootNode
.get("threadStore");
285 if (threadStoreNode
!= null) {
286 threadStore
= jsonProcessor
.convertValue(threadStoreNode
, JsonThreadStore
.class);
288 if (threadStore
== null) {
289 threadStore
= new JsonThreadStore();
293 private void migrateLegacyConfigs() {
294 // Copy group avatars that were previously stored in the attachments folder
295 // to the new avatar folder
296 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
297 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
298 File avatarFile
= getGroupAvatarFile(g
.groupId
);
299 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
300 if (!avatarFile
.exists() && attachmentFile
.exists()) {
302 createPrivateDirectories(avatarsPath
);
303 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
304 } catch (Exception e
) {
309 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
314 private void save() {
315 if (username
== null) {
318 ObjectNode rootNode
= jsonProcessor
.createObjectNode();
319 rootNode
.put("username", username
)
320 .put("deviceId", deviceId
)
321 .put("password", password
)
322 .put("signalingKey", signalingKey
)
323 .put("preKeyIdOffset", preKeyIdOffset
)
324 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
325 .put("registered", registered
)
326 .putPOJO("axolotlStore", signalProtocolStore
)
327 .putPOJO("groupStore", groupStore
)
328 .putPOJO("contactStore", contactStore
)
329 .putPOJO("threadStore", threadStore
)
333 fileChannel
.position(0);
334 jsonProcessor
.writeValue(Channels
.newOutputStream(fileChannel
), rootNode
);
335 fileChannel
.truncate(fileChannel
.position());
336 fileChannel
.force(false);
337 } catch (Exception e
) {
338 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
342 public void createNewIdentity() {
343 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
344 int registrationId
= KeyHelper
.generateRegistrationId(false);
345 signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
346 groupStore
= new JsonGroupStore();
351 public boolean isRegistered() {
355 public void register(boolean voiceVerification
) throws IOException
{
356 password
= Util
.getSecret(18);
358 accountManager
= new SignalServiceAccountManager(serviceUrls
, username
, password
, USER_AGENT
);
360 if (voiceVerification
)
361 accountManager
.requestVoiceVerificationCode();
363 accountManager
.requestSmsVerificationCode();
369 public void updateAccountAttributes() throws IOException
{
370 accountManager
.setAccountAttributes(signalingKey
, signalProtocolStore
.getLocalRegistrationId(), false, false, true);
373 public void unregister() throws IOException
{
374 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
375 // If this is the master device, other users can't send messages to this number anymore.
376 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
377 accountManager
.setGcmId(Optional
.<String
>absent());
380 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
381 password
= Util
.getSecret(18);
383 accountManager
= new SignalServiceAccountManager(serviceUrls
, username
, password
, USER_AGENT
);
384 String uuid
= accountManager
.getNewDeviceUuid();
388 return new URI("tsdevice:/?uuid=" + URLEncoder
.encode(uuid
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(signalProtocolStore
.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
389 } catch (URISyntaxException e
) {
395 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
396 signalingKey
= Util
.getSecret(52);
397 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(signalProtocolStore
.getIdentityKeyPair(), signalingKey
, false, true, signalProtocolStore
.getLocalRegistrationId(), deviceName
);
398 deviceId
= ret
.getDeviceId();
399 username
= ret
.getNumber();
400 // TODO do this check before actually registering
402 throw new UserAlreadyExists(username
, getFileName());
404 signalProtocolStore
= new JsonSignalProtocolStore(ret
.getIdentity(), signalProtocolStore
.getLocalRegistrationId());
410 requestSyncContacts();
415 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
416 return accountManager
.getDevices();
419 public void removeLinkedDevices(int deviceId
) throws IOException
{
420 accountManager
.removeDevice(deviceId
);
423 public static Map
<String
, String
> getQueryMap(String query
) {
424 String
[] params
= query
.split("&");
425 Map
<String
, String
> map
= new HashMap
<>();
426 for (String param
: params
) {
429 name
= URLDecoder
.decode(param
.split("=")[0], "utf-8");
430 } catch (UnsupportedEncodingException e
) {
435 value
= URLDecoder
.decode(param
.split("=")[1], "utf-8");
436 } catch (UnsupportedEncodingException e
) {
439 map
.put(name
, value
);
444 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
445 Map
<String
, String
> query
= getQueryMap(linkUri
.getRawQuery());
446 String deviceIdentifier
= query
.get("uuid");
447 String publicKeyEncoded
= query
.get("pub_key");
449 if (TextUtils
.isEmpty(deviceIdentifier
) || TextUtils
.isEmpty(publicKeyEncoded
)) {
450 throw new RuntimeException("Invalid device link uri");
453 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
455 addDevice(deviceIdentifier
, deviceKey
);
458 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
459 IdentityKeyPair identityKeyPair
= signalProtocolStore
.getIdentityKeyPair();
460 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
462 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, verificationCode
);
465 private List
<PreKeyRecord
> generatePreKeys() {
466 List
<PreKeyRecord
> records
= new LinkedList
<>();
468 for (int i
= 0; i
< PREKEY_BATCH_SIZE
; i
++) {
469 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
470 ECKeyPair keyPair
= Curve
.generateKeyPair();
471 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
473 signalProtocolStore
.storePreKey(preKeyId
, record);
477 preKeyIdOffset
= (preKeyIdOffset
+ PREKEY_BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
483 private PreKeyRecord
getOrGenerateLastResortPreKey() {
484 if (signalProtocolStore
.containsPreKey(Medium
.MAX_VALUE
)) {
486 return signalProtocolStore
.loadPreKey(Medium
.MAX_VALUE
);
487 } catch (InvalidKeyIdException e
) {
488 signalProtocolStore
.removePreKey(Medium
.MAX_VALUE
);
492 ECKeyPair keyPair
= Curve
.generateKeyPair();
493 PreKeyRecord
record = new PreKeyRecord(Medium
.MAX_VALUE
, keyPair
);
495 signalProtocolStore
.storePreKey(Medium
.MAX_VALUE
, record);
501 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
503 ECKeyPair keyPair
= Curve
.generateKeyPair();
504 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
505 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
507 signalProtocolStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
508 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
512 } catch (InvalidKeyException e
) {
513 throw new AssertionError(e
);
517 public void verifyAccount(String verificationCode
) throws IOException
{
518 verificationCode
= verificationCode
.replace("-", "");
519 signalingKey
= Util
.getSecret(52);
520 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, signalProtocolStore
.getLocalRegistrationId(), false, false, true);
522 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
529 private void refreshPreKeys() throws IOException
{
530 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
531 PreKeyRecord lastResortKey
= getOrGenerateLastResortPreKey();
532 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(signalProtocolStore
.getIdentityKeyPair());
534 accountManager
.setPreKeys(signalProtocolStore
.getIdentityKeyPair().getPublicKey(), lastResortKey
, signedPreKeyRecord
, oneTimePreKeys
);
538 private static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
539 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
540 if (attachments
!= null) {
541 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
542 for (String attachment
: attachments
) {
544 SignalServiceAttachments
.add(createAttachment(new File(attachment
)));
545 } catch (IOException e
) {
546 throw new AttachmentInvalidException(attachment
, e
);
550 return SignalServiceAttachments
;
553 private static SignalServiceAttachmentStream
createAttachment(File attachmentFile
) throws IOException
{
554 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
555 final long attachmentSize
= attachmentFile
.length();
556 String mime
= Files
.probeContentType(attachmentFile
.toPath());
558 mime
= "application/octet-stream";
560 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, null);
563 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
564 File file
= getGroupAvatarFile(groupId
);
565 if (!file
.exists()) {
566 return Optional
.absent();
569 return Optional
.of(createAttachment(file
));
572 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
573 File file
= getContactAvatarFile(number
);
574 if (!file
.exists()) {
575 return Optional
.absent();
578 return Optional
.of(createAttachment(file
));
581 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
582 GroupInfo g
= groupStore
.getGroup(groupId
);
584 throw new GroupNotFoundException(groupId
);
586 for (String member
: g
.members
) {
587 if (member
.equals(this.username
)) {
591 throw new NotAGroupMemberException(groupId
, g
.name
);
594 public List
<GroupInfo
> getGroups() {
595 return groupStore
.getGroups();
599 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
601 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
602 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
603 if (attachments
!= null) {
604 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
606 if (groupId
!= null) {
607 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
610 messageBuilder
.asGroupMessage(group
);
612 ThreadInfo thread
= threadStore
.getThread(Base64
.encodeBytes(groupId
));
613 if (thread
!= null) {
614 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
617 final GroupInfo g
= getGroupForSending(groupId
);
619 // Don't send group message to ourself
620 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
621 membersSend
.remove(this.username
);
622 sendMessage(messageBuilder
, membersSend
);
625 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
626 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
630 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
631 .asGroupMessage(group
);
633 final GroupInfo g
= getGroupForSending(groupId
);
634 g
.members
.remove(this.username
);
635 groupStore
.updateGroup(g
);
637 sendMessage(messageBuilder
, g
.members
);
640 private static String
join(CharSequence separator
, Iterable
<?
extends CharSequence
> list
) {
641 StringBuilder buf
= new StringBuilder();
642 for (CharSequence str
: list
) {
643 if (buf
.length() > 0) {
644 buf
.append(separator
);
649 return buf
.toString();
652 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
654 if (groupId
== null) {
656 g
= new GroupInfo(Util
.getSecretBytes(16));
657 g
.members
.add(username
);
659 g
= getGroupForSending(groupId
);
666 if (members
!= null) {
667 Set
<String
> newMembers
= new HashSet
<>();
668 for (String member
: members
) {
670 member
= canonicalizeNumber(member
);
671 } catch (InvalidNumberException e
) {
672 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
673 System
.err
.println("Aborting…");
676 if (g
.members
.contains(member
)) {
679 newMembers
.add(member
);
680 g
.members
.add(member
);
682 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
683 if (contacts
.size() != newMembers
.size()) {
684 // Some of the new members are not registered on Signal
685 for (ContactTokenDetails contact
: contacts
) {
686 newMembers
.remove(contact
.getNumber());
688 System
.err
.println("Failed to add members " + join(", ", newMembers
) + " to group: Not registered on Signal");
689 System
.err
.println("Aborting…");
694 if (avatarFile
!= null) {
695 createPrivateDirectories(avatarsPath
);
696 File aFile
= getGroupAvatarFile(g
.groupId
);
697 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
700 groupStore
.updateGroup(g
);
702 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
704 // Don't send group message to ourself
705 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
706 membersSend
.remove(this.username
);
707 sendMessage(messageBuilder
, membersSend
);
711 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
712 if (groupId
== null) {
715 GroupInfo g
= getGroupForSending(groupId
);
717 if (!g
.members
.contains(recipient
)) {
721 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
723 // Send group message only to the recipient who requested it
724 final List
<String
> membersSend
= new ArrayList
<>();
725 membersSend
.add(recipient
);
726 sendMessage(messageBuilder
, membersSend
);
729 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
730 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
733 .withMembers(new ArrayList
<>(g
.members
));
735 File aFile
= getGroupAvatarFile(g
.groupId
);
736 if (aFile
.exists()) {
738 group
.withAvatar(createAttachment(aFile
));
739 } catch (IOException e
) {
740 throw new AttachmentInvalidException(aFile
.toString(), e
);
744 return SignalServiceDataMessage
.newBuilder()
745 .asGroupMessage(group
.build());
748 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
749 if (groupId
== null) {
753 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
756 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
757 .asGroupMessage(group
.build());
759 // Send group info request message to the recipient who sent us a message with this groupId
760 final List
<String
> membersSend
= new ArrayList
<>();
761 membersSend
.add(recipient
);
762 sendMessage(messageBuilder
, membersSend
);
766 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
767 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
768 List
<String
> recipients
= new ArrayList
<>(1);
769 recipients
.add(recipient
);
770 sendMessage(message
, attachments
, recipients
);
774 public void sendMessage(String messageText
, List
<String
> attachments
,
775 List
<String
> recipients
)
776 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
777 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
778 if (attachments
!= null) {
779 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
781 sendMessage(messageBuilder
, recipients
);
785 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
786 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
787 .asEndSessionMessage();
789 sendMessage(messageBuilder
, recipients
);
793 public String
getContactName(String number
) {
794 ContactInfo contact
= contactStore
.getContact(number
);
795 if (contact
== null) {
803 public void setContactName(String number
, String name
) {
804 ContactInfo contact
= contactStore
.getContact(number
);
805 if (contact
== null) {
806 contact
= new ContactInfo();
807 contact
.number
= number
;
808 System
.out
.println("Add contact " + number
+ " named " + name
);
810 System
.out
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
813 contactStore
.updateContact(contact
);
818 public String
getGroupName(byte[] groupId
) {
819 GroupInfo group
= getGroup(groupId
);
828 public List
<String
> getGroupMembers(byte[] groupId
) {
829 GroupInfo group
= getGroup(groupId
);
831 return new ArrayList
<String
>();
833 return new ArrayList
<String
>(group
.members
);
838 public void updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
839 if (name
.isEmpty()) {
842 if (members
.size() == 0) {
845 if (avatar
.isEmpty()) {
848 sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
851 private void requestSyncGroups() throws IOException
{
852 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
853 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
855 sendSyncMessage(message
);
856 } catch (UntrustedIdentityException e
) {
861 private void requestSyncContacts() throws IOException
{
862 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
863 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
865 sendSyncMessage(message
);
866 } catch (UntrustedIdentityException e
) {
871 private void sendSyncMessage(SignalServiceSyncMessage message
)
872 throws IOException
, UntrustedIdentityException
{
873 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(serviceUrls
, username
, password
,
874 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.fromNullable(messagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
876 messageSender
.sendMessage(message
);
877 } catch (UntrustedIdentityException e
) {
878 signalProtocolStore
.saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
883 private void sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
884 throws EncapsulatedExceptions
, IOException
{
885 Set
<SignalServiceAddress
> recipientsTS
= getSignalServiceAddresses(recipients
);
886 if (recipientsTS
== null) return;
888 SignalServiceDataMessage message
= null;
890 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(serviceUrls
, username
, password
,
891 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.fromNullable(messagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
893 message
= messageBuilder
.build();
894 if (message
.getGroupInfo().isPresent()) {
896 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
897 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
898 for (UntrustedIdentityException e
: encapsulatedExceptions
.getUntrustedIdentityExceptions()) {
899 signalProtocolStore
.saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
903 // Send to all individually, so sync messages are sent correctly
904 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
905 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
906 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
907 for (SignalServiceAddress address
: recipientsTS
) {
908 ThreadInfo thread
= threadStore
.getThread(address
.getNumber());
909 if (thread
!= null) {
910 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
912 messageBuilder
.withExpiration(0);
914 message
= messageBuilder
.build();
916 messageSender
.sendMessage(address
, message
);
917 } catch (UntrustedIdentityException e
) {
918 signalProtocolStore
.saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
919 untrustedIdentities
.add(e
);
920 } catch (UnregisteredUserException e
) {
921 unregisteredUsers
.add(e
);
922 } catch (PushNetworkException e
) {
923 networkExceptions
.add(new NetworkFailureException(address
.getNumber(), e
));
926 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
927 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
931 if (message
!= null && message
.isEndSession()) {
932 for (SignalServiceAddress recipient
: recipientsTS
) {
933 handleEndSession(recipient
.getNumber());
940 private Set
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> recipients
) {
941 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
942 for (String recipient
: recipients
) {
944 recipientsTS
.add(getPushAddress(recipient
));
945 } catch (InvalidNumberException e
) {
946 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
947 System
.err
.println("Aborting sending.");
955 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws NoSessionException
, LegacyMessageException
, InvalidVersionException
, InvalidMessageException
, DuplicateMessageException
, InvalidKeyException
, InvalidKeyIdException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
956 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
958 return cipher
.decrypt(envelope
);
959 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
960 signalProtocolStore
.saveIdentity(e
.getName(), e
.getUntrustedIdentity(), TrustLevel
.UNTRUSTED
);
965 private void handleEndSession(String source
) {
966 signalProtocolStore
.deleteAllSessions(source
);
969 public interface ReceiveMessageHandler
{
970 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);
973 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
975 if (message
.getGroupInfo().isPresent()) {
976 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
977 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
978 GroupInfo group
= groupStore
.getGroup(groupInfo
.getGroupId());
979 switch (groupInfo
.getType()) {
982 group
= new GroupInfo(groupInfo
.getGroupId());
985 if (groupInfo
.getAvatar().isPresent()) {
986 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
987 if (avatar
.isPointer()) {
989 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
990 } catch (IOException
| InvalidMessageException e
) {
991 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
996 if (groupInfo
.getName().isPresent()) {
997 group
.name
= groupInfo
.getName().get();
1000 if (groupInfo
.getMembers().isPresent()) {
1001 group
.members
.addAll(groupInfo
.getMembers().get());
1004 groupStore
.updateGroup(group
);
1007 if (group
== null) {
1009 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1010 } catch (IOException
| EncapsulatedExceptions e
) {
1011 e
.printStackTrace();
1016 if (group
== null) {
1018 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1019 } catch (IOException
| EncapsulatedExceptions e
) {
1020 e
.printStackTrace();
1023 group
.members
.remove(source
);
1024 groupStore
.updateGroup(group
);
1028 if (group
!= null) {
1030 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
1031 } catch (IOException
| EncapsulatedExceptions e
) {
1032 e
.printStackTrace();
1033 } catch (NotAGroupMemberException e
) {
1034 // We have left this group, so don't send a group update message
1041 threadId
= destination
;
1046 if (message
.isEndSession()) {
1047 handleEndSession(isSync ? destination
: source
);
1049 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1050 ThreadInfo thread
= threadStore
.getThread(threadId
);
1051 if (thread
== null) {
1052 thread
= new ThreadInfo();
1053 thread
.id
= threadId
;
1055 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1056 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1057 threadStore
.updateThread(thread
);
1060 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1061 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1062 if (attachment
.isPointer()) {
1064 retrieveAttachment(attachment
.asPointer());
1065 } catch (IOException
| InvalidMessageException e
) {
1066 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1073 public void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1074 final File cachePath
= new File(getMessageCachePath());
1075 if (!cachePath
.exists()) {
1078 for (final File dir
: cachePath
.listFiles()) {
1079 if (!dir
.isDirectory()) {
1083 for (final File fileEntry
: dir
.listFiles()) {
1084 if (!fileEntry
.isFile()) {
1087 SignalServiceEnvelope envelope
;
1089 envelope
= loadEnvelope(fileEntry
);
1090 if (envelope
== null) {
1093 } catch (IOException e
) {
1094 e
.printStackTrace();
1097 SignalServiceContent content
= null;
1098 if (!envelope
.isReceipt()) {
1100 content
= decryptMessage(envelope
);
1101 } catch (Exception e
) {
1104 handleMessage(envelope
, content
, ignoreAttachments
);
1107 handler
.handleMessage(envelope
, content
, null);
1109 Files
.delete(fileEntry
.toPath());
1110 } catch (IOException e
) {
1111 System
.out
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1117 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1118 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1119 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(serviceUrls
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
1122 if (messagePipe
== null) {
1123 messagePipe
= messageReceiver
.createMessagePipe();
1127 SignalServiceEnvelope envelope
;
1128 SignalServiceContent content
= null;
1129 Exception exception
= null;
1130 final long now
= new Date().getTime();
1132 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1134 public void onMessage(SignalServiceEnvelope envelope
) {
1135 // store message on disk, before acknowledging receipt to the server
1137 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1138 storeEnvelope(envelope
, cacheFile
);
1139 } catch (IOException e
) {
1140 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1144 } catch (TimeoutException e
) {
1145 if (returnOnTimeout
)
1148 } catch (InvalidVersionException e
) {
1149 System
.err
.println("Ignoring error: " + e
.getMessage());
1152 if (!envelope
.isReceipt()) {
1154 content
= decryptMessage(envelope
);
1155 } catch (Exception e
) {
1158 handleMessage(envelope
, content
, ignoreAttachments
);
1161 handler
.handleMessage(envelope
, content
, exception
);
1162 if (exception
== null || !(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1163 File cacheFile
= null;
1165 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1166 Files
.delete(cacheFile
.toPath());
1167 } catch (IOException e
) {
1168 System
.out
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1173 if (messagePipe
!= null) {
1174 messagePipe
.shutdown();
1180 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1181 if (content
!= null) {
1182 if (content
.getDataMessage().isPresent()) {
1183 SignalServiceDataMessage message
= content
.getDataMessage().get();
1184 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1186 if (content
.getSyncMessage().isPresent()) {
1187 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1188 if (syncMessage
.getSent().isPresent()) {
1189 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1190 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1192 if (syncMessage
.getRequest().isPresent()) {
1193 RequestMessage rm
= syncMessage
.getRequest().get();
1194 if (rm
.isContactsRequest()) {
1197 } catch (UntrustedIdentityException
| IOException e
) {
1198 e
.printStackTrace();
1201 if (rm
.isGroupsRequest()) {
1204 } catch (UntrustedIdentityException
| IOException e
) {
1205 e
.printStackTrace();
1209 if (syncMessage
.getGroups().isPresent()) {
1210 File tmpFile
= null;
1212 tmpFile
= Util
.createTempFile();
1213 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
));
1215 while ((g
= s
.read()) != null) {
1216 GroupInfo syncGroup
= groupStore
.getGroup(g
.getId());
1217 if (syncGroup
== null) {
1218 syncGroup
= new GroupInfo(g
.getId());
1220 if (g
.getName().isPresent()) {
1221 syncGroup
.name
= g
.getName().get();
1223 syncGroup
.members
.addAll(g
.getMembers());
1224 syncGroup
.active
= g
.isActive();
1226 if (g
.getAvatar().isPresent()) {
1227 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1229 groupStore
.updateGroup(syncGroup
);
1231 } catch (Exception e
) {
1232 e
.printStackTrace();
1234 if (tmpFile
!= null) {
1236 Files
.delete(tmpFile
.toPath());
1237 } catch (IOException e
) {
1238 System
.out
.println("Failed to delete temp file “" + tmpFile
+ "”: " + e
.getMessage());
1242 if (syncMessage
.getBlockedList().isPresent()) {
1243 // TODO store list of blocked numbers
1246 if (syncMessage
.getContacts().isPresent()) {
1247 File tmpFile
= null;
1249 tmpFile
= Util
.createTempFile();
1250 DeviceContactsInputStream s
= new DeviceContactsInputStream(retrieveAttachmentAsStream(syncMessage
.getContacts().get().asPointer(), tmpFile
));
1252 while ((c
= s
.read()) != null) {
1253 ContactInfo contact
= contactStore
.getContact(c
.getNumber());
1254 if (contact
== null) {
1255 contact
= new ContactInfo();
1256 contact
.number
= c
.getNumber();
1258 if (c
.getName().isPresent()) {
1259 contact
.name
= c
.getName().get();
1261 if (c
.getColor().isPresent()) {
1262 contact
.color
= c
.getColor().get();
1264 contactStore
.updateContact(contact
);
1266 if (c
.getAvatar().isPresent()) {
1267 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1270 } catch (Exception e
) {
1271 e
.printStackTrace();
1273 if (tmpFile
!= null) {
1275 Files
.delete(tmpFile
.toPath());
1276 } catch (IOException e
) {
1277 System
.out
.println("Failed to delete temp file “" + tmpFile
+ "”: " + e
.getMessage());
1286 private SignalServiceEnvelope
loadEnvelope(File file
) throws IOException
{
1287 try (FileInputStream f
= new FileInputStream(file
)) {
1288 DataInputStream
in = new DataInputStream(f
);
1289 int version
= in.readInt();
1293 int type
= in.readInt();
1294 String source
= in.readUTF();
1295 int sourceDevice
= in.readInt();
1296 String relay
= in.readUTF();
1297 long timestamp
= in.readLong();
1298 byte[] content
= null;
1299 int contentLen
= in.readInt();
1300 if (contentLen
> 0) {
1301 content
= new byte[contentLen
];
1302 in.readFully(content
);
1304 byte[] legacyMessage
= null;
1305 int legacyMessageLen
= in.readInt();
1306 if (legacyMessageLen
> 0) {
1307 legacyMessage
= new byte[legacyMessageLen
];
1308 in.readFully(legacyMessage
);
1310 return new SignalServiceEnvelope(type
, source
, sourceDevice
, relay
, timestamp
, legacyMessage
, content
);
1314 private void storeEnvelope(SignalServiceEnvelope envelope
, File file
) throws IOException
{
1315 try (FileOutputStream f
= new FileOutputStream(file
)) {
1316 try (DataOutputStream out
= new DataOutputStream(f
)) {
1317 out
.writeInt(1); // version
1318 out
.writeInt(envelope
.getType());
1319 out
.writeUTF(envelope
.getSource());
1320 out
.writeInt(envelope
.getSourceDevice());
1321 out
.writeUTF(envelope
.getRelay());
1322 out
.writeLong(envelope
.getTimestamp());
1323 if (envelope
.hasContent()) {
1324 out
.writeInt(envelope
.getContent().length
);
1325 out
.write(envelope
.getContent());
1329 if (envelope
.hasLegacyMessage()) {
1330 out
.writeInt(envelope
.getLegacyMessage().length
);
1331 out
.write(envelope
.getLegacyMessage());
1339 public File
getContactAvatarFile(String number
) {
1340 return new File(avatarsPath
, "contact-" + number
);
1343 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1344 createPrivateDirectories(avatarsPath
);
1345 if (attachment
.isPointer()) {
1346 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1347 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1349 SignalServiceAttachmentStream stream
= attachment
.asStream();
1350 return retrieveAttachment(stream
, getContactAvatarFile(number
));
1354 public File
getGroupAvatarFile(byte[] groupId
) {
1355 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1358 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1359 createPrivateDirectories(avatarsPath
);
1360 if (attachment
.isPointer()) {
1361 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1362 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1364 SignalServiceAttachmentStream stream
= attachment
.asStream();
1365 return retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1369 public File
getAttachmentFile(long attachmentId
) {
1370 return new File(attachmentsPath
, attachmentId
+ "");
1373 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1374 createPrivateDirectories(attachmentsPath
);
1375 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1378 private File
retrieveAttachment(SignalServiceAttachmentStream stream
, File outputFile
) throws IOException
, InvalidMessageException
{
1379 InputStream input
= stream
.getInputStream();
1381 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1382 byte[] buffer
= new byte[4096];
1385 while ((read
= input
.read(buffer
)) != -1) {
1386 output
.write(buffer
, 0, read
);
1388 } catch (FileNotFoundException e
) {
1389 e
.printStackTrace();
1395 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1396 if (storePreview
&& pointer
.getPreview().isPresent()) {
1397 File previewFile
= new File(outputFile
+ ".preview");
1398 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1399 byte[] preview
= pointer
.getPreview().get();
1400 output
.write(preview
, 0, preview
.length
);
1401 } catch (FileNotFoundException e
) {
1402 e
.printStackTrace();
1407 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(serviceUrls
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
1409 File tmpFile
= Util
.createTempFile();
1410 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
)) {
1411 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1412 byte[] buffer
= new byte[4096];
1415 while ((read
= input
.read(buffer
)) != -1) {
1416 output
.write(buffer
, 0, read
);
1418 } catch (FileNotFoundException e
) {
1419 e
.printStackTrace();
1424 Files
.delete(tmpFile
.toPath());
1425 } catch (IOException e
) {
1426 System
.out
.println("Failed to delete temp file “" + tmpFile
+ "”: " + e
.getMessage());
1432 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1433 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(serviceUrls
, username
, password
, deviceId
, signalingKey
, USER_AGENT
);
1434 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
);
1437 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
1438 String localNumber
= username
;
1439 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
1442 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
1443 String e164number
= canonicalizeNumber(number
);
1444 return new SignalServiceAddress(e164number
);
1448 public boolean isRemote() {
1452 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1453 File groupsFile
= Util
.createTempFile();
1456 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1457 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1458 for (GroupInfo
record : groupStore
.getGroups()) {
1459 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1460 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1465 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1466 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1467 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1468 .withStream(groupsFileStream
)
1469 .withContentType("application/octet-stream")
1470 .withLength(groupsFile
.length())
1473 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1478 Files
.delete(groupsFile
.toPath());
1479 } catch (IOException e
) {
1480 System
.out
.println("Failed to delete temp file “" + groupsFile
+ "”: " + e
.getMessage());
1485 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1486 File contactsFile
= Util
.createTempFile();
1489 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1490 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1491 for (ContactInfo
record : contactStore
.getContacts()) {
1492 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1493 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
)));
1497 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1498 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1499 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1500 .withStream(contactsFileStream
)
1501 .withContentType("application/octet-stream")
1502 .withLength(contactsFile
.length())
1505 sendSyncMessage(SignalServiceSyncMessage
.forContacts(attachmentStream
));
1510 Files
.delete(contactsFile
.toPath());
1511 } catch (IOException e
) {
1512 System
.out
.println("Failed to delete temp file “" + contactsFile
+ "”: " + e
.getMessage());
1517 public ContactInfo
getContact(String number
) {
1518 return contactStore
.getContact(number
);
1521 public GroupInfo
getGroup(byte[] groupId
) {
1522 return groupStore
.getGroup(groupId
);
1525 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1526 return signalProtocolStore
.getIdentities();
1529 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1530 return signalProtocolStore
.getIdentities(number
);
1534 * Trust this the identity with this fingerprint
1536 * @param name username of the identity
1537 * @param fingerprint Fingerprint
1539 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1540 List
<JsonIdentityKeyStore
.Identity
> ids
= signalProtocolStore
.getIdentities(name
);
1544 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1545 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1549 signalProtocolStore
.saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1557 * Trust this the identity with this safety number
1559 * @param name username of the identity
1560 * @param safetyNumber Safety number
1562 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1563 List
<JsonIdentityKeyStore
.Identity
> ids
= signalProtocolStore
.getIdentities(name
);
1567 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1568 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1572 signalProtocolStore
.saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1580 * Trust all keys of this identity without verification
1582 * @param name username of the identity
1584 public boolean trustIdentityAllKeys(String name
) {
1585 List
<JsonIdentityKeyStore
.Identity
> ids
= signalProtocolStore
.getIdentities(name
);
1589 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1590 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1591 signalProtocolStore
.saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1598 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1599 Fingerprint fingerprint
= new NumericFingerprintGenerator(5200).createFor(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1600 return fingerprint
.getDisplayableFingerprint().getDisplayText();