]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/manager/Manager.java
Show contact name for message Sender
[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(), 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, 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 accountManager.setPin(pin);
411 if (pin.isPresent()) {
412 account.setRegistrationLockPin(pin.get());
413 } else {
414 account.setRegistrationLockPin(null);
415 }
416 account.save();
417 }
418
419 private void refreshPreKeys() throws IOException {
420 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
421 final IdentityKeyPair identityKeyPair = account.getSignalProtocolStore().getIdentityKeyPair();
422 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(identityKeyPair);
423
424 accountManager.setPreKeys(getIdentity(), signedPreKeyRecord, oneTimePreKeys);
425 }
426
427 private SignalServiceMessageReceiver getMessageReceiver() {
428 return new SignalServiceMessageReceiver(BaseConfig.serviceConfiguration, null, username, account.getPassword(), account.getDeviceId(), account.getSignalingKey(), BaseConfig.USER_AGENT, null, timer);
429 }
430
431 private SignalServiceMessageSender getMessageSender() {
432 return new SignalServiceMessageSender(BaseConfig.serviceConfiguration, null, username, account.getPassword(),
433 account.getDeviceId(), account.getSignalProtocolStore(), BaseConfig.USER_AGENT, account.isMultiDevice(), Optional.fromNullable(messagePipe), Optional.fromNullable(unidentifiedMessagePipe), Optional.<SignalServiceMessageSender.EventListener>absent());
434 }
435
436 private Optional<SignalServiceAttachmentStream> createGroupAvatarAttachment(byte[] groupId) throws IOException {
437 File file = getGroupAvatarFile(groupId);
438 if (!file.exists()) {
439 return Optional.absent();
440 }
441
442 return Optional.of(Utils.createAttachment(file));
443 }
444
445 private Optional<SignalServiceAttachmentStream> createContactAvatarAttachment(String number) throws IOException {
446 File file = getContactAvatarFile(number);
447 if (!file.exists()) {
448 return Optional.absent();
449 }
450
451 return Optional.of(Utils.createAttachment(file));
452 }
453
454 private GroupInfo getGroupForSending(byte[] groupId) throws GroupNotFoundException, NotAGroupMemberException {
455 GroupInfo g = account.getGroupStore().getGroup(groupId);
456 if (g == null) {
457 throw new GroupNotFoundException(groupId);
458 }
459 for (String member : g.members) {
460 if (member.equals(this.username)) {
461 return g;
462 }
463 }
464 throw new NotAGroupMemberException(groupId, g.name);
465 }
466
467 public List<GroupInfo> getGroups() {
468 return account.getGroupStore().getGroups();
469 }
470
471 @Override
472 public void sendGroupMessage(String messageText, List<String> attachments,
473 byte[] groupId)
474 throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
475 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
476 if (attachments != null) {
477 messageBuilder.withAttachments(Utils.getSignalServiceAttachments(attachments));
478 }
479 if (groupId != null) {
480 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.DELIVER)
481 .withId(groupId)
482 .build();
483 messageBuilder.asGroupMessage(group);
484 }
485 ThreadInfo thread = account.getThreadStore().getThread(Base64.encodeBytes(groupId));
486 if (thread != null) {
487 messageBuilder.withExpiration(thread.messageExpirationTime);
488 }
489
490 final GroupInfo g = getGroupForSending(groupId);
491
492 // Don't send group message to ourself
493 final List<String> membersSend = new ArrayList<>(g.members);
494 membersSend.remove(this.username);
495 sendMessageLegacy(messageBuilder, membersSend);
496 }
497
498 public void sendQuitGroupMessage(byte[] groupId) throws GroupNotFoundException, IOException, EncapsulatedExceptions {
499 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.QUIT)
500 .withId(groupId)
501 .build();
502
503 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
504 .asGroupMessage(group);
505
506 final GroupInfo g = getGroupForSending(groupId);
507 g.members.remove(this.username);
508 account.getGroupStore().updateGroup(g);
509
510 sendMessageLegacy(messageBuilder, g.members);
511 }
512
513 private byte[] sendUpdateGroupMessage(byte[] groupId, String name, Collection<String> members, String avatarFile) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
514 GroupInfo g;
515 if (groupId == null) {
516 // Create new group
517 g = new GroupInfo(KeyUtils.createGroupId());
518 g.members.add(username);
519 } else {
520 g = getGroupForSending(groupId);
521 }
522
523 if (name != null) {
524 g.name = name;
525 }
526
527 if (members != null) {
528 Set<String> newMembers = new HashSet<>();
529 for (String member : members) {
530 try {
531 member = Utils.canonicalizeNumber(member, username);
532 } catch (InvalidNumberException e) {
533 System.err.println("Failed to add member \"" + member + "\" to group: " + e.getMessage());
534 System.err.println("Aborting…");
535 System.exit(1);
536 }
537 if (g.members.contains(member)) {
538 continue;
539 }
540 newMembers.add(member);
541 g.members.add(member);
542 }
543 final List<ContactTokenDetails> contacts = accountManager.getContacts(newMembers);
544 if (contacts.size() != newMembers.size()) {
545 // Some of the new members are not registered on Signal
546 for (ContactTokenDetails contact : contacts) {
547 newMembers.remove(contact.getNumber());
548 }
549 System.err.println("Failed to add members " + Util.join(", ", newMembers) + " to group: Not registered on Signal");
550 System.err.println("Aborting…");
551 System.exit(1);
552 }
553 }
554
555 if (avatarFile != null) {
556 IOUtils.createPrivateDirectories(avatarsPath);
557 File aFile = getGroupAvatarFile(g.groupId);
558 Files.copy(Paths.get(avatarFile), aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
559 }
560
561 account.getGroupStore().updateGroup(g);
562
563 SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);
564
565 // Don't send group message to ourself
566 final List<String> membersSend = new ArrayList<>(g.members);
567 membersSend.remove(this.username);
568 sendMessageLegacy(messageBuilder, membersSend);
569 return g.groupId;
570 }
571
572 private void sendUpdateGroupMessage(byte[] groupId, String recipient) throws IOException, EncapsulatedExceptions {
573 if (groupId == null) {
574 return;
575 }
576 GroupInfo g = getGroupForSending(groupId);
577
578 if (!g.members.contains(recipient)) {
579 return;
580 }
581
582 SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);
583
584 // Send group message only to the recipient who requested it
585 final List<String> membersSend = new ArrayList<>();
586 membersSend.add(recipient);
587 sendMessageLegacy(messageBuilder, membersSend);
588 }
589
590 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfo g) {
591 SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.UPDATE)
592 .withId(g.groupId)
593 .withName(g.name)
594 .withMembers(new ArrayList<>(g.getMembers()));
595
596 File aFile = getGroupAvatarFile(g.groupId);
597 if (aFile.exists()) {
598 try {
599 group.withAvatar(Utils.createAttachment(aFile));
600 } catch (IOException e) {
601 throw new AttachmentInvalidException(aFile.toString(), e);
602 }
603 }
604
605 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
606 .asGroupMessage(group.build());
607
608 ThreadInfo thread = account.getThreadStore().getThread(Base64.encodeBytes(g.groupId));
609 if (thread != null) {
610 messageBuilder.withExpiration(thread.messageExpirationTime);
611 }
612
613 return messageBuilder;
614 }
615
616 private void sendGroupInfoRequest(byte[] groupId, String recipient) throws IOException, EncapsulatedExceptions {
617 if (groupId == null) {
618 return;
619 }
620
621 SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.REQUEST_INFO)
622 .withId(groupId);
623
624 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
625 .asGroupMessage(group.build());
626
627 ThreadInfo thread = account.getThreadStore().getThread(Base64.encodeBytes(groupId));
628 if (thread != null) {
629 messageBuilder.withExpiration(thread.messageExpirationTime);
630 }
631
632 // Send group info request message to the recipient who sent us a message with this groupId
633 final List<String> membersSend = new ArrayList<>();
634 membersSend.add(recipient);
635 sendMessageLegacy(messageBuilder, membersSend);
636 }
637
638 @Override
639 public void sendMessage(String message, List<String> attachments, String recipient)
640 throws EncapsulatedExceptions, AttachmentInvalidException, IOException {
641 List<String> recipients = new ArrayList<>(1);
642 recipients.add(recipient);
643 sendMessage(message, attachments, recipients);
644 }
645
646 @Override
647 public void sendMessage(String messageText, List<String> attachments,
648 List<String> recipients)
649 throws IOException, EncapsulatedExceptions, AttachmentInvalidException {
650 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().withBody(messageText);
651 if (attachments != null) {
652 List<SignalServiceAttachment> attachmentStreams = Utils.getSignalServiceAttachments(attachments);
653
654 // Upload attachments here, so we only upload once even for multiple recipients
655 SignalServiceMessageSender messageSender = getMessageSender();
656 List<SignalServiceAttachment> attachmentPointers = new ArrayList<>(attachmentStreams.size());
657 for (SignalServiceAttachment attachment : attachmentStreams) {
658 if (attachment.isStream()) {
659 attachmentPointers.add(messageSender.uploadAttachment(attachment.asStream()));
660 } else if (attachment.isPointer()) {
661 attachmentPointers.add(attachment.asPointer());
662 }
663 }
664
665 messageBuilder.withAttachments(attachmentPointers);
666 }
667 messageBuilder.withProfileKey(account.getProfileKey());
668 sendMessageLegacy(messageBuilder, recipients);
669 }
670
671 @Override
672 public void sendEndSessionMessage(List<String> recipients) throws IOException, EncapsulatedExceptions {
673 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
674 .asEndSessionMessage();
675
676 sendMessageLegacy(messageBuilder, recipients);
677 }
678
679 @Override
680 public String getContactName(String number) throws InvalidNumberException {
681 String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
682 ContactInfo contact = account.getContactStore().getContact(canonicalizedNumber);
683 if (contact == null) {
684 return "";
685 } else {
686 return contact.name;
687 }
688 }
689
690 @Override
691 public void setContactName(String number, String name) throws InvalidNumberException {
692 String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
693 ContactInfo contact = account.getContactStore().getContact(canonicalizedNumber);
694 if (contact == null) {
695 contact = new ContactInfo();
696 contact.number = canonicalizedNumber;
697 System.err.println("Add contact " + canonicalizedNumber + " named " + name);
698 } else {
699 System.err.println("Updating contact " + canonicalizedNumber + " name " + contact.name + " -> " + name);
700 }
701 contact.name = name;
702 account.getContactStore().updateContact(contact);
703 account.save();
704 }
705
706 @Override
707 public void setContactBlocked(String number, boolean blocked) throws InvalidNumberException {
708 number = Utils.canonicalizeNumber(number, username);
709 ContactInfo contact = account.getContactStore().getContact(number);
710 if (contact == null) {
711 contact = new ContactInfo();
712 contact.number = number;
713 System.err.println("Adding and " + (blocked ? "blocking" : "unblocking") + " contact " + number);
714 } else {
715 System.err.println((blocked ? "Blocking" : "Unblocking") + " contact " + number);
716 }
717 contact.blocked = blocked;
718 account.getContactStore().updateContact(contact);
719 account.save();
720 }
721
722 @Override
723 public void setGroupBlocked(final byte[] groupId, final boolean blocked) throws GroupNotFoundException {
724 GroupInfo group = getGroup(groupId);
725 if (group == null) {
726 throw new GroupNotFoundException(groupId);
727 } else {
728 System.err.println((blocked ? "Blocking" : "Unblocking") + " group " + Base64.encodeBytes(groupId));
729 group.blocked = blocked;
730 account.getGroupStore().updateGroup(group);
731 account.save();
732 }
733 }
734
735 @Override
736 public List<byte[]> getGroupIds() {
737 List<GroupInfo> groups = getGroups();
738 List<byte[]> ids = new ArrayList<>(groups.size());
739 for (GroupInfo group : groups) {
740 ids.add(group.groupId);
741 }
742 return ids;
743 }
744
745 @Override
746 public String getGroupName(byte[] groupId) {
747 GroupInfo group = getGroup(groupId);
748 if (group == null) {
749 return "";
750 } else {
751 return group.name;
752 }
753 }
754
755 @Override
756 public List<String> getGroupMembers(byte[] groupId) {
757 GroupInfo group = getGroup(groupId);
758 if (group == null) {
759 return new ArrayList<>();
760 } else {
761 return new ArrayList<>(group.members);
762 }
763 }
764
765 @Override
766 public byte[] updateGroup(byte[] groupId, String name, List<String> members, String avatar) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
767 if (groupId.length == 0) {
768 groupId = null;
769 }
770 if (name.isEmpty()) {
771 name = null;
772 }
773 if (members.size() == 0) {
774 members = null;
775 }
776 if (avatar.isEmpty()) {
777 avatar = null;
778 }
779 return sendUpdateGroupMessage(groupId, name, members, avatar);
780 }
781
782 /**
783 * Change the expiration timer for a thread (number of groupId)
784 *
785 * @param numberOrGroupId
786 * @param messageExpirationTimer
787 */
788 public void setExpirationTimer(String numberOrGroupId, int messageExpirationTimer) {
789 ThreadInfo thread = account.getThreadStore().getThread(numberOrGroupId);
790 thread.messageExpirationTime = messageExpirationTimer;
791 account.getThreadStore().updateThread(thread);
792 }
793
794 private void requestSyncGroups() throws IOException {
795 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS).build();
796 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
797 try {
798 sendSyncMessage(message);
799 } catch (UntrustedIdentityException e) {
800 e.printStackTrace();
801 }
802 }
803
804 private void requestSyncContacts() throws IOException {
805 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS).build();
806 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
807 try {
808 sendSyncMessage(message);
809 } catch (UntrustedIdentityException e) {
810 e.printStackTrace();
811 }
812 }
813
814 private void requestSyncBlocked() throws IOException {
815 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED).build();
816 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
817 try {
818 sendSyncMessage(message);
819 } catch (UntrustedIdentityException e) {
820 e.printStackTrace();
821 }
822 }
823
824 private void requestSyncConfiguration() throws IOException {
825 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION).build();
826 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
827 try {
828 sendSyncMessage(message);
829 } catch (UntrustedIdentityException e) {
830 e.printStackTrace();
831 }
832 }
833
834 private byte[] getSelfUnidentifiedAccessKey() {
835 return UnidentifiedAccess.deriveAccessKeyFrom(account.getProfileKey());
836 }
837
838 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient) {
839 // TODO implement
840 return null;
841 }
842
843 private Optional<UnidentifiedAccessPair> getAccessForSync() {
844 // TODO implement
845 return Optional.absent();
846 }
847
848 private List<Optional<UnidentifiedAccessPair>> getAccessFor(Collection<SignalServiceAddress> recipients) {
849 List<Optional<UnidentifiedAccessPair>> result = new ArrayList<>(recipients.size());
850 for (SignalServiceAddress recipient : recipients) {
851 result.add(Optional.<UnidentifiedAccessPair>absent());
852 }
853 return result;
854 }
855
856 private Optional<UnidentifiedAccessPair> getAccessFor(SignalServiceAddress recipient) {
857 // TODO implement
858 return Optional.absent();
859 }
860
861 private void sendSyncMessage(SignalServiceSyncMessage message)
862 throws IOException, UntrustedIdentityException {
863 SignalServiceMessageSender messageSender = getMessageSender();
864 try {
865 messageSender.sendMessage(message, getAccessForSync());
866 } catch (UntrustedIdentityException e) {
867 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
868 throw e;
869 }
870 }
871
872 /**
873 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
874 */
875 private void sendMessageLegacy(SignalServiceDataMessage.Builder messageBuilder, Collection<String> recipients)
876 throws EncapsulatedExceptions, IOException {
877 List<SendMessageResult> results = sendMessage(messageBuilder, recipients);
878
879 List<UntrustedIdentityException> untrustedIdentities = new LinkedList<>();
880 List<UnregisteredUserException> unregisteredUsers = new LinkedList<>();
881 List<NetworkFailureException> networkExceptions = new LinkedList<>();
882
883 for (SendMessageResult result : results) {
884 if (result.isUnregisteredFailure()) {
885 unregisteredUsers.add(new UnregisteredUserException(result.getAddress().getNumber().get(), null));
886 } else if (result.isNetworkFailure()) {
887 networkExceptions.add(new NetworkFailureException(result.getAddress().getNumber().get(), null));
888 } else if (result.getIdentityFailure() != null) {
889 untrustedIdentities.add(new UntrustedIdentityException("Untrusted", result.getAddress().getNumber().get(), result.getIdentityFailure().getIdentityKey()));
890 }
891 }
892 if (!untrustedIdentities.isEmpty() || !unregisteredUsers.isEmpty() || !networkExceptions.isEmpty()) {
893 throw new EncapsulatedExceptions(untrustedIdentities, unregisteredUsers, networkExceptions);
894 }
895 }
896
897 private List<SendMessageResult> sendMessage(SignalServiceDataMessage.Builder messageBuilder, Collection<String> recipients)
898 throws IOException {
899 Set<SignalServiceAddress> recipientsTS = Utils.getSignalServiceAddresses(recipients, username);
900 if (recipientsTS == null) {
901 account.save();
902 return Collections.emptyList();
903 }
904
905 SignalServiceDataMessage message = null;
906 try {
907 SignalServiceMessageSender messageSender = getMessageSender();
908
909 message = messageBuilder.build();
910 if (message.getGroupInfo().isPresent()) {
911 try {
912 final boolean isRecipientUpdate = false;
913 List<SendMessageResult> result = messageSender.sendMessage(new ArrayList<>(recipientsTS), getAccessFor(recipientsTS), isRecipientUpdate, message);
914 for (SendMessageResult r : result) {
915 if (r.getIdentityFailure() != null) {
916 account.getSignalProtocolStore().saveIdentity(r.getAddress().getNumber().get(), r.getIdentityFailure().getIdentityKey(), TrustLevel.UNTRUSTED);
917 }
918 }
919 return result;
920 } catch (UntrustedIdentityException e) {
921 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
922 return Collections.emptyList();
923 }
924 } else if (recipientsTS.size() == 1 && recipientsTS.contains(getSelfAddress())) {
925 SignalServiceAddress recipient = getSelfAddress();
926 final Optional<UnidentifiedAccessPair> unidentifiedAccess = getAccessFor(recipient);
927 SentTranscriptMessage transcript = new SentTranscriptMessage(Optional.of(recipient),
928 message.getTimestamp(),
929 message,
930 message.getExpiresInSeconds(),
931 Collections.singletonMap(recipient, unidentifiedAccess.isPresent()),
932 false);
933 SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
934
935 List<SendMessageResult> results = new ArrayList<>(recipientsTS.size());
936 try {
937 messageSender.sendMessage(syncMessage, unidentifiedAccess);
938 } catch (UntrustedIdentityException e) {
939 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
940 results.add(SendMessageResult.identityFailure(recipient, e.getIdentityKey()));
941 }
942 return results;
943 } else {
944 // Send to all individually, so sync messages are sent correctly
945 List<SendMessageResult> results = new ArrayList<>(recipientsTS.size());
946 for (SignalServiceAddress address : recipientsTS) {
947 ThreadInfo thread = account.getThreadStore().getThread(address.getNumber().get());
948 if (thread != null) {
949 messageBuilder.withExpiration(thread.messageExpirationTime);
950 } else {
951 messageBuilder.withExpiration(0);
952 }
953 message = messageBuilder.build();
954 try {
955 SendMessageResult result = messageSender.sendMessage(address, getAccessFor(address), message);
956 results.add(result);
957 } catch (UntrustedIdentityException e) {
958 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
959 results.add(SendMessageResult.identityFailure(address, e.getIdentityKey()));
960 }
961 }
962 return results;
963 }
964 } finally {
965 if (message != null && message.isEndSession()) {
966 for (SignalServiceAddress recipient : recipientsTS) {
967 handleEndSession(recipient.getNumber().get());
968 }
969 }
970 account.save();
971 }
972 }
973
974 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, ProtocolUntrustedIdentityException, SelfSendException, UnsupportedDataMessageException {
975 SignalServiceCipher cipher = new SignalServiceCipher(getSelfAddress(), account.getSignalProtocolStore(), Utils.getCertificateValidator());
976 try {
977 return cipher.decrypt(envelope);
978 } catch (ProtocolUntrustedIdentityException e) {
979 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
980 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
981 throw e;
982 }
983 }
984
985 private void handleEndSession(String source) {
986 account.getSignalProtocolStore().deleteAllSessions(source);
987 }
988
989 private void handleSignalServiceDataMessage(SignalServiceDataMessage message, boolean isSync, String source, SignalServiceAddress destination, boolean ignoreAttachments) {
990 String threadId;
991 if (message.getGroupInfo().isPresent()) {
992 SignalServiceGroup groupInfo = message.getGroupInfo().get();
993 threadId = Base64.encodeBytes(groupInfo.getGroupId());
994 GroupInfo group = account.getGroupStore().getGroup(groupInfo.getGroupId());
995 switch (groupInfo.getType()) {
996 case UPDATE:
997 if (group == null) {
998 group = new GroupInfo(groupInfo.getGroupId());
999 }
1000
1001 if (groupInfo.getAvatar().isPresent()) {
1002 SignalServiceAttachment avatar = groupInfo.getAvatar().get();
1003 if (avatar.isPointer()) {
1004 try {
1005 retrieveGroupAvatarAttachment(avatar.asPointer(), group.groupId);
1006 } catch (IOException | InvalidMessageException e) {
1007 System.err.println("Failed to retrieve group avatar (" + avatar.asPointer().getId() + "): " + e.getMessage());
1008 }
1009 }
1010 }
1011
1012 if (groupInfo.getName().isPresent()) {
1013 group.name = groupInfo.getName().get();
1014 }
1015
1016 if (groupInfo.getMembers().isPresent()) {
1017 group.addMembers(groupInfo.getMembers().get());
1018 }
1019
1020 account.getGroupStore().updateGroup(group);
1021 break;
1022 case DELIVER:
1023 if (group == null) {
1024 try {
1025 sendGroupInfoRequest(groupInfo.getGroupId(), source);
1026 } catch (IOException | EncapsulatedExceptions e) {
1027 e.printStackTrace();
1028 }
1029 }
1030 break;
1031 case QUIT:
1032 if (group == null) {
1033 try {
1034 sendGroupInfoRequest(groupInfo.getGroupId(), source);
1035 } catch (IOException | EncapsulatedExceptions e) {
1036 e.printStackTrace();
1037 }
1038 } else {
1039 group.members.remove(source);
1040 account.getGroupStore().updateGroup(group);
1041 }
1042 break;
1043 case REQUEST_INFO:
1044 if (group != null) {
1045 try {
1046 sendUpdateGroupMessage(groupInfo.getGroupId(), source);
1047 } catch (IOException | EncapsulatedExceptions e) {
1048 e.printStackTrace();
1049 } catch (NotAGroupMemberException e) {
1050 // We have left this group, so don't send a group update message
1051 }
1052 }
1053 break;
1054 }
1055 } else {
1056 if (isSync) {
1057 threadId = destination.getNumber().get();
1058 } else {
1059 threadId = source;
1060 }
1061 }
1062 if (message.isEndSession()) {
1063 handleEndSession(isSync ? destination.getNumber().get() : source);
1064 }
1065 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1066 ThreadInfo thread = account.getThreadStore().getThread(threadId);
1067 if (thread == null) {
1068 thread = new ThreadInfo();
1069 thread.id = threadId;
1070 }
1071 if (thread.messageExpirationTime != message.getExpiresInSeconds()) {
1072 thread.messageExpirationTime = message.getExpiresInSeconds();
1073 account.getThreadStore().updateThread(thread);
1074 }
1075 }
1076 if (message.getAttachments().isPresent() && !ignoreAttachments) {
1077 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1078 if (attachment.isPointer()) {
1079 try {
1080 retrieveAttachment(attachment.asPointer());
1081 } catch (IOException | InvalidMessageException e) {
1082 System.err.println("Failed to retrieve attachment (" + attachment.asPointer().getId() + "): " + e.getMessage());
1083 }
1084 }
1085 }
1086 }
1087 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1088 if (source.equals(username)) {
1089 this.account.setProfileKey(message.getProfileKey().get());
1090 }
1091 ContactInfo contact = account.getContactStore().getContact(source);
1092 if (contact == null) {
1093 contact = new ContactInfo();
1094 contact.number = source;
1095 }
1096 contact.profileKey = Base64.encodeBytes(message.getProfileKey().get());
1097 }
1098 if (message.getPreviews().isPresent()) {
1099 final List<SignalServiceDataMessage.Preview> previews = message.getPreviews().get();
1100 for (SignalServiceDataMessage.Preview preview : previews) {
1101 if (preview.getImage().isPresent() && preview.getImage().get().isPointer()) {
1102 SignalServiceAttachmentPointer attachment = preview.getImage().get().asPointer();
1103 try {
1104 retrieveAttachment(attachment);
1105 } catch (IOException | InvalidMessageException e) {
1106 System.err.println("Failed to retrieve attachment (" + attachment.getId() + "): " + e.getMessage());
1107 }
1108 }
1109 }
1110 }
1111 }
1112
1113 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1114 final File cachePath = new File(getMessageCachePath());
1115 if (!cachePath.exists()) {
1116 return;
1117 }
1118 for (final File dir : Objects.requireNonNull(cachePath.listFiles())) {
1119 if (!dir.isDirectory()) {
1120 continue;
1121 }
1122
1123 for (final File fileEntry : Objects.requireNonNull(dir.listFiles())) {
1124 if (!fileEntry.isFile()) {
1125 continue;
1126 }
1127 SignalServiceEnvelope envelope;
1128 try {
1129 envelope = Utils.loadEnvelope(fileEntry);
1130 if (envelope == null) {
1131 continue;
1132 }
1133 } catch (IOException e) {
1134 e.printStackTrace();
1135 continue;
1136 }
1137 SignalServiceContent content = null;
1138 if (!envelope.isReceipt()) {
1139 try {
1140 content = decryptMessage(envelope);
1141 } catch (Exception e) {
1142 continue;
1143 }
1144 handleMessage(envelope, content, ignoreAttachments);
1145 }
1146 account.save();
1147 handler.handleMessage(envelope, content, null);
1148 try {
1149 Files.delete(fileEntry.toPath());
1150 } catch (IOException e) {
1151 System.err.println("Failed to delete cached message file “" + fileEntry + "”: " + e.getMessage());
1152 }
1153 }
1154 // Try to delete directory if empty
1155 dir.delete();
1156 }
1157 }
1158
1159 public void receiveMessages(long timeout, TimeUnit unit, boolean returnOnTimeout, boolean ignoreAttachments, ReceiveMessageHandler handler) throws IOException {
1160 retryFailedReceivedMessages(handler, ignoreAttachments);
1161 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1162
1163 try {
1164 if (messagePipe == null) {
1165 messagePipe = messageReceiver.createMessagePipe();
1166 }
1167
1168 while (true) {
1169 SignalServiceEnvelope envelope;
1170 SignalServiceContent content = null;
1171 Exception exception = null;
1172 final long now = new Date().getTime();
1173 try {
1174 envelope = messagePipe.read(timeout, unit, new SignalServiceMessagePipe.MessagePipeCallback() {
1175 @Override
1176 public void onMessage(SignalServiceEnvelope envelope) {
1177 // store message on disk, before acknowledging receipt to the server
1178 try {
1179 File cacheFile = getMessageCacheFile(envelope.getSourceE164().get(), now, envelope.getTimestamp());
1180 Utils.storeEnvelope(envelope, cacheFile);
1181 } catch (IOException e) {
1182 System.err.println("Failed to store encrypted message in disk cache, ignoring: " + e.getMessage());
1183 }
1184 }
1185 });
1186 } catch (TimeoutException e) {
1187 if (returnOnTimeout)
1188 return;
1189 continue;
1190 } catch (InvalidVersionException e) {
1191 System.err.println("Ignoring error: " + e.getMessage());
1192 continue;
1193 }
1194 if (!envelope.isReceipt()) {
1195 try {
1196 content = decryptMessage(envelope);
1197 } catch (Exception e) {
1198 exception = e;
1199 }
1200 handleMessage(envelope, content, ignoreAttachments);
1201 }
1202 account.save();
1203 if (!isMessageBlocked(envelope, content)) {
1204 handler.handleMessage(envelope, content, exception);
1205 }
1206 if (!(exception instanceof ProtocolUntrustedIdentityException)) {
1207 File cacheFile = null;
1208 try {
1209 cacheFile = getMessageCacheFile(envelope.getSourceE164().get(), now, envelope.getTimestamp());
1210 Files.delete(cacheFile.toPath());
1211 // Try to delete directory if empty
1212 new File(getMessageCachePath()).delete();
1213 } catch (IOException e) {
1214 System.err.println("Failed to delete cached message file “" + cacheFile + "”: " + e.getMessage());
1215 }
1216 }
1217 }
1218 } finally {
1219 if (messagePipe != null) {
1220 messagePipe.shutdown();
1221 messagePipe = null;
1222 }
1223 }
1224 }
1225
1226 private boolean isMessageBlocked(SignalServiceEnvelope envelope, SignalServiceContent content) {
1227 SignalServiceAddress source;
1228 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1229 source = envelope.getSourceAddress();
1230 } else if (content != null) {
1231 source = content.getSender();
1232 } else {
1233 return false;
1234 }
1235 ContactInfo sourceContact = getContact(source.getNumber().get());
1236 if (sourceContact != null && sourceContact.blocked) {
1237 return true;
1238 }
1239
1240 if (content != null && content.getDataMessage().isPresent()) {
1241 SignalServiceDataMessage message = content.getDataMessage().get();
1242 if (message.getGroupInfo().isPresent()) {
1243 SignalServiceGroup groupInfo = message.getGroupInfo().get();
1244 GroupInfo group = getGroup(groupInfo.getGroupId());
1245 if (groupInfo.getType() == SignalServiceGroup.Type.DELIVER && group != null && group.blocked) {
1246 return true;
1247 }
1248 }
1249 }
1250 return false;
1251 }
1252
1253 private void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments) {
1254 if (content != null) {
1255 SignalServiceAddress sender;
1256 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1257 sender = envelope.getSourceAddress();
1258 } else {
1259 sender = content.getSender();
1260 }
1261 if (content.getDataMessage().isPresent()) {
1262 SignalServiceDataMessage message = content.getDataMessage().get();
1263 handleSignalServiceDataMessage(message, false, sender.getNumber().get(), getSelfAddress(), ignoreAttachments);
1264 }
1265 if (content.getSyncMessage().isPresent()) {
1266 account.setMultiDevice(true);
1267 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
1268 if (syncMessage.getSent().isPresent()) {
1269 SentTranscriptMessage message = syncMessage.getSent().get();
1270 handleSignalServiceDataMessage(message.getMessage(), true, sender.getNumber().get(), message.getDestination().orNull(), ignoreAttachments);
1271 }
1272 if (syncMessage.getRequest().isPresent()) {
1273 RequestMessage rm = syncMessage.getRequest().get();
1274 if (rm.isContactsRequest()) {
1275 try {
1276 sendContacts();
1277 } catch (UntrustedIdentityException | IOException e) {
1278 e.printStackTrace();
1279 }
1280 }
1281 if (rm.isGroupsRequest()) {
1282 try {
1283 sendGroups();
1284 } catch (UntrustedIdentityException | IOException e) {
1285 e.printStackTrace();
1286 }
1287 }
1288 if (rm.isBlockedListRequest()) {
1289 try {
1290 sendBlockedList();
1291 } catch (UntrustedIdentityException | IOException e) {
1292 e.printStackTrace();
1293 }
1294 }
1295 // TODO Handle rm.isConfigurationRequest();
1296 }
1297 if (syncMessage.getGroups().isPresent()) {
1298 File tmpFile = null;
1299 try {
1300 tmpFile = IOUtils.createTempFile();
1301 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(syncMessage.getGroups().get().asPointer(), tmpFile)) {
1302 DeviceGroupsInputStream s = new DeviceGroupsInputStream(attachmentAsStream);
1303 DeviceGroup g;
1304 while ((g = s.read()) != null) {
1305 GroupInfo syncGroup = account.getGroupStore().getGroup(g.getId());
1306 if (syncGroup == null) {
1307 syncGroup = new GroupInfo(g.getId());
1308 }
1309 if (g.getName().isPresent()) {
1310 syncGroup.name = g.getName().get();
1311 }
1312 syncGroup.addMembers(g.getMembers());
1313 syncGroup.active = g.isActive();
1314 syncGroup.blocked = g.isBlocked();
1315 if (g.getColor().isPresent()) {
1316 syncGroup.color = g.getColor().get();
1317 }
1318
1319 if (g.getAvatar().isPresent()) {
1320 retrieveGroupAvatarAttachment(g.getAvatar().get(), syncGroup.groupId);
1321 }
1322 account.getGroupStore().updateGroup(syncGroup);
1323 }
1324 }
1325 } catch (Exception e) {
1326 e.printStackTrace();
1327 } finally {
1328 if (tmpFile != null) {
1329 try {
1330 Files.delete(tmpFile.toPath());
1331 } catch (IOException e) {
1332 System.err.println("Failed to delete received groups temp file “" + tmpFile + "”: " + e.getMessage());
1333 }
1334 }
1335 }
1336 }
1337 if (syncMessage.getBlockedList().isPresent()) {
1338 final BlockedListMessage blockedListMessage = syncMessage.getBlockedList().get();
1339 for (SignalServiceAddress address : blockedListMessage.getAddresses()) {
1340 if (address.getNumber().isPresent()) {
1341 try {
1342 setContactBlocked(address.getNumber().get(), true);
1343 } catch (InvalidNumberException e) {
1344 e.printStackTrace();
1345 }
1346 }
1347 }
1348 for (byte[] groupId : blockedListMessage.getGroupIds()) {
1349 try {
1350 setGroupBlocked(groupId, true);
1351 } catch (GroupNotFoundException e) {
1352 System.err.println("BlockedListMessage contained groupID that was not found in GroupStore: " + Base64.encodeBytes(groupId));
1353 }
1354 }
1355 }
1356 if (syncMessage.getContacts().isPresent()) {
1357 File tmpFile = null;
1358 try {
1359 tmpFile = IOUtils.createTempFile();
1360 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
1361 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream().asPointer(), tmpFile)) {
1362 DeviceContactsInputStream s = new DeviceContactsInputStream(attachmentAsStream);
1363 if (contactsMessage.isComplete()) {
1364 account.getContactStore().clear();
1365 }
1366 DeviceContact c;
1367 while ((c = s.read()) != null) {
1368 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
1369 account.setProfileKey(c.getProfileKey().get());
1370 }
1371 ContactInfo contact = account.getContactStore().getContact(c.getAddress().getNumber().get());
1372 if (contact == null) {
1373 contact = new ContactInfo();
1374 contact.number = c.getAddress().getNumber().get();
1375 }
1376 if (c.getName().isPresent()) {
1377 contact.name = c.getName().get();
1378 }
1379 if (c.getColor().isPresent()) {
1380 contact.color = c.getColor().get();
1381 }
1382 if (c.getProfileKey().isPresent()) {
1383 contact.profileKey = Base64.encodeBytes(c.getProfileKey().get());
1384 }
1385 if (c.getVerified().isPresent()) {
1386 final VerifiedMessage verifiedMessage = c.getVerified().get();
1387 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination().getNumber().get(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1388 }
1389 if (c.getExpirationTimer().isPresent()) {
1390 ThreadInfo thread = account.getThreadStore().getThread(c.getAddress().getNumber().get());
1391 if (thread == null) {
1392 thread = new ThreadInfo();
1393 thread.id = c.getAddress().getNumber().get();
1394 }
1395 thread.messageExpirationTime = c.getExpirationTimer().get();
1396 account.getThreadStore().updateThread(thread);
1397 }
1398 contact.blocked = c.isBlocked();
1399 account.getContactStore().updateContact(contact);
1400
1401 if (c.getAvatar().isPresent()) {
1402 retrieveContactAvatarAttachment(c.getAvatar().get(), contact.number);
1403 }
1404 }
1405 }
1406 } catch (Exception e) {
1407 e.printStackTrace();
1408 } finally {
1409 if (tmpFile != null) {
1410 try {
1411 Files.delete(tmpFile.toPath());
1412 } catch (IOException e) {
1413 System.err.println("Failed to delete received contacts temp file “" + tmpFile + "”: " + e.getMessage());
1414 }
1415 }
1416 }
1417 }
1418 if (syncMessage.getVerified().isPresent()) {
1419 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1420 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination().getNumber().get(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1421 }
1422 if (syncMessage.getConfiguration().isPresent()) {
1423 // TODO
1424 }
1425 }
1426 }
1427 }
1428
1429 private File getContactAvatarFile(String number) {
1430 return new File(avatarsPath, "contact-" + number);
1431 }
1432
1433 private File retrieveContactAvatarAttachment(SignalServiceAttachment attachment, String number) throws IOException, InvalidMessageException {
1434 IOUtils.createPrivateDirectories(avatarsPath);
1435 if (attachment.isPointer()) {
1436 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1437 return retrieveAttachment(pointer, getContactAvatarFile(number), false);
1438 } else {
1439 SignalServiceAttachmentStream stream = attachment.asStream();
1440 return Utils.retrieveAttachment(stream, getContactAvatarFile(number));
1441 }
1442 }
1443
1444 private File getGroupAvatarFile(byte[] groupId) {
1445 return new File(avatarsPath, "group-" + Base64.encodeBytes(groupId).replace("/", "_"));
1446 }
1447
1448 private File retrieveGroupAvatarAttachment(SignalServiceAttachment attachment, byte[] groupId) throws IOException, InvalidMessageException {
1449 IOUtils.createPrivateDirectories(avatarsPath);
1450 if (attachment.isPointer()) {
1451 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1452 return retrieveAttachment(pointer, getGroupAvatarFile(groupId), false);
1453 } else {
1454 SignalServiceAttachmentStream stream = attachment.asStream();
1455 return Utils.retrieveAttachment(stream, getGroupAvatarFile(groupId));
1456 }
1457 }
1458
1459 public File getAttachmentFile(long attachmentId) {
1460 return new File(attachmentsPath, attachmentId + "");
1461 }
1462
1463 private File retrieveAttachment(SignalServiceAttachmentPointer pointer) throws IOException, InvalidMessageException {
1464 IOUtils.createPrivateDirectories(attachmentsPath);
1465 return retrieveAttachment(pointer, getAttachmentFile(pointer.getId()), true);
1466 }
1467
1468 private File retrieveAttachment(SignalServiceAttachmentPointer pointer, File outputFile, boolean storePreview) throws IOException, InvalidMessageException {
1469 if (storePreview && pointer.getPreview().isPresent()) {
1470 File previewFile = new File(outputFile + ".preview");
1471 try (OutputStream output = new FileOutputStream(previewFile)) {
1472 byte[] preview = pointer.getPreview().get();
1473 output.write(preview, 0, preview.length);
1474 } catch (FileNotFoundException e) {
1475 e.printStackTrace();
1476 return null;
1477 }
1478 }
1479
1480 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1481
1482 File tmpFile = IOUtils.createTempFile();
1483 try (InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE)) {
1484 try (OutputStream output = new FileOutputStream(outputFile)) {
1485 byte[] buffer = new byte[4096];
1486 int read;
1487
1488 while ((read = input.read(buffer)) != -1) {
1489 output.write(buffer, 0, read);
1490 }
1491 } catch (FileNotFoundException e) {
1492 e.printStackTrace();
1493 return null;
1494 }
1495 } finally {
1496 try {
1497 Files.delete(tmpFile.toPath());
1498 } catch (IOException e) {
1499 System.err.println("Failed to delete received attachment temp file “" + tmpFile + "”: " + e.getMessage());
1500 }
1501 }
1502 return outputFile;
1503 }
1504
1505 private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer, File tmpFile) throws IOException, InvalidMessageException {
1506 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1507 return messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE);
1508 }
1509
1510 @Override
1511 public boolean isRemote() {
1512 return false;
1513 }
1514
1515 private void sendGroups() throws IOException, UntrustedIdentityException {
1516 File groupsFile = IOUtils.createTempFile();
1517
1518 try {
1519 try (OutputStream fos = new FileOutputStream(groupsFile)) {
1520 DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(fos);
1521 for (GroupInfo record : account.getGroupStore().getGroups()) {
1522 ThreadInfo info = account.getThreadStore().getThread(Base64.encodeBytes(record.groupId));
1523 out.write(new DeviceGroup(record.groupId, Optional.fromNullable(record.name),
1524 new ArrayList<>(record.getMembers()), createGroupAvatarAttachment(record.groupId),
1525 record.active, Optional.fromNullable(info != null ? info.messageExpirationTime : null),
1526 Optional.fromNullable(record.color), record.blocked));
1527 }
1528 }
1529
1530 if (groupsFile.exists() && groupsFile.length() > 0) {
1531 try (FileInputStream groupsFileStream = new FileInputStream(groupsFile)) {
1532 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1533 .withStream(groupsFileStream)
1534 .withContentType("application/octet-stream")
1535 .withLength(groupsFile.length())
1536 .build();
1537
1538 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
1539 }
1540 }
1541 } finally {
1542 try {
1543 Files.delete(groupsFile.toPath());
1544 } catch (IOException e) {
1545 System.err.println("Failed to delete groups temp file “" + groupsFile + "”: " + e.getMessage());
1546 }
1547 }
1548 }
1549
1550 public void sendContacts() throws IOException, UntrustedIdentityException {
1551 File contactsFile = IOUtils.createTempFile();
1552
1553 try {
1554 try (OutputStream fos = new FileOutputStream(contactsFile)) {
1555 DeviceContactsOutputStream out = new DeviceContactsOutputStream(fos);
1556 for (ContactInfo record : account.getContactStore().getContacts()) {
1557 VerifiedMessage verifiedMessage = null;
1558 ThreadInfo info = account.getThreadStore().getThread(record.number);
1559 if (getIdentities().containsKey(record.number)) {
1560 JsonIdentityKeyStore.Identity currentIdentity = null;
1561 for (JsonIdentityKeyStore.Identity id : getIdentities().get(record.number)) {
1562 if (currentIdentity == null || id.getDateAdded().after(currentIdentity.getDateAdded())) {
1563 currentIdentity = id;
1564 }
1565 }
1566 if (currentIdentity != null) {
1567 verifiedMessage = new VerifiedMessage(record.getAddress(), currentIdentity.getIdentityKey(), currentIdentity.getTrustLevel().toVerifiedState(), currentIdentity.getDateAdded().getTime());
1568 }
1569 }
1570
1571 byte[] profileKey = record.profileKey == null ? null : Base64.decode(record.profileKey);
1572 out.write(new DeviceContact(record.getAddress(), Optional.fromNullable(record.name),
1573 createContactAvatarAttachment(record.number), Optional.fromNullable(record.color),
1574 Optional.fromNullable(verifiedMessage), Optional.fromNullable(profileKey), record.blocked,
1575 Optional.fromNullable(info != null ? info.messageExpirationTime : null)));
1576 }
1577
1578 if (account.getProfileKey() != null) {
1579 // Send our own profile key as well
1580 out.write(new DeviceContact(account.getSelfAddress(),
1581 Optional.<String>absent(), Optional.<SignalServiceAttachmentStream>absent(),
1582 Optional.<String>absent(), Optional.<VerifiedMessage>absent(),
1583 Optional.of(account.getProfileKey()),
1584 false, Optional.<Integer>absent()));
1585 }
1586 }
1587
1588 if (contactsFile.exists() && contactsFile.length() > 0) {
1589 try (FileInputStream contactsFileStream = new FileInputStream(contactsFile)) {
1590 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1591 .withStream(contactsFileStream)
1592 .withContentType("application/octet-stream")
1593 .withLength(contactsFile.length())
1594 .build();
1595
1596 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
1597 }
1598 }
1599 } finally {
1600 try {
1601 Files.delete(contactsFile.toPath());
1602 } catch (IOException e) {
1603 System.err.println("Failed to delete contacts temp file “" + contactsFile + "”: " + e.getMessage());
1604 }
1605 }
1606 }
1607
1608 private void sendBlockedList() throws IOException, UntrustedIdentityException {
1609 List<SignalServiceAddress> addresses = new ArrayList<>();
1610 for (ContactInfo record : account.getContactStore().getContacts()) {
1611 if (record.blocked) {
1612 addresses.add(record.getAddress());
1613 }
1614 }
1615 List<byte[]> groupIds = new ArrayList<>();
1616 for (GroupInfo record : account.getGroupStore().getGroups()) {
1617 if (record.blocked) {
1618 groupIds.add(record.groupId);
1619 }
1620 }
1621 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
1622 }
1623
1624 private void sendVerifiedMessage(SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel) throws IOException, UntrustedIdentityException {
1625 VerifiedMessage verifiedMessage = new VerifiedMessage(destination, identityKey, trustLevel.toVerifiedState(), System.currentTimeMillis());
1626 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
1627 }
1628
1629 public List<ContactInfo> getContacts() {
1630 return account.getContactStore().getContacts();
1631 }
1632
1633 public ContactInfo getContact(String number) {
1634 return account.getContactStore().getContact(number);
1635 }
1636
1637 public GroupInfo getGroup(byte[] groupId) {
1638 return account.getGroupStore().getGroup(groupId);
1639 }
1640
1641 public Map<String, List<JsonIdentityKeyStore.Identity>> getIdentities() {
1642 return account.getSignalProtocolStore().getIdentities();
1643 }
1644
1645 public Pair<String, List<JsonIdentityKeyStore.Identity>> getIdentities(String number) throws InvalidNumberException {
1646 String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
1647 return new Pair<>(canonicalizedNumber, account.getSignalProtocolStore().getIdentities(canonicalizedNumber));
1648 }
1649
1650 /**
1651 * Trust this the identity with this fingerprint
1652 *
1653 * @param name username of the identity
1654 * @param fingerprint Fingerprint
1655 */
1656 public boolean trustIdentityVerified(String name, byte[] fingerprint) {
1657 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1658 if (ids == null) {
1659 return false;
1660 }
1661 for (JsonIdentityKeyStore.Identity id : ids) {
1662 if (!Arrays.equals(id.getIdentityKey().serialize(), fingerprint)) {
1663 continue;
1664 }
1665
1666 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1667 try {
1668 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1669 } catch (IOException | UntrustedIdentityException e) {
1670 e.printStackTrace();
1671 }
1672 account.save();
1673 return true;
1674 }
1675 return false;
1676 }
1677
1678 /**
1679 * Trust this the identity with this safety number
1680 *
1681 * @param name username of the identity
1682 * @param safetyNumber Safety number
1683 */
1684 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) {
1685 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1686 if (ids == null) {
1687 return false;
1688 }
1689 for (JsonIdentityKeyStore.Identity id : ids) {
1690 if (!safetyNumber.equals(computeSafetyNumber(name, id.getIdentityKey()))) {
1691 continue;
1692 }
1693
1694 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1695 try {
1696 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1697 } catch (IOException | UntrustedIdentityException e) {
1698 e.printStackTrace();
1699 }
1700 account.save();
1701 return true;
1702 }
1703 return false;
1704 }
1705
1706 /**
1707 * Trust all keys of this identity without verification
1708 *
1709 * @param name username of the identity
1710 */
1711 public boolean trustIdentityAllKeys(String name) {
1712 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1713 if (ids == null) {
1714 return false;
1715 }
1716 for (JsonIdentityKeyStore.Identity id : ids) {
1717 if (id.getTrustLevel() == TrustLevel.UNTRUSTED) {
1718 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1719 try {
1720 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1721 } catch (IOException | UntrustedIdentityException e) {
1722 e.printStackTrace();
1723 }
1724 }
1725 }
1726 account.save();
1727 return true;
1728 }
1729
1730 public String computeSafetyNumber(String theirUsername, IdentityKey theirIdentityKey) {
1731 return Utils.computeSafetyNumber(username, getIdentity(), theirUsername, theirIdentityKey);
1732 }
1733
1734 public interface ReceiveMessageHandler {
1735
1736 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
1737 }
1738 }