]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Output "SharedContacts" field from a SignalDataMessage (#529)
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / Manager.java
1 /*
2 Copyright (C) 2015-2021 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.manager.config.ServiceConfig;
20 import org.asamk.signal.manager.config.ServiceEnvironment;
21 import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
22 import org.asamk.signal.manager.groups.GroupId;
23 import org.asamk.signal.manager.groups.GroupIdV1;
24 import org.asamk.signal.manager.groups.GroupIdV2;
25 import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
26 import org.asamk.signal.manager.groups.GroupNotFoundException;
27 import org.asamk.signal.manager.groups.GroupUtils;
28 import org.asamk.signal.manager.groups.NotAGroupMemberException;
29 import org.asamk.signal.manager.helper.GroupHelper;
30 import org.asamk.signal.manager.helper.PinHelper;
31 import org.asamk.signal.manager.helper.ProfileHelper;
32 import org.asamk.signal.manager.helper.UnidentifiedAccessHelper;
33 import org.asamk.signal.manager.storage.SignalAccount;
34 import org.asamk.signal.manager.storage.contacts.ContactInfo;
35 import org.asamk.signal.manager.storage.groups.GroupInfo;
36 import org.asamk.signal.manager.storage.groups.GroupInfoV1;
37 import org.asamk.signal.manager.storage.groups.GroupInfoV2;
38 import org.asamk.signal.manager.storage.messageCache.CachedMessage;
39 import org.asamk.signal.manager.storage.profiles.SignalProfile;
40 import org.asamk.signal.manager.storage.profiles.SignalProfileEntry;
41 import org.asamk.signal.manager.storage.protocol.IdentityInfo;
42 import org.asamk.signal.manager.storage.stickers.Sticker;
43 import org.asamk.signal.manager.util.AttachmentUtils;
44 import org.asamk.signal.manager.util.IOUtils;
45 import org.asamk.signal.manager.util.KeyUtils;
46 import org.asamk.signal.manager.util.ProfileUtils;
47 import org.asamk.signal.manager.util.StickerUtils;
48 import org.asamk.signal.manager.util.Utils;
49 import org.signal.libsignal.metadata.InvalidMetadataMessageException;
50 import org.signal.libsignal.metadata.InvalidMetadataVersionException;
51 import org.signal.libsignal.metadata.ProtocolDuplicateMessageException;
52 import org.signal.libsignal.metadata.ProtocolInvalidKeyException;
53 import org.signal.libsignal.metadata.ProtocolInvalidKeyIdException;
54 import org.signal.libsignal.metadata.ProtocolInvalidMessageException;
55 import org.signal.libsignal.metadata.ProtocolInvalidVersionException;
56 import org.signal.libsignal.metadata.ProtocolLegacyMessageException;
57 import org.signal.libsignal.metadata.ProtocolNoSessionException;
58 import org.signal.libsignal.metadata.ProtocolUntrustedIdentityException;
59 import org.signal.libsignal.metadata.SelfSendException;
60 import org.signal.libsignal.metadata.certificate.CertificateValidator;
61 import org.signal.storageservice.protos.groups.GroupChange;
62 import org.signal.storageservice.protos.groups.local.DecryptedGroup;
63 import org.signal.storageservice.protos.groups.local.DecryptedGroupJoinInfo;
64 import org.signal.storageservice.protos.groups.local.DecryptedMember;
65 import org.signal.zkgroup.InvalidInputException;
66 import org.signal.zkgroup.VerificationFailedException;
67 import org.signal.zkgroup.auth.AuthCredentialResponse;
68 import org.signal.zkgroup.groups.GroupMasterKey;
69 import org.signal.zkgroup.groups.GroupSecretParams;
70 import org.signal.zkgroup.profiles.ClientZkProfileOperations;
71 import org.signal.zkgroup.profiles.ProfileKey;
72 import org.signal.zkgroup.profiles.ProfileKeyCredential;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75 import org.whispersystems.libsignal.IdentityKey;
76 import org.whispersystems.libsignal.IdentityKeyPair;
77 import org.whispersystems.libsignal.InvalidKeyException;
78 import org.whispersystems.libsignal.InvalidMessageException;
79 import org.whispersystems.libsignal.ecc.ECPublicKey;
80 import org.whispersystems.libsignal.state.PreKeyRecord;
81 import org.whispersystems.libsignal.state.SignedPreKeyRecord;
82 import org.whispersystems.libsignal.util.Pair;
83 import org.whispersystems.libsignal.util.guava.Optional;
84 import org.whispersystems.signalservice.api.KeyBackupService;
85 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
86 import org.whispersystems.signalservice.api.SignalServiceMessagePipe;
87 import org.whispersystems.signalservice.api.SignalServiceMessageReceiver;
88 import org.whispersystems.signalservice.api.SignalServiceMessageSender;
89 import org.whispersystems.signalservice.api.crypto.SignalServiceCipher;
90 import org.whispersystems.signalservice.api.crypto.UnidentifiedAccessPair;
91 import org.whispersystems.signalservice.api.crypto.UntrustedIdentityException;
92 import org.whispersystems.signalservice.api.groupsv2.ClientZkOperations;
93 import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
94 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Api;
95 import org.whispersystems.signalservice.api.groupsv2.GroupsV2AuthorizationString;
96 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
97 import org.whispersystems.signalservice.api.kbs.MasterKey;
98 import org.whispersystems.signalservice.api.messages.SendMessageResult;
99 import org.whispersystems.signalservice.api.messages.SignalServiceAttachment;
100 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentPointer;
101 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentRemoteId;
102 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentStream;
103 import org.whispersystems.signalservice.api.messages.SignalServiceContent;
104 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
105 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
106 import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
107 import org.whispersystems.signalservice.api.messages.SignalServiceGroupV2;
108 import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
109 import org.whispersystems.signalservice.api.messages.SignalServiceStickerManifestUpload;
110 import org.whispersystems.signalservice.api.messages.multidevice.BlockedListMessage;
111 import org.whispersystems.signalservice.api.messages.multidevice.ContactsMessage;
112 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContact;
113 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsInputStream;
114 import org.whispersystems.signalservice.api.messages.multidevice.DeviceContactsOutputStream;
115 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroup;
116 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroupsInputStream;
117 import org.whispersystems.signalservice.api.messages.multidevice.DeviceGroupsOutputStream;
118 import org.whispersystems.signalservice.api.messages.multidevice.DeviceInfo;
119 import org.whispersystems.signalservice.api.messages.multidevice.KeysMessage;
120 import org.whispersystems.signalservice.api.messages.multidevice.RequestMessage;
121 import org.whispersystems.signalservice.api.messages.multidevice.SentTranscriptMessage;
122 import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
123 import org.whispersystems.signalservice.api.messages.multidevice.StickerPackOperationMessage;
124 import org.whispersystems.signalservice.api.messages.multidevice.VerifiedMessage;
125 import org.whispersystems.signalservice.api.messages.shared.SharedContact;
126 import org.whispersystems.signalservice.api.profiles.ProfileAndCredential;
127 import org.whispersystems.signalservice.api.profiles.SignalServiceProfile;
128 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
129 import org.whispersystems.signalservice.api.push.exceptions.MissingConfigurationException;
130 import org.whispersystems.signalservice.api.storage.StorageKey;
131 import org.whispersystems.signalservice.api.util.InvalidNumberException;
132 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
133 import org.whispersystems.signalservice.api.util.SleepTimer;
134 import org.whispersystems.signalservice.api.util.StreamDetails;
135 import org.whispersystems.signalservice.api.util.UptimeSleepTimer;
136 import org.whispersystems.signalservice.api.util.UuidUtil;
137 import org.whispersystems.signalservice.internal.contacts.crypto.Quote;
138 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedQuoteException;
139 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedResponseException;
140 import org.whispersystems.signalservice.internal.push.SignalServiceProtos;
141 import org.whispersystems.signalservice.internal.push.UnsupportedDataMessageException;
142 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
143 import org.whispersystems.signalservice.internal.util.Hex;
144 import org.whispersystems.signalservice.internal.util.Util;
145
146 import java.io.Closeable;
147 import java.io.File;
148 import java.io.FileInputStream;
149 import java.io.FileOutputStream;
150 import java.io.IOException;
151 import java.io.InputStream;
152 import java.io.OutputStream;
153 import java.net.URI;
154 import java.net.URISyntaxException;
155 import java.net.URLEncoder;
156 import java.nio.charset.StandardCharsets;
157 import java.nio.file.Files;
158 import java.security.SignatureException;
159 import java.util.ArrayList;
160 import java.util.Arrays;
161 import java.util.Collection;
162 import java.util.Date;
163 import java.util.HashMap;
164 import java.util.HashSet;
165 import java.util.List;
166 import java.util.Map;
167 import java.util.Set;
168 import java.util.UUID;
169 import java.util.concurrent.ExecutorService;
170 import java.util.concurrent.Executors;
171 import java.util.concurrent.TimeUnit;
172 import java.util.concurrent.TimeoutException;
173 import java.util.stream.Collectors;
174
175 import static org.asamk.signal.manager.config.ServiceConfig.capabilities;
176
177 public class Manager implements Closeable {
178
179 private final static Logger logger = LoggerFactory.getLogger(Manager.class);
180
181 private final CertificateValidator certificateValidator;
182
183 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
184 private final String userAgent;
185
186 private SignalAccount account;
187 private final SignalServiceAccountManager accountManager;
188 private final GroupsV2Api groupsV2Api;
189 private final GroupsV2Operations groupsV2Operations;
190 private final SignalServiceMessageReceiver messageReceiver;
191 private final ClientZkProfileOperations clientZkProfileOperations;
192
193 private final ExecutorService executor = Executors.newCachedThreadPool();
194
195 private SignalServiceMessagePipe messagePipe = null;
196 private SignalServiceMessagePipe unidentifiedMessagePipe = null;
197
198 private final UnidentifiedAccessHelper unidentifiedAccessHelper;
199 private final ProfileHelper profileHelper;
200 private final GroupHelper groupHelper;
201 private final PinHelper pinHelper;
202 private final AvatarStore avatarStore;
203 private final AttachmentStore attachmentStore;
204
205 Manager(
206 SignalAccount account,
207 PathConfig pathConfig,
208 ServiceEnvironmentConfig serviceEnvironmentConfig,
209 String userAgent
210 ) {
211 this.account = account;
212 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
213 this.certificateValidator = new CertificateValidator(serviceEnvironmentConfig.getUnidentifiedSenderTrustRoot());
214 this.userAgent = userAgent;
215 this.groupsV2Operations = capabilities.isGv2() ? new GroupsV2Operations(ClientZkOperations.create(
216 serviceEnvironmentConfig.getSignalServiceConfiguration())) : null;
217 final SleepTimer timer = new UptimeSleepTimer();
218 this.accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.getSignalServiceConfiguration(),
219 new DynamicCredentialsProvider(account.getUuid(),
220 account.getUsername(),
221 account.getPassword(),
222 account.getDeviceId()),
223 userAgent,
224 groupsV2Operations,
225 ServiceConfig.AUTOMATIC_NETWORK_RETRY,
226 timer);
227 this.groupsV2Api = accountManager.getGroupsV2Api();
228 final KeyBackupService keyBackupService = accountManager.getKeyBackupService(ServiceConfig.getIasKeyStore(),
229 serviceEnvironmentConfig.getKeyBackupConfig().getEnclaveName(),
230 serviceEnvironmentConfig.getKeyBackupConfig().getServiceId(),
231 serviceEnvironmentConfig.getKeyBackupConfig().getMrenclave(),
232 10);
233
234 this.pinHelper = new PinHelper(keyBackupService);
235 this.clientZkProfileOperations = capabilities.isGv2()
236 ? ClientZkOperations.create(serviceEnvironmentConfig.getSignalServiceConfiguration())
237 .getProfileOperations()
238 : null;
239 this.messageReceiver = new SignalServiceMessageReceiver(serviceEnvironmentConfig.getSignalServiceConfiguration(),
240 account.getUuid(),
241 account.getUsername(),
242 account.getPassword(),
243 account.getDeviceId(),
244 userAgent,
245 null,
246 timer,
247 clientZkProfileOperations,
248 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
249
250 this.account.setResolver(this::resolveSignalServiceAddress);
251
252 this.unidentifiedAccessHelper = new UnidentifiedAccessHelper(account::getProfileKey,
253 account.getProfileStore()::getProfileKey,
254 this::getRecipientProfile,
255 this::getSenderCertificate);
256 this.profileHelper = new ProfileHelper(account.getProfileStore()::getProfileKey,
257 unidentifiedAccessHelper::getAccessFor,
258 unidentified -> unidentified ? getOrCreateUnidentifiedMessagePipe() : getOrCreateMessagePipe(),
259 () -> messageReceiver);
260 this.groupHelper = new GroupHelper(this::getRecipientProfileKeyCredential,
261 this::getRecipientProfile,
262 account::getSelfAddress,
263 groupsV2Operations,
264 groupsV2Api,
265 this::getGroupAuthForToday);
266 this.avatarStore = new AvatarStore(pathConfig.getAvatarsPath());
267 this.attachmentStore = new AttachmentStore(pathConfig.getAttachmentsPath());
268 }
269
270 public String getUsername() {
271 return account.getUsername();
272 }
273
274 public SignalServiceAddress getSelfAddress() {
275 return account.getSelfAddress();
276 }
277
278 private IdentityKeyPair getIdentityKeyPair() {
279 return account.getSignalProtocolStore().getIdentityKeyPair();
280 }
281
282 public int getDeviceId() {
283 return account.getDeviceId();
284 }
285
286 public static Manager init(
287 String username, File settingsPath, ServiceEnvironment serviceEnvironment, String userAgent
288 ) throws IOException, NotRegisteredException {
289 PathConfig pathConfig = PathConfig.createDefault(settingsPath);
290
291 if (!SignalAccount.userExists(pathConfig.getDataPath(), username)) {
292 throw new NotRegisteredException();
293 }
294
295 SignalAccount account = SignalAccount.load(pathConfig.getDataPath(), username);
296
297 if (!account.isRegistered()) {
298 throw new NotRegisteredException();
299 }
300
301 final ServiceEnvironmentConfig serviceEnvironmentConfig = ServiceConfig.getServiceEnvironmentConfig(
302 serviceEnvironment,
303 userAgent);
304
305 return new Manager(account, pathConfig, serviceEnvironmentConfig, userAgent);
306 }
307
308 public static List<String> getAllLocalUsernames(File settingsPath) {
309 PathConfig pathConfig = PathConfig.createDefault(settingsPath);
310 final File dataPath = pathConfig.getDataPath();
311 final File[] files = dataPath.listFiles();
312
313 if (files == null) {
314 return List.of();
315 }
316
317 return Arrays.stream(files)
318 .filter(File::isFile)
319 .map(File::getName)
320 .filter(file -> PhoneNumberFormatter.isValidNumber(file, null))
321 .collect(Collectors.toList());
322 }
323
324 public void checkAccountState() throws IOException {
325 if (accountManager.getPreKeysCount() < ServiceConfig.PREKEY_MINIMUM_COUNT) {
326 refreshPreKeys();
327 account.save();
328 }
329 if (account.getUuid() == null) {
330 account.setUuid(accountManager.getOwnUuid());
331 account.save();
332 }
333 updateAccountAttributes();
334 }
335
336 /**
337 * This is used for checking a set of phone numbers for registration on Signal
338 *
339 * @param numbers The set of phone number in question
340 * @return A map of numbers to booleans. True if registered, false otherwise. Should never be null
341 * @throws IOException if its unable to get the contacts to check if they're registered
342 */
343 public Map<String, Boolean> areUsersRegistered(Set<String> numbers) throws IOException {
344 // Note "contactDetails" has no optionals. It only gives us info on users who are registered
345 Map<String, UUID> contactDetails = getRegisteredUsers(numbers);
346
347 Set<String> registeredUsers = contactDetails.keySet();
348
349 return numbers.stream().collect(Collectors.toMap(x -> x, registeredUsers::contains));
350 }
351
352 public void updateAccountAttributes() throws IOException {
353 accountManager.setAccountAttributes(null,
354 account.getSignalProtocolStore().getLocalRegistrationId(),
355 true,
356 // set legacy pin only if no KBS master key is set
357 account.getPinMasterKey() == null ? account.getRegistrationLockPin() : null,
358 account.getPinMasterKey() == null ? null : account.getPinMasterKey().deriveRegistrationLock(),
359 account.getSelfUnidentifiedAccessKey(),
360 account.isUnrestrictedUnidentifiedAccess(),
361 capabilities,
362 account.isDiscoverableByPhoneNumber());
363 }
364
365 /**
366 * @param name if null, the previous name will be kept
367 * @param about if null, the previous about text will be kept
368 * @param aboutEmoji if null, the previous about emoji will be kept
369 * @param avatar if avatar is null the image from the local avatar store is used (if present),
370 * if it's Optional.absent(), the avatar will be removed
371 */
372 public void setProfile(String name, String about, String aboutEmoji, Optional<File> avatar) throws IOException {
373 SignalProfileEntry profileEntry = account.getProfileStore().getProfileEntry(getSelfAddress());
374 SignalProfile profile = profileEntry == null ? null : profileEntry.getProfile();
375 SignalProfile newProfile = new SignalProfile(profile == null ? null : profile.getIdentityKey(),
376 name != null ? name : profile == null || profile.getName() == null ? "" : profile.getName(),
377 about != null ? about : profile == null || profile.getAbout() == null ? "" : profile.getAbout(),
378 aboutEmoji != null
379 ? aboutEmoji
380 : profile == null || profile.getAboutEmoji() == null ? "" : profile.getAboutEmoji(),
381 profile == null ? null : profile.getUnidentifiedAccess(),
382 account.isUnrestrictedUnidentifiedAccess(),
383 profile == null ? null : profile.getCapabilities());
384
385 try (final StreamDetails streamDetails = avatar == null
386 ? avatarStore.retrieveProfileAvatar(getSelfAddress())
387 : avatar.isPresent() ? Utils.createStreamDetailsFromFile(avatar.get()) : null) {
388 accountManager.setVersionedProfile(account.getUuid(),
389 account.getProfileKey(),
390 newProfile.getName(),
391 newProfile.getAbout(),
392 newProfile.getAboutEmoji(),
393 streamDetails);
394 }
395
396 if (avatar != null) {
397 if (avatar.isPresent()) {
398 avatarStore.storeProfileAvatar(getSelfAddress(),
399 outputStream -> IOUtils.copyFileToStream(avatar.get(), outputStream));
400 } else {
401 avatarStore.deleteProfileAvatar(getSelfAddress());
402 }
403 }
404 account.getProfileStore()
405 .updateProfile(getSelfAddress(),
406 account.getProfileKey(),
407 System.currentTimeMillis(),
408 newProfile,
409 profileEntry == null ? null : profileEntry.getProfileKeyCredential());
410
411 try {
412 sendSyncMessage(SignalServiceSyncMessage.forFetchLatest(SignalServiceSyncMessage.FetchType.LOCAL_PROFILE));
413 } catch (UntrustedIdentityException ignored) {
414 }
415 }
416
417 public void unregister() throws IOException {
418 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
419 // If this is the master device, other users can't send messages to this number anymore.
420 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
421 accountManager.setGcmId(Optional.absent());
422 accountManager.deleteAccount();
423
424 account.setRegistered(false);
425 account.save();
426 }
427
428 public List<DeviceInfo> getLinkedDevices() throws IOException {
429 List<DeviceInfo> devices = accountManager.getDevices();
430 account.setMultiDevice(devices.size() > 1);
431 account.save();
432 return devices;
433 }
434
435 public void removeLinkedDevices(int deviceId) throws IOException {
436 accountManager.removeDevice(deviceId);
437 List<DeviceInfo> devices = accountManager.getDevices();
438 account.setMultiDevice(devices.size() > 1);
439 account.save();
440 }
441
442 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
443 DeviceLinkInfo info = DeviceLinkInfo.parseDeviceLinkUri(linkUri);
444
445 addDevice(info.deviceIdentifier, info.deviceKey);
446 }
447
448 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
449 IdentityKeyPair identityKeyPair = getIdentityKeyPair();
450 String verificationCode = accountManager.getNewDeviceVerificationCode();
451
452 accountManager.addDevice(deviceIdentifier,
453 deviceKey,
454 identityKeyPair,
455 Optional.of(account.getProfileKey().serialize()),
456 verificationCode);
457 account.setMultiDevice(true);
458 account.save();
459 }
460
461 public void setRegistrationLockPin(Optional<String> pin) throws IOException, UnauthenticatedResponseException {
462 if (!account.isMasterDevice()) {
463 throw new RuntimeException("Only master device can set a PIN");
464 }
465 if (pin.isPresent()) {
466 final MasterKey masterKey = account.getPinMasterKey() != null
467 ? account.getPinMasterKey()
468 : KeyUtils.createMasterKey();
469
470 pinHelper.setRegistrationLockPin(pin.get(), masterKey);
471
472 account.setRegistrationLockPin(pin.get());
473 account.setPinMasterKey(masterKey);
474 } else {
475 // Remove legacy registration lock
476 accountManager.removeRegistrationLockV1();
477
478 // Remove KBS Pin
479 pinHelper.removeRegistrationLockPin();
480
481 account.setRegistrationLockPin(null);
482 account.setPinMasterKey(null);
483 }
484 account.save();
485 }
486
487 void refreshPreKeys() throws IOException {
488 List<PreKeyRecord> oneTimePreKeys = generatePreKeys();
489 final IdentityKeyPair identityKeyPair = getIdentityKeyPair();
490 SignedPreKeyRecord signedPreKeyRecord = generateSignedPreKey(identityKeyPair);
491
492 accountManager.setPreKeys(identityKeyPair.getPublicKey(), signedPreKeyRecord, oneTimePreKeys);
493 }
494
495 private List<PreKeyRecord> generatePreKeys() {
496 final int offset = account.getPreKeyIdOffset();
497
498 List<PreKeyRecord> records = KeyUtils.generatePreKeyRecords(offset, ServiceConfig.PREKEY_BATCH_SIZE);
499 account.addPreKeys(records);
500 account.save();
501
502 return records;
503 }
504
505 private SignedPreKeyRecord generateSignedPreKey(IdentityKeyPair identityKeyPair) {
506 final int signedPreKeyId = account.getNextSignedPreKeyId();
507
508 SignedPreKeyRecord record = KeyUtils.generateSignedPreKeyRecord(identityKeyPair, signedPreKeyId);
509 account.addSignedPreKey(record);
510 account.save();
511
512 return record;
513 }
514
515 private SignalServiceMessagePipe getOrCreateMessagePipe() {
516 if (messagePipe == null) {
517 messagePipe = messageReceiver.createMessagePipe();
518 }
519 return messagePipe;
520 }
521
522 private SignalServiceMessagePipe getOrCreateUnidentifiedMessagePipe() {
523 if (unidentifiedMessagePipe == null) {
524 unidentifiedMessagePipe = messageReceiver.createUnidentifiedMessagePipe();
525 }
526 return unidentifiedMessagePipe;
527 }
528
529 private SignalServiceMessageSender createMessageSender() {
530 return new SignalServiceMessageSender(serviceEnvironmentConfig.getSignalServiceConfiguration(),
531 account.getUuid(),
532 account.getUsername(),
533 account.getPassword(),
534 account.getDeviceId(),
535 account.getSignalProtocolStore(),
536 userAgent,
537 account.isMultiDevice(),
538 Optional.fromNullable(messagePipe),
539 Optional.fromNullable(unidentifiedMessagePipe),
540 Optional.absent(),
541 clientZkProfileOperations,
542 executor,
543 ServiceConfig.MAX_ENVELOPE_SIZE,
544 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
545 }
546
547 private SignalProfile getRecipientProfile(
548 SignalServiceAddress address
549 ) {
550 return getRecipientProfile(address, false);
551 }
552
553 private SignalProfile getRecipientProfile(
554 SignalServiceAddress address, boolean force
555 ) {
556 SignalProfileEntry profileEntry = account.getProfileStore().getProfileEntry(address);
557 if (profileEntry == null) {
558 return null;
559 }
560 long now = new Date().getTime();
561 // Profiles are cached for 24h before retrieving them again
562 if (!profileEntry.isRequestPending() && (
563 force
564 || profileEntry.getProfile() == null
565 || now - profileEntry.getLastUpdateTimestamp() > 24 * 60 * 60 * 1000
566 )) {
567 profileEntry.setRequestPending(true);
568 final SignalServiceProfile encryptedProfile;
569 try {
570 encryptedProfile = profileHelper.retrieveProfileSync(address, SignalServiceProfile.RequestType.PROFILE)
571 .getProfile();
572 } catch (IOException e) {
573 logger.warn("Failed to retrieve profile, ignoring: {}", e.getMessage());
574 return null;
575 } finally {
576 profileEntry.setRequestPending(false);
577 }
578
579 final ProfileKey profileKey = profileEntry.getProfileKey();
580 final SignalProfile profile = decryptProfileAndDownloadAvatar(address, profileKey, encryptedProfile);
581 account.getProfileStore()
582 .updateProfile(address, profileKey, now, profile, profileEntry.getProfileKeyCredential());
583 return profile;
584 }
585 return profileEntry.getProfile();
586 }
587
588 private ProfileKeyCredential getRecipientProfileKeyCredential(SignalServiceAddress address) {
589 SignalProfileEntry profileEntry = account.getProfileStore().getProfileEntry(address);
590 if (profileEntry == null) {
591 return null;
592 }
593 if (profileEntry.getProfileKeyCredential() == null) {
594 ProfileAndCredential profileAndCredential;
595 try {
596 profileAndCredential = profileHelper.retrieveProfileSync(address,
597 SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL);
598 } catch (IOException e) {
599 logger.warn("Failed to retrieve profile key credential, ignoring: {}", e.getMessage());
600 return null;
601 }
602
603 long now = new Date().getTime();
604 final ProfileKeyCredential profileKeyCredential = profileAndCredential.getProfileKeyCredential().orNull();
605 final SignalProfile profile = decryptProfileAndDownloadAvatar(address,
606 profileEntry.getProfileKey(),
607 profileAndCredential.getProfile());
608 account.getProfileStore()
609 .updateProfile(address, profileEntry.getProfileKey(), now, profile, profileKeyCredential);
610 return profileKeyCredential;
611 }
612 return profileEntry.getProfileKeyCredential();
613 }
614
615 private SignalProfile decryptProfileAndDownloadAvatar(
616 final SignalServiceAddress address, final ProfileKey profileKey, final SignalServiceProfile encryptedProfile
617 ) {
618 if (encryptedProfile.getAvatar() != null) {
619 downloadProfileAvatar(address, encryptedProfile.getAvatar(), profileKey);
620 }
621
622 return ProfileUtils.decryptProfile(profileKey, encryptedProfile);
623 }
624
625 private Optional<SignalServiceAttachmentStream> createGroupAvatarAttachment(GroupId groupId) throws IOException {
626 final StreamDetails streamDetails = avatarStore.retrieveGroupAvatar(groupId);
627 if (streamDetails == null) {
628 return Optional.absent();
629 }
630
631 return Optional.of(AttachmentUtils.createAttachment(streamDetails, Optional.absent()));
632 }
633
634 private Optional<SignalServiceAttachmentStream> createContactAvatarAttachment(SignalServiceAddress address) throws IOException {
635 final StreamDetails streamDetails = avatarStore.retrieveContactAvatar(address);
636 if (streamDetails == null) {
637 return Optional.absent();
638 }
639
640 return Optional.of(AttachmentUtils.createAttachment(streamDetails, Optional.absent()));
641 }
642
643 private GroupInfo getGroupForSending(GroupId groupId) throws GroupNotFoundException, NotAGroupMemberException {
644 GroupInfo g = getGroup(groupId);
645 if (g == null) {
646 throw new GroupNotFoundException(groupId);
647 }
648 if (!g.isMember(account.getSelfAddress())) {
649 throw new NotAGroupMemberException(groupId, g.getTitle());
650 }
651 return g;
652 }
653
654 private GroupInfo getGroupForUpdating(GroupId groupId) throws GroupNotFoundException, NotAGroupMemberException {
655 GroupInfo g = getGroup(groupId);
656 if (g == null) {
657 throw new GroupNotFoundException(groupId);
658 }
659 if (!g.isMember(account.getSelfAddress()) && !g.isPendingMember(account.getSelfAddress())) {
660 throw new NotAGroupMemberException(groupId, g.getTitle());
661 }
662 return g;
663 }
664
665 public List<GroupInfo> getGroups() {
666 return account.getGroupStore().getGroups();
667 }
668
669 public Pair<Long, List<SendMessageResult>> sendGroupMessage(
670 String messageText, List<String> attachments, GroupId groupId
671 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException {
672 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
673 .withBody(messageText);
674 if (attachments != null) {
675 messageBuilder.withAttachments(AttachmentUtils.getSignalServiceAttachments(attachments));
676 }
677
678 return sendGroupMessage(messageBuilder, groupId);
679 }
680
681 public Pair<Long, List<SendMessageResult>> sendGroupMessageReaction(
682 String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, GroupId groupId
683 ) throws IOException, InvalidNumberException, NotAGroupMemberException, GroupNotFoundException {
684 SignalServiceDataMessage.Reaction reaction = new SignalServiceDataMessage.Reaction(emoji,
685 remove,
686 canonicalizeAndResolveSignalServiceAddress(targetAuthor),
687 targetSentTimestamp);
688 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
689 .withReaction(reaction);
690
691 return sendGroupMessage(messageBuilder, groupId);
692 }
693
694 public Pair<Long, List<SendMessageResult>> sendGroupMessage(
695 SignalServiceDataMessage.Builder messageBuilder, GroupId groupId
696 ) throws IOException, GroupNotFoundException, NotAGroupMemberException {
697 final GroupInfo g = getGroupForSending(groupId);
698
699 GroupUtils.setGroupContext(messageBuilder, g);
700 messageBuilder.withExpiration(g.getMessageExpirationTime());
701
702 return sendMessage(messageBuilder, g.getMembersWithout(account.getSelfAddress()));
703 }
704
705 public Pair<Long, List<SendMessageResult>> sendQuitGroupMessage(GroupId groupId) throws GroupNotFoundException, IOException, NotAGroupMemberException {
706 SignalServiceDataMessage.Builder messageBuilder;
707
708 final GroupInfo g = getGroupForUpdating(groupId);
709 if (g instanceof GroupInfoV1) {
710 GroupInfoV1 groupInfoV1 = (GroupInfoV1) g;
711 SignalServiceGroup group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.QUIT)
712 .withId(groupId.serialize())
713 .build();
714 messageBuilder = SignalServiceDataMessage.newBuilder().asGroupMessage(group);
715 groupInfoV1.removeMember(account.getSelfAddress());
716 account.getGroupStore().updateGroup(groupInfoV1);
717 } else {
718 final GroupInfoV2 groupInfoV2 = (GroupInfoV2) g;
719 final Pair<DecryptedGroup, GroupChange> groupGroupChangePair = groupHelper.leaveGroup(groupInfoV2);
720 groupInfoV2.setGroup(groupGroupChangePair.first());
721 messageBuilder = getGroupUpdateMessageBuilder(groupInfoV2, groupGroupChangePair.second().toByteArray());
722 account.getGroupStore().updateGroup(groupInfoV2);
723 }
724
725 return sendMessage(messageBuilder, g.getMembersWithout(account.getSelfAddress()));
726 }
727
728 public Pair<GroupId, List<SendMessageResult>> updateGroup(
729 GroupId groupId, String name, List<String> members, File avatarFile
730 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, InvalidNumberException, NotAGroupMemberException {
731 return sendUpdateGroupMessage(groupId,
732 name,
733 members == null ? null : getSignalServiceAddresses(members),
734 avatarFile);
735 }
736
737 private Pair<GroupId, List<SendMessageResult>> sendUpdateGroupMessage(
738 GroupId groupId, String name, Collection<SignalServiceAddress> members, File avatarFile
739 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException {
740 GroupInfo g;
741 SignalServiceDataMessage.Builder messageBuilder;
742 if (groupId == null) {
743 // Create new group
744 GroupInfoV2 gv2 = groupHelper.createGroupV2(name == null ? "" : name,
745 members == null ? List.of() : members,
746 avatarFile);
747 if (gv2 == null) {
748 GroupInfoV1 gv1 = new GroupInfoV1(GroupIdV1.createRandom());
749 gv1.addMembers(List.of(account.getSelfAddress()));
750 updateGroupV1(gv1, name, members, avatarFile);
751 messageBuilder = getGroupUpdateMessageBuilder(gv1);
752 g = gv1;
753 } else {
754 if (avatarFile != null) {
755 avatarStore.storeGroupAvatar(gv2.getGroupId(),
756 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
757 }
758 messageBuilder = getGroupUpdateMessageBuilder(gv2, null);
759 g = gv2;
760 }
761 } else {
762 GroupInfo group = getGroupForUpdating(groupId);
763 if (group instanceof GroupInfoV2) {
764 final GroupInfoV2 groupInfoV2 = (GroupInfoV2) group;
765
766 Pair<Long, List<SendMessageResult>> result = null;
767 if (groupInfoV2.isPendingMember(getSelfAddress())) {
768 Pair<DecryptedGroup, GroupChange> groupGroupChangePair = groupHelper.acceptInvite(groupInfoV2);
769 result = sendUpdateGroupMessage(groupInfoV2,
770 groupGroupChangePair.first(),
771 groupGroupChangePair.second());
772 }
773
774 if (members != null) {
775 final Set<SignalServiceAddress> newMembers = new HashSet<>(members);
776 newMembers.removeAll(group.getMembers()
777 .stream()
778 .map(this::resolveSignalServiceAddress)
779 .collect(Collectors.toSet()));
780 if (newMembers.size() > 0) {
781 Pair<DecryptedGroup, GroupChange> groupGroupChangePair = groupHelper.updateGroupV2(groupInfoV2,
782 newMembers);
783 result = sendUpdateGroupMessage(groupInfoV2,
784 groupGroupChangePair.first(),
785 groupGroupChangePair.second());
786 }
787 }
788 if (result == null || name != null || avatarFile != null) {
789 Pair<DecryptedGroup, GroupChange> groupGroupChangePair = groupHelper.updateGroupV2(groupInfoV2,
790 name,
791 avatarFile);
792 if (avatarFile != null) {
793 avatarStore.storeGroupAvatar(groupInfoV2.getGroupId(),
794 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
795 }
796 result = sendUpdateGroupMessage(groupInfoV2,
797 groupGroupChangePair.first(),
798 groupGroupChangePair.second());
799 }
800
801 return new Pair<>(group.getGroupId(), result.second());
802 } else {
803 GroupInfoV1 gv1 = (GroupInfoV1) group;
804 updateGroupV1(gv1, name, members, avatarFile);
805 messageBuilder = getGroupUpdateMessageBuilder(gv1);
806 g = gv1;
807 }
808 }
809
810 account.getGroupStore().updateGroup(g);
811
812 final Pair<Long, List<SendMessageResult>> result = sendMessage(messageBuilder,
813 g.getMembersIncludingPendingWithout(account.getSelfAddress()));
814 return new Pair<>(g.getGroupId(), result.second());
815 }
816
817 private void updateGroupV1(
818 final GroupInfoV1 g,
819 final String name,
820 final Collection<SignalServiceAddress> members,
821 final File avatarFile
822 ) throws IOException {
823 if (name != null) {
824 g.name = name;
825 }
826
827 if (members != null) {
828 final Set<String> newE164Members = new HashSet<>();
829 for (SignalServiceAddress member : members) {
830 if (g.isMember(member) || !member.getNumber().isPresent()) {
831 continue;
832 }
833 newE164Members.add(member.getNumber().get());
834 }
835
836 final Map<String, UUID> registeredUsers = getRegisteredUsers(newE164Members);
837 if (registeredUsers.size() != newE164Members.size()) {
838 // Some of the new members are not registered on Signal
839 newE164Members.removeAll(registeredUsers.keySet());
840 throw new IOException("Failed to add members "
841 + String.join(", ", newE164Members)
842 + " to group: Not registered on Signal");
843 }
844
845 g.addMembers(members);
846 }
847
848 if (avatarFile != null) {
849 avatarStore.storeGroupAvatar(g.getGroupId(),
850 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
851 }
852 }
853
854 public Pair<GroupId, List<SendMessageResult>> joinGroup(
855 GroupInviteLinkUrl inviteLinkUrl
856 ) throws IOException, GroupLinkNotActiveException {
857 return sendJoinGroupMessage(inviteLinkUrl);
858 }
859
860 private Pair<GroupId, List<SendMessageResult>> sendJoinGroupMessage(
861 GroupInviteLinkUrl inviteLinkUrl
862 ) throws IOException, GroupLinkNotActiveException {
863 final DecryptedGroupJoinInfo groupJoinInfo = groupHelper.getDecryptedGroupJoinInfo(inviteLinkUrl.getGroupMasterKey(),
864 inviteLinkUrl.getPassword());
865 final GroupChange groupChange = groupHelper.joinGroup(inviteLinkUrl.getGroupMasterKey(),
866 inviteLinkUrl.getPassword(),
867 groupJoinInfo);
868 final GroupInfoV2 group = getOrMigrateGroup(inviteLinkUrl.getGroupMasterKey(),
869 groupJoinInfo.getRevision() + 1,
870 groupChange.toByteArray());
871
872 if (group.getGroup() == null) {
873 // Only requested member, can't send update to group members
874 return new Pair<>(group.getGroupId(), List.of());
875 }
876
877 final Pair<Long, List<SendMessageResult>> result = sendUpdateGroupMessage(group, group.getGroup(), groupChange);
878
879 return new Pair<>(group.getGroupId(), result.second());
880 }
881
882 private static int currentTimeDays() {
883 return (int) TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis());
884 }
885
886 private GroupsV2AuthorizationString getGroupAuthForToday(
887 final GroupSecretParams groupSecretParams
888 ) throws IOException {
889 final int today = currentTimeDays();
890 // Returns credentials for the next 7 days
891 final HashMap<Integer, AuthCredentialResponse> credentials = groupsV2Api.getCredentials(today);
892 // TODO cache credentials until they expire
893 AuthCredentialResponse authCredentialResponse = credentials.get(today);
894 try {
895 return groupsV2Api.getGroupsV2AuthorizationString(account.getUuid(),
896 today,
897 groupSecretParams,
898 authCredentialResponse);
899 } catch (VerificationFailedException e) {
900 throw new IOException(e);
901 }
902 }
903
904 private Pair<Long, List<SendMessageResult>> sendUpdateGroupMessage(
905 GroupInfoV2 group, DecryptedGroup newDecryptedGroup, GroupChange groupChange
906 ) throws IOException {
907 group.setGroup(newDecryptedGroup);
908 final SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(group,
909 groupChange.toByteArray());
910 account.getGroupStore().updateGroup(group);
911 return sendMessage(messageBuilder, group.getMembersIncludingPendingWithout(account.getSelfAddress()));
912 }
913
914 Pair<Long, List<SendMessageResult>> sendGroupInfoMessage(
915 GroupIdV1 groupId, SignalServiceAddress recipient
916 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, AttachmentInvalidException {
917 GroupInfoV1 g;
918 GroupInfo group = getGroupForSending(groupId);
919 if (!(group instanceof GroupInfoV1)) {
920 throw new RuntimeException("Received an invalid group request for a v2 group!");
921 }
922 g = (GroupInfoV1) group;
923
924 if (!g.isMember(recipient)) {
925 throw new NotAGroupMemberException(groupId, g.name);
926 }
927
928 SignalServiceDataMessage.Builder messageBuilder = getGroupUpdateMessageBuilder(g);
929
930 // Send group message only to the recipient who requested it
931 return sendMessage(messageBuilder, List.of(recipient));
932 }
933
934 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfoV1 g) throws AttachmentInvalidException {
935 SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.UPDATE)
936 .withId(g.getGroupId().serialize())
937 .withName(g.name)
938 .withMembers(new ArrayList<>(g.getMembers()));
939
940 try {
941 final Optional<SignalServiceAttachmentStream> attachment = createGroupAvatarAttachment(g.getGroupId());
942 if (attachment.isPresent()) {
943 group.withAvatar(attachment.get());
944 }
945 } catch (IOException e) {
946 throw new AttachmentInvalidException(g.getGroupId().toBase64(), e);
947 }
948
949 return SignalServiceDataMessage.newBuilder()
950 .asGroupMessage(group.build())
951 .withExpiration(g.getMessageExpirationTime());
952 }
953
954 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfoV2 g, byte[] signedGroupChange) {
955 SignalServiceGroupV2.Builder group = SignalServiceGroupV2.newBuilder(g.getMasterKey())
956 .withRevision(g.getGroup().getRevision())
957 .withSignedGroupChange(signedGroupChange);
958 return SignalServiceDataMessage.newBuilder()
959 .asGroupMessage(group.build())
960 .withExpiration(g.getMessageExpirationTime());
961 }
962
963 Pair<Long, List<SendMessageResult>> sendGroupInfoRequest(
964 GroupIdV1 groupId, SignalServiceAddress recipient
965 ) throws IOException {
966 SignalServiceGroup.Builder group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.REQUEST_INFO)
967 .withId(groupId.serialize());
968
969 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
970 .asGroupMessage(group.build());
971
972 // Send group info request message to the recipient who sent us a message with this groupId
973 return sendMessage(messageBuilder, List.of(recipient));
974 }
975
976 void sendReceipt(
977 SignalServiceAddress remoteAddress, long messageId
978 ) throws IOException, UntrustedIdentityException {
979 SignalServiceReceiptMessage receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.DELIVERY,
980 List.of(messageId),
981 System.currentTimeMillis());
982
983 createMessageSender().sendReceipt(remoteAddress,
984 unidentifiedAccessHelper.getAccessFor(remoteAddress),
985 receiptMessage);
986 }
987
988 public Pair<Long, List<SendMessageResult>> sendMessage(
989 String messageText, List<String> attachments, List<String> recipients
990 ) throws IOException, AttachmentInvalidException, InvalidNumberException {
991 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
992 .withBody(messageText);
993 if (attachments != null) {
994 List<SignalServiceAttachment> attachmentStreams = AttachmentUtils.getSignalServiceAttachments(attachments);
995
996 // Upload attachments here, so we only upload once even for multiple recipients
997 SignalServiceMessageSender messageSender = createMessageSender();
998 List<SignalServiceAttachment> attachmentPointers = new ArrayList<>(attachmentStreams.size());
999 for (SignalServiceAttachment attachment : attachmentStreams) {
1000 if (attachment.isStream()) {
1001 attachmentPointers.add(messageSender.uploadAttachment(attachment.asStream()));
1002 } else if (attachment.isPointer()) {
1003 attachmentPointers.add(attachment.asPointer());
1004 }
1005 }
1006
1007 messageBuilder.withAttachments(attachmentPointers);
1008 }
1009 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1010 }
1011
1012 public Pair<Long, SendMessageResult> sendSelfMessage(
1013 String messageText, List<String> attachments
1014 ) throws IOException, AttachmentInvalidException {
1015 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
1016 .withBody(messageText);
1017 if (attachments != null) {
1018 messageBuilder.withAttachments(AttachmentUtils.getSignalServiceAttachments(attachments));
1019 }
1020 return sendSelfMessage(messageBuilder);
1021 }
1022
1023 public Pair<Long, List<SendMessageResult>> sendMessageReaction(
1024 String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, List<String> recipients
1025 ) throws IOException, InvalidNumberException {
1026 SignalServiceDataMessage.Reaction reaction = new SignalServiceDataMessage.Reaction(emoji,
1027 remove,
1028 canonicalizeAndResolveSignalServiceAddress(targetAuthor),
1029 targetSentTimestamp);
1030 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
1031 .withReaction(reaction);
1032 return sendMessage(messageBuilder, getSignalServiceAddresses(recipients));
1033 }
1034
1035 public Pair<Long, List<SendMessageResult>> sendEndSessionMessage(List<String> recipients) throws IOException, InvalidNumberException {
1036 SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
1037
1038 final Collection<SignalServiceAddress> signalServiceAddresses = getSignalServiceAddresses(recipients);
1039 try {
1040 return sendMessage(messageBuilder, signalServiceAddresses);
1041 } catch (Exception e) {
1042 for (SignalServiceAddress address : signalServiceAddresses) {
1043 handleEndSession(address);
1044 }
1045 account.save();
1046 throw e;
1047 }
1048 }
1049
1050 public String getContactName(String number) throws InvalidNumberException {
1051 ContactInfo contact = account.getContactStore().getContact(canonicalizeAndResolveSignalServiceAddress(number));
1052 if (contact == null) {
1053 return "";
1054 } else {
1055 return contact.name;
1056 }
1057 }
1058
1059 public void setContactName(String number, String name) throws InvalidNumberException {
1060 final SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(number);
1061 ContactInfo contact = account.getContactStore().getContact(address);
1062 if (contact == null) {
1063 contact = new ContactInfo(address);
1064 }
1065 contact.name = name;
1066 account.getContactStore().updateContact(contact);
1067 account.save();
1068 }
1069
1070 public void setContactBlocked(String number, boolean blocked) throws InvalidNumberException {
1071 setContactBlocked(canonicalizeAndResolveSignalServiceAddress(number), blocked);
1072 }
1073
1074 private void setContactBlocked(SignalServiceAddress address, boolean blocked) {
1075 ContactInfo contact = account.getContactStore().getContact(address);
1076 if (contact == null) {
1077 contact = new ContactInfo(address);
1078 }
1079 contact.blocked = blocked;
1080 account.getContactStore().updateContact(contact);
1081 account.save();
1082 }
1083
1084 public void setGroupBlocked(final GroupId groupId, final boolean blocked) throws GroupNotFoundException {
1085 GroupInfo group = getGroup(groupId);
1086 if (group == null) {
1087 throw new GroupNotFoundException(groupId);
1088 }
1089
1090 group.setBlocked(blocked);
1091 account.getGroupStore().updateGroup(group);
1092 account.save();
1093 }
1094
1095 /**
1096 * Change the expiration timer for a contact
1097 */
1098 public void setExpirationTimer(SignalServiceAddress address, int messageExpirationTimer) throws IOException {
1099 ContactInfo contact = account.getContactStore().getContact(address);
1100 contact.messageExpirationTime = messageExpirationTimer;
1101 account.getContactStore().updateContact(contact);
1102 sendExpirationTimerUpdate(address);
1103 account.save();
1104 }
1105
1106 private void sendExpirationTimerUpdate(SignalServiceAddress address) throws IOException {
1107 final SignalServiceDataMessage.Builder messageBuilder = SignalServiceDataMessage.newBuilder()
1108 .asExpirationUpdate();
1109 sendMessage(messageBuilder, List.of(address));
1110 }
1111
1112 /**
1113 * Change the expiration timer for a contact
1114 */
1115 public void setExpirationTimer(
1116 String number, int messageExpirationTimer
1117 ) throws IOException, InvalidNumberException {
1118 SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(number);
1119 setExpirationTimer(address, messageExpirationTimer);
1120 }
1121
1122 /**
1123 * Change the expiration timer for a group
1124 */
1125 public void setExpirationTimer(GroupId groupId, int messageExpirationTimer) {
1126 GroupInfo g = getGroup(groupId);
1127 if (g instanceof GroupInfoV1) {
1128 GroupInfoV1 groupInfoV1 = (GroupInfoV1) g;
1129 groupInfoV1.messageExpirationTime = messageExpirationTimer;
1130 account.getGroupStore().updateGroup(groupInfoV1);
1131 } else {
1132 throw new RuntimeException("TODO Not implemented!");
1133 }
1134 }
1135
1136 /**
1137 * Upload the sticker pack from path.
1138 *
1139 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1140 * @return if successful, returns the URL to install the sticker pack in the signal app
1141 */
1142 public String uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
1143 SignalServiceStickerManifestUpload manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
1144
1145 SignalServiceMessageSender messageSender = createMessageSender();
1146
1147 byte[] packKey = KeyUtils.createStickerUploadKey();
1148 String packId = messageSender.uploadStickerManifest(manifest, packKey);
1149
1150 Sticker sticker = new Sticker(Hex.fromStringCondensed(packId), packKey);
1151 account.getStickerStore().updateSticker(sticker);
1152 account.save();
1153
1154 try {
1155 return new URI("https",
1156 "signal.art",
1157 "/addstickers/",
1158 "pack_id=" + URLEncoder.encode(packId, StandardCharsets.UTF_8) + "&pack_key=" + URLEncoder.encode(
1159 Hex.toStringCondensed(packKey),
1160 StandardCharsets.UTF_8)).toString();
1161 } catch (URISyntaxException e) {
1162 throw new AssertionError(e);
1163 }
1164 }
1165
1166 void requestSyncGroups() throws IOException {
1167 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1168 .setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS)
1169 .build();
1170 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1171 try {
1172 sendSyncMessage(message);
1173 } catch (UntrustedIdentityException e) {
1174 throw new AssertionError(e);
1175 }
1176 }
1177
1178 void requestSyncContacts() throws IOException {
1179 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1180 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS)
1181 .build();
1182 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1183 try {
1184 sendSyncMessage(message);
1185 } catch (UntrustedIdentityException e) {
1186 throw new AssertionError(e);
1187 }
1188 }
1189
1190 void requestSyncBlocked() throws IOException {
1191 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1192 .setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED)
1193 .build();
1194 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1195 try {
1196 sendSyncMessage(message);
1197 } catch (UntrustedIdentityException e) {
1198 throw new AssertionError(e);
1199 }
1200 }
1201
1202 void requestSyncConfiguration() throws IOException {
1203 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1204 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION)
1205 .build();
1206 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1207 try {
1208 sendSyncMessage(message);
1209 } catch (UntrustedIdentityException e) {
1210 throw new AssertionError(e);
1211 }
1212 }
1213
1214 void requestSyncKeys() throws IOException {
1215 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1216 .setType(SignalServiceProtos.SyncMessage.Request.Type.KEYS)
1217 .build();
1218 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1219 try {
1220 sendSyncMessage(message);
1221 } catch (UntrustedIdentityException e) {
1222 throw new AssertionError(e);
1223 }
1224 }
1225
1226 private byte[] getSenderCertificate() {
1227 // TODO support UUID capable sender certificates
1228 // byte[] certificate = accountManager.getSenderCertificateForPhoneNumberPrivacy();
1229 byte[] certificate;
1230 try {
1231 certificate = accountManager.getSenderCertificate();
1232 } catch (IOException e) {
1233 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
1234 return null;
1235 }
1236 // TODO cache for a day
1237 return certificate;
1238 }
1239
1240 private void sendSyncMessage(SignalServiceSyncMessage message) throws IOException, UntrustedIdentityException {
1241 SignalServiceMessageSender messageSender = createMessageSender();
1242 try {
1243 messageSender.sendMessage(message, unidentifiedAccessHelper.getAccessForSync());
1244 } catch (UntrustedIdentityException e) {
1245 account.getSignalProtocolStore()
1246 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1247 e.getIdentityKey(),
1248 TrustLevel.UNTRUSTED);
1249 throw e;
1250 }
1251 }
1252
1253 private Collection<SignalServiceAddress> getSignalServiceAddresses(Collection<String> numbers) throws InvalidNumberException {
1254 final Set<SignalServiceAddress> signalServiceAddresses = new HashSet<>(numbers.size());
1255 final Set<SignalServiceAddress> addressesMissingUuid = new HashSet<>();
1256
1257 for (String number : numbers) {
1258 final SignalServiceAddress resolvedAddress = canonicalizeAndResolveSignalServiceAddress(number);
1259 if (resolvedAddress.getUuid().isPresent()) {
1260 signalServiceAddresses.add(resolvedAddress);
1261 } else {
1262 addressesMissingUuid.add(resolvedAddress);
1263 }
1264 }
1265
1266 final Set<String> numbersMissingUuid = addressesMissingUuid.stream()
1267 .map(a -> a.getNumber().get())
1268 .collect(Collectors.toSet());
1269 Map<String, UUID> registeredUsers;
1270 try {
1271 registeredUsers = getRegisteredUsers(numbersMissingUuid);
1272 } catch (IOException e) {
1273 logger.warn("Failed to resolve uuids from server, ignoring: {}", e.getMessage());
1274 registeredUsers = Map.of();
1275 }
1276
1277 for (SignalServiceAddress address : addressesMissingUuid) {
1278 final String number = address.getNumber().get();
1279 if (registeredUsers.containsKey(number)) {
1280 final SignalServiceAddress newAddress = resolveSignalServiceAddress(new SignalServiceAddress(
1281 registeredUsers.get(number),
1282 number));
1283 signalServiceAddresses.add(newAddress);
1284 } else {
1285 signalServiceAddresses.add(address);
1286 }
1287 }
1288
1289 return signalServiceAddresses;
1290 }
1291
1292 private Map<String, UUID> getRegisteredUsers(final Set<String> numbersMissingUuid) throws IOException {
1293 try {
1294 return accountManager.getRegisteredUsers(ServiceConfig.getIasKeyStore(),
1295 numbersMissingUuid,
1296 serviceEnvironmentConfig.getCdsMrenclave());
1297 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
1298 throw new IOException(e);
1299 }
1300 }
1301
1302 private Pair<Long, List<SendMessageResult>> sendMessage(
1303 SignalServiceDataMessage.Builder messageBuilder, Collection<SignalServiceAddress> recipients
1304 ) throws IOException {
1305 recipients = recipients.stream().map(this::resolveSignalServiceAddress).collect(Collectors.toSet());
1306 final long timestamp = System.currentTimeMillis();
1307 messageBuilder.withTimestamp(timestamp);
1308 getOrCreateMessagePipe();
1309 getOrCreateUnidentifiedMessagePipe();
1310 SignalServiceDataMessage message = null;
1311 try {
1312 message = messageBuilder.build();
1313 if (message.getGroupContext().isPresent()) {
1314 try {
1315 SignalServiceMessageSender messageSender = createMessageSender();
1316 final boolean isRecipientUpdate = false;
1317 List<SendMessageResult> result = messageSender.sendMessage(new ArrayList<>(recipients),
1318 unidentifiedAccessHelper.getAccessFor(recipients),
1319 isRecipientUpdate,
1320 message);
1321 for (SendMessageResult r : result) {
1322 if (r.getIdentityFailure() != null) {
1323 account.getSignalProtocolStore()
1324 .saveIdentity(r.getAddress(),
1325 r.getIdentityFailure().getIdentityKey(),
1326 TrustLevel.UNTRUSTED);
1327 }
1328 }
1329 return new Pair<>(timestamp, result);
1330 } catch (UntrustedIdentityException e) {
1331 account.getSignalProtocolStore()
1332 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1333 e.getIdentityKey(),
1334 TrustLevel.UNTRUSTED);
1335 return new Pair<>(timestamp, List.of());
1336 }
1337 } else {
1338 // Send to all individually, so sync messages are sent correctly
1339 messageBuilder.withProfileKey(account.getProfileKey().serialize());
1340 List<SendMessageResult> results = new ArrayList<>(recipients.size());
1341 for (SignalServiceAddress address : recipients) {
1342 final ContactInfo contact = account.getContactStore().getContact(address);
1343 final int expirationTime = contact != null ? contact.messageExpirationTime : 0;
1344 messageBuilder.withExpiration(expirationTime);
1345 message = messageBuilder.build();
1346 results.add(sendMessage(address, message));
1347 }
1348 return new Pair<>(timestamp, results);
1349 }
1350 } finally {
1351 if (message != null && message.isEndSession()) {
1352 for (SignalServiceAddress recipient : recipients) {
1353 handleEndSession(recipient);
1354 }
1355 }
1356 account.save();
1357 }
1358 }
1359
1360 private Pair<Long, SendMessageResult> sendSelfMessage(
1361 SignalServiceDataMessage.Builder messageBuilder
1362 ) throws IOException {
1363 final long timestamp = System.currentTimeMillis();
1364 messageBuilder.withTimestamp(timestamp);
1365 getOrCreateMessagePipe();
1366 getOrCreateUnidentifiedMessagePipe();
1367 try {
1368 final SignalServiceAddress address = getSelfAddress();
1369
1370 final ContactInfo contact = account.getContactStore().getContact(address);
1371 final int expirationTime = contact != null ? contact.messageExpirationTime : 0;
1372 messageBuilder.withExpiration(expirationTime);
1373
1374 SignalServiceDataMessage message = messageBuilder.build();
1375 final SendMessageResult result = sendSelfMessage(message);
1376 return new Pair<>(timestamp, result);
1377 } finally {
1378 account.save();
1379 }
1380 }
1381
1382 private SendMessageResult sendSelfMessage(SignalServiceDataMessage message) throws IOException {
1383 SignalServiceMessageSender messageSender = createMessageSender();
1384
1385 SignalServiceAddress recipient = account.getSelfAddress();
1386
1387 final Optional<UnidentifiedAccessPair> unidentifiedAccess = unidentifiedAccessHelper.getAccessFor(recipient);
1388 SentTranscriptMessage transcript = new SentTranscriptMessage(Optional.of(recipient),
1389 message.getTimestamp(),
1390 message,
1391 message.getExpiresInSeconds(),
1392 Map.of(recipient, unidentifiedAccess.isPresent()),
1393 false);
1394 SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
1395
1396 try {
1397 long startTime = System.currentTimeMillis();
1398 messageSender.sendMessage(syncMessage, unidentifiedAccess);
1399 return SendMessageResult.success(recipient,
1400 unidentifiedAccess.isPresent(),
1401 false,
1402 System.currentTimeMillis() - startTime);
1403 } catch (UntrustedIdentityException e) {
1404 account.getSignalProtocolStore()
1405 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1406 e.getIdentityKey(),
1407 TrustLevel.UNTRUSTED);
1408 return SendMessageResult.identityFailure(recipient, e.getIdentityKey());
1409 }
1410 }
1411
1412 private SendMessageResult sendMessage(
1413 SignalServiceAddress address, SignalServiceDataMessage message
1414 ) throws IOException {
1415 SignalServiceMessageSender messageSender = createMessageSender();
1416
1417 try {
1418 return messageSender.sendMessage(address, unidentifiedAccessHelper.getAccessFor(address), message);
1419 } catch (UntrustedIdentityException e) {
1420 account.getSignalProtocolStore()
1421 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1422 e.getIdentityKey(),
1423 TrustLevel.UNTRUSTED);
1424 return SendMessageResult.identityFailure(address, e.getIdentityKey());
1425 }
1426 }
1427
1428 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, SelfSendException, UnsupportedDataMessageException, org.whispersystems.libsignal.UntrustedIdentityException {
1429 SignalServiceCipher cipher = new SignalServiceCipher(account.getSelfAddress(),
1430 account.getSignalProtocolStore(),
1431 certificateValidator);
1432 try {
1433 return cipher.decrypt(envelope);
1434 } catch (ProtocolUntrustedIdentityException e) {
1435 if (e.getCause() instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
1436 org.whispersystems.libsignal.UntrustedIdentityException identityException = (org.whispersystems.libsignal.UntrustedIdentityException) e
1437 .getCause();
1438 final IdentityKey untrustedIdentity = identityException.getUntrustedIdentity();
1439 if (untrustedIdentity != null) {
1440 account.getSignalProtocolStore()
1441 .saveIdentity(resolveSignalServiceAddress(identityException.getName()),
1442 untrustedIdentity,
1443 TrustLevel.UNTRUSTED);
1444 }
1445 throw identityException;
1446 }
1447 throw new AssertionError(e);
1448 }
1449 }
1450
1451 private void handleEndSession(SignalServiceAddress source) {
1452 account.getSignalProtocolStore().deleteAllSessions(source);
1453 }
1454
1455 private List<HandleAction> handleSignalServiceDataMessage(
1456 SignalServiceDataMessage message,
1457 boolean isSync,
1458 SignalServiceAddress source,
1459 SignalServiceAddress destination,
1460 boolean ignoreAttachments
1461 ) {
1462 List<HandleAction> actions = new ArrayList<>();
1463 if (message.getGroupContext().isPresent()) {
1464 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1465 SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
1466 GroupIdV1 groupId = GroupId.v1(groupInfo.getGroupId());
1467 GroupInfo group = getGroup(groupId);
1468 if (group == null || group instanceof GroupInfoV1) {
1469 GroupInfoV1 groupV1 = (GroupInfoV1) group;
1470 switch (groupInfo.getType()) {
1471 case UPDATE: {
1472 if (groupV1 == null) {
1473 groupV1 = new GroupInfoV1(groupId);
1474 }
1475
1476 if (groupInfo.getAvatar().isPresent()) {
1477 SignalServiceAttachment avatar = groupInfo.getAvatar().get();
1478 downloadGroupAvatar(avatar, groupV1.getGroupId());
1479 }
1480
1481 if (groupInfo.getName().isPresent()) {
1482 groupV1.name = groupInfo.getName().get();
1483 }
1484
1485 if (groupInfo.getMembers().isPresent()) {
1486 groupV1.addMembers(groupInfo.getMembers()
1487 .get()
1488 .stream()
1489 .map(this::resolveSignalServiceAddress)
1490 .collect(Collectors.toSet()));
1491 }
1492
1493 account.getGroupStore().updateGroup(groupV1);
1494 break;
1495 }
1496 case DELIVER:
1497 if (groupV1 == null && !isSync) {
1498 actions.add(new SendGroupInfoRequestAction(source, groupId));
1499 }
1500 break;
1501 case QUIT: {
1502 if (groupV1 != null) {
1503 groupV1.removeMember(source);
1504 account.getGroupStore().updateGroup(groupV1);
1505 }
1506 break;
1507 }
1508 case REQUEST_INFO:
1509 if (groupV1 != null && !isSync) {
1510 actions.add(new SendGroupInfoAction(source, groupV1.getGroupId()));
1511 }
1512 break;
1513 }
1514 } else {
1515 // Received a group v1 message for a v2 group
1516 }
1517 }
1518 if (message.getGroupContext().get().getGroupV2().isPresent()) {
1519 final SignalServiceGroupV2 groupContext = message.getGroupContext().get().getGroupV2().get();
1520 final GroupMasterKey groupMasterKey = groupContext.getMasterKey();
1521
1522 getOrMigrateGroup(groupMasterKey,
1523 groupContext.getRevision(),
1524 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
1525 }
1526 }
1527
1528 final SignalServiceAddress conversationPartnerAddress = isSync ? destination : source;
1529 if (conversationPartnerAddress != null && message.isEndSession()) {
1530 handleEndSession(conversationPartnerAddress);
1531 }
1532 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1533 if (message.getGroupContext().isPresent()) {
1534 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1535 SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
1536 GroupInfoV1 group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
1537 if (group != null) {
1538 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
1539 group.messageExpirationTime = message.getExpiresInSeconds();
1540 account.getGroupStore().updateGroup(group);
1541 }
1542 }
1543 } else if (message.getGroupContext().get().getGroupV2().isPresent()) {
1544 // disappearing message timer already stored in the DecryptedGroup
1545 }
1546 } else if (conversationPartnerAddress != null) {
1547 ContactInfo contact = account.getContactStore().getContact(conversationPartnerAddress);
1548 if (contact == null) {
1549 contact = new ContactInfo(conversationPartnerAddress);
1550 }
1551 if (contact.messageExpirationTime != message.getExpiresInSeconds()) {
1552 contact.messageExpirationTime = message.getExpiresInSeconds();
1553 account.getContactStore().updateContact(contact);
1554 }
1555 }
1556 }
1557 if (!ignoreAttachments) {
1558 if (message.getAttachments().isPresent()) {
1559 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1560 downloadAttachment(attachment);
1561 }
1562 }
1563 if (message.getSharedContacts().isPresent()) {
1564 for (SharedContact contact : message.getSharedContacts().get()) {
1565 if (contact.getAvatar().isPresent()) {
1566 downloadAttachment(contact.getAvatar().get().getAttachment());
1567 }
1568 }
1569 }
1570 }
1571 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1572 final ProfileKey profileKey;
1573 try {
1574 profileKey = new ProfileKey(message.getProfileKey().get());
1575 } catch (InvalidInputException e) {
1576 throw new AssertionError(e);
1577 }
1578 if (source.matches(account.getSelfAddress())) {
1579 this.account.setProfileKey(profileKey);
1580 }
1581 this.account.getProfileStore().storeProfileKey(source, profileKey);
1582 }
1583 if (message.getPreviews().isPresent()) {
1584 final List<SignalServiceDataMessage.Preview> previews = message.getPreviews().get();
1585 for (SignalServiceDataMessage.Preview preview : previews) {
1586 if (preview.getImage().isPresent()) {
1587 downloadAttachment(preview.getImage().get());
1588 }
1589 }
1590 }
1591 if (message.getQuote().isPresent()) {
1592 final SignalServiceDataMessage.Quote quote = message.getQuote().get();
1593
1594 for (SignalServiceDataMessage.Quote.QuotedAttachment quotedAttachment : quote.getAttachments()) {
1595 final SignalServiceAttachment thumbnail = quotedAttachment.getThumbnail();
1596 if (thumbnail != null) {
1597 downloadAttachment(thumbnail);
1598 }
1599 }
1600 }
1601 if (message.getSticker().isPresent()) {
1602 final SignalServiceDataMessage.Sticker messageSticker = message.getSticker().get();
1603 Sticker sticker = account.getStickerStore().getSticker(messageSticker.getPackId());
1604 if (sticker == null) {
1605 sticker = new Sticker(messageSticker.getPackId(), messageSticker.getPackKey());
1606 account.getStickerStore().updateSticker(sticker);
1607 }
1608 }
1609 return actions;
1610 }
1611
1612 private GroupInfoV2 getOrMigrateGroup(
1613 final GroupMasterKey groupMasterKey, final int revision, final byte[] signedGroupChange
1614 ) {
1615 final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
1616
1617 GroupIdV2 groupId = GroupUtils.getGroupIdV2(groupSecretParams);
1618 GroupInfo groupInfo = getGroup(groupId);
1619 final GroupInfoV2 groupInfoV2;
1620 if (groupInfo instanceof GroupInfoV1) {
1621 // Received a v2 group message for a v1 group, we need to locally migrate the group
1622 account.getGroupStore().deleteGroup(groupInfo.getGroupId());
1623 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1624 logger.info("Locally migrated group {} to group v2, id: {}",
1625 groupInfo.getGroupId().toBase64(),
1626 groupInfoV2.getGroupId().toBase64());
1627 } else if (groupInfo instanceof GroupInfoV2) {
1628 groupInfoV2 = (GroupInfoV2) groupInfo;
1629 } else {
1630 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1631 }
1632
1633 if (groupInfoV2.getGroup() == null || groupInfoV2.getGroup().getRevision() < revision) {
1634 DecryptedGroup group = null;
1635 if (signedGroupChange != null
1636 && groupInfoV2.getGroup() != null
1637 && groupInfoV2.getGroup().getRevision() + 1 == revision) {
1638 group = groupHelper.getUpdatedDecryptedGroup(groupInfoV2.getGroup(), signedGroupChange, groupMasterKey);
1639 }
1640 if (group == null) {
1641 group = groupHelper.getDecryptedGroup(groupSecretParams);
1642 }
1643 if (group != null) {
1644 storeProfileKeysFromMembers(group);
1645 final String avatar = group.getAvatar();
1646 if (avatar != null && !avatar.isEmpty()) {
1647 downloadGroupAvatar(groupId, groupSecretParams, avatar);
1648 }
1649 }
1650 groupInfoV2.setGroup(group);
1651 account.getGroupStore().updateGroup(groupInfoV2);
1652 }
1653
1654 return groupInfoV2;
1655 }
1656
1657 private void storeProfileKeysFromMembers(final DecryptedGroup group) {
1658 for (DecryptedMember member : group.getMembersList()) {
1659 final SignalServiceAddress address = resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil.parseOrThrow(
1660 member.getUuid().toByteArray()), null));
1661 try {
1662 account.getProfileStore()
1663 .storeProfileKey(address, new ProfileKey(member.getProfileKey().toByteArray()));
1664 } catch (InvalidInputException ignored) {
1665 }
1666 }
1667 }
1668
1669 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1670 for (CachedMessage cachedMessage : account.getMessageCache().getCachedMessages()) {
1671 retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
1672 }
1673 }
1674
1675 private void retryFailedReceivedMessage(
1676 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
1677 ) {
1678 SignalServiceEnvelope envelope = cachedMessage.loadEnvelope();
1679 if (envelope == null) {
1680 return;
1681 }
1682 SignalServiceContent content = null;
1683 if (!envelope.isReceipt()) {
1684 try {
1685 content = decryptMessage(envelope);
1686 } catch (org.whispersystems.libsignal.UntrustedIdentityException e) {
1687 return;
1688 } catch (Exception er) {
1689 // All other errors are not recoverable, so delete the cached message
1690 cachedMessage.delete();
1691 return;
1692 }
1693 List<HandleAction> actions = handleMessage(envelope, content, ignoreAttachments);
1694 for (HandleAction action : actions) {
1695 try {
1696 action.execute(this);
1697 } catch (Throwable e) {
1698 logger.warn("Message action failed.", e);
1699 }
1700 }
1701 }
1702 account.save();
1703 handler.handleMessage(envelope, content, null);
1704 cachedMessage.delete();
1705 }
1706
1707 public void receiveMessages(
1708 long timeout,
1709 TimeUnit unit,
1710 boolean returnOnTimeout,
1711 boolean ignoreAttachments,
1712 ReceiveMessageHandler handler
1713 ) throws IOException {
1714 retryFailedReceivedMessages(handler, ignoreAttachments);
1715
1716 Set<HandleAction> queuedActions = null;
1717
1718 final SignalServiceMessagePipe messagePipe = getOrCreateMessagePipe();
1719
1720 boolean hasCaughtUpWithOldMessages = false;
1721
1722 while (true) {
1723 SignalServiceEnvelope envelope;
1724 SignalServiceContent content = null;
1725 Exception exception = null;
1726 final CachedMessage[] cachedMessage = {null};
1727 try {
1728 Optional<SignalServiceEnvelope> result = messagePipe.readOrEmpty(timeout, unit, envelope1 -> {
1729 // store message on disk, before acknowledging receipt to the server
1730 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1);
1731 });
1732 if (result.isPresent()) {
1733 envelope = result.get();
1734 } else {
1735 // Received indicator that server queue is empty
1736 hasCaughtUpWithOldMessages = true;
1737
1738 if (queuedActions != null) {
1739 for (HandleAction action : queuedActions) {
1740 try {
1741 action.execute(this);
1742 } catch (Throwable e) {
1743 logger.warn("Message action failed.", e);
1744 }
1745 }
1746 account.save();
1747 queuedActions.clear();
1748 queuedActions = null;
1749 }
1750
1751 // Continue to wait another timeout for new messages
1752 continue;
1753 }
1754 } catch (TimeoutException e) {
1755 if (returnOnTimeout) return;
1756 continue;
1757 }
1758
1759 if (envelope.hasSource()) {
1760 // Store uuid if we don't have it already
1761 SignalServiceAddress source = envelope.getSourceAddress();
1762 resolveSignalServiceAddress(source);
1763 }
1764 if (!envelope.isReceipt()) {
1765 try {
1766 content = decryptMessage(envelope);
1767 } catch (Exception e) {
1768 exception = e;
1769 }
1770 List<HandleAction> actions = handleMessage(envelope, content, ignoreAttachments);
1771 if (hasCaughtUpWithOldMessages) {
1772 for (HandleAction action : actions) {
1773 try {
1774 action.execute(this);
1775 } catch (Throwable e) {
1776 logger.warn("Message action failed.", e);
1777 }
1778 }
1779 } else {
1780 if (queuedActions == null) {
1781 queuedActions = new HashSet<>();
1782 }
1783 queuedActions.addAll(actions);
1784 }
1785 }
1786 account.save();
1787 if (isMessageBlocked(envelope, content)) {
1788 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
1789 } else if (isNotAGroupMember(envelope, content)) {
1790 logger.info("Ignoring a message from a non group member: {}", envelope.getTimestamp());
1791 } else {
1792 handler.handleMessage(envelope, content, exception);
1793 }
1794 if (!(exception instanceof org.whispersystems.libsignal.UntrustedIdentityException)) {
1795 if (cachedMessage[0] != null) {
1796 cachedMessage[0].delete();
1797 }
1798 }
1799 }
1800 }
1801
1802 private boolean isMessageBlocked(
1803 SignalServiceEnvelope envelope, SignalServiceContent content
1804 ) {
1805 SignalServiceAddress source;
1806 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1807 source = envelope.getSourceAddress();
1808 } else if (content != null) {
1809 source = content.getSender();
1810 } else {
1811 return false;
1812 }
1813 ContactInfo sourceContact = account.getContactStore().getContact(source);
1814 if (sourceContact != null && sourceContact.blocked) {
1815 return true;
1816 }
1817
1818 if (content != null && content.getDataMessage().isPresent()) {
1819 SignalServiceDataMessage message = content.getDataMessage().get();
1820 if (message.getGroupContext().isPresent()) {
1821 GroupId groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1822 GroupInfo group = getGroup(groupId);
1823 if (group != null && group.isBlocked()) {
1824 return true;
1825 }
1826 }
1827 }
1828 return false;
1829 }
1830
1831 private boolean isNotAGroupMember(
1832 SignalServiceEnvelope envelope, SignalServiceContent content
1833 ) {
1834 SignalServiceAddress source;
1835 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1836 source = envelope.getSourceAddress();
1837 } else if (content != null) {
1838 source = content.getSender();
1839 } else {
1840 return false;
1841 }
1842
1843 if (content != null && content.getDataMessage().isPresent()) {
1844 SignalServiceDataMessage message = content.getDataMessage().get();
1845 if (message.getGroupContext().isPresent()) {
1846 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1847 SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
1848 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
1849 return false;
1850 }
1851 }
1852 GroupId groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1853 GroupInfo group = getGroup(groupId);
1854 if (group != null && !group.isMember(source)) {
1855 return true;
1856 }
1857 }
1858 }
1859 return false;
1860 }
1861
1862 private List<HandleAction> handleMessage(
1863 SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments
1864 ) {
1865 List<HandleAction> actions = new ArrayList<>();
1866 if (content != null) {
1867 final SignalServiceAddress sender;
1868 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1869 sender = envelope.getSourceAddress();
1870 } else {
1871 sender = content.getSender();
1872 }
1873 // Store uuid if we don't have it already
1874 resolveSignalServiceAddress(sender);
1875
1876 if (content.getDataMessage().isPresent()) {
1877 SignalServiceDataMessage message = content.getDataMessage().get();
1878
1879 if (content.isNeedsReceipt()) {
1880 actions.add(new SendReceiptAction(sender, message.getTimestamp()));
1881 }
1882
1883 actions.addAll(handleSignalServiceDataMessage(message,
1884 false,
1885 sender,
1886 account.getSelfAddress(),
1887 ignoreAttachments));
1888 }
1889 if (content.getSyncMessage().isPresent()) {
1890 account.setMultiDevice(true);
1891 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
1892 if (syncMessage.getSent().isPresent()) {
1893 SentTranscriptMessage message = syncMessage.getSent().get();
1894 final SignalServiceAddress destination = message.getDestination().orNull();
1895 actions.addAll(handleSignalServiceDataMessage(message.getMessage(),
1896 true,
1897 sender,
1898 destination,
1899 ignoreAttachments));
1900 }
1901 if (syncMessage.getRequest().isPresent()) {
1902 RequestMessage rm = syncMessage.getRequest().get();
1903 if (rm.isContactsRequest()) {
1904 actions.add(SendSyncContactsAction.create());
1905 }
1906 if (rm.isGroupsRequest()) {
1907 actions.add(SendSyncGroupsAction.create());
1908 }
1909 if (rm.isBlockedListRequest()) {
1910 actions.add(SendSyncBlockedListAction.create());
1911 }
1912 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1913 }
1914 if (syncMessage.getGroups().isPresent()) {
1915 File tmpFile = null;
1916 try {
1917 tmpFile = IOUtils.createTempFile();
1918 final SignalServiceAttachment groupsMessage = syncMessage.getGroups().get();
1919 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(groupsMessage.asPointer(),
1920 tmpFile)) {
1921 DeviceGroupsInputStream s = new DeviceGroupsInputStream(attachmentAsStream);
1922 DeviceGroup g;
1923 while ((g = s.read()) != null) {
1924 GroupInfoV1 syncGroup = account.getGroupStore()
1925 .getOrCreateGroupV1(GroupId.v1(g.getId()));
1926 if (syncGroup != null) {
1927 if (g.getName().isPresent()) {
1928 syncGroup.name = g.getName().get();
1929 }
1930 syncGroup.addMembers(g.getMembers()
1931 .stream()
1932 .map(this::resolveSignalServiceAddress)
1933 .collect(Collectors.toSet()));
1934 if (!g.isActive()) {
1935 syncGroup.removeMember(account.getSelfAddress());
1936 } else {
1937 // Add ourself to the member set as it's marked as active
1938 syncGroup.addMembers(List.of(account.getSelfAddress()));
1939 }
1940 syncGroup.blocked = g.isBlocked();
1941 if (g.getColor().isPresent()) {
1942 syncGroup.color = g.getColor().get();
1943 }
1944
1945 if (g.getAvatar().isPresent()) {
1946 downloadGroupAvatar(g.getAvatar().get(), syncGroup.getGroupId());
1947 }
1948 syncGroup.inboxPosition = g.getInboxPosition().orNull();
1949 syncGroup.archived = g.isArchived();
1950 account.getGroupStore().updateGroup(syncGroup);
1951 }
1952 }
1953 }
1954 } catch (Exception e) {
1955 logger.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1956 tmpFile,
1957 e.getMessage());
1958 } finally {
1959 if (tmpFile != null) {
1960 try {
1961 Files.delete(tmpFile.toPath());
1962 } catch (IOException e) {
1963 logger.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1964 tmpFile,
1965 e.getMessage());
1966 }
1967 }
1968 }
1969 }
1970 if (syncMessage.getBlockedList().isPresent()) {
1971 final BlockedListMessage blockedListMessage = syncMessage.getBlockedList().get();
1972 for (SignalServiceAddress address : blockedListMessage.getAddresses()) {
1973 setContactBlocked(resolveSignalServiceAddress(address), true);
1974 }
1975 for (GroupId groupId : blockedListMessage.getGroupIds()
1976 .stream()
1977 .map(GroupId::unknownVersion)
1978 .collect(Collectors.toSet())) {
1979 try {
1980 setGroupBlocked(groupId, true);
1981 } catch (GroupNotFoundException e) {
1982 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
1983 groupId.toBase64());
1984 }
1985 }
1986 }
1987 if (syncMessage.getContacts().isPresent()) {
1988 File tmpFile = null;
1989 try {
1990 tmpFile = IOUtils.createTempFile();
1991 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
1992 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream()
1993 .asPointer(), tmpFile)) {
1994 DeviceContactsInputStream s = new DeviceContactsInputStream(attachmentAsStream);
1995 if (contactsMessage.isComplete()) {
1996 account.getContactStore().clear();
1997 }
1998 DeviceContact c;
1999 while ((c = s.read()) != null) {
2000 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
2001 account.setProfileKey(c.getProfileKey().get());
2002 }
2003 final SignalServiceAddress address = resolveSignalServiceAddress(c.getAddress());
2004 ContactInfo contact = account.getContactStore().getContact(address);
2005 if (contact == null) {
2006 contact = new ContactInfo(address);
2007 }
2008 if (c.getName().isPresent()) {
2009 contact.name = c.getName().get();
2010 }
2011 if (c.getColor().isPresent()) {
2012 contact.color = c.getColor().get();
2013 }
2014 if (c.getProfileKey().isPresent()) {
2015 account.getProfileStore().storeProfileKey(address, c.getProfileKey().get());
2016 }
2017 if (c.getVerified().isPresent()) {
2018 final VerifiedMessage verifiedMessage = c.getVerified().get();
2019 account.getSignalProtocolStore()
2020 .setIdentityTrustLevel(verifiedMessage.getDestination(),
2021 verifiedMessage.getIdentityKey(),
2022 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2023 }
2024 if (c.getExpirationTimer().isPresent()) {
2025 contact.messageExpirationTime = c.getExpirationTimer().get();
2026 }
2027 contact.blocked = c.isBlocked();
2028 contact.inboxPosition = c.getInboxPosition().orNull();
2029 contact.archived = c.isArchived();
2030 account.getContactStore().updateContact(contact);
2031
2032 if (c.getAvatar().isPresent()) {
2033 downloadContactAvatar(c.getAvatar().get(), contact.getAddress());
2034 }
2035 }
2036 }
2037 } catch (Exception e) {
2038 logger.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2039 tmpFile,
2040 e.getMessage());
2041 } finally {
2042 if (tmpFile != null) {
2043 try {
2044 Files.delete(tmpFile.toPath());
2045 } catch (IOException e) {
2046 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2047 tmpFile,
2048 e.getMessage());
2049 }
2050 }
2051 }
2052 }
2053 if (syncMessage.getVerified().isPresent()) {
2054 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
2055 account.getSignalProtocolStore()
2056 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage.getDestination()),
2057 verifiedMessage.getIdentityKey(),
2058 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2059 }
2060 if (syncMessage.getStickerPackOperations().isPresent()) {
2061 final List<StickerPackOperationMessage> stickerPackOperationMessages = syncMessage.getStickerPackOperations()
2062 .get();
2063 for (StickerPackOperationMessage m : stickerPackOperationMessages) {
2064 if (!m.getPackId().isPresent()) {
2065 continue;
2066 }
2067 Sticker sticker = account.getStickerStore().getSticker(m.getPackId().get());
2068 if (sticker == null) {
2069 if (!m.getPackKey().isPresent()) {
2070 continue;
2071 }
2072 sticker = new Sticker(m.getPackId().get(), m.getPackKey().get());
2073 }
2074 sticker.setInstalled(!m.getType().isPresent()
2075 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL);
2076 account.getStickerStore().updateSticker(sticker);
2077 }
2078 }
2079 if (syncMessage.getFetchType().isPresent()) {
2080 switch (syncMessage.getFetchType().get()) {
2081 case LOCAL_PROFILE:
2082 getRecipientProfile(getSelfAddress(), true);
2083 case STORAGE_MANIFEST:
2084 // TODO
2085 }
2086 }
2087 if (syncMessage.getKeys().isPresent()) {
2088 final KeysMessage keysMessage = syncMessage.getKeys().get();
2089 if (keysMessage.getStorageService().isPresent()) {
2090 final StorageKey storageKey = keysMessage.getStorageService().get();
2091 account.setStorageKey(storageKey);
2092 }
2093 }
2094 if (syncMessage.getConfiguration().isPresent()) {
2095 // TODO
2096 }
2097 }
2098 }
2099 return actions;
2100 }
2101
2102 private void downloadContactAvatar(SignalServiceAttachment avatar, SignalServiceAddress address) {
2103 try {
2104 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(avatar, outputStream));
2105 } catch (IOException e) {
2106 logger.warn("Failed to download avatar for contact {}, ignoring: {}", address, e.getMessage());
2107 }
2108 }
2109
2110 private void downloadGroupAvatar(SignalServiceAttachment avatar, GroupId groupId) {
2111 try {
2112 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(avatar, outputStream));
2113 } catch (IOException e) {
2114 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2115 }
2116 }
2117
2118 private void downloadGroupAvatar(GroupId groupId, GroupSecretParams groupSecretParams, String cdnKey) {
2119 try {
2120 avatarStore.storeGroupAvatar(groupId,
2121 outputStream -> retrieveGroupV2Avatar(groupSecretParams, cdnKey, outputStream));
2122 } catch (IOException e) {
2123 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2124 }
2125 }
2126
2127 private void downloadProfileAvatar(
2128 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
2129 ) {
2130 try {
2131 avatarStore.storeProfileAvatar(address,
2132 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
2133 } catch (Throwable e) {
2134 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
2135 }
2136 }
2137
2138 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
2139 return attachmentStore.getAttachmentFile(attachmentId);
2140 }
2141
2142 private void downloadAttachment(final SignalServiceAttachment attachment) {
2143 if (!attachment.isPointer()) {
2144 logger.warn("Invalid state, can't store an attachment stream.");
2145 }
2146
2147 SignalServiceAttachmentPointer pointer = attachment.asPointer();
2148 if (pointer.getPreview().isPresent()) {
2149 final byte[] preview = pointer.getPreview().get();
2150 try {
2151 attachmentStore.storeAttachmentPreview(pointer.getRemoteId(),
2152 outputStream -> outputStream.write(preview, 0, preview.length));
2153 } catch (IOException e) {
2154 logger.warn("Failed to download attachment preview, ignoring: {}", e.getMessage());
2155 }
2156 }
2157
2158 try {
2159 attachmentStore.storeAttachment(pointer.getRemoteId(),
2160 outputStream -> retrieveAttachmentPointer(pointer, outputStream));
2161 } catch (IOException e) {
2162 logger.warn("Failed to download attachment ({}), ignoring: {}", pointer.getRemoteId(), e.getMessage());
2163 }
2164 }
2165
2166 private void retrieveGroupV2Avatar(
2167 GroupSecretParams groupSecretParams, String cdnKey, OutputStream outputStream
2168 ) throws IOException {
2169 GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
2170
2171 File tmpFile = IOUtils.createTempFile();
2172 try (InputStream input = messageReceiver.retrieveGroupsV2ProfileAvatar(cdnKey,
2173 tmpFile,
2174 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2175 byte[] encryptedData = IOUtils.readFully(input);
2176
2177 byte[] decryptedData = groupOperations.decryptAvatar(encryptedData);
2178 outputStream.write(decryptedData);
2179 } finally {
2180 try {
2181 Files.delete(tmpFile.toPath());
2182 } catch (IOException e) {
2183 logger.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2184 tmpFile,
2185 e.getMessage());
2186 }
2187 }
2188 }
2189
2190 private void retrieveProfileAvatar(
2191 String avatarPath, ProfileKey profileKey, OutputStream outputStream
2192 ) throws IOException {
2193 File tmpFile = IOUtils.createTempFile();
2194 try (InputStream input = messageReceiver.retrieveProfileAvatar(avatarPath,
2195 tmpFile,
2196 profileKey,
2197 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2198 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2199 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
2200 } finally {
2201 try {
2202 Files.delete(tmpFile.toPath());
2203 } catch (IOException e) {
2204 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2205 tmpFile,
2206 e.getMessage());
2207 }
2208 }
2209 }
2210
2211 private void retrieveAttachment(
2212 final SignalServiceAttachment attachment, final OutputStream outputStream
2213 ) throws IOException {
2214 if (attachment.isPointer()) {
2215 SignalServiceAttachmentPointer pointer = attachment.asPointer();
2216 retrieveAttachmentPointer(pointer, outputStream);
2217 } else {
2218 SignalServiceAttachmentStream stream = attachment.asStream();
2219 IOUtils.copyStream(stream.getInputStream(), outputStream);
2220 }
2221 }
2222
2223 private void retrieveAttachmentPointer(
2224 SignalServiceAttachmentPointer pointer, OutputStream outputStream
2225 ) throws IOException {
2226 File tmpFile = IOUtils.createTempFile();
2227 try (InputStream input = retrieveAttachmentAsStream(pointer, tmpFile)) {
2228 IOUtils.copyStream(input, outputStream);
2229 } catch (MissingConfigurationException | InvalidMessageException e) {
2230 throw new IOException(e);
2231 } finally {
2232 try {
2233 Files.delete(tmpFile.toPath());
2234 } catch (IOException e) {
2235 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2236 tmpFile,
2237 e.getMessage());
2238 }
2239 }
2240 }
2241
2242 private InputStream retrieveAttachmentAsStream(
2243 SignalServiceAttachmentPointer pointer, File tmpFile
2244 ) throws IOException, InvalidMessageException, MissingConfigurationException {
2245 return messageReceiver.retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
2246 }
2247
2248 void sendGroups() throws IOException, UntrustedIdentityException {
2249 File groupsFile = IOUtils.createTempFile();
2250
2251 try {
2252 try (OutputStream fos = new FileOutputStream(groupsFile)) {
2253 DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(fos);
2254 for (GroupInfo record : getGroups()) {
2255 if (record instanceof GroupInfoV1) {
2256 GroupInfoV1 groupInfo = (GroupInfoV1) record;
2257 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
2258 Optional.fromNullable(groupInfo.name),
2259 new ArrayList<>(groupInfo.getMembers()),
2260 createGroupAvatarAttachment(groupInfo.getGroupId()),
2261 groupInfo.isMember(account.getSelfAddress()),
2262 Optional.of(groupInfo.messageExpirationTime),
2263 Optional.fromNullable(groupInfo.color),
2264 groupInfo.blocked,
2265 Optional.fromNullable(groupInfo.inboxPosition),
2266 groupInfo.archived));
2267 }
2268 }
2269 }
2270
2271 if (groupsFile.exists() && groupsFile.length() > 0) {
2272 try (FileInputStream groupsFileStream = new FileInputStream(groupsFile)) {
2273 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
2274 .withStream(groupsFileStream)
2275 .withContentType("application/octet-stream")
2276 .withLength(groupsFile.length())
2277 .build();
2278
2279 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
2280 }
2281 }
2282 } finally {
2283 try {
2284 Files.delete(groupsFile.toPath());
2285 } catch (IOException e) {
2286 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
2287 }
2288 }
2289 }
2290
2291 public void sendContacts() throws IOException, UntrustedIdentityException {
2292 File contactsFile = IOUtils.createTempFile();
2293
2294 try {
2295 try (OutputStream fos = new FileOutputStream(contactsFile)) {
2296 DeviceContactsOutputStream out = new DeviceContactsOutputStream(fos);
2297 for (ContactInfo record : account.getContactStore().getContacts()) {
2298 VerifiedMessage verifiedMessage = null;
2299 IdentityInfo currentIdentity = account.getSignalProtocolStore().getIdentity(record.getAddress());
2300 if (currentIdentity != null) {
2301 verifiedMessage = new VerifiedMessage(record.getAddress(),
2302 currentIdentity.getIdentityKey(),
2303 currentIdentity.getTrustLevel().toVerifiedState(),
2304 currentIdentity.getDateAdded().getTime());
2305 }
2306
2307 ProfileKey profileKey = account.getProfileStore().getProfileKey(record.getAddress());
2308 out.write(new DeviceContact(record.getAddress(),
2309 Optional.fromNullable(record.name),
2310 createContactAvatarAttachment(record.getAddress()),
2311 Optional.fromNullable(record.color),
2312 Optional.fromNullable(verifiedMessage),
2313 Optional.fromNullable(profileKey),
2314 record.blocked,
2315 Optional.of(record.messageExpirationTime),
2316 Optional.fromNullable(record.inboxPosition),
2317 record.archived));
2318 }
2319
2320 if (account.getProfileKey() != null) {
2321 // Send our own profile key as well
2322 out.write(new DeviceContact(account.getSelfAddress(),
2323 Optional.absent(),
2324 Optional.absent(),
2325 Optional.absent(),
2326 Optional.absent(),
2327 Optional.of(account.getProfileKey()),
2328 false,
2329 Optional.absent(),
2330 Optional.absent(),
2331 false));
2332 }
2333 }
2334
2335 if (contactsFile.exists() && contactsFile.length() > 0) {
2336 try (FileInputStream contactsFileStream = new FileInputStream(contactsFile)) {
2337 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
2338 .withStream(contactsFileStream)
2339 .withContentType("application/octet-stream")
2340 .withLength(contactsFile.length())
2341 .build();
2342
2343 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
2344 }
2345 }
2346 } finally {
2347 try {
2348 Files.delete(contactsFile.toPath());
2349 } catch (IOException e) {
2350 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
2351 }
2352 }
2353 }
2354
2355 void sendBlockedList() throws IOException, UntrustedIdentityException {
2356 List<SignalServiceAddress> addresses = new ArrayList<>();
2357 for (ContactInfo record : account.getContactStore().getContacts()) {
2358 if (record.blocked) {
2359 addresses.add(record.getAddress());
2360 }
2361 }
2362 List<byte[]> groupIds = new ArrayList<>();
2363 for (GroupInfo record : getGroups()) {
2364 if (record.isBlocked()) {
2365 groupIds.add(record.getGroupId().serialize());
2366 }
2367 }
2368 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
2369 }
2370
2371 private void sendVerifiedMessage(
2372 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
2373 ) throws IOException, UntrustedIdentityException {
2374 VerifiedMessage verifiedMessage = new VerifiedMessage(destination,
2375 identityKey,
2376 trustLevel.toVerifiedState(),
2377 System.currentTimeMillis());
2378 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
2379 }
2380
2381 public List<ContactInfo> getContacts() {
2382 return account.getContactStore().getContacts();
2383 }
2384
2385 public String getContactOrProfileName(String number) {
2386 final SignalServiceAddress address = Utils.getSignalServiceAddressFromIdentifier(number);
2387
2388 final ContactInfo contact = account.getContactStore().getContact(address);
2389 if (contact != null && !Util.isEmpty(contact.name)) {
2390 return contact.name;
2391 }
2392
2393 final SignalProfileEntry profileEntry = account.getProfileStore().getProfileEntry(address);
2394 if (profileEntry != null && profileEntry.getProfile() != null) {
2395 return profileEntry.getProfile().getName();
2396 }
2397
2398 return null;
2399 }
2400
2401 public GroupInfo getGroup(GroupId groupId) {
2402 final GroupInfo group = account.getGroupStore().getGroup(groupId);
2403 if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() == null) {
2404 final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(((GroupInfoV2) group).getMasterKey());
2405 ((GroupInfoV2) group).setGroup(groupHelper.getDecryptedGroup(groupSecretParams));
2406 account.getGroupStore().updateGroup(group);
2407 }
2408 return group;
2409 }
2410
2411 public List<IdentityInfo> getIdentities() {
2412 return account.getSignalProtocolStore().getIdentities();
2413 }
2414
2415 public List<IdentityInfo> getIdentities(String number) throws InvalidNumberException {
2416 return account.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number));
2417 }
2418
2419 /**
2420 * Trust this the identity with this fingerprint
2421 *
2422 * @param name username of the identity
2423 * @param fingerprint Fingerprint
2424 */
2425 public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
2426 SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(name);
2427 List<IdentityInfo> ids = account.getSignalProtocolStore().getIdentities(address);
2428 if (ids == null) {
2429 return false;
2430 }
2431 for (IdentityInfo id : ids) {
2432 if (!Arrays.equals(id.getIdentityKey().serialize(), fingerprint)) {
2433 continue;
2434 }
2435
2436 account.getSignalProtocolStore()
2437 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2438 try {
2439 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2440 } catch (IOException | UntrustedIdentityException e) {
2441 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2442 }
2443 account.save();
2444 return true;
2445 }
2446 return false;
2447 }
2448
2449 /**
2450 * Trust this the identity with this safety number
2451 *
2452 * @param name username of the identity
2453 * @param safetyNumber Safety number
2454 */
2455 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) throws InvalidNumberException {
2456 SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(name);
2457 List<IdentityInfo> ids = account.getSignalProtocolStore().getIdentities(address);
2458 if (ids == null) {
2459 return false;
2460 }
2461 for (IdentityInfo id : ids) {
2462 if (!safetyNumber.equals(computeSafetyNumber(address, id.getIdentityKey()))) {
2463 continue;
2464 }
2465
2466 account.getSignalProtocolStore()
2467 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2468 try {
2469 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2470 } catch (IOException | UntrustedIdentityException e) {
2471 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2472 }
2473 account.save();
2474 return true;
2475 }
2476 return false;
2477 }
2478
2479 /**
2480 * Trust all keys of this identity without verification
2481 *
2482 * @param name username of the identity
2483 */
2484 public boolean trustIdentityAllKeys(String name) {
2485 SignalServiceAddress address = resolveSignalServiceAddress(name);
2486 List<IdentityInfo> ids = account.getSignalProtocolStore().getIdentities(address);
2487 if (ids == null) {
2488 return false;
2489 }
2490 for (IdentityInfo id : ids) {
2491 if (id.getTrustLevel() == TrustLevel.UNTRUSTED) {
2492 account.getSignalProtocolStore()
2493 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
2494 try {
2495 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
2496 } catch (IOException | UntrustedIdentityException e) {
2497 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2498 }
2499 }
2500 }
2501 account.save();
2502 return true;
2503 }
2504
2505 public String computeSafetyNumber(
2506 SignalServiceAddress theirAddress, IdentityKey theirIdentityKey
2507 ) {
2508 return Utils.computeSafetyNumber(ServiceConfig.capabilities.isUuid(),
2509 account.getSelfAddress(),
2510 getIdentityKeyPair().getPublicKey(),
2511 theirAddress,
2512 theirIdentityKey);
2513 }
2514
2515 public SignalServiceAddress canonicalizeAndResolveSignalServiceAddress(String identifier) throws InvalidNumberException {
2516 String canonicalizedNumber = UuidUtil.isUuid(identifier)
2517 ? identifier
2518 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2519 return resolveSignalServiceAddress(canonicalizedNumber);
2520 }
2521
2522 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2523 SignalServiceAddress address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2524
2525 return resolveSignalServiceAddress(address);
2526 }
2527
2528 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2529 if (address.matches(account.getSelfAddress())) {
2530 return account.getSelfAddress();
2531 }
2532
2533 return account.getRecipientStore().resolveServiceAddress(address);
2534 }
2535
2536 @Override
2537 public void close() throws IOException {
2538 close(true);
2539 }
2540
2541 void close(boolean closeAccount) throws IOException {
2542 executor.shutdown();
2543
2544 if (messagePipe != null) {
2545 messagePipe.shutdown();
2546 messagePipe = null;
2547 }
2548
2549 if (unidentifiedMessagePipe != null) {
2550 unidentifiedMessagePipe.shutdown();
2551 unidentifiedMessagePipe = null;
2552 }
2553
2554 if (closeAccount && account != null) {
2555 account.close();
2556 }
2557 account = null;
2558 }
2559
2560 public interface ReceiveMessageHandler {
2561
2562 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2563 }
2564 }