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