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