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