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