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