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