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