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