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