]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/Manager.java
Implement announcement groups
[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 Boolean isAnnouncementGroup
814 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, InvalidNumberException, NotAGroupMemberException {
815 return updateGroup(groupId,
816 name,
817 description,
818 members == null ? null : getRecipientIds(members),
819 removeMembers == null ? null : getRecipientIds(removeMembers),
820 admins == null ? null : getRecipientIds(admins),
821 removeAdmins == null ? null : getRecipientIds(removeAdmins),
822 resetGroupLink,
823 groupLinkState,
824 addMemberPermission,
825 editDetailsPermission,
826 avatarFile,
827 expirationTimer,
828 isAnnouncementGroup);
829 }
830
831 private Pair<Long, List<SendMessageResult>> updateGroup(
832 final GroupId groupId,
833 final String name,
834 final String description,
835 final Set<RecipientId> members,
836 final Set<RecipientId> removeMembers,
837 final Set<RecipientId> admins,
838 final Set<RecipientId> removeAdmins,
839 final boolean resetGroupLink,
840 final GroupLinkState groupLinkState,
841 final GroupPermission addMemberPermission,
842 final GroupPermission editDetailsPermission,
843 final File avatarFile,
844 final Integer expirationTimer,
845 final Boolean isAnnouncementGroup
846 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException {
847 var group = getGroupForUpdating(groupId);
848
849 if (group instanceof GroupInfoV2) {
850 try {
851 return updateGroupV2((GroupInfoV2) group,
852 name,
853 description,
854 members,
855 removeMembers,
856 admins,
857 removeAdmins,
858 resetGroupLink,
859 groupLinkState,
860 addMemberPermission,
861 editDetailsPermission,
862 avatarFile,
863 expirationTimer,
864 isAnnouncementGroup);
865 } catch (ConflictException e) {
866 // Detected conflicting update, refreshing group and trying again
867 group = getGroup(groupId, true);
868 return updateGroupV2((GroupInfoV2) group,
869 name,
870 description,
871 members,
872 removeMembers,
873 admins,
874 removeAdmins,
875 resetGroupLink,
876 groupLinkState,
877 addMemberPermission,
878 editDetailsPermission,
879 avatarFile,
880 expirationTimer,
881 isAnnouncementGroup);
882 }
883 }
884
885 final var gv1 = (GroupInfoV1) group;
886 final var result = updateGroupV1(gv1, name, members, avatarFile);
887 if (expirationTimer != null) {
888 setExpirationTimer(gv1, expirationTimer);
889 }
890 return result;
891 }
892
893 private Pair<Long, List<SendMessageResult>> updateGroupV1(
894 final GroupInfoV1 gv1, final String name, final Set<RecipientId> members, final File avatarFile
895 ) throws IOException, AttachmentInvalidException {
896 updateGroupV1Details(gv1, name, members, avatarFile);
897 var messageBuilder = getGroupUpdateMessageBuilder(gv1);
898
899 account.getGroupStore().updateGroup(gv1);
900
901 return sendHelper.sendGroupMessage(messageBuilder.build(),
902 gv1.getMembersIncludingPendingWithout(account.getSelfRecipientId()));
903 }
904
905 private void updateGroupV1Details(
906 final GroupInfoV1 g, final String name, final Collection<RecipientId> members, final File avatarFile
907 ) throws IOException {
908 if (name != null) {
909 g.name = name;
910 }
911
912 if (members != null) {
913 final var newMemberAddresses = members.stream()
914 .filter(member -> !g.isMember(member))
915 .map(this::resolveSignalServiceAddress)
916 .collect(Collectors.toList());
917 final var newE164Members = new HashSet<String>();
918 for (var member : newMemberAddresses) {
919 if (!member.getNumber().isPresent()) {
920 continue;
921 }
922 newE164Members.add(member.getNumber().get());
923 }
924
925 final var registeredUsers = getRegisteredUsers(newE164Members);
926 if (registeredUsers.size() != newE164Members.size()) {
927 // Some of the new members are not registered on Signal
928 newE164Members.removeAll(registeredUsers.keySet());
929 throw new IOException("Failed to add members "
930 + String.join(", ", newE164Members)
931 + " to group: Not registered on Signal");
932 }
933
934 g.addMembers(members);
935 }
936
937 if (avatarFile != null) {
938 avatarStore.storeGroupAvatar(g.getGroupId(),
939 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
940 }
941 }
942
943 private Pair<Long, List<SendMessageResult>> updateGroupV2(
944 final GroupInfoV2 group,
945 final String name,
946 final String description,
947 final Set<RecipientId> members,
948 final Set<RecipientId> removeMembers,
949 final Set<RecipientId> admins,
950 final Set<RecipientId> removeAdmins,
951 final boolean resetGroupLink,
952 final GroupLinkState groupLinkState,
953 final GroupPermission addMemberPermission,
954 final GroupPermission editDetailsPermission,
955 final File avatarFile,
956 final Integer expirationTimer,
957 final Boolean isAnnouncementGroup
958 ) throws IOException {
959 Pair<Long, List<SendMessageResult>> result = null;
960 if (group.isPendingMember(account.getSelfRecipientId())) {
961 var groupGroupChangePair = groupV2Helper.acceptInvite(group);
962 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
963 }
964
965 if (members != null) {
966 final var newMembers = new HashSet<>(members);
967 newMembers.removeAll(group.getMembers());
968 if (newMembers.size() > 0) {
969 var groupGroupChangePair = groupV2Helper.addMembers(group, newMembers);
970 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
971 }
972 }
973
974 if (removeMembers != null) {
975 var existingRemoveMembers = new HashSet<>(removeMembers);
976 existingRemoveMembers.retainAll(group.getMembers());
977 existingRemoveMembers.remove(getSelfRecipientId());// self can be removed with sendQuitGroupMessage
978 if (existingRemoveMembers.size() > 0) {
979 var groupGroupChangePair = groupV2Helper.removeMembers(group, existingRemoveMembers);
980 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
981 }
982
983 var pendingRemoveMembers = new HashSet<>(removeMembers);
984 pendingRemoveMembers.retainAll(group.getPendingMembers());
985 if (pendingRemoveMembers.size() > 0) {
986 var groupGroupChangePair = groupV2Helper.revokeInvitedMembers(group, pendingRemoveMembers);
987 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
988 }
989 }
990
991 if (admins != null) {
992 final var newAdmins = new HashSet<>(admins);
993 newAdmins.retainAll(group.getMembers());
994 newAdmins.removeAll(group.getAdminMembers());
995 if (newAdmins.size() > 0) {
996 for (var admin : newAdmins) {
997 var groupGroupChangePair = groupV2Helper.setMemberAdmin(group, admin, true);
998 result = sendUpdateGroupV2Message(group,
999 groupGroupChangePair.first(),
1000 groupGroupChangePair.second());
1001 }
1002 }
1003 }
1004
1005 if (removeAdmins != null) {
1006 final var existingRemoveAdmins = new HashSet<>(removeAdmins);
1007 existingRemoveAdmins.retainAll(group.getAdminMembers());
1008 if (existingRemoveAdmins.size() > 0) {
1009 for (var admin : existingRemoveAdmins) {
1010 var groupGroupChangePair = groupV2Helper.setMemberAdmin(group, admin, false);
1011 result = sendUpdateGroupV2Message(group,
1012 groupGroupChangePair.first(),
1013 groupGroupChangePair.second());
1014 }
1015 }
1016 }
1017
1018 if (resetGroupLink) {
1019 var groupGroupChangePair = groupV2Helper.resetGroupLinkPassword(group);
1020 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
1021 }
1022
1023 if (groupLinkState != null) {
1024 var groupGroupChangePair = groupV2Helper.setGroupLinkState(group, groupLinkState);
1025 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
1026 }
1027
1028 if (addMemberPermission != null) {
1029 var groupGroupChangePair = groupV2Helper.setAddMemberPermission(group, addMemberPermission);
1030 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
1031 }
1032
1033 if (editDetailsPermission != null) {
1034 var groupGroupChangePair = groupV2Helper.setEditDetailsPermission(group, editDetailsPermission);
1035 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
1036 }
1037
1038 if (expirationTimer != null) {
1039 var groupGroupChangePair = groupV2Helper.setMessageExpirationTimer(group, expirationTimer);
1040 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
1041 }
1042
1043 if (isAnnouncementGroup != null) {
1044 var groupGroupChangePair = groupV2Helper.setIsAnnouncementGroup(group, isAnnouncementGroup);
1045 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
1046 }
1047
1048 if (name != null || description != null || avatarFile != null) {
1049 var groupGroupChangePair = groupV2Helper.updateGroup(group, name, description, avatarFile);
1050 if (avatarFile != null) {
1051 avatarStore.storeGroupAvatar(group.getGroupId(),
1052 outputStream -> IOUtils.copyFileToStream(avatarFile, outputStream));
1053 }
1054 result = sendUpdateGroupV2Message(group, groupGroupChangePair.first(), groupGroupChangePair.second());
1055 }
1056
1057 return result;
1058 }
1059
1060 public Pair<GroupId, List<SendMessageResult>> joinGroup(
1061 GroupInviteLinkUrl inviteLinkUrl
1062 ) throws IOException, GroupLinkNotActiveException {
1063 final var groupJoinInfo = groupV2Helper.getDecryptedGroupJoinInfo(inviteLinkUrl.getGroupMasterKey(),
1064 inviteLinkUrl.getPassword());
1065 final var groupChange = groupV2Helper.joinGroup(inviteLinkUrl.getGroupMasterKey(),
1066 inviteLinkUrl.getPassword(),
1067 groupJoinInfo);
1068 final var group = getOrMigrateGroup(inviteLinkUrl.getGroupMasterKey(),
1069 groupJoinInfo.getRevision() + 1,
1070 groupChange.toByteArray());
1071
1072 if (group.getGroup() == null) {
1073 // Only requested member, can't send update to group members
1074 return new Pair<>(group.getGroupId(), List.of());
1075 }
1076
1077 final var result = sendUpdateGroupV2Message(group, group.getGroup(), groupChange);
1078
1079 return new Pair<>(group.getGroupId(), result.second());
1080 }
1081
1082 private Pair<Long, List<SendMessageResult>> sendUpdateGroupV2Message(
1083 GroupInfoV2 group, DecryptedGroup newDecryptedGroup, GroupChange groupChange
1084 ) throws IOException {
1085 final var selfRecipientId = account.getSelfRecipientId();
1086 final var members = group.getMembersIncludingPendingWithout(selfRecipientId);
1087 group.setGroup(newDecryptedGroup, this::resolveRecipient);
1088 members.addAll(group.getMembersIncludingPendingWithout(selfRecipientId));
1089
1090 final var messageBuilder = getGroupUpdateMessageBuilder(group, groupChange.toByteArray());
1091 account.getGroupStore().updateGroup(group);
1092 return sendHelper.sendGroupMessage(messageBuilder.build(), members);
1093 }
1094
1095 private static int currentTimeDays() {
1096 return (int) TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis());
1097 }
1098
1099 private GroupsV2AuthorizationString getGroupAuthForToday(
1100 final GroupSecretParams groupSecretParams
1101 ) throws IOException {
1102 final var today = currentTimeDays();
1103 // Returns credentials for the next 7 days
1104 final var credentials = dependencies.getGroupsV2Api().getCredentials(today);
1105 // TODO cache credentials until they expire
1106 var authCredentialResponse = credentials.get(today);
1107 try {
1108 return dependencies.getGroupsV2Api()
1109 .getGroupsV2AuthorizationString(account.getUuid(),
1110 today,
1111 groupSecretParams,
1112 authCredentialResponse);
1113 } catch (VerificationFailedException e) {
1114 throw new IOException(e);
1115 }
1116 }
1117
1118 Pair<Long, List<SendMessageResult>> sendGroupInfoMessage(
1119 GroupIdV1 groupId, SignalServiceAddress recipient
1120 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, AttachmentInvalidException {
1121 GroupInfoV1 g;
1122 var group = getGroupForUpdating(groupId);
1123 if (!(group instanceof GroupInfoV1)) {
1124 throw new IOException("Received an invalid group request for a v2 group!");
1125 }
1126 g = (GroupInfoV1) group;
1127
1128 final var recipientId = resolveRecipient(recipient);
1129 if (!g.isMember(recipientId)) {
1130 throw new NotAGroupMemberException(groupId, g.name);
1131 }
1132
1133 var messageBuilder = getGroupUpdateMessageBuilder(g);
1134
1135 // Send group message only to the recipient who requested it
1136 return sendHelper.sendGroupMessage(messageBuilder.build(), Set.of(recipientId));
1137 }
1138
1139 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfoV1 g) throws AttachmentInvalidException {
1140 var group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.UPDATE)
1141 .withId(g.getGroupId().serialize())
1142 .withName(g.name)
1143 .withMembers(g.getMembers()
1144 .stream()
1145 .map(this::resolveSignalServiceAddress)
1146 .collect(Collectors.toList()));
1147
1148 try {
1149 final var attachment = createGroupAvatarAttachment(g.getGroupId());
1150 if (attachment.isPresent()) {
1151 group.withAvatar(attachment.get());
1152 }
1153 } catch (IOException e) {
1154 throw new AttachmentInvalidException(g.getGroupId().toBase64(), e);
1155 }
1156
1157 return createMessageBuilder().asGroupMessage(group.build()).withExpiration(g.getMessageExpirationTime());
1158 }
1159
1160 private SignalServiceDataMessage.Builder getGroupUpdateMessageBuilder(GroupInfoV2 g, byte[] signedGroupChange) {
1161 var group = SignalServiceGroupV2.newBuilder(g.getMasterKey())
1162 .withRevision(g.getGroup().getRevision())
1163 .withSignedGroupChange(signedGroupChange);
1164 return createMessageBuilder().asGroupMessage(group.build()).withExpiration(g.getMessageExpirationTime());
1165 }
1166
1167 Pair<Long, List<SendMessageResult>> sendGroupInfoRequest(
1168 GroupIdV1 groupId, SignalServiceAddress recipient
1169 ) throws IOException {
1170 var group = SignalServiceGroup.newBuilder(SignalServiceGroup.Type.REQUEST_INFO).withId(groupId.serialize());
1171
1172 var messageBuilder = createMessageBuilder().asGroupMessage(group.build());
1173
1174 // Send group info request message to the recipient who sent us a message with this groupId
1175 return sendHelper.sendGroupMessage(messageBuilder.build(), Set.of(resolveRecipient(recipient)));
1176 }
1177
1178 void sendReceipt(
1179 SignalServiceAddress remoteAddress, long messageId
1180 ) throws IOException, UntrustedIdentityException {
1181 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.DELIVERY,
1182 List.of(messageId),
1183 System.currentTimeMillis());
1184
1185 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(remoteAddress));
1186 }
1187
1188 public Pair<Long, List<SendMessageResult>> sendMessage(
1189 String messageText, List<String> attachments, List<String> recipients
1190 ) throws IOException, AttachmentInvalidException, InvalidNumberException {
1191 final var messageBuilder = createMessageBuilder().withBody(messageText);
1192 if (attachments != null) {
1193 var attachmentStreams = AttachmentUtils.getSignalServiceAttachments(attachments);
1194
1195 // Upload attachments here, so we only upload once even for multiple recipients
1196 var messageSender = dependencies.getMessageSender();
1197 var attachmentPointers = new ArrayList<SignalServiceAttachment>(attachmentStreams.size());
1198 for (var attachment : attachmentStreams) {
1199 if (attachment.isStream()) {
1200 attachmentPointers.add(messageSender.uploadAttachment(attachment.asStream()));
1201 } else if (attachment.isPointer()) {
1202 attachmentPointers.add(attachment.asPointer());
1203 }
1204 }
1205
1206 messageBuilder.withAttachments(attachmentPointers);
1207 }
1208 return sendHelper.sendMessage(messageBuilder, getRecipientIds(recipients));
1209 }
1210
1211 public Pair<Long, SendMessageResult> sendSelfMessage(
1212 String messageText, List<String> attachments
1213 ) throws IOException, AttachmentInvalidException {
1214 final var messageBuilder = createMessageBuilder().withBody(messageText);
1215 if (attachments != null) {
1216 messageBuilder.withAttachments(AttachmentUtils.getSignalServiceAttachments(attachments));
1217 }
1218 return sendHelper.sendSelfMessage(messageBuilder);
1219 }
1220
1221 public Pair<Long, List<SendMessageResult>> sendRemoteDeleteMessage(
1222 long targetSentTimestamp, List<String> recipients
1223 ) throws IOException, InvalidNumberException {
1224 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
1225 final var messageBuilder = createMessageBuilder().withRemoteDelete(delete);
1226 return sendHelper.sendMessage(messageBuilder, getRecipientIds(recipients));
1227 }
1228
1229 public Pair<Long, List<SendMessageResult>> sendGroupRemoteDeleteMessage(
1230 long targetSentTimestamp, GroupId groupId
1231 ) throws IOException, NotAGroupMemberException, GroupNotFoundException {
1232 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
1233 final var messageBuilder = createMessageBuilder().withRemoteDelete(delete);
1234 return sendHelper.sendAsGroupMessage(messageBuilder, groupId);
1235 }
1236
1237 public Pair<Long, List<SendMessageResult>> sendMessageReaction(
1238 String emoji, boolean remove, String targetAuthor, long targetSentTimestamp, List<String> recipients
1239 ) throws IOException, InvalidNumberException {
1240 var targetAuthorRecipientId = canonicalizeAndResolveRecipient(targetAuthor);
1241 var reaction = new SignalServiceDataMessage.Reaction(emoji,
1242 remove,
1243 resolveSignalServiceAddress(targetAuthorRecipientId),
1244 targetSentTimestamp);
1245 final var messageBuilder = createMessageBuilder().withReaction(reaction);
1246 return sendHelper.sendMessage(messageBuilder, getRecipientIds(recipients));
1247 }
1248
1249 public Pair<Long, List<SendMessageResult>> sendEndSessionMessage(List<String> recipients) throws IOException, InvalidNumberException {
1250 var messageBuilder = createMessageBuilder().asEndSessionMessage();
1251
1252 final var recipientIds = getRecipientIds(recipients);
1253 try {
1254 return sendHelper.sendMessage(messageBuilder, recipientIds);
1255 } finally {
1256 for (var recipientId : recipientIds) {
1257 handleEndSession(recipientId);
1258 }
1259 }
1260 }
1261
1262 void renewSession(RecipientId recipientId) throws IOException {
1263 account.getSessionStore().archiveSessions(recipientId);
1264 if (!recipientId.equals(getSelfRecipientId())) {
1265 sendHelper.sendNullMessage(recipientId);
1266 }
1267 }
1268
1269 public void setContactName(String number, String name) throws InvalidNumberException, NotMasterDeviceException {
1270 if (!account.isMasterDevice()) {
1271 throw new NotMasterDeviceException();
1272 }
1273 final var recipientId = canonicalizeAndResolveRecipient(number);
1274 var contact = account.getContactStore().getContact(recipientId);
1275 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
1276 account.getContactStore().storeContact(recipientId, builder.withName(name).build());
1277 }
1278
1279 public void setContactBlocked(
1280 String number, boolean blocked
1281 ) throws InvalidNumberException, NotMasterDeviceException {
1282 if (!account.isMasterDevice()) {
1283 throw new NotMasterDeviceException();
1284 }
1285 setContactBlocked(canonicalizeAndResolveRecipient(number), blocked);
1286 }
1287
1288 private void setContactBlocked(RecipientId recipientId, boolean blocked) {
1289 var contact = account.getContactStore().getContact(recipientId);
1290 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
1291 account.getContactStore().storeContact(recipientId, builder.withBlocked(blocked).build());
1292 }
1293
1294 public void setGroupBlocked(final GroupId groupId, final boolean blocked) throws GroupNotFoundException {
1295 var group = getGroup(groupId);
1296 if (group == null) {
1297 throw new GroupNotFoundException(groupId);
1298 }
1299
1300 group.setBlocked(blocked);
1301 account.getGroupStore().updateGroup(group);
1302 }
1303
1304 private void setExpirationTimer(RecipientId recipientId, int messageExpirationTimer) {
1305 var contact = account.getContactStore().getContact(recipientId);
1306 if (contact != null && contact.getMessageExpirationTime() == messageExpirationTimer) {
1307 return;
1308 }
1309 final var builder = contact == null ? Contact.newBuilder() : Contact.newBuilder(contact);
1310 account.getContactStore()
1311 .storeContact(recipientId, builder.withMessageExpirationTime(messageExpirationTimer).build());
1312 }
1313
1314 private void sendExpirationTimerUpdate(RecipientId recipientId) throws IOException {
1315 final var messageBuilder = createMessageBuilder().asExpirationUpdate();
1316 sendHelper.sendMessage(messageBuilder, Set.of(recipientId));
1317 }
1318
1319 /**
1320 * Change the expiration timer for a contact
1321 */
1322 public void setExpirationTimer(
1323 String number, int messageExpirationTimer
1324 ) throws IOException, InvalidNumberException {
1325 var recipientId = canonicalizeAndResolveRecipient(number);
1326 setExpirationTimer(recipientId, messageExpirationTimer);
1327 sendExpirationTimerUpdate(recipientId);
1328 }
1329
1330 /**
1331 * Change the expiration timer for a group
1332 */
1333 private void setExpirationTimer(
1334 GroupInfoV1 groupInfoV1, int messageExpirationTimer
1335 ) throws NotAGroupMemberException, GroupNotFoundException, IOException {
1336 groupInfoV1.messageExpirationTime = messageExpirationTimer;
1337 account.getGroupStore().updateGroup(groupInfoV1);
1338 sendExpirationTimerUpdate(groupInfoV1.getGroupId());
1339 }
1340
1341 private void sendExpirationTimerUpdate(GroupIdV1 groupId) throws IOException, NotAGroupMemberException, GroupNotFoundException {
1342 final var messageBuilder = createMessageBuilder().asExpirationUpdate();
1343 sendHelper.sendAsGroupMessage(messageBuilder, groupId);
1344 }
1345
1346 /**
1347 * Upload the sticker pack from path.
1348 *
1349 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
1350 * @return if successful, returns the URL to install the sticker pack in the signal app
1351 */
1352 public String uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
1353 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
1354
1355 var messageSender = dependencies.getMessageSender();
1356
1357 var packKey = KeyUtils.createStickerUploadKey();
1358 var packIdString = messageSender.uploadStickerManifest(manifest, packKey);
1359 var packId = StickerPackId.deserialize(Hex.fromStringCondensed(packIdString));
1360
1361 var sticker = new Sticker(packId, packKey);
1362 account.getStickerStore().updateSticker(sticker);
1363
1364 try {
1365 return new URI("https",
1366 "signal.art",
1367 "/addstickers/",
1368 "pack_id="
1369 + URLEncoder.encode(Hex.toStringCondensed(packId.serialize()), StandardCharsets.UTF_8)
1370 + "&pack_key="
1371 + URLEncoder.encode(Hex.toStringCondensed(packKey), StandardCharsets.UTF_8)).toString();
1372 } catch (URISyntaxException e) {
1373 throw new AssertionError(e);
1374 }
1375 }
1376
1377 public void requestAllSyncData() throws IOException {
1378 requestSyncGroups();
1379 requestSyncContacts();
1380 requestSyncBlocked();
1381 requestSyncConfiguration();
1382 requestSyncKeys();
1383 }
1384
1385 private void requestSyncGroups() throws IOException {
1386 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1387 .setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS)
1388 .build();
1389 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1390 sendHelper.sendSyncMessage(message);
1391 }
1392
1393 private void requestSyncContacts() throws IOException {
1394 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1395 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS)
1396 .build();
1397 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1398 sendHelper.sendSyncMessage(message);
1399 }
1400
1401 private void requestSyncBlocked() throws IOException {
1402 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1403 .setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED)
1404 .build();
1405 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1406 sendHelper.sendSyncMessage(message);
1407 }
1408
1409 private void requestSyncConfiguration() throws IOException {
1410 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1411 .setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION)
1412 .build();
1413 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1414 sendHelper.sendSyncMessage(message);
1415 }
1416
1417 private void requestSyncKeys() throws IOException {
1418 var r = SignalServiceProtos.SyncMessage.Request.newBuilder()
1419 .setType(SignalServiceProtos.SyncMessage.Request.Type.KEYS)
1420 .build();
1421 var message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
1422 sendHelper.sendSyncMessage(message);
1423 }
1424
1425 private byte[] getSenderCertificate() {
1426 byte[] certificate;
1427 try {
1428 if (account.isPhoneNumberShared()) {
1429 certificate = dependencies.getAccountManager().getSenderCertificate();
1430 } else {
1431 certificate = dependencies.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
1432 }
1433 } catch (IOException e) {
1434 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
1435 return null;
1436 }
1437 // TODO cache for a day
1438 return certificate;
1439 }
1440
1441 private Set<RecipientId> getRecipientIds(Collection<String> numbers) throws InvalidNumberException {
1442 final var signalServiceAddresses = new HashSet<SignalServiceAddress>(numbers.size());
1443 final var addressesMissingUuid = new HashSet<SignalServiceAddress>();
1444
1445 for (var number : numbers) {
1446 final var resolvedAddress = resolveSignalServiceAddress(canonicalizeAndResolveRecipient(number));
1447 if (resolvedAddress.getUuid().isPresent()) {
1448 signalServiceAddresses.add(resolvedAddress);
1449 } else {
1450 addressesMissingUuid.add(resolvedAddress);
1451 }
1452 }
1453
1454 final var numbersMissingUuid = addressesMissingUuid.stream()
1455 .map(a -> a.getNumber().get())
1456 .collect(Collectors.toSet());
1457 Map<String, UUID> registeredUsers;
1458 try {
1459 registeredUsers = getRegisteredUsers(numbersMissingUuid);
1460 } catch (IOException e) {
1461 logger.warn("Failed to resolve uuids from server, ignoring: {}", e.getMessage());
1462 registeredUsers = Map.of();
1463 }
1464
1465 for (var address : addressesMissingUuid) {
1466 final var number = address.getNumber().get();
1467 if (registeredUsers.containsKey(number)) {
1468 final var newAddress = resolveSignalServiceAddress(resolveRecipientTrusted(new SignalServiceAddress(
1469 registeredUsers.get(number),
1470 number)));
1471 signalServiceAddresses.add(newAddress);
1472 } else {
1473 signalServiceAddresses.add(address);
1474 }
1475 }
1476
1477 return signalServiceAddresses.stream().map(this::resolveRecipient).collect(Collectors.toSet());
1478 }
1479
1480 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
1481 final var address = resolveSignalServiceAddress(recipientId);
1482 if (!address.getNumber().isPresent()) {
1483 return recipientId;
1484 }
1485 final var number = address.getNumber().get();
1486 final var uuidMap = getRegisteredUsers(Set.of(number));
1487 return resolveRecipientTrusted(new SignalServiceAddress(uuidMap.getOrDefault(number, null), number));
1488 }
1489
1490 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
1491 try {
1492 return dependencies.getAccountManager()
1493 .getRegisteredUsers(ServiceConfig.getIasKeyStore(),
1494 numbers,
1495 serviceEnvironmentConfig.getCdsMrenclave());
1496 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
1497 throw new IOException(e);
1498 }
1499 }
1500
1501 public void sendTypingMessage(
1502 TypingAction action, Set<String> recipients
1503 ) throws IOException, UntrustedIdentityException, InvalidNumberException {
1504 final var timestamp = System.currentTimeMillis();
1505 var message = new SignalServiceTypingMessage(action.toSignalService(), timestamp, Optional.absent());
1506 sendHelper.sendTypingMessage(message, getRecipientIds(recipients));
1507 }
1508
1509 public void sendGroupTypingMessage(
1510 TypingAction action, GroupId groupId
1511 ) throws IOException, NotAGroupMemberException, GroupNotFoundException {
1512 final var timestamp = System.currentTimeMillis();
1513 final var message = new SignalServiceTypingMessage(action.toSignalService(),
1514 timestamp,
1515 Optional.of(groupId.serialize()));
1516 sendHelper.sendGroupTypingMessage(message, groupId);
1517 }
1518
1519 private SignalServiceDataMessage.Builder createMessageBuilder() {
1520 final var timestamp = System.currentTimeMillis();
1521
1522 var messageBuilder = SignalServiceDataMessage.newBuilder();
1523 messageBuilder.withTimestamp(timestamp);
1524 return messageBuilder;
1525 }
1526
1527 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, SelfSendException, UnsupportedDataMessageException, ProtocolUntrustedIdentityException, InvalidMessageStructureException {
1528 return dependencies.getCipher().decrypt(envelope);
1529 }
1530
1531 private void handleEndSession(RecipientId recipientId) {
1532 account.getSessionStore().deleteAllSessions(recipientId);
1533 }
1534
1535 private List<HandleAction> handleSignalServiceDataMessage(
1536 SignalServiceDataMessage message,
1537 boolean isSync,
1538 SignalServiceAddress source,
1539 SignalServiceAddress destination,
1540 boolean ignoreAttachments
1541 ) {
1542 var actions = new ArrayList<HandleAction>();
1543 if (message.getGroupContext().isPresent()) {
1544 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1545 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1546 var groupId = GroupId.v1(groupInfo.getGroupId());
1547 var group = getGroup(groupId);
1548 if (group == null || group instanceof GroupInfoV1) {
1549 var groupV1 = (GroupInfoV1) group;
1550 switch (groupInfo.getType()) {
1551 case UPDATE: {
1552 if (groupV1 == null) {
1553 groupV1 = new GroupInfoV1(groupId);
1554 }
1555
1556 if (groupInfo.getAvatar().isPresent()) {
1557 var avatar = groupInfo.getAvatar().get();
1558 downloadGroupAvatar(avatar, groupV1.getGroupId());
1559 }
1560
1561 if (groupInfo.getName().isPresent()) {
1562 groupV1.name = groupInfo.getName().get();
1563 }
1564
1565 if (groupInfo.getMembers().isPresent()) {
1566 groupV1.addMembers(groupInfo.getMembers()
1567 .get()
1568 .stream()
1569 .map(this::resolveRecipient)
1570 .collect(Collectors.toSet()));
1571 }
1572
1573 account.getGroupStore().updateGroup(groupV1);
1574 break;
1575 }
1576 case DELIVER:
1577 if (groupV1 == null && !isSync) {
1578 actions.add(new SendGroupInfoRequestAction(source, groupId));
1579 }
1580 break;
1581 case QUIT: {
1582 if (groupV1 != null) {
1583 groupV1.removeMember(resolveRecipient(source));
1584 account.getGroupStore().updateGroup(groupV1);
1585 }
1586 break;
1587 }
1588 case REQUEST_INFO:
1589 if (groupV1 != null && !isSync) {
1590 actions.add(new SendGroupInfoAction(source, groupV1.getGroupId()));
1591 }
1592 break;
1593 }
1594 } else {
1595 // Received a group v1 message for a v2 group
1596 }
1597 }
1598 if (message.getGroupContext().get().getGroupV2().isPresent()) {
1599 final var groupContext = message.getGroupContext().get().getGroupV2().get();
1600 final var groupMasterKey = groupContext.getMasterKey();
1601
1602 getOrMigrateGroup(groupMasterKey,
1603 groupContext.getRevision(),
1604 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
1605 }
1606 }
1607
1608 final var conversationPartnerAddress = isSync ? destination : source;
1609 if (conversationPartnerAddress != null && message.isEndSession()) {
1610 handleEndSession(resolveRecipient(conversationPartnerAddress));
1611 }
1612 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1613 if (message.getGroupContext().isPresent()) {
1614 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1615 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1616 var group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
1617 if (group != null) {
1618 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
1619 group.messageExpirationTime = message.getExpiresInSeconds();
1620 account.getGroupStore().updateGroup(group);
1621 }
1622 }
1623 } else if (message.getGroupContext().get().getGroupV2().isPresent()) {
1624 // disappearing message timer already stored in the DecryptedGroup
1625 }
1626 } else if (conversationPartnerAddress != null) {
1627 setExpirationTimer(resolveRecipient(conversationPartnerAddress), message.getExpiresInSeconds());
1628 }
1629 }
1630 if (!ignoreAttachments) {
1631 if (message.getAttachments().isPresent()) {
1632 for (var attachment : message.getAttachments().get()) {
1633 downloadAttachment(attachment);
1634 }
1635 }
1636 if (message.getSharedContacts().isPresent()) {
1637 for (var contact : message.getSharedContacts().get()) {
1638 if (contact.getAvatar().isPresent()) {
1639 downloadAttachment(contact.getAvatar().get().getAttachment());
1640 }
1641 }
1642 }
1643 }
1644 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1645 final ProfileKey profileKey;
1646 try {
1647 profileKey = new ProfileKey(message.getProfileKey().get());
1648 } catch (InvalidInputException e) {
1649 throw new AssertionError(e);
1650 }
1651 if (source.matches(account.getSelfAddress())) {
1652 this.account.setProfileKey(profileKey);
1653 }
1654 this.account.getProfileStore().storeProfileKey(resolveRecipient(source), profileKey);
1655 }
1656 if (message.getPreviews().isPresent()) {
1657 final var previews = message.getPreviews().get();
1658 for (var preview : previews) {
1659 if (preview.getImage().isPresent()) {
1660 downloadAttachment(preview.getImage().get());
1661 }
1662 }
1663 }
1664 if (message.getQuote().isPresent()) {
1665 final var quote = message.getQuote().get();
1666
1667 for (var quotedAttachment : quote.getAttachments()) {
1668 final var thumbnail = quotedAttachment.getThumbnail();
1669 if (thumbnail != null) {
1670 downloadAttachment(thumbnail);
1671 }
1672 }
1673 }
1674 if (message.getSticker().isPresent()) {
1675 final var messageSticker = message.getSticker().get();
1676 final var stickerPackId = StickerPackId.deserialize(messageSticker.getPackId());
1677 var sticker = account.getStickerStore().getSticker(stickerPackId);
1678 if (sticker == null) {
1679 sticker = new Sticker(stickerPackId, messageSticker.getPackKey());
1680 account.getStickerStore().updateSticker(sticker);
1681 }
1682 enqueueJob(new RetrieveStickerPackJob(stickerPackId, messageSticker.getPackKey()));
1683 }
1684 return actions;
1685 }
1686
1687 private GroupInfoV2 getOrMigrateGroup(
1688 final GroupMasterKey groupMasterKey, final int revision, final byte[] signedGroupChange
1689 ) {
1690 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
1691
1692 var groupId = GroupUtils.getGroupIdV2(groupSecretParams);
1693 var groupInfo = getGroup(groupId);
1694 final GroupInfoV2 groupInfoV2;
1695 if (groupInfo instanceof GroupInfoV1) {
1696 // Received a v2 group message for a v1 group, we need to locally migrate the group
1697 account.getGroupStore().deleteGroupV1(((GroupInfoV1) groupInfo).getGroupId());
1698 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1699 logger.info("Locally migrated group {} to group v2, id: {}",
1700 groupInfo.getGroupId().toBase64(),
1701 groupInfoV2.getGroupId().toBase64());
1702 } else if (groupInfo instanceof GroupInfoV2) {
1703 groupInfoV2 = (GroupInfoV2) groupInfo;
1704 } else {
1705 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1706 }
1707
1708 if (groupInfoV2.getGroup() == null || groupInfoV2.getGroup().getRevision() < revision) {
1709 DecryptedGroup group = null;
1710 if (signedGroupChange != null
1711 && groupInfoV2.getGroup() != null
1712 && groupInfoV2.getGroup().getRevision() + 1 == revision) {
1713 group = groupV2Helper.getUpdatedDecryptedGroup(groupInfoV2.getGroup(),
1714 signedGroupChange,
1715 groupMasterKey);
1716 }
1717 if (group == null) {
1718 group = groupV2Helper.getDecryptedGroup(groupSecretParams);
1719 }
1720 if (group != null) {
1721 storeProfileKeysFromMembers(group);
1722 final var avatar = group.getAvatar();
1723 if (avatar != null && !avatar.isEmpty()) {
1724 downloadGroupAvatar(groupId, groupSecretParams, avatar);
1725 }
1726 }
1727 groupInfoV2.setGroup(group, this::resolveRecipient);
1728 account.getGroupStore().updateGroup(groupInfoV2);
1729 }
1730
1731 return groupInfoV2;
1732 }
1733
1734 private void storeProfileKeysFromMembers(final DecryptedGroup group) {
1735 for (var member : group.getMembersList()) {
1736 final var uuid = UuidUtil.parseOrThrow(member.getUuid().toByteArray());
1737 final var recipientId = account.getRecipientStore().resolveRecipient(uuid);
1738 try {
1739 account.getProfileStore()
1740 .storeProfileKey(recipientId, new ProfileKey(member.getProfileKey().toByteArray()));
1741 } catch (InvalidInputException ignored) {
1742 }
1743 }
1744 }
1745
1746 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1747 Set<HandleAction> queuedActions = new HashSet<>();
1748 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
1749 var actions = retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
1750 if (actions != null) {
1751 queuedActions.addAll(actions);
1752 }
1753 }
1754 for (var action : queuedActions) {
1755 try {
1756 action.execute(this);
1757 } catch (Throwable e) {
1758 if (e instanceof AssertionError && e.getCause() instanceof InterruptedException) {
1759 Thread.currentThread().interrupt();
1760 }
1761 logger.warn("Message action failed.", e);
1762 }
1763 }
1764 }
1765
1766 private List<HandleAction> retryFailedReceivedMessage(
1767 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
1768 ) {
1769 var envelope = cachedMessage.loadEnvelope();
1770 if (envelope == null) {
1771 return null;
1772 }
1773 SignalServiceContent content = null;
1774 List<HandleAction> actions = null;
1775 if (!envelope.isReceipt()) {
1776 try {
1777 content = decryptMessage(envelope);
1778 } catch (ProtocolUntrustedIdentityException e) {
1779 if (!envelope.hasSource()) {
1780 final var identifier = e.getSender();
1781 final var recipientId = resolveRecipient(identifier);
1782 try {
1783 account.getMessageCache().replaceSender(cachedMessage, recipientId);
1784 } catch (IOException ioException) {
1785 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
1786 }
1787 }
1788 return null;
1789 } catch (Exception er) {
1790 // All other errors are not recoverable, so delete the cached message
1791 cachedMessage.delete();
1792 return null;
1793 }
1794 actions = handleMessage(envelope, content, ignoreAttachments);
1795 }
1796 handler.handleMessage(envelope, content, null);
1797 cachedMessage.delete();
1798 return actions;
1799 }
1800
1801 public void receiveMessages(
1802 long timeout,
1803 TimeUnit unit,
1804 boolean returnOnTimeout,
1805 boolean ignoreAttachments,
1806 ReceiveMessageHandler handler
1807 ) throws IOException, InterruptedException {
1808 retryFailedReceivedMessages(handler, ignoreAttachments);
1809
1810 Set<HandleAction> queuedActions = null;
1811
1812 final var signalWebSocket = dependencies.getSignalWebSocket();
1813 signalWebSocket.connect();
1814
1815 var hasCaughtUpWithOldMessages = false;
1816
1817 while (!Thread.interrupted()) {
1818 SignalServiceEnvelope envelope;
1819 SignalServiceContent content = null;
1820 Exception exception = null;
1821 final CachedMessage[] cachedMessage = {null};
1822 account.setLastReceiveTimestamp(System.currentTimeMillis());
1823 logger.debug("Checking for new message from server");
1824 try {
1825 var result = signalWebSocket.readOrEmpty(unit.toMillis(timeout), envelope1 -> {
1826 final var recipientId = envelope1.hasSource()
1827 ? resolveRecipient(envelope1.getSourceIdentifier())
1828 : null;
1829 // store message on disk, before acknowledging receipt to the server
1830 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
1831 });
1832 logger.debug("New message received from server");
1833 if (result.isPresent()) {
1834 envelope = result.get();
1835 } else {
1836 // Received indicator that server queue is empty
1837 hasCaughtUpWithOldMessages = true;
1838
1839 if (queuedActions != null) {
1840 for (var action : queuedActions) {
1841 try {
1842 action.execute(this);
1843 } catch (Throwable e) {
1844 if (e instanceof AssertionError && e.getCause() instanceof InterruptedException) {
1845 Thread.currentThread().interrupt();
1846 }
1847 logger.warn("Message action failed.", e);
1848 }
1849 }
1850 queuedActions.clear();
1851 queuedActions = null;
1852 }
1853
1854 // Continue to wait another timeout for new messages
1855 continue;
1856 }
1857 } catch (AssertionError e) {
1858 if (e.getCause() instanceof InterruptedException) {
1859 throw (InterruptedException) e.getCause();
1860 } else {
1861 throw e;
1862 }
1863 } catch (WebSocketUnavailableException e) {
1864 logger.debug("Pipe unexpectedly unavailable, connecting");
1865 signalWebSocket.connect();
1866 continue;
1867 } catch (TimeoutException e) {
1868 if (returnOnTimeout) return;
1869 continue;
1870 }
1871
1872 if (envelope.hasSource()) {
1873 // Store uuid if we don't have it already
1874 // address/uuid in envelope is sent by server
1875 resolveRecipientTrusted(envelope.getSourceAddress());
1876 }
1877 final var notAGroupMember = isNotAGroupMember(envelope, content);
1878 if (!envelope.isReceipt()) {
1879 try {
1880 content = decryptMessage(envelope);
1881 } catch (Exception e) {
1882 exception = e;
1883 }
1884 if (!envelope.hasSource() && content != null) {
1885 // Store uuid if we don't have it already
1886 // address/uuid is validated by unidentified sender certificate
1887 resolveRecipientTrusted(content.getSender());
1888 }
1889 var actions = handleMessage(envelope, content, ignoreAttachments);
1890 if (exception instanceof ProtocolInvalidMessageException) {
1891 final var sender = resolveRecipient(((ProtocolInvalidMessageException) exception).getSender());
1892 logger.debug("Received invalid message, queuing renew session action.");
1893 actions.add(new RenewSessionAction(sender));
1894 }
1895 if (hasCaughtUpWithOldMessages) {
1896 for (var action : actions) {
1897 try {
1898 action.execute(this);
1899 } catch (Throwable e) {
1900 if (e instanceof AssertionError && e.getCause() instanceof InterruptedException) {
1901 Thread.currentThread().interrupt();
1902 }
1903 logger.warn("Message action failed.", e);
1904 }
1905 }
1906 } else {
1907 if (queuedActions == null) {
1908 queuedActions = new HashSet<>();
1909 }
1910 queuedActions.addAll(actions);
1911 }
1912 }
1913 if (isMessageBlocked(envelope, content)) {
1914 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
1915 } else if (notAGroupMember) {
1916 logger.info("Ignoring a message from a non group member: {}", envelope.getTimestamp());
1917 } else {
1918 handler.handleMessage(envelope, content, exception);
1919 }
1920 if (cachedMessage[0] != null) {
1921 if (exception instanceof ProtocolUntrustedIdentityException) {
1922 final var identifier = ((ProtocolUntrustedIdentityException) exception).getSender();
1923 final var recipientId = resolveRecipient(identifier);
1924 queuedActions.add(new RetrieveProfileAction(recipientId));
1925 if (!envelope.hasSource()) {
1926 try {
1927 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
1928 } catch (IOException ioException) {
1929 logger.warn("Failed to move cached message to recipient folder: {}",
1930 ioException.getMessage());
1931 }
1932 }
1933 } else {
1934 cachedMessage[0].delete();
1935 }
1936 }
1937 }
1938 }
1939
1940 private boolean isMessageBlocked(
1941 SignalServiceEnvelope envelope, SignalServiceContent content
1942 ) {
1943 SignalServiceAddress source;
1944 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1945 source = envelope.getSourceAddress();
1946 } else if (content != null) {
1947 source = content.getSender();
1948 } else {
1949 return false;
1950 }
1951 final var recipientId = resolveRecipient(source);
1952 if (isContactBlocked(recipientId)) {
1953 return true;
1954 }
1955
1956 if (content != null && content.getDataMessage().isPresent()) {
1957 var message = content.getDataMessage().get();
1958 if (message.getGroupContext().isPresent()) {
1959 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1960 var group = getGroup(groupId);
1961 if (group != null && group.isBlocked()) {
1962 return true;
1963 }
1964 }
1965 }
1966 return false;
1967 }
1968
1969 public boolean isContactBlocked(final String identifier) throws InvalidNumberException {
1970 final var recipientId = canonicalizeAndResolveRecipient(identifier);
1971 return isContactBlocked(recipientId);
1972 }
1973
1974 private boolean isContactBlocked(final RecipientId recipientId) {
1975 var sourceContact = account.getContactStore().getContact(recipientId);
1976 return sourceContact != null && sourceContact.isBlocked();
1977 }
1978
1979 private boolean isNotAGroupMember(
1980 SignalServiceEnvelope envelope, SignalServiceContent content
1981 ) {
1982 SignalServiceAddress source;
1983 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1984 source = envelope.getSourceAddress();
1985 } else if (content != null) {
1986 source = content.getSender();
1987 } else {
1988 return false;
1989 }
1990
1991 if (content != null && content.getDataMessage().isPresent()) {
1992 var message = content.getDataMessage().get();
1993 if (message.getGroupContext().isPresent()) {
1994 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1995 var groupInfo = message.getGroupContext().get().getGroupV1().get();
1996 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
1997 return false;
1998 }
1999 }
2000 var groupId = GroupUtils.getGroupId(message.getGroupContext().get());
2001 var group = getGroup(groupId);
2002 if (group != null && !group.isMember(resolveRecipient(source))) {
2003 return true;
2004 }
2005 }
2006 }
2007 return false;
2008 }
2009
2010 private List<HandleAction> handleMessage(
2011 SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments
2012 ) {
2013 var actions = new ArrayList<HandleAction>();
2014 if (content != null) {
2015 final SignalServiceAddress sender;
2016 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
2017 sender = envelope.getSourceAddress();
2018 } else {
2019 sender = content.getSender();
2020 }
2021
2022 if (content.getDataMessage().isPresent()) {
2023 var message = content.getDataMessage().get();
2024
2025 if (content.isNeedsReceipt()) {
2026 actions.add(new SendReceiptAction(sender, message.getTimestamp()));
2027 }
2028
2029 actions.addAll(handleSignalServiceDataMessage(message,
2030 false,
2031 sender,
2032 account.getSelfAddress(),
2033 ignoreAttachments));
2034 }
2035 if (content.getSyncMessage().isPresent()) {
2036 account.setMultiDevice(true);
2037 var syncMessage = content.getSyncMessage().get();
2038 if (syncMessage.getSent().isPresent()) {
2039 var message = syncMessage.getSent().get();
2040 final var destination = message.getDestination().orNull();
2041 actions.addAll(handleSignalServiceDataMessage(message.getMessage(),
2042 true,
2043 sender,
2044 destination,
2045 ignoreAttachments));
2046 }
2047 if (syncMessage.getRequest().isPresent() && account.isMasterDevice()) {
2048 var rm = syncMessage.getRequest().get();
2049 if (rm.isContactsRequest()) {
2050 actions.add(SendSyncContactsAction.create());
2051 }
2052 if (rm.isGroupsRequest()) {
2053 actions.add(SendSyncGroupsAction.create());
2054 }
2055 if (rm.isBlockedListRequest()) {
2056 actions.add(SendSyncBlockedListAction.create());
2057 }
2058 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
2059 }
2060 if (syncMessage.getGroups().isPresent()) {
2061 File tmpFile = null;
2062 try {
2063 tmpFile = IOUtils.createTempFile();
2064 final var groupsMessage = syncMessage.getGroups().get();
2065 try (var attachmentAsStream = retrieveAttachmentAsStream(groupsMessage.asPointer(), tmpFile)) {
2066 var s = new DeviceGroupsInputStream(attachmentAsStream);
2067 DeviceGroup g;
2068 while (true) {
2069 try {
2070 g = s.read();
2071 } catch (IOException e) {
2072 logger.warn("Sync groups contained invalid group, ignoring: {}", e.getMessage());
2073 continue;
2074 }
2075 if (g == null) {
2076 break;
2077 }
2078 var syncGroup = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(g.getId()));
2079 if (syncGroup != null) {
2080 if (g.getName().isPresent()) {
2081 syncGroup.name = g.getName().get();
2082 }
2083 syncGroup.addMembers(g.getMembers()
2084 .stream()
2085 .map(this::resolveRecipient)
2086 .collect(Collectors.toSet()));
2087 if (!g.isActive()) {
2088 syncGroup.removeMember(account.getSelfRecipientId());
2089 } else {
2090 // Add ourself to the member set as it's marked as active
2091 syncGroup.addMembers(List.of(account.getSelfRecipientId()));
2092 }
2093 syncGroup.blocked = g.isBlocked();
2094 if (g.getColor().isPresent()) {
2095 syncGroup.color = g.getColor().get();
2096 }
2097
2098 if (g.getAvatar().isPresent()) {
2099 downloadGroupAvatar(g.getAvatar().get(), syncGroup.getGroupId());
2100 }
2101 syncGroup.archived = g.isArchived();
2102 account.getGroupStore().updateGroup(syncGroup);
2103 }
2104 }
2105 }
2106 } catch (Exception e) {
2107 logger.warn("Failed to handle received sync groups “{}”, ignoring: {}",
2108 tmpFile,
2109 e.getMessage());
2110 } finally {
2111 if (tmpFile != null) {
2112 try {
2113 Files.delete(tmpFile.toPath());
2114 } catch (IOException e) {
2115 logger.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
2116 tmpFile,
2117 e.getMessage());
2118 }
2119 }
2120 }
2121 }
2122 if (syncMessage.getBlockedList().isPresent()) {
2123 final var blockedListMessage = syncMessage.getBlockedList().get();
2124 for (var address : blockedListMessage.getAddresses()) {
2125 setContactBlocked(resolveRecipient(address), true);
2126 }
2127 for (var groupId : blockedListMessage.getGroupIds()
2128 .stream()
2129 .map(GroupId::unknownVersion)
2130 .collect(Collectors.toSet())) {
2131 try {
2132 setGroupBlocked(groupId, true);
2133 } catch (GroupNotFoundException e) {
2134 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2135 groupId.toBase64());
2136 }
2137 }
2138 }
2139 if (syncMessage.getContacts().isPresent()) {
2140 File tmpFile = null;
2141 try {
2142 tmpFile = IOUtils.createTempFile();
2143 final var contactsMessage = syncMessage.getContacts().get();
2144 try (var attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream()
2145 .asPointer(), tmpFile)) {
2146 var s = new DeviceContactsInputStream(attachmentAsStream);
2147 DeviceContact c;
2148 while (true) {
2149 try {
2150 c = s.read();
2151 } catch (IOException e) {
2152 logger.warn("Sync contacts contained invalid contact, ignoring: {}",
2153 e.getMessage());
2154 continue;
2155 }
2156 if (c == null) {
2157 break;
2158 }
2159 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
2160 account.setProfileKey(c.getProfileKey().get());
2161 }
2162 final var recipientId = resolveRecipientTrusted(c.getAddress());
2163 var contact = account.getContactStore().getContact(recipientId);
2164 final var builder = contact == null
2165 ? Contact.newBuilder()
2166 : Contact.newBuilder(contact);
2167 if (c.getName().isPresent()) {
2168 builder.withName(c.getName().get());
2169 }
2170 if (c.getColor().isPresent()) {
2171 builder.withColor(c.getColor().get());
2172 }
2173 if (c.getProfileKey().isPresent()) {
2174 account.getProfileStore().storeProfileKey(recipientId, c.getProfileKey().get());
2175 }
2176 if (c.getVerified().isPresent()) {
2177 final var verifiedMessage = c.getVerified().get();
2178 account.getIdentityKeyStore()
2179 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
2180 verifiedMessage.getIdentityKey(),
2181 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2182 }
2183 if (c.getExpirationTimer().isPresent()) {
2184 builder.withMessageExpirationTime(c.getExpirationTimer().get());
2185 }
2186 builder.withBlocked(c.isBlocked());
2187 builder.withArchived(c.isArchived());
2188 account.getContactStore().storeContact(recipientId, builder.build());
2189
2190 if (c.getAvatar().isPresent()) {
2191 downloadContactAvatar(c.getAvatar().get(), c.getAddress());
2192 }
2193 }
2194 }
2195 } catch (Exception e) {
2196 logger.warn("Failed to handle received sync contacts “{}”, ignoring: {}",
2197 tmpFile,
2198 e.getMessage());
2199 } finally {
2200 if (tmpFile != null) {
2201 try {
2202 Files.delete(tmpFile.toPath());
2203 } catch (IOException e) {
2204 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2205 tmpFile,
2206 e.getMessage());
2207 }
2208 }
2209 }
2210 }
2211 if (syncMessage.getVerified().isPresent()) {
2212 final var verifiedMessage = syncMessage.getVerified().get();
2213 account.getIdentityKeyStore()
2214 .setIdentityTrustLevel(resolveRecipientTrusted(verifiedMessage.getDestination()),
2215 verifiedMessage.getIdentityKey(),
2216 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2217 }
2218 if (syncMessage.getStickerPackOperations().isPresent()) {
2219 final var stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
2220 for (var m : stickerPackOperationMessages) {
2221 if (!m.getPackId().isPresent()) {
2222 continue;
2223 }
2224 final var stickerPackId = StickerPackId.deserialize(m.getPackId().get());
2225 final var installed = !m.getType().isPresent()
2226 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL;
2227
2228 var sticker = account.getStickerStore().getSticker(stickerPackId);
2229 if (m.getPackKey().isPresent()) {
2230 if (sticker == null) {
2231 sticker = new Sticker(stickerPackId, m.getPackKey().get());
2232 }
2233 if (installed) {
2234 enqueueJob(new RetrieveStickerPackJob(stickerPackId, m.getPackKey().get()));
2235 }
2236 }
2237
2238 if (sticker != null) {
2239 sticker.setInstalled(installed);
2240 account.getStickerStore().updateSticker(sticker);
2241 }
2242 }
2243 }
2244 if (syncMessage.getFetchType().isPresent()) {
2245 switch (syncMessage.getFetchType().get()) {
2246 case LOCAL_PROFILE:
2247 getRecipientProfile(account.getSelfRecipientId(), true);
2248 case STORAGE_MANIFEST:
2249 // TODO
2250 }
2251 }
2252 if (syncMessage.getKeys().isPresent()) {
2253 final var keysMessage = syncMessage.getKeys().get();
2254 if (keysMessage.getStorageService().isPresent()) {
2255 final var storageKey = keysMessage.getStorageService().get();
2256 account.setStorageKey(storageKey);
2257 }
2258 }
2259 if (syncMessage.getConfiguration().isPresent()) {
2260 // TODO
2261 }
2262 }
2263 }
2264 return actions;
2265 }
2266
2267 private void downloadContactAvatar(SignalServiceAttachment avatar, SignalServiceAddress address) {
2268 try {
2269 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(avatar, outputStream));
2270 } catch (IOException e) {
2271 logger.warn("Failed to download avatar for contact {}, ignoring: {}", address, e.getMessage());
2272 }
2273 }
2274
2275 private void downloadGroupAvatar(SignalServiceAttachment avatar, GroupId groupId) {
2276 try {
2277 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(avatar, outputStream));
2278 } catch (IOException e) {
2279 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2280 }
2281 }
2282
2283 private void downloadGroupAvatar(GroupId groupId, GroupSecretParams groupSecretParams, String cdnKey) {
2284 try {
2285 avatarStore.storeGroupAvatar(groupId,
2286 outputStream -> retrieveGroupV2Avatar(groupSecretParams, cdnKey, outputStream));
2287 } catch (IOException e) {
2288 logger.warn("Failed to download avatar for group {}, ignoring: {}", groupId.toBase64(), e.getMessage());
2289 }
2290 }
2291
2292 private void downloadProfileAvatar(
2293 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
2294 ) {
2295 try {
2296 avatarStore.storeProfileAvatar(address,
2297 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
2298 } catch (Throwable e) {
2299 if (e instanceof AssertionError && e.getCause() instanceof InterruptedException) {
2300 Thread.currentThread().interrupt();
2301 }
2302 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
2303 }
2304 }
2305
2306 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
2307 return attachmentStore.getAttachmentFile(attachmentId);
2308 }
2309
2310 private void downloadAttachment(final SignalServiceAttachment attachment) {
2311 if (!attachment.isPointer()) {
2312 logger.warn("Invalid state, can't store an attachment stream.");
2313 }
2314
2315 var pointer = attachment.asPointer();
2316 if (pointer.getPreview().isPresent()) {
2317 final var preview = pointer.getPreview().get();
2318 try {
2319 attachmentStore.storeAttachmentPreview(pointer.getRemoteId(),
2320 outputStream -> outputStream.write(preview, 0, preview.length));
2321 } catch (IOException e) {
2322 logger.warn("Failed to download attachment preview, ignoring: {}", e.getMessage());
2323 }
2324 }
2325
2326 try {
2327 attachmentStore.storeAttachment(pointer.getRemoteId(),
2328 outputStream -> retrieveAttachmentPointer(pointer, outputStream));
2329 } catch (IOException e) {
2330 logger.warn("Failed to download attachment ({}), ignoring: {}", pointer.getRemoteId(), e.getMessage());
2331 }
2332 }
2333
2334 private void retrieveGroupV2Avatar(
2335 GroupSecretParams groupSecretParams, String cdnKey, OutputStream outputStream
2336 ) throws IOException {
2337 var groupOperations = dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
2338
2339 var tmpFile = IOUtils.createTempFile();
2340 try (InputStream input = dependencies.getMessageReceiver()
2341 .retrieveGroupsV2ProfileAvatar(cdnKey, tmpFile, ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2342 var encryptedData = IOUtils.readFully(input);
2343
2344 var decryptedData = groupOperations.decryptAvatar(encryptedData);
2345 outputStream.write(decryptedData);
2346 } finally {
2347 try {
2348 Files.delete(tmpFile.toPath());
2349 } catch (IOException e) {
2350 logger.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2351 tmpFile,
2352 e.getMessage());
2353 }
2354 }
2355 }
2356
2357 private void retrieveProfileAvatar(
2358 String avatarPath, ProfileKey profileKey, OutputStream outputStream
2359 ) throws IOException {
2360 var tmpFile = IOUtils.createTempFile();
2361 try (var input = dependencies.getMessageReceiver()
2362 .retrieveProfileAvatar(avatarPath,
2363 tmpFile,
2364 profileKey,
2365 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2366 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2367 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
2368 } finally {
2369 try {
2370 Files.delete(tmpFile.toPath());
2371 } catch (IOException e) {
2372 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2373 tmpFile,
2374 e.getMessage());
2375 }
2376 }
2377 }
2378
2379 private void retrieveAttachment(
2380 final SignalServiceAttachment attachment, final OutputStream outputStream
2381 ) throws IOException {
2382 if (attachment.isPointer()) {
2383 var pointer = attachment.asPointer();
2384 retrieveAttachmentPointer(pointer, outputStream);
2385 } else {
2386 var stream = attachment.asStream();
2387 IOUtils.copyStream(stream.getInputStream(), outputStream);
2388 }
2389 }
2390
2391 private void retrieveAttachmentPointer(
2392 SignalServiceAttachmentPointer pointer, OutputStream outputStream
2393 ) throws IOException {
2394 var tmpFile = IOUtils.createTempFile();
2395 try (var input = retrieveAttachmentAsStream(pointer, tmpFile)) {
2396 IOUtils.copyStream(input, outputStream);
2397 } catch (MissingConfigurationException | InvalidMessageException e) {
2398 throw new IOException(e);
2399 } finally {
2400 try {
2401 Files.delete(tmpFile.toPath());
2402 } catch (IOException e) {
2403 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2404 tmpFile,
2405 e.getMessage());
2406 }
2407 }
2408 }
2409
2410 private InputStream retrieveAttachmentAsStream(
2411 SignalServiceAttachmentPointer pointer, File tmpFile
2412 ) throws IOException, InvalidMessageException, MissingConfigurationException {
2413 return dependencies.getMessageReceiver()
2414 .retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
2415 }
2416
2417 void sendGroups() throws IOException {
2418 var groupsFile = IOUtils.createTempFile();
2419
2420 try {
2421 try (OutputStream fos = new FileOutputStream(groupsFile)) {
2422 var out = new DeviceGroupsOutputStream(fos);
2423 for (var record : getGroups()) {
2424 if (record instanceof GroupInfoV1) {
2425 var groupInfo = (GroupInfoV1) record;
2426 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
2427 Optional.fromNullable(groupInfo.name),
2428 groupInfo.getMembers()
2429 .stream()
2430 .map(this::resolveSignalServiceAddress)
2431 .collect(Collectors.toList()),
2432 createGroupAvatarAttachment(groupInfo.getGroupId()),
2433 groupInfo.isMember(account.getSelfRecipientId()),
2434 Optional.of(groupInfo.messageExpirationTime),
2435 Optional.fromNullable(groupInfo.color),
2436 groupInfo.blocked,
2437 Optional.absent(),
2438 groupInfo.archived));
2439 }
2440 }
2441 }
2442
2443 if (groupsFile.exists() && groupsFile.length() > 0) {
2444 try (var groupsFileStream = new FileInputStream(groupsFile)) {
2445 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2446 .withStream(groupsFileStream)
2447 .withContentType("application/octet-stream")
2448 .withLength(groupsFile.length())
2449 .build();
2450
2451 sendHelper.sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
2452 }
2453 }
2454 } finally {
2455 try {
2456 Files.delete(groupsFile.toPath());
2457 } catch (IOException e) {
2458 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
2459 }
2460 }
2461 }
2462
2463 public void sendContacts() throws IOException {
2464 var contactsFile = IOUtils.createTempFile();
2465
2466 try {
2467 try (OutputStream fos = new FileOutputStream(contactsFile)) {
2468 var out = new DeviceContactsOutputStream(fos);
2469 for (var contactPair : account.getContactStore().getContacts()) {
2470 final var recipientId = contactPair.first();
2471 final var contact = contactPair.second();
2472 final var address = resolveSignalServiceAddress(recipientId);
2473
2474 var currentIdentity = account.getIdentityKeyStore().getIdentity(recipientId);
2475 VerifiedMessage verifiedMessage = null;
2476 if (currentIdentity != null) {
2477 verifiedMessage = new VerifiedMessage(address,
2478 currentIdentity.getIdentityKey(),
2479 currentIdentity.getTrustLevel().toVerifiedState(),
2480 currentIdentity.getDateAdded().getTime());
2481 }
2482
2483 var profileKey = account.getProfileStore().getProfileKey(recipientId);
2484 out.write(new DeviceContact(address,
2485 Optional.fromNullable(contact.getName()),
2486 createContactAvatarAttachment(address),
2487 Optional.fromNullable(contact.getColor()),
2488 Optional.fromNullable(verifiedMessage),
2489 Optional.fromNullable(profileKey),
2490 contact.isBlocked(),
2491 Optional.of(contact.getMessageExpirationTime()),
2492 Optional.absent(),
2493 contact.isArchived()));
2494 }
2495
2496 if (account.getProfileKey() != null) {
2497 // Send our own profile key as well
2498 out.write(new DeviceContact(account.getSelfAddress(),
2499 Optional.absent(),
2500 Optional.absent(),
2501 Optional.absent(),
2502 Optional.absent(),
2503 Optional.of(account.getProfileKey()),
2504 false,
2505 Optional.absent(),
2506 Optional.absent(),
2507 false));
2508 }
2509 }
2510
2511 if (contactsFile.exists() && contactsFile.length() > 0) {
2512 try (var contactsFileStream = new FileInputStream(contactsFile)) {
2513 var attachmentStream = SignalServiceAttachment.newStreamBuilder()
2514 .withStream(contactsFileStream)
2515 .withContentType("application/octet-stream")
2516 .withLength(contactsFile.length())
2517 .build();
2518
2519 sendHelper.sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream,
2520 true)));
2521 }
2522 }
2523 } finally {
2524 try {
2525 Files.delete(contactsFile.toPath());
2526 } catch (IOException e) {
2527 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
2528 }
2529 }
2530 }
2531
2532 void sendBlockedList() throws IOException {
2533 var addresses = new ArrayList<SignalServiceAddress>();
2534 for (var record : account.getContactStore().getContacts()) {
2535 if (record.second().isBlocked()) {
2536 addresses.add(resolveSignalServiceAddress(record.first()));
2537 }
2538 }
2539 var groupIds = new ArrayList<byte[]>();
2540 for (var record : getGroups()) {
2541 if (record.isBlocked()) {
2542 groupIds.add(record.getGroupId().serialize());
2543 }
2544 }
2545 sendHelper.sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
2546 }
2547
2548 private void sendVerifiedMessage(
2549 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
2550 ) throws IOException {
2551 var verifiedMessage = new VerifiedMessage(destination,
2552 identityKey,
2553 trustLevel.toVerifiedState(),
2554 System.currentTimeMillis());
2555 sendHelper.sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
2556 }
2557
2558 public List<Pair<RecipientId, Contact>> getContacts() {
2559 return account.getContactStore().getContacts();
2560 }
2561
2562 public String getContactOrProfileName(String number) throws InvalidNumberException {
2563 final var recipientId = canonicalizeAndResolveRecipient(number);
2564 final var recipient = account.getRecipientStore().getRecipient(recipientId);
2565 if (recipient == null) {
2566 return null;
2567 }
2568
2569 if (recipient.getContact() != null && !Util.isEmpty(recipient.getContact().getName())) {
2570 return recipient.getContact().getName();
2571 }
2572
2573 if (recipient.getProfile() != null && recipient.getProfile() != null) {
2574 return recipient.getProfile().getDisplayName();
2575 }
2576
2577 return null;
2578 }
2579
2580 public GroupInfo getGroup(GroupId groupId) {
2581 return getGroup(groupId, false);
2582 }
2583
2584 public GroupInfo getGroup(GroupId groupId, boolean forceUpdate) {
2585 final var group = account.getGroupStore().getGroup(groupId);
2586 if (group instanceof GroupInfoV2 && (forceUpdate || ((GroupInfoV2) group).getGroup() == null)) {
2587 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(((GroupInfoV2) group).getMasterKey());
2588 ((GroupInfoV2) group).setGroup(groupV2Helper.getDecryptedGroup(groupSecretParams), this::resolveRecipient);
2589 account.getGroupStore().updateGroup(group);
2590 }
2591 return group;
2592 }
2593
2594 public List<IdentityInfo> getIdentities() {
2595 return account.getIdentityKeyStore().getIdentities();
2596 }
2597
2598 public List<IdentityInfo> getIdentities(String number) throws InvalidNumberException {
2599 final var identity = account.getIdentityKeyStore().getIdentity(canonicalizeAndResolveRecipient(number));
2600 return identity == null ? List.of() : List.of(identity);
2601 }
2602
2603 /**
2604 * Trust this the identity with this fingerprint
2605 *
2606 * @param name username of the identity
2607 * @param fingerprint Fingerprint
2608 */
2609 public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
2610 var recipientId = canonicalizeAndResolveRecipient(name);
2611 return trustIdentity(recipientId,
2612 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
2613 TrustLevel.TRUSTED_VERIFIED);
2614 }
2615
2616 /**
2617 * Trust this the identity with this safety number
2618 *
2619 * @param name username of the identity
2620 * @param safetyNumber Safety number
2621 */
2622 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) throws InvalidNumberException {
2623 var recipientId = canonicalizeAndResolveRecipient(name);
2624 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2625 return trustIdentity(recipientId,
2626 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
2627 TrustLevel.TRUSTED_VERIFIED);
2628 }
2629
2630 /**
2631 * Trust all keys of this identity without verification
2632 *
2633 * @param name username of the identity
2634 */
2635 public boolean trustIdentityAllKeys(String name) throws InvalidNumberException {
2636 var recipientId = canonicalizeAndResolveRecipient(name);
2637 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
2638 }
2639
2640 private boolean trustIdentity(
2641 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
2642 ) {
2643 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
2644 if (identity == null) {
2645 return false;
2646 }
2647
2648 if (!verifier.apply(identity.getIdentityKey())) {
2649 return false;
2650 }
2651
2652 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
2653 try {
2654 var address = account.getRecipientStore().resolveServiceAddress(recipientId);
2655 sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
2656 } catch (IOException e) {
2657 logger.warn("Failed to send verification sync message: {}", e.getMessage());
2658 }
2659
2660 return true;
2661 }
2662
2663 private void handleIdentityFailure(
2664 final RecipientId recipientId, final SendMessageResult.IdentityFailure identityFailure
2665 ) {
2666 final var identityKey = identityFailure.getIdentityKey();
2667 if (identityKey != null) {
2668 final var newIdentity = account.getIdentityKeyStore().saveIdentity(recipientId, identityKey, new Date());
2669 if (newIdentity) {
2670 account.getSessionStore().archiveSessions(recipientId);
2671 }
2672 } else {
2673 // Retrieve profile to get the current identity key from the server
2674 retrieveEncryptedProfile(recipientId);
2675 }
2676 }
2677
2678 public String computeSafetyNumber(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
2679 final var fingerprint = Utils.computeSafetyNumber(capabilities.isUuid(),
2680 account.getSelfAddress(),
2681 getIdentityKeyPair().getPublicKey(),
2682 theirAddress,
2683 theirIdentityKey);
2684 return fingerprint == null ? null : fingerprint.getDisplayableFingerprint().getDisplayText();
2685 }
2686
2687 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
2688 final var fingerprint = Utils.computeSafetyNumber(capabilities.isUuid(),
2689 account.getSelfAddress(),
2690 getIdentityKeyPair().getPublicKey(),
2691 theirAddress,
2692 theirIdentityKey);
2693 return fingerprint == null ? null : fingerprint.getScannableFingerprint().getSerialized();
2694 }
2695
2696 @Deprecated
2697 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2698 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2699
2700 return resolveSignalServiceAddress(address);
2701 }
2702
2703 @Deprecated
2704 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2705 if (address.matches(account.getSelfAddress())) {
2706 return account.getSelfAddress();
2707 }
2708
2709 return account.getRecipientStore().resolveServiceAddress(address);
2710 }
2711
2712 public SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
2713 return account.getRecipientStore().resolveServiceAddress(recipientId);
2714 }
2715
2716 public RecipientId canonicalizeAndResolveRecipient(String identifier) throws InvalidNumberException {
2717 var canonicalizedNumber = UuidUtil.isUuid(identifier)
2718 ? identifier
2719 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2720
2721 return resolveRecipient(canonicalizedNumber);
2722 }
2723
2724 private RecipientId resolveRecipient(final String identifier) {
2725 var address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2726
2727 return resolveRecipient(address);
2728 }
2729
2730 public RecipientId resolveRecipient(SignalServiceAddress address) {
2731 return account.getRecipientStore().resolveRecipient(address);
2732 }
2733
2734 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
2735 return account.getRecipientStore().resolveRecipientTrusted(address);
2736 }
2737
2738 private void enqueueJob(Job job) {
2739 var context = new Context(account,
2740 dependencies.getAccountManager(),
2741 dependencies.getMessageReceiver(),
2742 stickerPackStore);
2743 job.run(context);
2744 }
2745
2746 @Override
2747 public void close() throws IOException {
2748 close(true);
2749 }
2750
2751 void close(boolean closeAccount) throws IOException {
2752 executor.shutdown();
2753
2754 dependencies.getSignalWebSocket().disconnect();
2755
2756 if (closeAccount && account != null) {
2757 account.close();
2758 }
2759 account = null;
2760 }
2761
2762 public interface ReceiveMessageHandler {
2763
2764 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2765 }
2766 }