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
.Util
;
39 import org
.whispersystems
.libsignal
.*;
40 import org
.whispersystems
.libsignal
.ecc
.Curve
;
41 import org
.whispersystems
.libsignal
.ecc
.ECKeyPair
;
42 import org
.whispersystems
.libsignal
.ecc
.ECPublicKey
;
43 import org
.whispersystems
.libsignal
.fingerprint
.Fingerprint
;
44 import org
.whispersystems
.libsignal
.fingerprint
.NumericFingerprintGenerator
;
45 import org
.whispersystems
.libsignal
.state
.PreKeyRecord
;
46 import org
.whispersystems
.libsignal
.state
.SignedPreKeyRecord
;
47 import org
.whispersystems
.libsignal
.util
.KeyHelper
;
48 import org
.whispersystems
.libsignal
.util
.Medium
;
49 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
50 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
51 import org
.whispersystems
.signalservice
.api
.SignalServiceMessagePipe
;
52 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageReceiver
;
53 import org
.whispersystems
.signalservice
.api
.SignalServiceMessageSender
;
54 import org
.whispersystems
.signalservice
.api
.crypto
.SignalServiceCipher
;
55 import org
.whispersystems
.signalservice
.api
.crypto
.UntrustedIdentityException
;
56 import org
.whispersystems
.signalservice
.api
.messages
.*;
57 import org
.whispersystems
.signalservice
.api
.messages
.multidevice
.*;
58 import org
.whispersystems
.signalservice
.api
.push
.ContactTokenDetails
;
59 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
60 import org
.whispersystems
.signalservice
.api
.push
.TrustStore
;
61 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.*;
62 import org
.whispersystems
.signalservice
.api
.util
.InvalidNumberException
;
63 import org
.whispersystems
.signalservice
.api
.util
.PhoneNumberFormatter
;
64 import org
.whispersystems
.signalservice
.api
.util
.SleepTimer
;
65 import org
.whispersystems
.signalservice
.api
.util
.UptimeSleepTimer
;
66 import org
.whispersystems
.signalservice
.internal
.configuration
.SignalCdnUrl
;
67 import org
.whispersystems
.signalservice
.internal
.configuration
.SignalServiceConfiguration
;
68 import org
.whispersystems
.signalservice
.internal
.configuration
.SignalServiceUrl
;
69 import org
.whispersystems
.signalservice
.internal
.push
.SignalServiceProtos
;
70 import org
.whispersystems
.signalservice
.internal
.util
.Base64
;
74 import java
.net
.URISyntaxException
;
75 import java
.net
.URLDecoder
;
76 import java
.net
.URLEncoder
;
77 import java
.nio
.channels
.Channels
;
78 import java
.nio
.channels
.FileChannel
;
79 import java
.nio
.channels
.FileLock
;
80 import java
.nio
.file
.Files
;
81 import java
.nio
.file
.Path
;
82 import java
.nio
.file
.Paths
;
83 import java
.nio
.file
.StandardCopyOption
;
84 import java
.nio
.file
.attribute
.PosixFilePermission
;
85 import java
.nio
.file
.attribute
.PosixFilePermissions
;
87 import java
.util
.concurrent
.TimeUnit
;
88 import java
.util
.concurrent
.TimeoutException
;
90 import static java
.nio
.file
.attribute
.PosixFilePermission
.*;
92 class Manager
implements Signal
{
93 private final static String URL
= "https://textsecure-service.whispersystems.org";
94 private final static String CDN_URL
= "https://cdn.signal.org";
95 private final static TrustStore TRUST_STORE
= new WhisperTrustStore();
96 private final static SignalServiceConfiguration serviceConfiguration
= new SignalServiceConfiguration(
97 new SignalServiceUrl
[]{new SignalServiceUrl(URL
, TRUST_STORE
)},
98 new SignalCdnUrl
[]{new SignalCdnUrl(CDN_URL
, TRUST_STORE
)}
101 public final static String PROJECT_NAME
= Manager
.class.getPackage().getImplementationTitle();
102 public final static String PROJECT_VERSION
= Manager
.class.getPackage().getImplementationVersion();
103 private final static String USER_AGENT
= PROJECT_NAME
== null ?
null : PROJECT_NAME
+ " " + PROJECT_VERSION
;
105 private final static int PREKEY_MINIMUM_COUNT
= 20;
106 private static final int PREKEY_BATCH_SIZE
= 100;
107 private static final int MAX_ATTACHMENT_SIZE
= 150 * 1024 * 1024;
109 private final String settingsPath
;
110 private final String dataPath
;
111 private final String attachmentsPath
;
112 private final String avatarsPath
;
114 private FileChannel fileChannel
;
115 private FileLock lock
;
117 private final ObjectMapper jsonProcessor
= new ObjectMapper();
118 private String username
;
119 private int deviceId
= SignalServiceAddress
.DEFAULT_DEVICE_ID
;
120 private String password
;
121 private String registrationLockPin
;
122 private String signalingKey
;
123 private int preKeyIdOffset
;
124 private int nextSignedPreKeyId
;
126 private boolean registered
= false;
128 private JsonSignalProtocolStore signalProtocolStore
;
129 private SignalServiceAccountManager accountManager
;
130 private JsonGroupStore groupStore
;
131 private JsonContactsStore contactStore
;
132 private JsonThreadStore threadStore
;
133 private SignalServiceMessagePipe messagePipe
= null;
135 private SleepTimer timer
= new UptimeSleepTimer();
137 public Manager(String username
, String settingsPath
) {
138 this.username
= username
;
139 this.settingsPath
= settingsPath
;
140 this.dataPath
= this.settingsPath
+ "/data";
141 this.attachmentsPath
= this.settingsPath
+ "/attachments";
142 this.avatarsPath
= this.settingsPath
+ "/avatars";
144 jsonProcessor
.setVisibility(PropertyAccessor
.ALL
, JsonAutoDetect
.Visibility
.NONE
); // disable autodetect
145 jsonProcessor
.enable(SerializationFeature
.INDENT_OUTPUT
); // for pretty print, you can disable it.
146 jsonProcessor
.enable(SerializationFeature
.WRITE_NULL_MAP_VALUES
);
147 jsonProcessor
.disable(DeserializationFeature
.FAIL_ON_UNKNOWN_PROPERTIES
);
148 jsonProcessor
.disable(JsonParser
.Feature
.AUTO_CLOSE_SOURCE
);
149 jsonProcessor
.disable(JsonGenerator
.Feature
.AUTO_CLOSE_TARGET
);
152 public String
getUsername() {
156 private IdentityKey
getIdentity() {
157 return signalProtocolStore
.getIdentityKeyPair().getPublicKey();
160 public int getDeviceId() {
164 public String
getFileName() {
165 return dataPath
+ "/" + username
;
168 private String
getMessageCachePath() {
169 return this.dataPath
+ "/" + username
+ ".d/msg-cache";
172 private String
getMessageCachePath(String sender
) {
173 return getMessageCachePath() + "/" + sender
.replace("/", "_");
176 private File
getMessageCacheFile(String sender
, long now
, long timestamp
) throws IOException
{
177 String cachePath
= getMessageCachePath(sender
);
178 createPrivateDirectories(cachePath
);
179 return new File(cachePath
+ "/" + now
+ "_" + timestamp
);
182 private static void createPrivateDirectories(String path
) throws IOException
{
183 final Path file
= new File(path
).toPath();
185 Set
<PosixFilePermission
> perms
= EnumSet
.of(OWNER_READ
, OWNER_WRITE
, OWNER_EXECUTE
);
186 Files
.createDirectories(file
, PosixFilePermissions
.asFileAttribute(perms
));
187 } catch (UnsupportedOperationException e
) {
188 Files
.createDirectories(file
);
192 private static void createPrivateFile(String path
) throws IOException
{
193 final Path file
= new File(path
).toPath();
195 Set
<PosixFilePermission
> perms
= EnumSet
.of(OWNER_READ
, OWNER_WRITE
);
196 Files
.createFile(file
, PosixFilePermissions
.asFileAttribute(perms
));
197 } catch (UnsupportedOperationException e
) {
198 Files
.createFile(file
);
202 public boolean userExists() {
203 if (username
== null) {
206 File f
= new File(getFileName());
207 return !(!f
.exists() || f
.isDirectory());
210 public boolean userHasKeys() {
211 return signalProtocolStore
!= null;
214 private JsonNode
getNotNullNode(JsonNode parent
, String name
) throws InvalidObjectException
{
215 JsonNode node
= parent
.get(name
);
217 throw new InvalidObjectException(String
.format("Incorrect file format: expected parameter %s not found ", name
));
223 private void openFileChannel() throws IOException
{
224 if (fileChannel
!= null)
227 createPrivateDirectories(dataPath
);
228 if (!new File(getFileName()).exists()) {
229 createPrivateFile(getFileName());
231 fileChannel
= new RandomAccessFile(new File(getFileName()), "rw").getChannel();
232 lock
= fileChannel
.tryLock();
234 System
.err
.println("Config file is in use by another instance, waiting…");
235 lock
= fileChannel
.lock();
236 System
.err
.println("Config file lock acquired.");
240 public void init() throws IOException
{
243 migrateLegacyConfigs();
245 accountManager
= new SignalServiceAccountManager(serviceConfiguration
, username
, password
, deviceId
, USER_AGENT
, timer
);
247 if (registered
&& accountManager
.getPreKeysCount() < PREKEY_MINIMUM_COUNT
) {
251 } catch (AuthorizationFailedException e
) {
252 System
.err
.println("Authorization failed, was the number registered elsewhere?");
256 private void load() throws IOException
{
258 JsonNode rootNode
= jsonProcessor
.readTree(Channels
.newInputStream(fileChannel
));
260 JsonNode node
= rootNode
.get("deviceId");
262 deviceId
= node
.asInt();
264 username
= getNotNullNode(rootNode
, "username").asText();
265 password
= getNotNullNode(rootNode
, "password").asText();
266 JsonNode pinNode
= rootNode
.get("registrationLockPin");
267 registrationLockPin
= pinNode
== null ?
null : pinNode
.asText();
268 if (rootNode
.has("signalingKey")) {
269 signalingKey
= getNotNullNode(rootNode
, "signalingKey").asText();
271 if (rootNode
.has("preKeyIdOffset")) {
272 preKeyIdOffset
= getNotNullNode(rootNode
, "preKeyIdOffset").asInt(0);
276 if (rootNode
.has("nextSignedPreKeyId")) {
277 nextSignedPreKeyId
= getNotNullNode(rootNode
, "nextSignedPreKeyId").asInt();
279 nextSignedPreKeyId
= 0;
281 signalProtocolStore
= jsonProcessor
.convertValue(getNotNullNode(rootNode
, "axolotlStore"), JsonSignalProtocolStore
.class);
282 registered
= getNotNullNode(rootNode
, "registered").asBoolean();
283 JsonNode groupStoreNode
= rootNode
.get("groupStore");
284 if (groupStoreNode
!= null) {
285 groupStore
= jsonProcessor
.convertValue(groupStoreNode
, JsonGroupStore
.class);
287 if (groupStore
== null) {
288 groupStore
= new JsonGroupStore();
291 JsonNode contactStoreNode
= rootNode
.get("contactStore");
292 if (contactStoreNode
!= null) {
293 contactStore
= jsonProcessor
.convertValue(contactStoreNode
, JsonContactsStore
.class);
295 if (contactStore
== null) {
296 contactStore
= new JsonContactsStore();
298 JsonNode threadStoreNode
= rootNode
.get("threadStore");
299 if (threadStoreNode
!= null) {
300 threadStore
= jsonProcessor
.convertValue(threadStoreNode
, JsonThreadStore
.class);
302 if (threadStore
== null) {
303 threadStore
= new JsonThreadStore();
307 private void migrateLegacyConfigs() {
308 // Copy group avatars that were previously stored in the attachments folder
309 // to the new avatar folder
310 if (JsonGroupStore
.groupsWithLegacyAvatarId
.size() > 0) {
311 for (GroupInfo g
: JsonGroupStore
.groupsWithLegacyAvatarId
) {
312 File avatarFile
= getGroupAvatarFile(g
.groupId
);
313 File attachmentFile
= getAttachmentFile(g
.getAvatarId());
314 if (!avatarFile
.exists() && attachmentFile
.exists()) {
316 createPrivateDirectories(avatarsPath
);
317 Files
.copy(attachmentFile
.toPath(), avatarFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
318 } catch (Exception e
) {
323 JsonGroupStore
.groupsWithLegacyAvatarId
.clear();
328 private void save() {
329 if (username
== null) {
332 ObjectNode rootNode
= jsonProcessor
.createObjectNode();
333 rootNode
.put("username", username
)
334 .put("deviceId", deviceId
)
335 .put("password", password
)
336 .put("registrationLockPin", registrationLockPin
)
337 .put("signalingKey", signalingKey
)
338 .put("preKeyIdOffset", preKeyIdOffset
)
339 .put("nextSignedPreKeyId", nextSignedPreKeyId
)
340 .put("registered", registered
)
341 .putPOJO("axolotlStore", signalProtocolStore
)
342 .putPOJO("groupStore", groupStore
)
343 .putPOJO("contactStore", contactStore
)
344 .putPOJO("threadStore", threadStore
)
348 fileChannel
.position(0);
349 jsonProcessor
.writeValue(Channels
.newOutputStream(fileChannel
), rootNode
);
350 fileChannel
.truncate(fileChannel
.position());
351 fileChannel
.force(false);
352 } catch (Exception e
) {
353 System
.err
.println(String
.format("Error saving file: %s", e
.getMessage()));
357 public void createNewIdentity() {
358 IdentityKeyPair identityKey
= KeyHelper
.generateIdentityKeyPair();
359 int registrationId
= KeyHelper
.generateRegistrationId(false);
360 signalProtocolStore
= new JsonSignalProtocolStore(identityKey
, registrationId
);
361 groupStore
= new JsonGroupStore();
366 public boolean isRegistered() {
370 public void register(boolean voiceVerification
) throws IOException
{
371 password
= Util
.getSecret(18);
373 accountManager
= new SignalServiceAccountManager(serviceConfiguration
, username
, password
, USER_AGENT
, timer
);
375 if (voiceVerification
)
376 accountManager
.requestVoiceVerificationCode();
378 accountManager
.requestSmsVerificationCode();
384 public void updateAccountAttributes() throws IOException
{
385 accountManager
.setAccountAttributes(signalingKey
, signalProtocolStore
.getLocalRegistrationId(), true, registrationLockPin
);
388 public void unregister() throws IOException
{
389 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
390 // If this is the master device, other users can't send messages to this number anymore.
391 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
392 accountManager
.setGcmId(Optional
.<String
>absent());
395 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
396 password
= Util
.getSecret(18);
398 accountManager
= new SignalServiceAccountManager(serviceConfiguration
, username
, password
, USER_AGENT
, timer
);
399 String uuid
= accountManager
.getNewDeviceUuid();
403 return new URI("tsdevice:/?uuid=" + URLEncoder
.encode(uuid
, "utf-8") + "&pub_key=" + URLEncoder
.encode(Base64
.encodeBytesWithoutPadding(signalProtocolStore
.getIdentityKeyPair().getPublicKey().serialize()), "utf-8"));
404 } catch (URISyntaxException e
) {
410 public void finishDeviceLink(String deviceName
) throws IOException
, InvalidKeyException
, TimeoutException
, UserAlreadyExists
{
411 signalingKey
= Util
.getSecret(52);
412 SignalServiceAccountManager
.NewDeviceRegistrationReturn ret
= accountManager
.finishNewDeviceRegistration(signalProtocolStore
.getIdentityKeyPair(), signalingKey
, false, true, signalProtocolStore
.getLocalRegistrationId(), deviceName
);
413 deviceId
= ret
.getDeviceId();
414 username
= ret
.getNumber();
415 // TODO do this check before actually registering
417 throw new UserAlreadyExists(username
, getFileName());
419 signalProtocolStore
= new JsonSignalProtocolStore(ret
.getIdentity(), signalProtocolStore
.getLocalRegistrationId());
425 requestSyncContacts();
430 public List
<DeviceInfo
> getLinkedDevices() throws IOException
{
431 return accountManager
.getDevices();
434 public void removeLinkedDevices(int deviceId
) throws IOException
{
435 accountManager
.removeDevice(deviceId
);
438 public static Map
<String
, String
> getQueryMap(String query
) {
439 String
[] params
= query
.split("&");
440 Map
<String
, String
> map
= new HashMap
<>();
441 for (String param
: params
) {
444 name
= URLDecoder
.decode(param
.split("=")[0], "utf-8");
445 } catch (UnsupportedEncodingException e
) {
450 value
= URLDecoder
.decode(param
.split("=")[1], "utf-8");
451 } catch (UnsupportedEncodingException e
) {
454 map
.put(name
, value
);
459 public void addDeviceLink(URI linkUri
) throws IOException
, InvalidKeyException
{
460 Map
<String
, String
> query
= getQueryMap(linkUri
.getRawQuery());
461 String deviceIdentifier
= query
.get("uuid");
462 String publicKeyEncoded
= query
.get("pub_key");
464 if (TextUtils
.isEmpty(deviceIdentifier
) || TextUtils
.isEmpty(publicKeyEncoded
)) {
465 throw new RuntimeException("Invalid device link uri");
468 ECPublicKey deviceKey
= Curve
.decodePoint(Base64
.decode(publicKeyEncoded
), 0);
470 addDevice(deviceIdentifier
, deviceKey
);
473 private void addDevice(String deviceIdentifier
, ECPublicKey deviceKey
) throws IOException
, InvalidKeyException
{
474 IdentityKeyPair identityKeyPair
= signalProtocolStore
.getIdentityKeyPair();
475 String verificationCode
= accountManager
.getNewDeviceVerificationCode();
477 // TODO send profile key
478 accountManager
.addDevice(deviceIdentifier
, deviceKey
, identityKeyPair
, Optional
.<byte[]>absent(), verificationCode
);
481 private List
<PreKeyRecord
> generatePreKeys() {
482 List
<PreKeyRecord
> records
= new LinkedList
<>();
484 for (int i
= 0; i
< PREKEY_BATCH_SIZE
; i
++) {
485 int preKeyId
= (preKeyIdOffset
+ i
) % Medium
.MAX_VALUE
;
486 ECKeyPair keyPair
= Curve
.generateKeyPair();
487 PreKeyRecord
record = new PreKeyRecord(preKeyId
, keyPair
);
489 signalProtocolStore
.storePreKey(preKeyId
, record);
493 preKeyIdOffset
= (preKeyIdOffset
+ PREKEY_BATCH_SIZE
+ 1) % Medium
.MAX_VALUE
;
499 private SignedPreKeyRecord
generateSignedPreKey(IdentityKeyPair identityKeyPair
) {
501 ECKeyPair keyPair
= Curve
.generateKeyPair();
502 byte[] signature
= Curve
.calculateSignature(identityKeyPair
.getPrivateKey(), keyPair
.getPublicKey().serialize());
503 SignedPreKeyRecord
record = new SignedPreKeyRecord(nextSignedPreKeyId
, System
.currentTimeMillis(), keyPair
, signature
);
505 signalProtocolStore
.storeSignedPreKey(nextSignedPreKeyId
, record);
506 nextSignedPreKeyId
= (nextSignedPreKeyId
+ 1) % Medium
.MAX_VALUE
;
510 } catch (InvalidKeyException e
) {
511 throw new AssertionError(e
);
515 public void verifyAccount(String verificationCode
, String pin
) throws IOException
{
516 verificationCode
= verificationCode
.replace("-", "");
517 signalingKey
= Util
.getSecret(52);
518 accountManager
.verifyAccountWithCode(verificationCode
, signalingKey
, signalProtocolStore
.getLocalRegistrationId(), true, pin
);
520 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
522 registrationLockPin
= pin
;
528 public void setRegistrationLockPin(Optional
<String
> pin
) throws IOException
{
529 accountManager
.setPin(pin
);
530 if (pin
.isPresent()) {
531 registrationLockPin
= pin
.get();
533 registrationLockPin
= null;
537 private void refreshPreKeys() throws IOException
{
538 List
<PreKeyRecord
> oneTimePreKeys
= generatePreKeys();
539 SignedPreKeyRecord signedPreKeyRecord
= generateSignedPreKey(signalProtocolStore
.getIdentityKeyPair());
541 accountManager
.setPreKeys(signalProtocolStore
.getIdentityKeyPair().getPublicKey(), signedPreKeyRecord
, oneTimePreKeys
);
545 private static List
<SignalServiceAttachment
> getSignalServiceAttachments(List
<String
> attachments
) throws AttachmentInvalidException
{
546 List
<SignalServiceAttachment
> SignalServiceAttachments
= null;
547 if (attachments
!= null) {
548 SignalServiceAttachments
= new ArrayList
<>(attachments
.size());
549 for (String attachment
: attachments
) {
551 SignalServiceAttachments
.add(createAttachment(new File(attachment
)));
552 } catch (IOException e
) {
553 throw new AttachmentInvalidException(attachment
, e
);
557 return SignalServiceAttachments
;
560 private static SignalServiceAttachmentStream
createAttachment(File attachmentFile
) throws IOException
{
561 InputStream attachmentStream
= new FileInputStream(attachmentFile
);
562 final long attachmentSize
= attachmentFile
.length();
563 String mime
= Files
.probeContentType(attachmentFile
.toPath());
565 mime
= "application/octet-stream";
567 // TODO mabybe add a parameter to set the voiceNote and preview option
568 return new SignalServiceAttachmentStream(attachmentStream
, mime
, attachmentSize
, Optional
.of(attachmentFile
.getName()), false, Optional
.<byte[]>absent(), 0, 0, null);
571 private Optional
<SignalServiceAttachmentStream
> createGroupAvatarAttachment(byte[] groupId
) throws IOException
{
572 File file
= getGroupAvatarFile(groupId
);
573 if (!file
.exists()) {
574 return Optional
.absent();
577 return Optional
.of(createAttachment(file
));
580 private Optional
<SignalServiceAttachmentStream
> createContactAvatarAttachment(String number
) throws IOException
{
581 File file
= getContactAvatarFile(number
);
582 if (!file
.exists()) {
583 return Optional
.absent();
586 return Optional
.of(createAttachment(file
));
589 private GroupInfo
getGroupForSending(byte[] groupId
) throws GroupNotFoundException
, NotAGroupMemberException
{
590 GroupInfo g
= groupStore
.getGroup(groupId
);
592 throw new GroupNotFoundException(groupId
);
594 for (String member
: g
.members
) {
595 if (member
.equals(this.username
)) {
599 throw new NotAGroupMemberException(groupId
, g
.name
);
602 public List
<GroupInfo
> getGroups() {
603 return groupStore
.getGroups();
607 public void sendGroupMessage(String messageText
, List
<String
> attachments
,
609 throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
610 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
611 if (attachments
!= null) {
612 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
614 if (groupId
!= null) {
615 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.DELIVER
)
618 messageBuilder
.asGroupMessage(group
);
620 ThreadInfo thread
= threadStore
.getThread(Base64
.encodeBytes(groupId
));
621 if (thread
!= null) {
622 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
625 final GroupInfo g
= getGroupForSending(groupId
);
627 // Don't send group message to ourself
628 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
629 membersSend
.remove(this.username
);
630 sendMessage(messageBuilder
, membersSend
);
633 public void sendQuitGroupMessage(byte[] groupId
) throws GroupNotFoundException
, IOException
, EncapsulatedExceptions
{
634 SignalServiceGroup group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.QUIT
)
638 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
639 .asGroupMessage(group
);
641 final GroupInfo g
= getGroupForSending(groupId
);
642 g
.members
.remove(this.username
);
643 groupStore
.updateGroup(g
);
645 sendMessage(messageBuilder
, g
.members
);
648 private static String
join(CharSequence separator
, Iterable
<?
extends CharSequence
> list
) {
649 StringBuilder buf
= new StringBuilder();
650 for (CharSequence str
: list
) {
651 if (buf
.length() > 0) {
652 buf
.append(separator
);
657 return buf
.toString();
660 public byte[] sendUpdateGroupMessage(byte[] groupId
, String name
, Collection
<String
> members
, String avatarFile
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
662 if (groupId
== null) {
664 g
= new GroupInfo(Util
.getSecretBytes(16));
665 g
.members
.add(username
);
667 g
= getGroupForSending(groupId
);
674 if (members
!= null) {
675 Set
<String
> newMembers
= new HashSet
<>();
676 for (String member
: members
) {
678 member
= canonicalizeNumber(member
);
679 } catch (InvalidNumberException e
) {
680 System
.err
.println("Failed to add member \"" + member
+ "\" to group: " + e
.getMessage());
681 System
.err
.println("Aborting…");
684 if (g
.members
.contains(member
)) {
687 newMembers
.add(member
);
688 g
.members
.add(member
);
690 final List
<ContactTokenDetails
> contacts
= accountManager
.getContacts(newMembers
);
691 if (contacts
.size() != newMembers
.size()) {
692 // Some of the new members are not registered on Signal
693 for (ContactTokenDetails contact
: contacts
) {
694 newMembers
.remove(contact
.getNumber());
696 System
.err
.println("Failed to add members " + join(", ", newMembers
) + " to group: Not registered on Signal");
697 System
.err
.println("Aborting…");
702 if (avatarFile
!= null) {
703 createPrivateDirectories(avatarsPath
);
704 File aFile
= getGroupAvatarFile(g
.groupId
);
705 Files
.copy(Paths
.get(avatarFile
), aFile
.toPath(), StandardCopyOption
.REPLACE_EXISTING
);
708 groupStore
.updateGroup(g
);
710 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
712 // Don't send group message to ourself
713 final List
<String
> membersSend
= new ArrayList
<>(g
.members
);
714 membersSend
.remove(this.username
);
715 sendMessage(messageBuilder
, membersSend
);
719 private void sendUpdateGroupMessage(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
720 if (groupId
== null) {
723 GroupInfo g
= getGroupForSending(groupId
);
725 if (!g
.members
.contains(recipient
)) {
729 SignalServiceDataMessage
.Builder messageBuilder
= getGroupUpdateMessageBuilder(g
);
731 // Send group message only to the recipient who requested it
732 final List
<String
> membersSend
= new ArrayList
<>();
733 membersSend
.add(recipient
);
734 sendMessage(messageBuilder
, membersSend
);
737 private SignalServiceDataMessage
.Builder
getGroupUpdateMessageBuilder(GroupInfo g
) {
738 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.UPDATE
)
741 .withMembers(new ArrayList
<>(g
.members
));
743 File aFile
= getGroupAvatarFile(g
.groupId
);
744 if (aFile
.exists()) {
746 group
.withAvatar(createAttachment(aFile
));
747 } catch (IOException e
) {
748 throw new AttachmentInvalidException(aFile
.toString(), e
);
752 return SignalServiceDataMessage
.newBuilder()
753 .asGroupMessage(group
.build());
756 private void sendGroupInfoRequest(byte[] groupId
, String recipient
) throws IOException
, EncapsulatedExceptions
{
757 if (groupId
== null) {
761 SignalServiceGroup
.Builder group
= SignalServiceGroup
.newBuilder(SignalServiceGroup
.Type
.REQUEST_INFO
)
764 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
765 .asGroupMessage(group
.build());
767 // Send group info request message to the recipient who sent us a message with this groupId
768 final List
<String
> membersSend
= new ArrayList
<>();
769 membersSend
.add(recipient
);
770 sendMessage(messageBuilder
, membersSend
);
774 public void sendMessage(String message
, List
<String
> attachments
, String recipient
)
775 throws EncapsulatedExceptions
, AttachmentInvalidException
, IOException
{
776 List
<String
> recipients
= new ArrayList
<>(1);
777 recipients
.add(recipient
);
778 sendMessage(message
, attachments
, recipients
);
782 public void sendMessage(String messageText
, List
<String
> attachments
,
783 List
<String
> recipients
)
784 throws IOException
, EncapsulatedExceptions
, AttachmentInvalidException
{
785 final SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder().withBody(messageText
);
786 if (attachments
!= null) {
787 messageBuilder
.withAttachments(getSignalServiceAttachments(attachments
));
789 sendMessage(messageBuilder
, recipients
);
793 public void sendEndSessionMessage(List
<String
> recipients
) throws IOException
, EncapsulatedExceptions
{
794 SignalServiceDataMessage
.Builder messageBuilder
= SignalServiceDataMessage
.newBuilder()
795 .asEndSessionMessage();
797 sendMessage(messageBuilder
, recipients
);
801 public String
getContactName(String number
) {
802 ContactInfo contact
= contactStore
.getContact(number
);
803 if (contact
== null) {
811 public void setContactName(String number
, String name
) {
812 ContactInfo contact
= contactStore
.getContact(number
);
813 if (contact
== null) {
814 contact
= new ContactInfo();
815 contact
.number
= number
;
816 System
.err
.println("Add contact " + number
+ " named " + name
);
818 System
.err
.println("Updating contact " + number
+ " name " + contact
.name
+ " -> " + name
);
821 contactStore
.updateContact(contact
);
826 public List
<byte[]> getGroupIds() {
827 List
<GroupInfo
> groups
= getGroups();
828 List
<byte[]> ids
= new ArrayList
<byte[]>(groups
.size());
829 for (GroupInfo group
: groups
) {
830 ids
.add(group
.groupId
);
836 public String
getGroupName(byte[] groupId
) {
837 GroupInfo group
= getGroup(groupId
);
846 public List
<String
> getGroupMembers(byte[] groupId
) {
847 GroupInfo group
= getGroup(groupId
);
849 return new ArrayList
<String
>();
851 return new ArrayList
<String
>(group
.members
);
856 public byte[] updateGroup(byte[] groupId
, String name
, List
<String
> members
, String avatar
) throws IOException
, EncapsulatedExceptions
, GroupNotFoundException
, AttachmentInvalidException
{
857 if (groupId
.length
== 0) {
860 if (name
.isEmpty()) {
863 if (members
.size() == 0) {
866 if (avatar
.isEmpty()) {
869 return sendUpdateGroupMessage(groupId
, name
, members
, avatar
);
872 private void requestSyncGroups() throws IOException
{
873 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.GROUPS
).build();
874 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
876 sendSyncMessage(message
);
877 } catch (UntrustedIdentityException e
) {
882 private void requestSyncContacts() throws IOException
{
883 SignalServiceProtos
.SyncMessage
.Request r
= SignalServiceProtos
.SyncMessage
.Request
.newBuilder().setType(SignalServiceProtos
.SyncMessage
.Request
.Type
.CONTACTS
).build();
884 SignalServiceSyncMessage message
= SignalServiceSyncMessage
.forRequest(new RequestMessage(r
));
886 sendSyncMessage(message
);
887 } catch (UntrustedIdentityException e
) {
892 private void sendSyncMessage(SignalServiceSyncMessage message
)
893 throws IOException
, UntrustedIdentityException
{
894 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(serviceConfiguration
, username
, password
,
895 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.fromNullable(messagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
897 messageSender
.sendMessage(message
);
898 } catch (UntrustedIdentityException e
) {
899 signalProtocolStore
.saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
904 private void sendMessage(SignalServiceDataMessage
.Builder messageBuilder
, Collection
<String
> recipients
)
905 throws EncapsulatedExceptions
, IOException
{
906 Set
<SignalServiceAddress
> recipientsTS
= getSignalServiceAddresses(recipients
);
907 if (recipientsTS
== null) return;
909 SignalServiceDataMessage message
= null;
911 SignalServiceMessageSender messageSender
= new SignalServiceMessageSender(serviceConfiguration
, username
, password
,
912 deviceId
, signalProtocolStore
, USER_AGENT
, Optional
.fromNullable(messagePipe
), Optional
.<SignalServiceMessageSender
.EventListener
>absent());
914 message
= messageBuilder
.build();
915 if (message
.getGroupInfo().isPresent()) {
917 messageSender
.sendMessage(new ArrayList
<>(recipientsTS
), message
);
918 } catch (EncapsulatedExceptions encapsulatedExceptions
) {
919 for (UntrustedIdentityException e
: encapsulatedExceptions
.getUntrustedIdentityExceptions()) {
920 signalProtocolStore
.saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
924 // Send to all individually, so sync messages are sent correctly
925 List
<UntrustedIdentityException
> untrustedIdentities
= new LinkedList
<>();
926 List
<UnregisteredUserException
> unregisteredUsers
= new LinkedList
<>();
927 List
<NetworkFailureException
> networkExceptions
= new LinkedList
<>();
928 for (SignalServiceAddress address
: recipientsTS
) {
929 ThreadInfo thread
= threadStore
.getThread(address
.getNumber());
930 if (thread
!= null) {
931 messageBuilder
.withExpiration(thread
.messageExpirationTime
);
933 messageBuilder
.withExpiration(0);
935 message
= messageBuilder
.build();
937 messageSender
.sendMessage(address
, message
);
938 } catch (UntrustedIdentityException e
) {
939 signalProtocolStore
.saveIdentity(e
.getE164Number(), e
.getIdentityKey(), TrustLevel
.UNTRUSTED
);
940 untrustedIdentities
.add(e
);
941 } catch (UnregisteredUserException e
) {
942 unregisteredUsers
.add(e
);
943 } catch (PushNetworkException e
) {
944 networkExceptions
.add(new NetworkFailureException(address
.getNumber(), e
));
947 if (!untrustedIdentities
.isEmpty() || !unregisteredUsers
.isEmpty() || !networkExceptions
.isEmpty()) {
948 throw new EncapsulatedExceptions(untrustedIdentities
, unregisteredUsers
, networkExceptions
);
952 if (message
!= null && message
.isEndSession()) {
953 for (SignalServiceAddress recipient
: recipientsTS
) {
954 handleEndSession(recipient
.getNumber());
961 private Set
<SignalServiceAddress
> getSignalServiceAddresses(Collection
<String
> recipients
) {
962 Set
<SignalServiceAddress
> recipientsTS
= new HashSet
<>(recipients
.size());
963 for (String recipient
: recipients
) {
965 recipientsTS
.add(getPushAddress(recipient
));
966 } catch (InvalidNumberException e
) {
967 System
.err
.println("Failed to add recipient \"" + recipient
+ "\": " + e
.getMessage());
968 System
.err
.println("Aborting sending.");
976 private SignalServiceContent
decryptMessage(SignalServiceEnvelope envelope
) throws NoSessionException
, LegacyMessageException
, InvalidVersionException
, InvalidMessageException
, DuplicateMessageException
, InvalidKeyException
, InvalidKeyIdException
, org
.whispersystems
.libsignal
.UntrustedIdentityException
{
977 SignalServiceCipher cipher
= new SignalServiceCipher(new SignalServiceAddress(username
), signalProtocolStore
);
979 return cipher
.decrypt(envelope
);
980 } catch (org
.whispersystems
.libsignal
.UntrustedIdentityException e
) {
981 signalProtocolStore
.saveIdentity(e
.getName(), e
.getUntrustedIdentity(), TrustLevel
.UNTRUSTED
);
986 private void handleEndSession(String source
) {
987 signalProtocolStore
.deleteAllSessions(source
);
990 public interface ReceiveMessageHandler
{
991 void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent decryptedContent
, Throwable e
);
994 private void handleSignalServiceDataMessage(SignalServiceDataMessage message
, boolean isSync
, String source
, String destination
, boolean ignoreAttachments
) {
996 if (message
.getGroupInfo().isPresent()) {
997 SignalServiceGroup groupInfo
= message
.getGroupInfo().get();
998 threadId
= Base64
.encodeBytes(groupInfo
.getGroupId());
999 GroupInfo group
= groupStore
.getGroup(groupInfo
.getGroupId());
1000 switch (groupInfo
.getType()) {
1002 if (group
== null) {
1003 group
= new GroupInfo(groupInfo
.getGroupId());
1006 if (groupInfo
.getAvatar().isPresent()) {
1007 SignalServiceAttachment avatar
= groupInfo
.getAvatar().get();
1008 if (avatar
.isPointer()) {
1010 retrieveGroupAvatarAttachment(avatar
.asPointer(), group
.groupId
);
1011 } catch (IOException
| InvalidMessageException e
) {
1012 System
.err
.println("Failed to retrieve group avatar (" + avatar
.asPointer().getId() + "): " + e
.getMessage());
1017 if (groupInfo
.getName().isPresent()) {
1018 group
.name
= groupInfo
.getName().get();
1021 if (groupInfo
.getMembers().isPresent()) {
1022 group
.members
.addAll(groupInfo
.getMembers().get());
1025 groupStore
.updateGroup(group
);
1028 if (group
== null) {
1030 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1031 } catch (IOException
| EncapsulatedExceptions e
) {
1032 e
.printStackTrace();
1037 if (group
== null) {
1039 sendGroupInfoRequest(groupInfo
.getGroupId(), source
);
1040 } catch (IOException
| EncapsulatedExceptions e
) {
1041 e
.printStackTrace();
1044 group
.members
.remove(source
);
1045 groupStore
.updateGroup(group
);
1049 if (group
!= null) {
1051 sendUpdateGroupMessage(groupInfo
.getGroupId(), source
);
1052 } catch (IOException
| EncapsulatedExceptions e
) {
1053 e
.printStackTrace();
1054 } catch (NotAGroupMemberException e
) {
1055 // We have left this group, so don't send a group update message
1062 threadId
= destination
;
1067 if (message
.isEndSession()) {
1068 handleEndSession(isSync ? destination
: source
);
1070 if (message
.isExpirationUpdate() || message
.getBody().isPresent()) {
1071 ThreadInfo thread
= threadStore
.getThread(threadId
);
1072 if (thread
== null) {
1073 thread
= new ThreadInfo();
1074 thread
.id
= threadId
;
1076 if (thread
.messageExpirationTime
!= message
.getExpiresInSeconds()) {
1077 thread
.messageExpirationTime
= message
.getExpiresInSeconds();
1078 threadStore
.updateThread(thread
);
1081 if (message
.getAttachments().isPresent() && !ignoreAttachments
) {
1082 for (SignalServiceAttachment attachment
: message
.getAttachments().get()) {
1083 if (attachment
.isPointer()) {
1085 retrieveAttachment(attachment
.asPointer());
1086 } catch (IOException
| InvalidMessageException e
) {
1087 System
.err
.println("Failed to retrieve attachment (" + attachment
.asPointer().getId() + "): " + e
.getMessage());
1094 public void retryFailedReceivedMessages(ReceiveMessageHandler handler
, boolean ignoreAttachments
) {
1095 final File cachePath
= new File(getMessageCachePath());
1096 if (!cachePath
.exists()) {
1099 for (final File dir
: cachePath
.listFiles()) {
1100 if (!dir
.isDirectory()) {
1104 for (final File fileEntry
: dir
.listFiles()) {
1105 if (!fileEntry
.isFile()) {
1108 SignalServiceEnvelope envelope
;
1110 envelope
= loadEnvelope(fileEntry
);
1111 if (envelope
== null) {
1114 } catch (IOException e
) {
1115 e
.printStackTrace();
1118 SignalServiceContent content
= null;
1119 if (!envelope
.isReceipt()) {
1121 content
= decryptMessage(envelope
);
1122 } catch (Exception e
) {
1125 handleMessage(envelope
, content
, ignoreAttachments
);
1128 handler
.handleMessage(envelope
, content
, null);
1130 Files
.delete(fileEntry
.toPath());
1131 } catch (IOException e
) {
1132 System
.err
.println("Failed to delete cached message file “" + fileEntry
+ "”: " + e
.getMessage());
1135 // Try to delete directory if empty
1140 public void receiveMessages(long timeout
, TimeUnit unit
, boolean returnOnTimeout
, boolean ignoreAttachments
, ReceiveMessageHandler handler
) throws IOException
{
1141 retryFailedReceivedMessages(handler
, ignoreAttachments
);
1142 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
, username
, password
, deviceId
, signalingKey
, USER_AGENT
, null, timer
);
1145 if (messagePipe
== null) {
1146 messagePipe
= messageReceiver
.createMessagePipe();
1150 SignalServiceEnvelope envelope
;
1151 SignalServiceContent content
= null;
1152 Exception exception
= null;
1153 final long now
= new Date().getTime();
1155 envelope
= messagePipe
.read(timeout
, unit
, new SignalServiceMessagePipe
.MessagePipeCallback() {
1157 public void onMessage(SignalServiceEnvelope envelope
) {
1158 // store message on disk, before acknowledging receipt to the server
1160 File cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1161 storeEnvelope(envelope
, cacheFile
);
1162 } catch (IOException e
) {
1163 System
.err
.println("Failed to store encrypted message in disk cache, ignoring: " + e
.getMessage());
1167 } catch (TimeoutException e
) {
1168 if (returnOnTimeout
)
1171 } catch (InvalidVersionException e
) {
1172 System
.err
.println("Ignoring error: " + e
.getMessage());
1175 if (!envelope
.isReceipt()) {
1177 content
= decryptMessage(envelope
);
1178 } catch (Exception e
) {
1181 handleMessage(envelope
, content
, ignoreAttachments
);
1184 handler
.handleMessage(envelope
, content
, exception
);
1185 if (exception
== null || !(exception
instanceof org
.whispersystems
.libsignal
.UntrustedIdentityException
)) {
1186 File cacheFile
= null;
1188 cacheFile
= getMessageCacheFile(envelope
.getSource(), now
, envelope
.getTimestamp());
1189 Files
.delete(cacheFile
.toPath());
1190 // Try to delete directory if empty
1191 new File(getMessageCachePath()).delete();
1192 } catch (IOException e
) {
1193 System
.err
.println("Failed to delete cached message file “" + cacheFile
+ "”: " + e
.getMessage());
1198 if (messagePipe
!= null) {
1199 messagePipe
.shutdown();
1205 private void handleMessage(SignalServiceEnvelope envelope
, SignalServiceContent content
, boolean ignoreAttachments
) {
1206 if (content
!= null) {
1207 if (content
.getDataMessage().isPresent()) {
1208 SignalServiceDataMessage message
= content
.getDataMessage().get();
1209 handleSignalServiceDataMessage(message
, false, envelope
.getSource(), username
, ignoreAttachments
);
1211 if (content
.getSyncMessage().isPresent()) {
1212 SignalServiceSyncMessage syncMessage
= content
.getSyncMessage().get();
1213 if (syncMessage
.getSent().isPresent()) {
1214 SignalServiceDataMessage message
= syncMessage
.getSent().get().getMessage();
1215 handleSignalServiceDataMessage(message
, true, envelope
.getSource(), syncMessage
.getSent().get().getDestination().get(), ignoreAttachments
);
1217 if (syncMessage
.getRequest().isPresent()) {
1218 RequestMessage rm
= syncMessage
.getRequest().get();
1219 if (rm
.isContactsRequest()) {
1222 } catch (UntrustedIdentityException
| IOException e
) {
1223 e
.printStackTrace();
1226 if (rm
.isGroupsRequest()) {
1229 } catch (UntrustedIdentityException
| IOException e
) {
1230 e
.printStackTrace();
1234 if (syncMessage
.getGroups().isPresent()) {
1235 File tmpFile
= null;
1237 tmpFile
= Util
.createTempFile();
1238 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(syncMessage
.getGroups().get().asPointer(), tmpFile
)) {
1239 DeviceGroupsInputStream s
= new DeviceGroupsInputStream(attachmentAsStream
);
1241 while ((g
= s
.read()) != null) {
1242 GroupInfo syncGroup
= groupStore
.getGroup(g
.getId());
1243 if (syncGroup
== null) {
1244 syncGroup
= new GroupInfo(g
.getId());
1246 if (g
.getName().isPresent()) {
1247 syncGroup
.name
= g
.getName().get();
1249 syncGroup
.members
.addAll(g
.getMembers());
1250 syncGroup
.active
= g
.isActive();
1251 if (g
.getColor().isPresent()) {
1252 syncGroup
.color
= g
.getColor().get();
1255 if (g
.getAvatar().isPresent()) {
1256 retrieveGroupAvatarAttachment(g
.getAvatar().get(), syncGroup
.groupId
);
1258 groupStore
.updateGroup(syncGroup
);
1261 } catch (Exception e
) {
1262 e
.printStackTrace();
1264 if (tmpFile
!= null) {
1266 Files
.delete(tmpFile
.toPath());
1267 } catch (IOException e
) {
1268 System
.err
.println("Failed to delete received groups temp file “" + tmpFile
+ "”: " + e
.getMessage());
1272 if (syncMessage
.getBlockedList().isPresent()) {
1273 // TODO store list of blocked numbers
1276 if (syncMessage
.getContacts().isPresent()) {
1277 File tmpFile
= null;
1279 tmpFile
= Util
.createTempFile();
1280 final ContactsMessage contactsMessage
= syncMessage
.getContacts().get();
1281 try (InputStream attachmentAsStream
= retrieveAttachmentAsStream(contactsMessage
.getContactsStream().asPointer(), tmpFile
)) {
1282 DeviceContactsInputStream s
= new DeviceContactsInputStream(attachmentAsStream
);
1283 if (contactsMessage
.isComplete()) {
1284 contactStore
.clear();
1287 while ((c
= s
.read()) != null) {
1288 ContactInfo contact
= contactStore
.getContact(c
.getNumber());
1289 if (contact
== null) {
1290 contact
= new ContactInfo();
1291 contact
.number
= c
.getNumber();
1293 if (c
.getName().isPresent()) {
1294 contact
.name
= c
.getName().get();
1296 if (c
.getColor().isPresent()) {
1297 contact
.color
= c
.getColor().get();
1299 contactStore
.updateContact(contact
);
1301 if (c
.getAvatar().isPresent()) {
1302 retrieveContactAvatarAttachment(c
.getAvatar().get(), contact
.number
);
1306 } catch (Exception e
) {
1307 e
.printStackTrace();
1309 if (tmpFile
!= null) {
1311 Files
.delete(tmpFile
.toPath());
1312 } catch (IOException e
) {
1313 System
.err
.println("Failed to delete received contacts temp file “" + tmpFile
+ "”: " + e
.getMessage());
1318 if (syncMessage
.getVerified().isPresent()) {
1319 final VerifiedMessage verifiedMessage
= syncMessage
.getVerified().get();
1320 signalProtocolStore
.saveIdentity(verifiedMessage
.getDestination(), verifiedMessage
.getIdentityKey(), TrustLevel
.fromVerifiedState(verifiedMessage
.getVerified()));
1326 private SignalServiceEnvelope
loadEnvelope(File file
) throws IOException
{
1327 try (FileInputStream f
= new FileInputStream(file
)) {
1328 DataInputStream
in = new DataInputStream(f
);
1329 int version
= in.readInt();
1333 int type
= in.readInt();
1334 String source
= in.readUTF();
1335 int sourceDevice
= in.readInt();
1336 String relay
= in.readUTF();
1337 long timestamp
= in.readLong();
1338 byte[] content
= null;
1339 int contentLen
= in.readInt();
1340 if (contentLen
> 0) {
1341 content
= new byte[contentLen
];
1342 in.readFully(content
);
1344 byte[] legacyMessage
= null;
1345 int legacyMessageLen
= in.readInt();
1346 if (legacyMessageLen
> 0) {
1347 legacyMessage
= new byte[legacyMessageLen
];
1348 in.readFully(legacyMessage
);
1350 return new SignalServiceEnvelope(type
, source
, sourceDevice
, relay
, timestamp
, legacyMessage
, content
);
1354 private void storeEnvelope(SignalServiceEnvelope envelope
, File file
) throws IOException
{
1355 try (FileOutputStream f
= new FileOutputStream(file
)) {
1356 try (DataOutputStream out
= new DataOutputStream(f
)) {
1357 out
.writeInt(1); // version
1358 out
.writeInt(envelope
.getType());
1359 out
.writeUTF(envelope
.getSource());
1360 out
.writeInt(envelope
.getSourceDevice());
1361 out
.writeUTF(envelope
.getRelay());
1362 out
.writeLong(envelope
.getTimestamp());
1363 if (envelope
.hasContent()) {
1364 out
.writeInt(envelope
.getContent().length
);
1365 out
.write(envelope
.getContent());
1369 if (envelope
.hasLegacyMessage()) {
1370 out
.writeInt(envelope
.getLegacyMessage().length
);
1371 out
.write(envelope
.getLegacyMessage());
1379 public File
getContactAvatarFile(String number
) {
1380 return new File(avatarsPath
, "contact-" + number
);
1383 private File
retrieveContactAvatarAttachment(SignalServiceAttachment attachment
, String number
) throws IOException
, InvalidMessageException
{
1384 createPrivateDirectories(avatarsPath
);
1385 if (attachment
.isPointer()) {
1386 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1387 return retrieveAttachment(pointer
, getContactAvatarFile(number
), false);
1389 SignalServiceAttachmentStream stream
= attachment
.asStream();
1390 return retrieveAttachment(stream
, getContactAvatarFile(number
));
1394 public File
getGroupAvatarFile(byte[] groupId
) {
1395 return new File(avatarsPath
, "group-" + Base64
.encodeBytes(groupId
).replace("/", "_"));
1398 private File
retrieveGroupAvatarAttachment(SignalServiceAttachment attachment
, byte[] groupId
) throws IOException
, InvalidMessageException
{
1399 createPrivateDirectories(avatarsPath
);
1400 if (attachment
.isPointer()) {
1401 SignalServiceAttachmentPointer pointer
= attachment
.asPointer();
1402 return retrieveAttachment(pointer
, getGroupAvatarFile(groupId
), false);
1404 SignalServiceAttachmentStream stream
= attachment
.asStream();
1405 return retrieveAttachment(stream
, getGroupAvatarFile(groupId
));
1409 public File
getAttachmentFile(long attachmentId
) {
1410 return new File(attachmentsPath
, attachmentId
+ "");
1413 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
) throws IOException
, InvalidMessageException
{
1414 createPrivateDirectories(attachmentsPath
);
1415 return retrieveAttachment(pointer
, getAttachmentFile(pointer
.getId()), true);
1418 private File
retrieveAttachment(SignalServiceAttachmentStream stream
, File outputFile
) throws IOException
, InvalidMessageException
{
1419 InputStream input
= stream
.getInputStream();
1421 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1422 byte[] buffer
= new byte[4096];
1425 while ((read
= input
.read(buffer
)) != -1) {
1426 output
.write(buffer
, 0, read
);
1428 } catch (FileNotFoundException e
) {
1429 e
.printStackTrace();
1435 private File
retrieveAttachment(SignalServiceAttachmentPointer pointer
, File outputFile
, boolean storePreview
) throws IOException
, InvalidMessageException
{
1436 if (storePreview
&& pointer
.getPreview().isPresent()) {
1437 File previewFile
= new File(outputFile
+ ".preview");
1438 try (OutputStream output
= new FileOutputStream(previewFile
)) {
1439 byte[] preview
= pointer
.getPreview().get();
1440 output
.write(preview
, 0, preview
.length
);
1441 } catch (FileNotFoundException e
) {
1442 e
.printStackTrace();
1447 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
, username
, password
, deviceId
, signalingKey
, USER_AGENT
, null, timer
);
1449 File tmpFile
= Util
.createTempFile();
1450 try (InputStream input
= messageReceiver
.retrieveAttachment(pointer
, tmpFile
, MAX_ATTACHMENT_SIZE
)) {
1451 try (OutputStream output
= new FileOutputStream(outputFile
)) {
1452 byte[] buffer
= new byte[4096];
1455 while ((read
= input
.read(buffer
)) != -1) {
1456 output
.write(buffer
, 0, read
);
1458 } catch (FileNotFoundException e
) {
1459 e
.printStackTrace();
1464 Files
.delete(tmpFile
.toPath());
1465 } catch (IOException e
) {
1466 System
.err
.println("Failed to delete received attachment temp file “" + tmpFile
+ "”: " + e
.getMessage());
1472 private InputStream
retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer
, File tmpFile
) throws IOException
, InvalidMessageException
{
1473 final SignalServiceMessageReceiver messageReceiver
= new SignalServiceMessageReceiver(serviceConfiguration
, username
, password
, deviceId
, signalingKey
, USER_AGENT
, null, timer
);
1474 return messageReceiver
.retrieveAttachment(pointer
, tmpFile
, MAX_ATTACHMENT_SIZE
);
1477 private String
canonicalizeNumber(String number
) throws InvalidNumberException
{
1478 String localNumber
= username
;
1479 return PhoneNumberFormatter
.formatNumber(number
, localNumber
);
1482 private SignalServiceAddress
getPushAddress(String number
) throws InvalidNumberException
{
1483 String e164number
= canonicalizeNumber(number
);
1484 return new SignalServiceAddress(e164number
);
1488 public boolean isRemote() {
1492 private void sendGroups() throws IOException
, UntrustedIdentityException
{
1493 File groupsFile
= Util
.createTempFile();
1496 try (OutputStream fos
= new FileOutputStream(groupsFile
)) {
1497 DeviceGroupsOutputStream out
= new DeviceGroupsOutputStream(fos
);
1498 for (GroupInfo
record : groupStore
.getGroups()) {
1499 ThreadInfo info
= threadStore
.getThread(Base64
.encodeBytes(record.groupId
));
1500 out
.write(new DeviceGroup(record.groupId
, Optional
.fromNullable(record.name
),
1501 new ArrayList
<>(record.members
), createGroupAvatarAttachment(record.groupId
),
1502 record.active
, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null),
1503 Optional
.fromNullable(record.color
)));
1507 if (groupsFile
.exists() && groupsFile
.length() > 0) {
1508 try (FileInputStream groupsFileStream
= new FileInputStream(groupsFile
)) {
1509 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1510 .withStream(groupsFileStream
)
1511 .withContentType("application/octet-stream")
1512 .withLength(groupsFile
.length())
1515 sendSyncMessage(SignalServiceSyncMessage
.forGroups(attachmentStream
));
1520 Files
.delete(groupsFile
.toPath());
1521 } catch (IOException e
) {
1522 System
.err
.println("Failed to delete groups temp file “" + groupsFile
+ "”: " + e
.getMessage());
1527 private void sendContacts() throws IOException
, UntrustedIdentityException
{
1528 File contactsFile
= Util
.createTempFile();
1531 try (OutputStream fos
= new FileOutputStream(contactsFile
)) {
1532 DeviceContactsOutputStream out
= new DeviceContactsOutputStream(fos
);
1533 for (ContactInfo
record : contactStore
.getContacts()) {
1534 VerifiedMessage verifiedMessage
= null;
1535 ThreadInfo info
= threadStore
.getThread(record.number
);
1536 if (getIdentities().containsKey(record.number
)) {
1537 JsonIdentityKeyStore
.Identity currentIdentity
= null;
1538 for (JsonIdentityKeyStore
.Identity id
: getIdentities().get(record.number
)) {
1539 if (currentIdentity
== null || id
.getDateAdded().after(currentIdentity
.getDateAdded())) {
1540 currentIdentity
= id
;
1543 if (currentIdentity
!= null) {
1544 verifiedMessage
= new VerifiedMessage(record.number
, currentIdentity
.getIdentityKey(), currentIdentity
.getTrustLevel().toVerifiedState(), currentIdentity
.getDateAdded().getTime());
1548 // TODO include profile key
1549 out
.write(new DeviceContact(record.number
, Optional
.fromNullable(record.name
),
1550 createContactAvatarAttachment(record.number
), Optional
.fromNullable(record.color
),
1551 Optional
.fromNullable(verifiedMessage
), Optional
.<byte[]>absent(), false, Optional
.fromNullable(info
!= null ? info
.messageExpirationTime
: null)));
1555 if (contactsFile
.exists() && contactsFile
.length() > 0) {
1556 try (FileInputStream contactsFileStream
= new FileInputStream(contactsFile
)) {
1557 SignalServiceAttachmentStream attachmentStream
= SignalServiceAttachment
.newStreamBuilder()
1558 .withStream(contactsFileStream
)
1559 .withContentType("application/octet-stream")
1560 .withLength(contactsFile
.length())
1563 sendSyncMessage(SignalServiceSyncMessage
.forContacts(new ContactsMessage(attachmentStream
, true)));
1568 Files
.delete(contactsFile
.toPath());
1569 } catch (IOException e
) {
1570 System
.err
.println("Failed to delete contacts temp file “" + contactsFile
+ "”: " + e
.getMessage());
1575 private void sendVerifiedMessage(String destination
, IdentityKey identityKey
, TrustLevel trustLevel
) throws IOException
, UntrustedIdentityException
{
1576 VerifiedMessage verifiedMessage
= new VerifiedMessage(destination
, identityKey
, trustLevel
.toVerifiedState(), System
.currentTimeMillis());
1577 sendSyncMessage(SignalServiceSyncMessage
.forVerified(verifiedMessage
));
1580 public ContactInfo
getContact(String number
) {
1581 return contactStore
.getContact(number
);
1584 public GroupInfo
getGroup(byte[] groupId
) {
1585 return groupStore
.getGroup(groupId
);
1588 public Map
<String
, List
<JsonIdentityKeyStore
.Identity
>> getIdentities() {
1589 return signalProtocolStore
.getIdentities();
1592 public List
<JsonIdentityKeyStore
.Identity
> getIdentities(String number
) {
1593 return signalProtocolStore
.getIdentities(number
);
1597 * Trust this the identity with this fingerprint
1599 * @param name username of the identity
1600 * @param fingerprint Fingerprint
1602 public boolean trustIdentityVerified(String name
, byte[] fingerprint
) {
1603 List
<JsonIdentityKeyStore
.Identity
> ids
= signalProtocolStore
.getIdentities(name
);
1607 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1608 if (!Arrays
.equals(id
.getIdentityKey().serialize(), fingerprint
)) {
1612 signalProtocolStore
.saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1614 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1615 } catch (IOException
| UntrustedIdentityException e
) {
1616 e
.printStackTrace();
1625 * Trust this the identity with this safety number
1627 * @param name username of the identity
1628 * @param safetyNumber Safety number
1630 public boolean trustIdentityVerifiedSafetyNumber(String name
, String safetyNumber
) {
1631 List
<JsonIdentityKeyStore
.Identity
> ids
= signalProtocolStore
.getIdentities(name
);
1635 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1636 if (!safetyNumber
.equals(computeSafetyNumber(name
, id
.getIdentityKey()))) {
1640 signalProtocolStore
.saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1642 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_VERIFIED
);
1643 } catch (IOException
| UntrustedIdentityException e
) {
1644 e
.printStackTrace();
1653 * Trust all keys of this identity without verification
1655 * @param name username of the identity
1657 public boolean trustIdentityAllKeys(String name
) {
1658 List
<JsonIdentityKeyStore
.Identity
> ids
= signalProtocolStore
.getIdentities(name
);
1662 for (JsonIdentityKeyStore
.Identity id
: ids
) {
1663 if (id
.getTrustLevel() == TrustLevel
.UNTRUSTED
) {
1664 signalProtocolStore
.saveIdentity(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1666 sendVerifiedMessage(name
, id
.getIdentityKey(), TrustLevel
.TRUSTED_UNVERIFIED
);
1667 } catch (IOException
| UntrustedIdentityException e
) {
1668 e
.printStackTrace();
1676 public String
computeSafetyNumber(String theirUsername
, IdentityKey theirIdentityKey
) {
1677 Fingerprint fingerprint
= new NumericFingerprintGenerator(5200).createFor(username
, getIdentity(), theirUsername
, theirIdentityKey
);
1678 return fingerprint
.getDisplayableFingerprint().getDisplayText();