]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/manager/Manager.java
5a26ff56622bec74b45d543f249eb8b67a7981e3
[signal-cli] / src / main / java / org / asamk / signal / manager / Manager.java
1 /*
2 Copyright (C) 2015-2018 AsamK
3
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.
8
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.
13
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/>.
16 */
17 package org.asamk.signal.manager;
18
19 import org.asamk.Signal;
20 import org.asamk.signal.*;
21 import org.asamk.signal.storage.SignalAccount;
22 import org.asamk.signal.storage.contacts.ContactInfo;
23 import org.asamk.signal.storage.groups.GroupInfo;
24 import org.asamk.signal.storage.groups.JsonGroupStore;
25 import org.asamk.signal.storage.protocol.JsonIdentityKeyStore;
26 import org.asamk.signal.storage.threads.ThreadInfo;
27 import org.asamk.signal.util.IOUtils;
28 import org.asamk.signal.util.Util;
29 import org.signal.libsignal.metadata.*;
30 import org.whispersystems.libsignal.*;
31 import org.whispersystems.libsignal.ecc.Curve;
32 import org.whispersystems.libsignal.ecc.ECKeyPair;
33 import org.whispersystems.libsignal.ecc.ECPublicKey;
34 import org.whispersystems.libsignal.state.PreKeyRecord;
35 import org.whispersystems.libsignal.state.SignedPreKeyRecord;
36 import org.whispersystems.libsignal.util.KeyHelper;
37 import org.whispersystems.libsignal.util.Medium;
38 import org.whispersystems.libsignal.util.guava.Optional;
39 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
40 import org.whispersystems.signalservice.api.SignalServiceMessagePipe;
41 import org.whispersystems.signalservice.api.SignalServiceMessageReceiver;
42 import org.whispersystems.signalservice.api.SignalServiceMessageSender;
43 import org.whispersystems.signalservice.api.crypto.SignalServiceCipher;
44 import org.whispersystems.signalservice.api.crypto.UnidentifiedAccess;
45 import org.whispersystems.signalservice.api.crypto.UnidentifiedAccessPair;
46 import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
47 import org.whispersystems.signalservice.api.messages.*;
48 import org.whispersystems.signalservice.api.messages.multidevice.*;
49 import org.whispersystems.signalservice.api.push.ContactTokenDetails;
50 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
51 import org.whispersystems.signalservice.api.push.exceptions.AuthorizationFailedException;
52 import org.whispersystems.signalservice.api.push.exceptions.EncapsulatedExceptions;
53 import org.whispersystems.signalservice.api.push.exceptions.NetworkFailureException;
54 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
55 import org.whispersystems.signalservice.api.util.InvalidNumberException;
56 import org.whispersystems.signalservice.api.util.SleepTimer;
57 import org.whispersystems.signalservice.api.util.StreamDetails;
58 import org.whispersystems.signalservice.api.util.UptimeSleepTimer;
59 import org.whispersystems.signalservice.internal.push.SignalServiceProtos;
60 import org.whispersystems.signalservice.internal.push.UnsupportedDataMessageException;
61 import org.whispersystems.signalservice.internal.util.Base64;
62
63 import java.io.*;
64 import java.net.URI;
65 import java.nio.file.Files;
66 import java.nio.file.Paths;
67 import java.nio.file.StandardCopyOption;
68 import java.util.*;
69 import java.util.concurrent.TimeUnit;
70 import java.util.concurrent.TimeoutException;
71
72 public class Manager implements Signal {
73
74 private final String settingsPath;
75 private final String dataPath;
76 private final String attachmentsPath;
77 private final String avatarsPath;
78 private final SleepTimer timer = new UptimeSleepTimer();
79
80 private SignalAccount account;
81 private String username;
82 private SignalServiceAccountManager accountManager;
83 private SignalServiceMessagePipe messagePipe = null;
84 private SignalServiceMessagePipe unidentifiedMessagePipe = null;
85
86 public Manager(String username, String settingsPath) {
87 this.username = username;
88 this.settingsPath = settingsPath;
89 this.dataPath = this.settingsPath + "/data";
90 this.attachmentsPath = this.settingsPath + "/attachments";
91 this.avatarsPath = this.settingsPath + "/avatars";
92
93 }
94
95 public String getUsername() {
96 return username;
97 }
98
99 private IdentityKey getIdentity() {
100 return account.getSignalProtocolStore().getIdentityKeyPair().getPublicKey();
101 }
102
103 public int getDeviceId() {
104 return account.getDeviceId();
105 }
106
107 private String getMessageCachePath() {
108 return this.dataPath + "/" + username + ".d/msg-cache";
109 }
110
111 private String getMessageCachePath(String sender) {
112 return getMessageCachePath() + "/" + sender.replace("/", "_");
113 }
114
115 private File getMessageCacheFile(String sender, long now, long timestamp) throws IOException {
116 String cachePath = getMessageCachePath(sender);
117 IOUtils.createPrivateDirectories(cachePath);
118 return new File(cachePath + "/" + now + "_" + timestamp);
119 }
120
121 public boolean userHasKeys() {
122 return account != null && account.getSignalProtocolStore() != null;
123 }
124
125 public void init() throws IOException {
126 if (!SignalAccount.userExists(dataPath, username)) {
127 return;
128 }
129 account = SignalAccount.load(dataPath, username);
130
131 migrateLegacyConfigs();
132
133 accountManager = new SignalServiceAccountManager(BaseConfig.serviceConfiguration, username, account.getPassword(), account.getDeviceId(), BaseConfig.USER_AGENT, timer);
134 try {
135 if (account.isRegistered() && accountManager.getPreKeysCount() < BaseConfig.PREKEY_MINIMUM_COUNT) {
136 refreshPreKeys();
137 account.save();
138 }
139 } catch (AuthorizationFailedException e) {
140 System.err.println("Authorization failed, was the number registered elsewhere?");
141 throw e;
142 }
143 }
144
145 private void migrateLegacyConfigs() {
146 // Copy group avatars that were previously stored in the attachments folder
147 // to the new avatar folder
148 if (JsonGroupStore.groupsWithLegacyAvatarId.size() > 0) {
149 for (GroupInfo g : JsonGroupStore.groupsWithLegacyAvatarId) {
150 File avatarFile = getGroupAvatarFile(g.groupId);
151 File attachmentFile = getAttachmentFile(g.getAvatarId());
152 if (!avatarFile.exists() && attachmentFile.exists()) {
153 try {
154 IOUtils.createPrivateDirectories(avatarsPath);
155 Files.copy(attachmentFile.toPath(), avatarFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
156 } catch (Exception e) {
157 // Ignore
158 }
159 }
160 }
161 JsonGroupStore.groupsWithLegacyAvatarId.clear();
162 account.save();
163 }
164 if (account.getProfileKey() == null) {
165 // Old config file, creating new profile key
166 account.setProfileKey(KeyUtils.createProfileKey());
167 account.save();
168 }
169 }
170
171 private void createNewIdentity() throws IOException {
172 IdentityKeyPair identityKey = KeyHelper.generateIdentityKeyPair();
173 int registrationId = KeyHelper.generateRegistrationId(false);
174 if (username == null) {
175 account = SignalAccount.createTemporaryAccount(identityKey, registrationId);
176 } else {
177 byte[] profileKey = KeyUtils.createProfileKey();
178 account = SignalAccount.create(dataPath, username, identityKey, registrationId, profileKey);
179 account.save();
180 }
181 }
182
183 public boolean isRegistered() {
184 return account != null && account.isRegistered();
185 }
186
187 public void register(boolean voiceVerification) throws IOException {
188 if (account == null) {
189 createNewIdentity();
190 }
191 account.setPassword(KeyUtils.createPassword());
192 accountManager = new SignalServiceAccountManager(BaseConfig.serviceConfiguration, account.getUsername(), account.getPassword(), BaseConfig.USER_AGENT, timer);
193
194 if (voiceVerification) {
195 accountManager.requestVoiceVerificationCode(Locale.getDefault(), Optional.<String>absent(), Optional.<String>absent());
196 } else {
197 accountManager.requestSmsVerificationCode(false, Optional.<String>absent(), Optional.<String>absent());
198 }
199
200 account.setRegistered(false);
201 account.save();
202 }
203
204 public void updateAccountAttributes() throws IOException {
205 accountManager.setAccountAttributes(account.getSignalingKey(), account.getSignalProtocolStore().getLocalRegistrationId(), true, account.getRegistrationLockPin(), getSelfUnidentifiedAccessKey(), false);
206 }
207
208 public void setProfileName(String name) throws IOException {
209 accountManager.setProfileName(account.getProfileKey(), name);
210 }
211
212 public void setProfileAvatar(File avatar) throws IOException {
213 accountManager.setProfileAvatar(account.getProfileKey(), Utils.createStreamDetailsFromFile(avatar));
214 }
215
216 public void unregister() throws IOException {
217 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
218 // If this is the master device, other users can't send messages to this number anymore.
219 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
220 accountManager.setGcmId(Optional.<String>absent());
221
222 account.setRegistered(false);
223 account.save();
224 }
225
226 public String getDeviceLinkUri() throws TimeoutException, IOException {
227 if (account == null) {
228 createNewIdentity();
229 }
230 account.setPassword(KeyUtils.createPassword());
231 accountManager = new SignalServiceAccountManager(BaseConfig.serviceConfiguration, username, account.getPassword(), BaseConfig.USER_AGENT, timer);
232 String uuid = accountManager.getNewDeviceUuid();
233
234 return Utils.createDeviceLinkUri(new Utils.DeviceLinkInfo(uuid, getIdentity().getPublicKey()));
235 }
236
237 public void finishDeviceLink(String deviceName) throws IOException, InvalidKeyException, TimeoutException, UserAlreadyExists {
238 account.setSignalingKey(KeyUtils.createSignalingKey());
239 SignalServiceAccountManager.NewDeviceRegistrationReturn ret = accountManager.finishNewDeviceRegistration(account.getSignalProtocolStore().getIdentityKeyPair(), account.getSignalingKey(), false, true, account.getSignalProtocolStore().getLocalRegistrationId(), deviceName);
240
241 username = ret.getNumber();
242 // TODO do this check before actually registering
243 if (SignalAccount.userExists(dataPath, username)) {
244 throw new UserAlreadyExists(username, SignalAccount.getFileName(dataPath, username));
245 }
246
247 // Create new account with the synced identity
248 byte[] profileKey = ret.getProfileKey();
249 if (profileKey == null) {
250 profileKey = KeyUtils.createProfileKey();
251 }
252 account = SignalAccount.createLinkedAccount(dataPath, username, account.getPassword(), ret.getDeviceId(), ret.getIdentity(), account.getSignalProtocolStore().getLocalRegistrationId(), account.getSignalingKey(), profileKey);
253
254 refreshPreKeys();
255
256 requestSyncGroups();
257 requestSyncContacts();
258 requestSyncBlocked();
259 requestSyncConfiguration();
260
261 account.save();
262 }
263
264 public List<DeviceInfo> getLinkedDevices() throws IOException {
265 List<DeviceInfo> devices = accountManager.getDevices();
266 account.setMultiDevice(devices.size() > 1);
267 account.save();
268 return devices;
269 }
270
271 public void removeLinkedDevices(int deviceId) throws IOException {
272 accountManager.removeDevice(deviceId);
273 List<DeviceInfo> devices = accountManager.getDevices();
274 account.setMultiDevice(devices.size() > 1);
275 account.save();
276 }
277
278 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
279 Utils.DeviceLinkInfo info = Utils.parseDeviceLinkUri(linkUri);
280
281 addDevice(info.deviceIdentifier, info.deviceKey);
282 }
283
284 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
285 IdentityKeyPair identityKeyPair = account.getSignalProtocolStore().getIdentityKeyPair();
286 String verificationCode = accountManager.getNewDeviceVerificationCode();
287
288 accountManager.addDevice(deviceIdentifier, deviceKey, identityKeyPair, Optional.of(account.getProfileKey()), verificationCode);
289 account.setMultiDevice(true);
290 account.save();
291 }
292
293 private List<PreKeyRecord> generatePreKeys() {
294 List<PreKeyRecord> records = new ArrayList<>(BaseConfig.PREKEY_BATCH_SIZE);
295
296 final int offset = account.getPreKeyIdOffset();
297 for (int i = 0; i < BaseConfig.PREKEY_BATCH_SIZE; i++) {
298 int preKeyId = (offset + i) % Medium.MAX_VALUE;
299 ECKeyPair keyPair = Curve.generateKeyPair();
300 PreKeyRecord record = new PreKeyRecord(preKeyId, keyPair);
301
302 records.add(record);
303 }
304
305 account.addPreKeys(records);
306 account.save();
307
308 return records;
309 }
310
311 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
312 try {
313 ECKeyPair keyPair = Curve.generateKeyPair();
314 byte[] signature = Curve.calculateSignature(identityKeyPair.getPrivateKey(), keyPair.getPublicKey().serialize());
315 SignedPreKeyRecord record = new SignedPreKeyRecord(account.getNextSignedPreKeyId(), System.currentTimeMillis(), keyPair, signature);
316
317 account.addSignedPreKey(record);
318 account.save();
319
320 return record;
321 } catch (InvalidKeyException e) {
322 throw new AssertionError(e);
323 }
324 }
325
326 public void verifyAccount(String verificationCode, String pin) throws IOException {
327 verificationCode = verificationCode.replace("-", "");
328 account.setSignalingKey(KeyUtils.createSignalingKey());
329 // TODO make unrestricted unidentified access configurable
330 accountManager.verifyAccountWithCode(verificationCode, account.getSignalingKey(), account.getSignalProtocolStore().getLocalRegistrationId(), true, pin, getSelfUnidentifiedAccessKey(), false);
331
332 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
333 account.setRegistered(true);
334 account.setRegistrationLockPin(pin);
335
336 refreshPreKeys();
337 account.save();
338 }
339
340 public void setRegistrationLockPin(Optional<String> pin) throws IOException {
341 accountManager.setPin(pin);
342 if (pin.isPresent()) {
343 account.setRegistrationLockPin(pin.get());
344 } else {
345 account.setRegistrationLockPin(null);
346 }
347 account.save();
348 }
349
350 private void refreshPreKeys() throws IOException {
351 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
352 final IdentityKeyPair identityKeyPair = account.getSignalProtocolStore().getIdentityKeyPair();
353 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(identityKeyPair);
354
355 accountManager.setPreKeys(getIdentity(), signedPreKeyRecord, oneTimePreKeys);
356 }
357
358 private Optional<SignalServiceAttachmentStream> createGroupAvatarAttachment(byte[] groupId) throws IOException {
359 File file = getGroupAvatarFile(groupId);
360 if (!file.exists()) {
361 return Optional.absent();
362 }
363
364 return Optional.of(Utils.createAttachment(file));
365 }
366
367 private Optional<SignalServiceAttachmentStream> createContactAvatarAttachment(String number) throws IOException {
368 File file = getContactAvatarFile(number);
369 if (!file.exists()) {
370 return Optional.absent();
371 }
372
373 return Optional.of(Utils.createAttachment(file));
374 }
375
376 private GroupInfo getGroupForSending(byte[] groupId) throws GroupNotFoundException, NotAGroupMemberException {
377 GroupInfo g = account.getGroupStore().getGroup(groupId);
378 if (g == null) {
379 throw new GroupNotFoundException(groupId);
380 }
381 for (String member : g.members) {
382 if (member.equals(this.username)) {
383 return g;
384 }
385 }
386 throw new NotAGroupMemberException(groupId, g.name);
387 }
388
389 public List<GroupInfo> getGroups() {
390 return account.getGroupStore().getGroups();
391 }
392
393 @Override
394 public void sendGroupMessage(String messageText, List<String> attachments,
395 byte[] groupId)
396 throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
397 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
398 if (attachments != null) {
399 messageBuilder.withAttachments(Utils.getSignalServiceAttachments(attachments));
400 }
401 if (groupId != null) {
402 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.DELIVER)
403 .withId(groupId)
404 .build();
405 messageBuilder.asGroupMessage(group);
406 }
407 ThreadInfo thread = account.getThreadStore().getThread(Base64.encodeBytes(groupId));
408 if (thread != null) {
409 messageBuilder.withExpiration(thread.messageExpirationTime);
410 }
411
412 final GroupInfo g = getGroupForSending(groupId);
413
414 // Don't send group message to ourself
415 final List<String> membersSend = new ArrayList<>(g.members);
416 membersSend.remove(this.username);
417 sendMessageLegacy(messageBuilder, membersSend);
418 }
419
420 public void sendQuitGroupMessage(byte[] groupId) throws GroupNotFoundException, IOException, EncapsulatedExceptions {
421 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.QUIT)
422 .withId(groupId)
423 .build();
424
425 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
426 .asGroupMessage(group);
427
428 final GroupInfo g = getGroupForSending(groupId);
429 g.members.remove(this.username);
430 account.getGroupStore().updateGroup(g);
431
432 sendMessageLegacy(messageBuilder, g.members);
433 }
434
435 private byte[] sendUpdateGroupMessage(byte[] groupId, String name, Collection<String> members, String avatarFile) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
436 GroupInfo g;
437 if (groupId == null) {
438 // Create new group
439 g = new GroupInfo(KeyUtils.createGroupId());
440 g.members.add(username);
441 } else {
442 g = getGroupForSending(groupId);
443 }
444
445 if (name != null) {
446 g.name = name;
447 }
448
449 if (members != null) {
450 Set<String> newMembers = new HashSet<>();
451 for (String member : members) {
452 try {
453 member = Utils.canonicalizeNumber(member, username);
454 } catch (InvalidNumberException e) {
455 System.err.println("Failed to add member \"" + member + "\" to group: " + e.getMessage());
456 System.err.println("Aborting…");
457 System.exit(1);
458 }
459 if (g.members.contains(member)) {
460 continue;
461 }
462 newMembers.add(member);
463 g.members.add(member);
464 }
465 final List<ContactTokenDetails> contacts = accountManager.getContacts(newMembers);
466 if (contacts.size() != newMembers.size()) {
467 // Some of the new members are not registered on Signal
468 for (ContactTokenDetails contact : contacts) {
469 newMembers.remove(contact.getNumber());
470 }
471 System.err.println("Failed to add members " + Util.join(", ", newMembers) + " to group: Not registered on Signal");
472 System.err.println("Aborting…");
473 System.exit(1);
474 }
475 }
476
477 if (avatarFile != null) {
478 IOUtils.createPrivateDirectories(avatarsPath);
479 File aFile = getGroupAvatarFile(g.groupId);
480 Files.copy(Paths.get(avatarFile), aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
481 }
482
483 account.getGroupStore().updateGroup(g);
484
485 SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);
486
487 // Don't send group message to ourself
488 final List<String> membersSend = new ArrayList<>(g.members);
489 membersSend.remove(this.username);
490 sendMessageLegacy(messageBuilder, membersSend);
491 return g.groupId;
492 }
493
494 private void sendUpdateGroupMessage(byte[] groupId, String recipient) throws IOException, EncapsulatedExceptions {
495 if (groupId == null) {
496 return;
497 }
498 GroupInfo g = getGroupForSending(groupId);
499
500 if (!g.members.contains(recipient)) {
501 return;
502 }
503
504 SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);
505
506 // Send group message only to the recipient who requested it
507 final List<String> membersSend = new ArrayList<>();
508 membersSend.add(recipient);
509 sendMessageLegacy(messageBuilder, membersSend);
510 }
511
512 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfo g) {
513 SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.UPDATE)
514 .withId(g.groupId)
515 .withName(g.name)
516 .withMembers(new ArrayList<>(g.members));
517
518 File aFile = getGroupAvatarFile(g.groupId);
519 if (aFile.exists()) {
520 try {
521 group.withAvatar(Utils.createAttachment(aFile));
522 } catch (IOException e) {
523 throw new AttachmentInvalidException(aFile.toString(), e);
524 }
525 }
526
527 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
528 .asGroupMessage(group.build());
529
530 ThreadInfo thread = account.getThreadStore().getThread(Base64.encodeBytes(g.groupId));
531 if (thread != null) {
532 messageBuilder.withExpiration(thread.messageExpirationTime);
533 }
534
535 return messageBuilder;
536 }
537
538 private void sendGroupInfoRequest(byte[] groupId, String recipient) throws IOException, EncapsulatedExceptions {
539 if (groupId == null) {
540 return;
541 }
542
543 SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.REQUEST_INFO)
544 .withId(groupId);
545
546 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
547 .asGroupMessage(group.build());
548
549 ThreadInfo thread = account.getThreadStore().getThread(Base64.encodeBytes(groupId));
550 if (thread != null) {
551 messageBuilder.withExpiration(thread.messageExpirationTime);
552 }
553
554 // Send group info request message to the recipient who sent us a message with this groupId
555 final List<String> membersSend = new ArrayList<>();
556 membersSend.add(recipient);
557 sendMessageLegacy(messageBuilder, membersSend);
558 }
559
560 @Override
561 public void sendMessage(String message, List<String> attachments, String recipient)
562 throws EncapsulatedExceptions, AttachmentInvalidException, IOException {
563 List<String> recipients = new ArrayList<>(1);
564 recipients.add(recipient);
565 sendMessage(message, attachments, recipients);
566 }
567
568 @Override
569 public void sendMessage(String messageText, List<String> attachments,
570 List<String> recipients)
571 throws IOException, EncapsulatedExceptions, AttachmentInvalidException {
572 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
573 if (attachments != null) {
574 messageBuilder.withAttachments(Utils.getSignalServiceAttachments(attachments));
575 }
576 messageBuilder.withProfileKey(account.getProfileKey());
577 sendMessageLegacy(messageBuilder, recipients);
578 }
579
580 @Override
581 public void sendEndSessionMessage(List<String> recipients) throws IOException, EncapsulatedExceptions {
582 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
583 .asEndSessionMessage();
584
585 sendMessageLegacy(messageBuilder, recipients);
586 }
587
588 @Override
589 public String getContactName(String number) {
590 ContactInfo contact = account.getContactStore().getContact(number);
591 if (contact == null) {
592 return "";
593 } else {
594 return contact.name;
595 }
596 }
597
598 @Override
599 public void setContactName(String number, String name) {
600 ContactInfo contact = account.getContactStore().getContact(number);
601 if (contact == null) {
602 contact = new ContactInfo();
603 contact.number = number;
604 System.err.println("Add contact " + number + " named " + name);
605 } else {
606 System.err.println("Updating contact " + number + " name " + contact.name + " -> " + name);
607 }
608 contact.name = name;
609 account.getContactStore().updateContact(contact);
610 account.save();
611 }
612
613 @Override
614 public List<byte[]> getGroupIds() {
615 List<GroupInfo> groups = getGroups();
616 List<byte[]> ids = new ArrayList<>(groups.size());
617 for (GroupInfo group : groups) {
618 ids.add(group.groupId);
619 }
620 return ids;
621 }
622
623 @Override
624 public String getGroupName(byte[] groupId) {
625 GroupInfo group = getGroup(groupId);
626 if (group == null) {
627 return "";
628 } else {
629 return group.name;
630 }
631 }
632
633 @Override
634 public List<String> getGroupMembers(byte[] groupId) {
635 GroupInfo group = getGroup(groupId);
636 if (group == null) {
637 return new ArrayList<>();
638 } else {
639 return new ArrayList<>(group.members);
640 }
641 }
642
643 @Override
644 public byte[] updateGroup(byte[] groupId, String name, List<String> members, String avatar) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
645 if (groupId.length == 0) {
646 groupId = null;
647 }
648 if (name.isEmpty()) {
649 name = null;
650 }
651 if (members.size() == 0) {
652 members = null;
653 }
654 if (avatar.isEmpty()) {
655 avatar = null;
656 }
657 return sendUpdateGroupMessage(groupId, name, members, avatar);
658 }
659
660 /**
661 * Change the expiration timer for a thread (number of groupId)
662 *
663 * @param numberOrGroupId
664 * @param messageExpirationTimer
665 */
666 public void setExpirationTimer(String numberOrGroupId, int messageExpirationTimer) {
667 ThreadInfo thread = account.getThreadStore().getThread(numberOrGroupId);
668 thread.messageExpirationTime = messageExpirationTimer;
669 account.getThreadStore().updateThread(thread);
670 }
671
672 private void requestSyncGroups() throws IOException {
673 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS).build();
674 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
675 try {
676 sendSyncMessage(message);
677 } catch (UntrustedIdentityException e) {
678 e.printStackTrace();
679 }
680 }
681
682 private void requestSyncContacts() throws IOException {
683 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS).build();
684 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
685 try {
686 sendSyncMessage(message);
687 } catch (UntrustedIdentityException e) {
688 e.printStackTrace();
689 }
690 }
691
692 private void requestSyncBlocked() throws IOException {
693 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED).build();
694 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
695 try {
696 sendSyncMessage(message);
697 } catch (UntrustedIdentityException e) {
698 e.printStackTrace();
699 }
700 }
701
702 private void requestSyncConfiguration() throws IOException {
703 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION).build();
704 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
705 try {
706 sendSyncMessage(message);
707 } catch (UntrustedIdentityException e) {
708 e.printStackTrace();
709 }
710 }
711
712 private byte[] getSelfUnidentifiedAccessKey() {
713 return UnidentifiedAccess.deriveAccessKeyFrom(account.getProfileKey());
714 }
715
716 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient) {
717 // TODO implement
718 return null;
719 }
720
721 private Optional<UnidentifiedAccessPair> getAccessForSync() {
722 // TODO implement
723 return Optional.absent();
724 }
725
726 private List<Optional<UnidentifiedAccessPair>> getAccessFor(Collection<SignalServiceAddress> recipients) {
727 List<Optional<UnidentifiedAccessPair>> result = new ArrayList<>(recipients.size());
728 for (SignalServiceAddress recipient : recipients) {
729 result.add(Optional.<UnidentifiedAccessPair>absent());
730 }
731 return result;
732 }
733
734 private Optional<UnidentifiedAccessPair> getAccessFor(SignalServiceAddress recipient) {
735 // TODO implement
736 return Optional.absent();
737 }
738
739 private void sendSyncMessage(SignalServiceSyncMessage message)
740 throws IOException, UntrustedIdentityException {
741 SignalServiceMessageSender messageSender = new SignalServiceMessageSender(BaseConfig.serviceConfiguration, username, account.getPassword(),
742 account.getDeviceId(), account.getSignalProtocolStore(), BaseConfig.USER_AGENT, account.isMultiDevice(), Optional.fromNullable(messagePipe), Optional.fromNullable(unidentifiedMessagePipe), Optional.<SignalServiceMessageSender.EventListener>absent());
743 try {
744 messageSender.sendMessage(message, getAccessForSync());
745 } catch (UntrustedIdentityException e) {
746 account.getSignalProtocolStore().saveIdentity(e.getE164Number(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
747 throw e;
748 }
749 }
750
751 /**
752 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
753 */
754 private void sendMessageLegacy(SignalServiceDataMessage.Builder messageBuilder, Collection<String> recipients)
755 throws EncapsulatedExceptions, IOException {
756 List<SendMessageResult> results = sendMessage(messageBuilder, recipients);
757
758 List<UntrustedIdentityException> untrustedIdentities = new LinkedList<>();
759 List<UnregisteredUserException> unregisteredUsers = new LinkedList<>();
760 List<NetworkFailureException> networkExceptions = new LinkedList<>();
761
762 for (SendMessageResult result : results) {
763 if (result.isUnregisteredFailure()) {
764 unregisteredUsers.add(new UnregisteredUserException(result.getAddress().getNumber(), null));
765 } else if (result.isNetworkFailure()) {
766 networkExceptions.add(new NetworkFailureException(result.getAddress().getNumber(), null));
767 } else if (result.getIdentityFailure() != null) {
768 untrustedIdentities.add(new UntrustedIdentityException("Untrusted", result.getAddress().getNumber(), result.getIdentityFailure().getIdentityKey()));
769 }
770 }
771 if (!untrustedIdentities.isEmpty() || !unregisteredUsers.isEmpty() || !networkExceptions.isEmpty()) {
772 throw new EncapsulatedExceptions(untrustedIdentities, unregisteredUsers, networkExceptions);
773 }
774 }
775
776 private List<SendMessageResult> sendMessage(SignalServiceDataMessage.Builder messageBuilder, Collection<String> recipients)
777 throws IOException {
778 Set<SignalServiceAddress> recipientsTS = Utils.getSignalServiceAddresses(recipients, username);
779 if (recipientsTS == null) {
780 account.save();
781 return Collections.emptyList();
782 }
783
784 SignalServiceDataMessage message = null;
785 try {
786 SignalServiceMessageSender messageSender = new SignalServiceMessageSender(BaseConfig.serviceConfiguration, username, account.getPassword(),
787 account.getDeviceId(), account.getSignalProtocolStore(), BaseConfig.USER_AGENT, account.isMultiDevice(), Optional.fromNullable(messagePipe), Optional.fromNullable(unidentifiedMessagePipe), Optional.<SignalServiceMessageSender.EventListener>absent());
788
789 message = messageBuilder.build();
790 if (message.getGroupInfo().isPresent()) {
791 try {
792 final boolean isRecipientUpdate = false;
793 List<SendMessageResult> result = messageSender.sendMessage(new ArrayList<>(recipientsTS), getAccessFor(recipientsTS), isRecipientUpdate, message);
794 for (SendMessageResult r : result) {
795 if (r.getIdentityFailure() != null) {
796 account.getSignalProtocolStore().saveIdentity(r.getAddress().getNumber(), r.getIdentityFailure().getIdentityKey(), TrustLevel.UNTRUSTED);
797 }
798 }
799 return result;
800 } catch (UntrustedIdentityException e) {
801 account.getSignalProtocolStore().saveIdentity(e.getE164Number(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
802 return Collections.emptyList();
803 }
804 } else if (recipientsTS.size() == 1 && recipientsTS.contains(new SignalServiceAddress(username))) {
805 SignalServiceAddress recipient = new SignalServiceAddress(username);
806 final Optional<UnidentifiedAccessPair> unidentifiedAccess = getAccessFor(recipient);
807 SentTranscriptMessage transcript = new SentTranscriptMessage(recipient.getNumber(),
808 message.getTimestamp(),
809 message,
810 message.getExpiresInSeconds(),
811 Collections.singletonMap(recipient.getNumber(), unidentifiedAccess.isPresent()),
812 false);
813 SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
814
815 List<SendMessageResult> results = new ArrayList<>(recipientsTS.size());
816 try {
817 messageSender.sendMessage(syncMessage, unidentifiedAccess);
818 } catch (UntrustedIdentityException e) {
819 account.getSignalProtocolStore().saveIdentity(e.getE164Number(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
820 results.add(SendMessageResult.identityFailure(recipient, e.getIdentityKey()));
821 }
822 return results;
823 } else {
824 // Send to all individually, so sync messages are sent correctly
825 List<SendMessageResult> results = new ArrayList<>(recipientsTS.size());
826 for (SignalServiceAddress address : recipientsTS) {
827 ThreadInfo thread = account.getThreadStore().getThread(address.getNumber());
828 if (thread != null) {
829 messageBuilder.withExpiration(thread.messageExpirationTime);
830 } else {
831 messageBuilder.withExpiration(0);
832 }
833 message = messageBuilder.build();
834 try {
835 SendMessageResult result = messageSender.sendMessage(address, getAccessFor(address), message);
836 results.add(result);
837 } catch (UntrustedIdentityException e) {
838 account.getSignalProtocolStore().saveIdentity(e.getE164Number(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
839 results.add(SendMessageResult.identityFailure(address, e.getIdentityKey()));
840 }
841 }
842 return results;
843 }
844 } finally {
845 if (message != null && message.isEndSession()) {
846 for (SignalServiceAddress recipient : recipientsTS) {
847 handleEndSession(recipient.getNumber());
848 }
849 }
850 account.save();
851 }
852 }
853
854 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, ProtocolUntrustedIdentityException, SelfSendException, UnsupportedDataMessageException {
855 SignalServiceCipher cipher = new SignalServiceCipher(new SignalServiceAddress(username), account.getSignalProtocolStore(), Utils.getCertificateValidator());
856 try {
857 return cipher.decrypt(envelope);
858 } catch (ProtocolUntrustedIdentityException e) {
859 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
860 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
861 throw e;
862 }
863 }
864
865 private void handleEndSession(String source) {
866 account.getSignalProtocolStore().deleteAllSessions(source);
867 }
868
869 private void handleSignalServiceDataMessage(SignalServiceDataMessage message, boolean isSync, String source, String destination, boolean ignoreAttachments) {
870 String threadId;
871 if (message.getGroupInfo().isPresent()) {
872 SignalServiceGroup groupInfo = message.getGroupInfo().get();
873 threadId = Base64.encodeBytes(groupInfo.getGroupId());
874 GroupInfo group = account.getGroupStore().getGroup(groupInfo.getGroupId());
875 switch (groupInfo.getType()) {
876 case UPDATE:
877 if (group == null) {
878 group = new GroupInfo(groupInfo.getGroupId());
879 }
880
881 if (groupInfo.getAvatar().isPresent()) {
882 SignalServiceAttachment avatar = groupInfo.getAvatar().get();
883 if (avatar.isPointer()) {
884 try {
885 retrieveGroupAvatarAttachment(avatar.asPointer(), group.groupId);
886 } catch (IOException | InvalidMessageException e) {
887 System.err.println("Failed to retrieve group avatar (" + avatar.asPointer().getId() + "): " + e.getMessage());
888 }
889 }
890 }
891
892 if (groupInfo.getName().isPresent()) {
893 group.name = groupInfo.getName().get();
894 }
895
896 if (groupInfo.getMembers().isPresent()) {
897 group.members.addAll(groupInfo.getMembers().get());
898 }
899
900 account.getGroupStore().updateGroup(group);
901 break;
902 case DELIVER:
903 if (group == null) {
904 try {
905 sendGroupInfoRequest(groupInfo.getGroupId(), source);
906 } catch (IOException | EncapsulatedExceptions e) {
907 e.printStackTrace();
908 }
909 }
910 break;
911 case QUIT:
912 if (group == null) {
913 try {
914 sendGroupInfoRequest(groupInfo.getGroupId(), source);
915 } catch (IOException | EncapsulatedExceptions e) {
916 e.printStackTrace();
917 }
918 } else {
919 group.members.remove(source);
920 account.getGroupStore().updateGroup(group);
921 }
922 break;
923 case REQUEST_INFO:
924 if (group != null) {
925 try {
926 sendUpdateGroupMessage(groupInfo.getGroupId(), source);
927 } catch (IOException | EncapsulatedExceptions e) {
928 e.printStackTrace();
929 } catch (NotAGroupMemberException e) {
930 // We have left this group, so don't send a group update message
931 }
932 }
933 break;
934 }
935 } else {
936 if (isSync) {
937 threadId = destination;
938 } else {
939 threadId = source;
940 }
941 }
942 if (message.isEndSession()) {
943 handleEndSession(isSync ? destination : source);
944 }
945 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
946 ThreadInfo thread = account.getThreadStore().getThread(threadId);
947 if (thread == null) {
948 thread = new ThreadInfo();
949 thread.id = threadId;
950 }
951 if (thread.messageExpirationTime != message.getExpiresInSeconds()) {
952 thread.messageExpirationTime = message.getExpiresInSeconds();
953 account.getThreadStore().updateThread(thread);
954 }
955 }
956 if (message.getAttachments().isPresent() && !ignoreAttachments) {
957 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
958 if (attachment.isPointer()) {
959 try {
960 retrieveAttachment(attachment.asPointer());
961 } catch (IOException | InvalidMessageException e) {
962 System.err.println("Failed to retrieve attachment (" + attachment.asPointer().getId() + "): " + e.getMessage());
963 }
964 }
965 }
966 }
967 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
968 if (source.equals(username)) {
969 this.account.setProfileKey(message.getProfileKey().get());
970 }
971 ContactInfo contact = account.getContactStore().getContact(source);
972 if (contact == null) {
973 contact = new ContactInfo();
974 contact.number = source;
975 }
976 contact.profileKey = Base64.encodeBytes(message.getProfileKey().get());
977 }
978 }
979
980 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
981 final File cachePath = new File(getMessageCachePath());
982 if (!cachePath.exists()) {
983 return;
984 }
985 for (final File dir : Objects.requireNonNull(cachePath.listFiles())) {
986 if (!dir.isDirectory()) {
987 continue;
988 }
989
990 for (final File fileEntry : Objects.requireNonNull(dir.listFiles())) {
991 if (!fileEntry.isFile()) {
992 continue;
993 }
994 SignalServiceEnvelope envelope;
995 try {
996 envelope = Utils.loadEnvelope(fileEntry);
997 if (envelope == null) {
998 continue;
999 }
1000 } catch (IOException e) {
1001 e.printStackTrace();
1002 continue;
1003 }
1004 SignalServiceContent content = null;
1005 if (!envelope.isReceipt()) {
1006 try {
1007 content = decryptMessage(envelope);
1008 } catch (Exception e) {
1009 continue;
1010 }
1011 handleMessage(envelope, content, ignoreAttachments);
1012 }
1013 account.save();
1014 handler.handleMessage(envelope, content, null);
1015 try {
1016 Files.delete(fileEntry.toPath());
1017 } catch (IOException e) {
1018 System.err.println("Failed to delete cached message file “" + fileEntry + "”: " + e.getMessage());
1019 }
1020 }
1021 // Try to delete directory if empty
1022 dir.delete();
1023 }
1024 }
1025
1026 public void receiveMessages(long timeout, TimeUnit unit, boolean returnOnTimeout, boolean ignoreAttachments, ReceiveMessageHandler handler) throws IOException {
1027 retryFailedReceivedMessages(handler, ignoreAttachments);
1028 final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(BaseConfig.serviceConfiguration, username, account.getPassword(), account.getDeviceId(), account.getSignalingKey(), BaseConfig.USER_AGENT, null, timer);
1029
1030 try {
1031 if (messagePipe == null) {
1032 messagePipe = messageReceiver.createMessagePipe();
1033 }
1034
1035 while (true) {
1036 SignalServiceEnvelope envelope;
1037 SignalServiceContent content = null;
1038 Exception exception = null;
1039 final long now = new Date().getTime();
1040 try {
1041 envelope = messagePipe.read(timeout, unit, new SignalServiceMessagePipe.MessagePipeCallback() {
1042 @Override
1043 public void onMessage(SignalServiceEnvelope envelope) {
1044 // store message on disk, before acknowledging receipt to the server
1045 try {
1046 File cacheFile = getMessageCacheFile(envelope.getSource(), now, envelope.getTimestamp());
1047 Utils.storeEnvelope(envelope, cacheFile);
1048 } catch (IOException e) {
1049 System.err.println("Failed to store encrypted message in disk cache, ignoring: " + e.getMessage());
1050 }
1051 }
1052 });
1053 } catch (TimeoutException e) {
1054 if (returnOnTimeout)
1055 return;
1056 continue;
1057 } catch (InvalidVersionException e) {
1058 System.err.println("Ignoring error: " + e.getMessage());
1059 continue;
1060 }
1061 if (!envelope.isReceipt()) {
1062 try {
1063 content = decryptMessage(envelope);
1064 } catch (Exception e) {
1065 exception = e;
1066 }
1067 handleMessage(envelope, content, ignoreAttachments);
1068 }
1069 account.save();
1070 handler.handleMessage(envelope, content, exception);
1071 if (!(exception instanceof ProtocolUntrustedIdentityException)) {
1072 File cacheFile = null;
1073 try {
1074 cacheFile = getMessageCacheFile(envelope.getSource(), now, envelope.getTimestamp());
1075 Files.delete(cacheFile.toPath());
1076 // Try to delete directory if empty
1077 new File(getMessageCachePath()).delete();
1078 } catch (IOException e) {
1079 System.err.println("Failed to delete cached message file “" + cacheFile + "”: " + e.getMessage());
1080 }
1081 }
1082 }
1083 } finally {
1084 if (messagePipe != null) {
1085 messagePipe.shutdown();
1086 messagePipe = null;
1087 }
1088 }
1089 }
1090
1091 private void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments) {
1092 if (content != null) {
1093 if (content.getDataMessage().isPresent()) {
1094 SignalServiceDataMessage message = content.getDataMessage().get();
1095 handleSignalServiceDataMessage(message, false, envelope.getSource(), username, ignoreAttachments);
1096 }
1097 if (content.getSyncMessage().isPresent()) {
1098 account.setMultiDevice(true);
1099 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
1100 if (syncMessage.getSent().isPresent()) {
1101 SignalServiceDataMessage message = syncMessage.getSent().get().getMessage();
1102 handleSignalServiceDataMessage(message, true, envelope.getSource(), syncMessage.getSent().get().getDestination().get(), ignoreAttachments);
1103 }
1104 if (syncMessage.getRequest().isPresent()) {
1105 RequestMessage rm = syncMessage.getRequest().get();
1106 if (rm.isContactsRequest()) {
1107 try {
1108 sendContacts();
1109 } catch (UntrustedIdentityException | IOException e) {
1110 e.printStackTrace();
1111 }
1112 }
1113 if (rm.isGroupsRequest()) {
1114 try {
1115 sendGroups();
1116 } catch (UntrustedIdentityException | IOException e) {
1117 e.printStackTrace();
1118 }
1119 }
1120 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1121 }
1122 if (syncMessage.getGroups().isPresent()) {
1123 File tmpFile = null;
1124 try {
1125 tmpFile = IOUtils.createTempFile();
1126 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(syncMessage.getGroups().get().asPointer(), tmpFile)) {
1127 DeviceGroupsInputStream s = new DeviceGroupsInputStream(attachmentAsStream);
1128 DeviceGroup g;
1129 while ((g = s.read()) != null) {
1130 GroupInfo syncGroup = account.getGroupStore().getGroup(g.getId());
1131 if (syncGroup == null) {
1132 syncGroup = new GroupInfo(g.getId());
1133 }
1134 if (g.getName().isPresent()) {
1135 syncGroup.name = g.getName().get();
1136 }
1137 syncGroup.members.addAll(g.getMembers());
1138 syncGroup.active = g.isActive();
1139 if (g.getColor().isPresent()) {
1140 syncGroup.color = g.getColor().get();
1141 }
1142
1143 if (g.getAvatar().isPresent()) {
1144 retrieveGroupAvatarAttachment(g.getAvatar().get(), syncGroup.groupId);
1145 }
1146 account.getGroupStore().updateGroup(syncGroup);
1147 }
1148 }
1149 } catch (Exception e) {
1150 e.printStackTrace();
1151 } finally {
1152 if (tmpFile != null) {
1153 try {
1154 Files.delete(tmpFile.toPath());
1155 } catch (IOException e) {
1156 System.err.println("Failed to delete received groups temp file “" + tmpFile + "”: " + e.getMessage());
1157 }
1158 }
1159 }
1160 }
1161 if (syncMessage.getBlockedList().isPresent()) {
1162 // TODO store list of blocked numbers
1163 }
1164 if (syncMessage.getContacts().isPresent()) {
1165 File tmpFile = null;
1166 try {
1167 tmpFile = IOUtils.createTempFile();
1168 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
1169 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream().asPointer(), tmpFile)) {
1170 DeviceContactsInputStream s = new DeviceContactsInputStream(attachmentAsStream);
1171 if (contactsMessage.isComplete()) {
1172 account.getContactStore().clear();
1173 }
1174 DeviceContact c;
1175 while ((c = s.read()) != null) {
1176 if (c.getNumber().equals(account.getUsername()) && c.getProfileKey().isPresent()) {
1177 account.setProfileKey(c.getProfileKey().get());
1178 }
1179 ContactInfo contact = account.getContactStore().getContact(c.getNumber());
1180 if (contact == null) {
1181 contact = new ContactInfo();
1182 contact.number = c.getNumber();
1183 }
1184 if (c.getName().isPresent()) {
1185 contact.name = c.getName().get();
1186 }
1187 if (c.getColor().isPresent()) {
1188 contact.color = c.getColor().get();
1189 }
1190 if (c.getProfileKey().isPresent()) {
1191 contact.profileKey = Base64.encodeBytes(c.getProfileKey().get());
1192 }
1193 if (c.getVerified().isPresent()) {
1194 final VerifiedMessage verifiedMessage = c.getVerified().get();
1195 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1196 }
1197 if (c.getExpirationTimer().isPresent()) {
1198 ThreadInfo thread = account.getThreadStore().getThread(c.getNumber());
1199 if (thread == null) {
1200 thread = new ThreadInfo();
1201 thread.id = c.getNumber();
1202 }
1203 thread.messageExpirationTime = c.getExpirationTimer().get();
1204 account.getThreadStore().updateThread(thread);
1205 }
1206 if (c.isBlocked()) {
1207 // TODO store list of blocked numbers
1208 }
1209 account.getContactStore().updateContact(contact);
1210
1211 if (c.getAvatar().isPresent()) {
1212 retrieveContactAvatarAttachment(c.getAvatar().get(), contact.number);
1213 }
1214 }
1215 }
1216 } catch (Exception e) {
1217 e.printStackTrace();
1218 } finally {
1219 if (tmpFile != null) {
1220 try {
1221 Files.delete(tmpFile.toPath());
1222 } catch (IOException e) {
1223 System.err.println("Failed to delete received contacts temp file “" + tmpFile + "”: " + e.getMessage());
1224 }
1225 }
1226 }
1227 }
1228 if (syncMessage.getVerified().isPresent()) {
1229 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1230 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1231 }
1232 if (syncMessage.getConfiguration().isPresent()) {
1233 // TODO
1234 }
1235 }
1236 }
1237 }
1238
1239 private File getContactAvatarFile(String number) {
1240 return new File(avatarsPath, "contact-" + number);
1241 }
1242
1243 private File retrieveContactAvatarAttachment(SignalServiceAttachment attachment, String number) throws IOException, InvalidMessageException {
1244 IOUtils.createPrivateDirectories(avatarsPath);
1245 if (attachment.isPointer()) {
1246 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1247 return retrieveAttachment(pointer, getContactAvatarFile(number), false);
1248 } else {
1249 SignalServiceAttachmentStream stream = attachment.asStream();
1250 return Utils.retrieveAttachment(stream, getContactAvatarFile(number));
1251 }
1252 }
1253
1254 private File getGroupAvatarFile(byte[] groupId) {
1255 return new File(avatarsPath, "group-" + Base64.encodeBytes(groupId).replace("/", "_"));
1256 }
1257
1258 private File retrieveGroupAvatarAttachment(SignalServiceAttachment attachment, byte[] groupId) throws IOException, InvalidMessageException {
1259 IOUtils.createPrivateDirectories(avatarsPath);
1260 if (attachment.isPointer()) {
1261 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1262 return retrieveAttachment(pointer, getGroupAvatarFile(groupId), false);
1263 } else {
1264 SignalServiceAttachmentStream stream = attachment.asStream();
1265 return Utils.retrieveAttachment(stream, getGroupAvatarFile(groupId));
1266 }
1267 }
1268
1269 public File getAttachmentFile(long attachmentId) {
1270 return new File(attachmentsPath, attachmentId + "");
1271 }
1272
1273 private File retrieveAttachment(SignalServiceAttachmentPointer pointer) throws IOException, InvalidMessageException {
1274 IOUtils.createPrivateDirectories(attachmentsPath);
1275 return retrieveAttachment(pointer, getAttachmentFile(pointer.getId()), true);
1276 }
1277
1278 private File retrieveAttachment(SignalServiceAttachmentPointer pointer, File outputFile, boolean storePreview) throws IOException, InvalidMessageException {
1279 if (storePreview && pointer.getPreview().isPresent()) {
1280 File previewFile = new File(outputFile + ".preview");
1281 try (OutputStream output = new FileOutputStream(previewFile)) {
1282 byte[] preview = pointer.getPreview().get();
1283 output.write(preview, 0, preview.length);
1284 } catch (FileNotFoundException e) {
1285 e.printStackTrace();
1286 return null;
1287 }
1288 }
1289
1290 final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(BaseConfig.serviceConfiguration, username, account.getPassword(), account.getDeviceId(), account.getSignalingKey(), BaseConfig.USER_AGENT, null, timer);
1291
1292 File tmpFile = IOUtils.createTempFile();
1293 try (InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE)) {
1294 try (OutputStream output = new FileOutputStream(outputFile)) {
1295 byte[] buffer = new byte[4096];
1296 int read;
1297
1298 while ((read = input.read(buffer)) != -1) {
1299 output.write(buffer, 0, read);
1300 }
1301 } catch (FileNotFoundException e) {
1302 e.printStackTrace();
1303 return null;
1304 }
1305 } finally {
1306 try {
1307 Files.delete(tmpFile.toPath());
1308 } catch (IOException e) {
1309 System.err.println("Failed to delete received attachment temp file “" + tmpFile + "”: " + e.getMessage());
1310 }
1311 }
1312 return outputFile;
1313 }
1314
1315 private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer, File tmpFile) throws IOException, InvalidMessageException {
1316 final SignalServiceMessageReceiver messageReceiver = new SignalServiceMessageReceiver(BaseConfig.serviceConfiguration, username, account.getPassword(), account.getDeviceId(), account.getSignalingKey(), BaseConfig.USER_AGENT, null, timer);
1317 return messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE);
1318 }
1319
1320 @Override
1321 public boolean isRemote() {
1322 return false;
1323 }
1324
1325 private void sendGroups() throws IOException, UntrustedIdentityException {
1326 File groupsFile = IOUtils.createTempFile();
1327
1328 try {
1329 try (OutputStream fos = new FileOutputStream(groupsFile)) {
1330 DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(fos);
1331 for (GroupInfo record : account.getGroupStore().getGroups()) {
1332 ThreadInfo info = account.getThreadStore().getThread(Base64.encodeBytes(record.groupId));
1333 out.write(new DeviceGroup(record.groupId, Optional.fromNullable(record.name),
1334 new ArrayList<>(record.members), createGroupAvatarAttachment(record.groupId),
1335 record.active, Optional.fromNullable(info != null ? info.messageExpirationTime : null),
1336 Optional.fromNullable(record.color), false));
1337 }
1338 }
1339
1340 if (groupsFile.exists() && groupsFile.length() > 0) {
1341 try (FileInputStream groupsFileStream = new FileInputStream(groupsFile)) {
1342 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1343 .withStream(groupsFileStream)
1344 .withContentType("application/octet-stream")
1345 .withLength(groupsFile.length())
1346 .build();
1347
1348 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
1349 }
1350 }
1351 } finally {
1352 try {
1353 Files.delete(groupsFile.toPath());
1354 } catch (IOException e) {
1355 System.err.println("Failed to delete groups temp file “" + groupsFile + "”: " + e.getMessage());
1356 }
1357 }
1358 }
1359
1360 private void sendContacts() throws IOException, UntrustedIdentityException {
1361 File contactsFile = IOUtils.createTempFile();
1362
1363 try {
1364 try (OutputStream fos = new FileOutputStream(contactsFile)) {
1365 DeviceContactsOutputStream out = new DeviceContactsOutputStream(fos);
1366 for (ContactInfo record : account.getContactStore().getContacts()) {
1367 VerifiedMessage verifiedMessage = null;
1368 ThreadInfo info = account.getThreadStore().getThread(record.number);
1369 if (getIdentities().containsKey(record.number)) {
1370 JsonIdentityKeyStore.Identity currentIdentity = null;
1371 for (JsonIdentityKeyStore.Identity id : getIdentities().get(record.number)) {
1372 if (currentIdentity == null || id.getDateAdded().after(currentIdentity.getDateAdded())) {
1373 currentIdentity = id;
1374 }
1375 }
1376 if (currentIdentity != null) {
1377 verifiedMessage = new VerifiedMessage(record.number, currentIdentity.getIdentityKey(), currentIdentity.getTrustLevel().toVerifiedState(), currentIdentity.getDateAdded().getTime());
1378 }
1379 }
1380
1381 byte[] profileKey = record.profileKey == null ? null : Base64.decode(record.profileKey);
1382 // TODO store list of blocked numbers
1383 boolean blocked = false;
1384 out.write(new DeviceContact(record.number, Optional.fromNullable(record.name),
1385 createContactAvatarAttachment(record.number), Optional.fromNullable(record.color),
1386 Optional.fromNullable(verifiedMessage), Optional.fromNullable(profileKey), blocked, Optional.fromNullable(info != null ? info.messageExpirationTime : null)));
1387 }
1388
1389 if (account.getProfileKey() != null) {
1390 // Send our own profile key as well
1391 out.write(new DeviceContact(account.getUsername(),
1392 Optional.<String>absent(), Optional.<SignalServiceAttachmentStream>absent(),
1393 Optional.<String>absent(), Optional.<VerifiedMessage>absent(),
1394 Optional.of(account.getProfileKey()),
1395 false, Optional.<Integer>absent()));
1396 }
1397 }
1398
1399 if (contactsFile.exists() && contactsFile.length() > 0) {
1400 try (FileInputStream contactsFileStream = new FileInputStream(contactsFile)) {
1401 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1402 .withStream(contactsFileStream)
1403 .withContentType("application/octet-stream")
1404 .withLength(contactsFile.length())
1405 .build();
1406
1407 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
1408 }
1409 }
1410 } finally {
1411 try {
1412 Files.delete(contactsFile.toPath());
1413 } catch (IOException e) {
1414 System.err.println("Failed to delete contacts temp file “" + contactsFile + "”: " + e.getMessage());
1415 }
1416 }
1417 }
1418
1419 private void sendVerifiedMessage(String destination, IdentityKey identityKey, TrustLevel trustLevel) throws IOException, UntrustedIdentityException {
1420 VerifiedMessage verifiedMessage = new VerifiedMessage(destination, identityKey, trustLevel.toVerifiedState(), System.currentTimeMillis());
1421 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
1422 }
1423
1424 public ContactInfo getContact(String number) {
1425 return account.getContactStore().getContact(number);
1426 }
1427
1428 public GroupInfo getGroup(byte[] groupId) {
1429 return account.getGroupStore().getGroup(groupId);
1430 }
1431
1432 public Map<String, List<JsonIdentityKeyStore.Identity>> getIdentities() {
1433 return account.getSignalProtocolStore().getIdentities();
1434 }
1435
1436 public List<JsonIdentityKeyStore.Identity> getIdentities(String number) {
1437 return account.getSignalProtocolStore().getIdentities(number);
1438 }
1439
1440 /**
1441 * Trust this the identity with this fingerprint
1442 *
1443 * @param name username of the identity
1444 * @param fingerprint Fingerprint
1445 */
1446 public boolean trustIdentityVerified(String name, byte[] fingerprint) {
1447 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1448 if (ids == null) {
1449 return false;
1450 }
1451 for (JsonIdentityKeyStore.Identity id : ids) {
1452 if (!Arrays.equals(id.getIdentityKey().serialize(), fingerprint)) {
1453 continue;
1454 }
1455
1456 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1457 try {
1458 sendVerifiedMessage(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1459 } catch (IOException | UntrustedIdentityException e) {
1460 e.printStackTrace();
1461 }
1462 account.save();
1463 return true;
1464 }
1465 return false;
1466 }
1467
1468 /**
1469 * Trust this the identity with this safety number
1470 *
1471 * @param name username of the identity
1472 * @param safetyNumber Safety number
1473 */
1474 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) {
1475 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1476 if (ids == null) {
1477 return false;
1478 }
1479 for (JsonIdentityKeyStore.Identity id : ids) {
1480 if (!safetyNumber.equals(computeSafetyNumber(name, id.getIdentityKey()))) {
1481 continue;
1482 }
1483
1484 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1485 try {
1486 sendVerifiedMessage(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1487 } catch (IOException | UntrustedIdentityException e) {
1488 e.printStackTrace();
1489 }
1490 account.save();
1491 return true;
1492 }
1493 return false;
1494 }
1495
1496 /**
1497 * Trust all keys of this identity without verification
1498 *
1499 * @param name username of the identity
1500 */
1501 public boolean trustIdentityAllKeys(String name) {
1502 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1503 if (ids == null) {
1504 return false;
1505 }
1506 for (JsonIdentityKeyStore.Identity id : ids) {
1507 if (id.getTrustLevel() == TrustLevel.UNTRUSTED) {
1508 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1509 try {
1510 sendVerifiedMessage(name, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1511 } catch (IOException | UntrustedIdentityException e) {
1512 e.printStackTrace();
1513 }
1514 }
1515 }
1516 account.save();
1517 return true;
1518 }
1519
1520 public String computeSafetyNumber(String theirUsername, IdentityKey theirIdentityKey) {
1521 return Utils.computeSafetyNumber(username, getIdentity(), theirUsername, theirIdentityKey);
1522 }
1523
1524 public interface ReceiveMessageHandler {
1525
1526 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
1527 }
1528 }