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