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