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