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