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