]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/manager/Manager.java
Always include profile key in direct messages
[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 messageBuilder.withProfileKey(account.getProfileKey().serialize());
1346 List<SendMessageResult> results = new ArrayList<>(recipients.size());
1347 for (SignalServiceAddress address : recipients) {
1348 final ContactInfo contact = account.getContactStore().getContact(address);
1349 final int expirationTime = contact != null ? contact.messageExpirationTime : 0;
1350 messageBuilder.withExpiration(expirationTime);
1351 message = messageBuilder.build();
1352 if (address.matches(account.getSelfAddress())) {
1353 results.add(sendSelfMessage(message));
1354 } else {
1355 results.add(sendMessage(address, message));
1356 }
1357 }
1358 return new Pair<>(timestamp, results);
1359 }
1360 } finally {
1361 if (message != null && message.isEndSession()) {
1362 for (SignalServiceAddress recipient : recipients) {
1363 handleEndSession(recipient);
1364 }
1365 }
1366 account.save();
1367 }
1368 }
1369
1370 private SendMessageResult sendSelfMessage(SignalServiceDataMessage message) throws IOException {
1371 SignalServiceMessageSender messageSender = createMessageSender();
1372
1373 SignalServiceAddress recipient = account.getSelfAddress();
1374
1375 final Optional<UnidentifiedAccessPair> unidentifiedAccess = unidentifiedAccessHelper.getAccessFor(recipient);
1376 SentTranscriptMessage transcript = new SentTranscriptMessage(Optional.of(recipient),
1377 message.getTimestamp(),
1378 message,
1379 message.getExpiresInSeconds(),
1380 Map.of(recipient, unidentifiedAccess.isPresent()),
1381 false);
1382 SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
1383
1384 try {
1385 long startTime = System.currentTimeMillis();
1386 messageSender.sendMessage(syncMessage, unidentifiedAccess);
1387 return SendMessageResult.success(recipient,
1388 unidentifiedAccess.isPresent(),
1389 false,
1390 System.currentTimeMillis() - startTime);
1391 } catch (UntrustedIdentityException e) {
1392 account.getSignalProtocolStore()
1393 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1394 e.getIdentityKey(),
1395 TrustLevel.UNTRUSTED);
1396 return SendMessageResult.identityFailure(recipient, e.getIdentityKey());
1397 }
1398 }
1399
1400 private SendMessageResult sendMessage(
1401 SignalServiceAddress address, SignalServiceDataMessage message
1402 ) throws IOException {
1403 SignalServiceMessageSender messageSender = createMessageSender();
1404
1405 try {
1406 return messageSender.sendMessage(address, unidentifiedAccessHelper.getAccessFor(address), message);
1407 } catch (UntrustedIdentityException e) {
1408 account.getSignalProtocolStore()
1409 .saveIdentity(resolveSignalServiceAddress(e.getIdentifier()),
1410 e.getIdentityKey(),
1411 TrustLevel.UNTRUSTED);
1412 return SendMessageResult.identityFailure(address, e.getIdentityKey());
1413 }
1414 }
1415
1416 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, SelfSendException, UnsupportedDataMessageException, org.whispersystems.libsignal.UntrustedIdentityException {
1417 SignalServiceCipher cipher = new SignalServiceCipher(account.getSelfAddress(),
1418 account.getSignalProtocolStore(),
1419 certificateValidator);
1420 try {
1421 return cipher.decrypt(envelope);
1422 } catch (ProtocolUntrustedIdentityException e) {
1423 if (e.getCause() instanceof org.whispersystems.libsignal.UntrustedIdentityException) {
1424 org.whispersystems.libsignal.UntrustedIdentityException identityException = (org.whispersystems.libsignal.UntrustedIdentityException) e
1425 .getCause();
1426 account.getSignalProtocolStore()
1427 .saveIdentity(resolveSignalServiceAddress(identityException.getName()),
1428 identityException.getUntrustedIdentity(),
1429 TrustLevel.UNTRUSTED);
1430 throw identityException;
1431 }
1432 throw new AssertionError(e);
1433 }
1434 }
1435
1436 private void handleEndSession(SignalServiceAddress source) {
1437 account.getSignalProtocolStore().deleteAllSessions(source);
1438 }
1439
1440 private static int currentTimeDays() {
1441 return (int) TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis());
1442 }
1443
1444 private GroupsV2AuthorizationString getGroupAuthForToday(
1445 final GroupSecretParams groupSecretParams
1446 ) throws IOException {
1447 final int today = currentTimeDays();
1448 // Returns credentials for the next 7 days
1449 final HashMap<Integer, AuthCredentialResponse> credentials = groupsV2Api.getCredentials(today);
1450 // TODO cache credentials until they expire
1451 AuthCredentialResponse authCredentialResponse = credentials.get(today);
1452 try {
1453 return groupsV2Api.getGroupsV2AuthorizationString(account.getUuid(),
1454 today,
1455 groupSecretParams,
1456 authCredentialResponse);
1457 } catch (VerificationFailedException e) {
1458 throw new IOException(e);
1459 }
1460 }
1461
1462 private List<HandleAction> handleSignalServiceDataMessage(
1463 SignalServiceDataMessage message,
1464 boolean isSync,
1465 SignalServiceAddress source,
1466 SignalServiceAddress destination,
1467 boolean ignoreAttachments
1468 ) {
1469 List<HandleAction> actions = new ArrayList<>();
1470 if (message.getGroupContext().isPresent()) {
1471 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1472 SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
1473 GroupIdV1 groupId = GroupId.v1(groupInfo.getGroupId());
1474 GroupInfo group = getGroup(groupId);
1475 if (group == null || group instanceof GroupInfoV1) {
1476 GroupInfoV1 groupV1 = (GroupInfoV1) group;
1477 switch (groupInfo.getType()) {
1478 case UPDATE: {
1479 if (groupV1 == null) {
1480 groupV1 = new GroupInfoV1(groupId);
1481 }
1482
1483 if (groupInfo.getAvatar().isPresent()) {
1484 SignalServiceAttachment avatar = groupInfo.getAvatar().get();
1485 if (avatar.isPointer()) {
1486 try {
1487 retrieveGroupAvatarAttachment(avatar.asPointer(), groupV1.getGroupId());
1488 } catch (IOException e) {
1489 logger.warn("Failed to retrieve avatar for group {}, ignoring: {}",
1490 groupId.toBase64(),
1491 e.getMessage());
1492 }
1493 }
1494 }
1495
1496 if (groupInfo.getName().isPresent()) {
1497 groupV1.name = groupInfo.getName().get();
1498 }
1499
1500 if (groupInfo.getMembers().isPresent()) {
1501 groupV1.addMembers(groupInfo.getMembers()
1502 .get()
1503 .stream()
1504 .map(this::resolveSignalServiceAddress)
1505 .collect(Collectors.toSet()));
1506 }
1507
1508 account.getGroupStore().updateGroup(groupV1);
1509 break;
1510 }
1511 case DELIVER:
1512 if (groupV1 == null && !isSync) {
1513 actions.add(new SendGroupInfoRequestAction(source, groupId));
1514 }
1515 break;
1516 case QUIT: {
1517 if (groupV1 != null) {
1518 groupV1.removeMember(source);
1519 account.getGroupStore().updateGroup(groupV1);
1520 }
1521 break;
1522 }
1523 case REQUEST_INFO:
1524 if (groupV1 != null && !isSync) {
1525 actions.add(new SendGroupUpdateAction(source, groupV1.getGroupId()));
1526 }
1527 break;
1528 }
1529 } else {
1530 // Received a group v1 message for a v2 group
1531 }
1532 }
1533 if (message.getGroupContext().get().getGroupV2().isPresent()) {
1534 final SignalServiceGroupV2 groupContext = message.getGroupContext().get().getGroupV2().get();
1535 final GroupMasterKey groupMasterKey = groupContext.getMasterKey();
1536
1537 getOrMigrateGroup(groupMasterKey,
1538 groupContext.getRevision(),
1539 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
1540 }
1541 }
1542
1543 final SignalServiceAddress conversationPartnerAddress = isSync ? destination : source;
1544 if (conversationPartnerAddress != null && message.isEndSession()) {
1545 handleEndSession(conversationPartnerAddress);
1546 }
1547 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1548 if (message.getGroupContext().isPresent()) {
1549 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1550 SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
1551 GroupInfoV1 group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
1552 if (group != null) {
1553 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
1554 group.messageExpirationTime = message.getExpiresInSeconds();
1555 account.getGroupStore().updateGroup(group);
1556 }
1557 }
1558 } else if (message.getGroupContext().get().getGroupV2().isPresent()) {
1559 // disappearing message timer already stored in the DecryptedGroup
1560 }
1561 } else if (conversationPartnerAddress != null) {
1562 ContactInfo contact = account.getContactStore().getContact(conversationPartnerAddress);
1563 if (contact == null) {
1564 contact = new ContactInfo(conversationPartnerAddress);
1565 }
1566 if (contact.messageExpirationTime != message.getExpiresInSeconds()) {
1567 contact.messageExpirationTime = message.getExpiresInSeconds();
1568 account.getContactStore().updateContact(contact);
1569 }
1570 }
1571 }
1572 if (message.getAttachments().isPresent() && !ignoreAttachments) {
1573 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1574 if (attachment.isPointer()) {
1575 try {
1576 retrieveAttachment(attachment.asPointer());
1577 } catch (IOException e) {
1578 logger.warn("Failed to retrieve attachment ({}), ignoring: {}",
1579 attachment.asPointer().getRemoteId(),
1580 e.getMessage());
1581 }
1582 }
1583 }
1584 }
1585 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1586 final ProfileKey profileKey;
1587 try {
1588 profileKey = new ProfileKey(message.getProfileKey().get());
1589 } catch (InvalidInputException e) {
1590 throw new AssertionError(e);
1591 }
1592 if (source.matches(account.getSelfAddress())) {
1593 this.account.setProfileKey(profileKey);
1594 }
1595 this.account.getProfileStore().storeProfileKey(source, profileKey);
1596 }
1597 if (message.getPreviews().isPresent()) {
1598 final List<SignalServiceDataMessage.Preview> previews = message.getPreviews().get();
1599 for (SignalServiceDataMessage.Preview preview : previews) {
1600 if (preview.getImage().isPresent() && preview.getImage().get().isPointer()) {
1601 SignalServiceAttachmentPointer attachment = preview.getImage().get().asPointer();
1602 try {
1603 retrieveAttachment(attachment);
1604 } catch (IOException e) {
1605 logger.warn("Failed to retrieve preview image ({}), ignoring: {}",
1606 attachment.getRemoteId(),
1607 e.getMessage());
1608 }
1609 }
1610 }
1611 }
1612 if (message.getQuote().isPresent()) {
1613 final SignalServiceDataMessage.Quote quote = message.getQuote().get();
1614
1615 for (SignalServiceDataMessage.Quote.QuotedAttachment quotedAttachment : quote.getAttachments()) {
1616 final SignalServiceAttachment attachment = quotedAttachment.getThumbnail();
1617 if (attachment != null && attachment.isPointer()) {
1618 try {
1619 retrieveAttachment(attachment.asPointer());
1620 } catch (IOException e) {
1621 logger.warn("Failed to retrieve quote attachment thumbnail ({}), ignoring: {}",
1622 attachment.asPointer().getRemoteId(),
1623 e.getMessage());
1624 }
1625 }
1626 }
1627 }
1628 if (message.getSticker().isPresent()) {
1629 final SignalServiceDataMessage.Sticker messageSticker = message.getSticker().get();
1630 Sticker sticker = account.getStickerStore().getSticker(messageSticker.getPackId());
1631 if (sticker == null) {
1632 sticker = new Sticker(messageSticker.getPackId(), messageSticker.getPackKey());
1633 account.getStickerStore().updateSticker(sticker);
1634 }
1635 }
1636 return actions;
1637 }
1638
1639 private GroupInfoV2 getOrMigrateGroup(
1640 final GroupMasterKey groupMasterKey, final int revision, final byte[] signedGroupChange
1641 ) {
1642 final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
1643
1644 GroupIdV2 groupId = GroupUtils.getGroupIdV2(groupSecretParams);
1645 GroupInfo groupInfo = getGroup(groupId);
1646 final GroupInfoV2 groupInfoV2;
1647 if (groupInfo instanceof GroupInfoV1) {
1648 // Received a v2 group message for a v1 group, we need to locally migrate the group
1649 account.getGroupStore().deleteGroup(groupInfo.getGroupId());
1650 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1651 logger.info("Locally migrated group {} to group v2, id: {}",
1652 groupInfo.getGroupId().toBase64(),
1653 groupInfoV2.getGroupId().toBase64());
1654 } else if (groupInfo instanceof GroupInfoV2) {
1655 groupInfoV2 = (GroupInfoV2) groupInfo;
1656 } else {
1657 groupInfoV2 = new GroupInfoV2(groupId, groupMasterKey);
1658 }
1659
1660 if (groupInfoV2.getGroup() == null || groupInfoV2.getGroup().getRevision() < revision) {
1661 DecryptedGroup group = null;
1662 if (signedGroupChange != null
1663 && groupInfoV2.getGroup() != null
1664 && groupInfoV2.getGroup().getRevision() + 1 == revision) {
1665 group = groupHelper.getUpdatedDecryptedGroup(groupInfoV2.getGroup(), signedGroupChange, groupMasterKey);
1666 }
1667 if (group == null) {
1668 group = groupHelper.getDecryptedGroup(groupSecretParams);
1669 }
1670 if (group != null) {
1671 storeProfileKeysFromMembers(group);
1672 final String avatar = group.getAvatar();
1673 if (avatar != null && !avatar.isEmpty()) {
1674 try {
1675 retrieveGroupAvatar(groupId, groupSecretParams, avatar);
1676 } catch (IOException e) {
1677 logger.warn("Failed to download group avatar, ignoring: {}", e.getMessage());
1678 }
1679 }
1680 }
1681 groupInfoV2.setGroup(group);
1682 account.getGroupStore().updateGroup(groupInfoV2);
1683 }
1684
1685 return groupInfoV2;
1686 }
1687
1688 private void storeProfileKeysFromMembers(final DecryptedGroup group) {
1689 for (DecryptedMember member : group.getMembersList()) {
1690 final SignalServiceAddress address = resolveSignalServiceAddress(new SignalServiceAddress(UuidUtil.parseOrThrow(
1691 member.getUuid().toByteArray()), null));
1692 try {
1693 account.getProfileStore()
1694 .storeProfileKey(address, new ProfileKey(member.getProfileKey().toByteArray()));
1695 } catch (InvalidInputException ignored) {
1696 }
1697 }
1698 }
1699
1700 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1701 for (CachedMessage cachedMessage : account.getMessageCache().getCachedMessages()) {
1702 retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
1703 }
1704 }
1705
1706 private void retryFailedReceivedMessage(
1707 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
1708 ) {
1709 SignalServiceEnvelope envelope = cachedMessage.loadEnvelope();
1710 if (envelope == null) {
1711 return;
1712 }
1713 SignalServiceContent content = null;
1714 if (!envelope.isReceipt()) {
1715 try {
1716 content = decryptMessage(envelope);
1717 } catch (org.whispersystems.libsignal.UntrustedIdentityException e) {
1718 return;
1719 } catch (Exception er) {
1720 // All other errors are not recoverable, so delete the cached message
1721 cachedMessage.delete();
1722 return;
1723 }
1724 List<HandleAction> actions = handleMessage(envelope, content, ignoreAttachments);
1725 for (HandleAction action : actions) {
1726 try {
1727 action.execute(this);
1728 } catch (Throwable e) {
1729 e.printStackTrace();
1730 }
1731 }
1732 }
1733 account.save();
1734 handler.handleMessage(envelope, content, null);
1735 cachedMessage.delete();
1736 }
1737
1738 public void receiveMessages(
1739 long timeout,
1740 TimeUnit unit,
1741 boolean returnOnTimeout,
1742 boolean ignoreAttachments,
1743 ReceiveMessageHandler handler
1744 ) throws IOException {
1745 retryFailedReceivedMessages(handler, ignoreAttachments);
1746
1747 Set<HandleAction> queuedActions = null;
1748
1749 final SignalServiceMessagePipe messagePipe = getOrCreateMessagePipe();
1750
1751 boolean hasCaughtUpWithOldMessages = false;
1752
1753 while (true) {
1754 SignalServiceEnvelope envelope;
1755 SignalServiceContent content = null;
1756 Exception exception = null;
1757 final CachedMessage[] cachedMessage = {null};
1758 try {
1759 Optional<SignalServiceEnvelope> result = messagePipe.readOrEmpty(timeout, unit, envelope1 -> {
1760 // store message on disk, before acknowledging receipt to the server
1761 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1);
1762 });
1763 if (result.isPresent()) {
1764 envelope = result.get();
1765 } else {
1766 // Received indicator that server queue is empty
1767 hasCaughtUpWithOldMessages = true;
1768
1769 if (queuedActions != null) {
1770 for (HandleAction action : queuedActions) {
1771 try {
1772 action.execute(this);
1773 } catch (Throwable e) {
1774 e.printStackTrace();
1775 }
1776 }
1777 account.save();
1778 queuedActions.clear();
1779 queuedActions = null;
1780 }
1781
1782 // Continue to wait another timeout for new messages
1783 continue;
1784 }
1785 } catch (TimeoutException e) {
1786 if (returnOnTimeout) return;
1787 continue;
1788 } catch (InvalidVersionException e) {
1789 logger.warn("Error while receiving messages, ignoring: {}", e.getMessage());
1790 continue;
1791 }
1792
1793 if (envelope.hasSource()) {
1794 // Store uuid if we don't have it already
1795 SignalServiceAddress source = envelope.getSourceAddress();
1796 resolveSignalServiceAddress(source);
1797 }
1798 if (!envelope.isReceipt()) {
1799 try {
1800 content = decryptMessage(envelope);
1801 } catch (Exception e) {
1802 exception = e;
1803 }
1804 List<HandleAction> actions = handleMessage(envelope, content, ignoreAttachments);
1805 if (hasCaughtUpWithOldMessages) {
1806 for (HandleAction action : actions) {
1807 try {
1808 action.execute(this);
1809 } catch (Throwable e) {
1810 e.printStackTrace();
1811 }
1812 }
1813 } else {
1814 if (queuedActions == null) {
1815 queuedActions = new HashSet<>();
1816 }
1817 queuedActions.addAll(actions);
1818 }
1819 }
1820 account.save();
1821 if (isMessageBlocked(envelope, content)) {
1822 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
1823 } else if (isNotAGroupMember(envelope, content)) {
1824 logger.info("Ignoring a message from a non group member: {}", envelope.getTimestamp());
1825 } else {
1826 handler.handleMessage(envelope, content, exception);
1827 }
1828 if (!(exception instanceof org.whispersystems.libsignal.UntrustedIdentityException)) {
1829 if (cachedMessage[0] != null) {
1830 cachedMessage[0].delete();
1831 }
1832 }
1833 }
1834 }
1835
1836 private boolean isMessageBlocked(
1837 SignalServiceEnvelope envelope, SignalServiceContent content
1838 ) {
1839 SignalServiceAddress source;
1840 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1841 source = envelope.getSourceAddress();
1842 } else if (content != null) {
1843 source = content.getSender();
1844 } else {
1845 return false;
1846 }
1847 ContactInfo sourceContact = account.getContactStore().getContact(source);
1848 if (sourceContact != null && sourceContact.blocked) {
1849 return true;
1850 }
1851
1852 if (content != null && content.getDataMessage().isPresent()) {
1853 SignalServiceDataMessage message = content.getDataMessage().get();
1854 if (message.getGroupContext().isPresent()) {
1855 GroupId groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1856 GroupInfo group = getGroup(groupId);
1857 if (group != null && group.isBlocked()) {
1858 return true;
1859 }
1860 }
1861 }
1862 return false;
1863 }
1864
1865 private boolean isNotAGroupMember(
1866 SignalServiceEnvelope envelope, SignalServiceContent content
1867 ) {
1868 SignalServiceAddress source;
1869 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1870 source = envelope.getSourceAddress();
1871 } else if (content != null) {
1872 source = content.getSender();
1873 } else {
1874 return false;
1875 }
1876
1877 if (content != null && content.getDataMessage().isPresent()) {
1878 SignalServiceDataMessage message = content.getDataMessage().get();
1879 if (message.getGroupContext().isPresent()) {
1880 if (message.getGroupContext().get().getGroupV1().isPresent()) {
1881 SignalServiceGroup groupInfo = message.getGroupContext().get().getGroupV1().get();
1882 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
1883 return false;
1884 }
1885 }
1886 GroupId groupId = GroupUtils.getGroupId(message.getGroupContext().get());
1887 GroupInfo group = getGroup(groupId);
1888 if (group != null && !group.isMember(source)) {
1889 return true;
1890 }
1891 }
1892 }
1893 return false;
1894 }
1895
1896 private List<HandleAction> handleMessage(
1897 SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments
1898 ) {
1899 List<HandleAction> actions = new ArrayList<>();
1900 if (content != null) {
1901 final SignalServiceAddress sender;
1902 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1903 sender = envelope.getSourceAddress();
1904 } else {
1905 sender = content.getSender();
1906 }
1907 // Store uuid if we don't have it already
1908 resolveSignalServiceAddress(sender);
1909
1910 if (content.getDataMessage().isPresent()) {
1911 SignalServiceDataMessage message = content.getDataMessage().get();
1912
1913 if (content.isNeedsReceipt()) {
1914 actions.add(new SendReceiptAction(sender, message.getTimestamp()));
1915 }
1916
1917 actions.addAll(handleSignalServiceDataMessage(message,
1918 false,
1919 sender,
1920 account.getSelfAddress(),
1921 ignoreAttachments));
1922 }
1923 if (content.getSyncMessage().isPresent()) {
1924 account.setMultiDevice(true);
1925 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
1926 if (syncMessage.getSent().isPresent()) {
1927 SentTranscriptMessage message = syncMessage.getSent().get();
1928 final SignalServiceAddress destination = message.getDestination().orNull();
1929 actions.addAll(handleSignalServiceDataMessage(message.getMessage(),
1930 true,
1931 sender,
1932 destination,
1933 ignoreAttachments));
1934 }
1935 if (syncMessage.getRequest().isPresent()) {
1936 RequestMessage rm = syncMessage.getRequest().get();
1937 if (rm.isContactsRequest()) {
1938 actions.add(SendSyncContactsAction.create());
1939 }
1940 if (rm.isGroupsRequest()) {
1941 actions.add(SendSyncGroupsAction.create());
1942 }
1943 if (rm.isBlockedListRequest()) {
1944 actions.add(SendSyncBlockedListAction.create());
1945 }
1946 // TODO Handle rm.isConfigurationRequest(); rm.isKeysRequest();
1947 }
1948 if (syncMessage.getGroups().isPresent()) {
1949 File tmpFile = null;
1950 try {
1951 tmpFile = IOUtils.createTempFile();
1952 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(syncMessage.getGroups()
1953 .get()
1954 .asPointer(), tmpFile)) {
1955 DeviceGroupsInputStream s = new DeviceGroupsInputStream(attachmentAsStream);
1956 DeviceGroup g;
1957 while ((g = s.read()) != null) {
1958 GroupInfoV1 syncGroup = account.getGroupStore()
1959 .getOrCreateGroupV1(GroupId.v1(g.getId()));
1960 if (syncGroup != null) {
1961 if (g.getName().isPresent()) {
1962 syncGroup.name = g.getName().get();
1963 }
1964 syncGroup.addMembers(g.getMembers()
1965 .stream()
1966 .map(this::resolveSignalServiceAddress)
1967 .collect(Collectors.toSet()));
1968 if (!g.isActive()) {
1969 syncGroup.removeMember(account.getSelfAddress());
1970 } else {
1971 // Add ourself to the member set as it's marked as active
1972 syncGroup.addMembers(List.of(account.getSelfAddress()));
1973 }
1974 syncGroup.blocked = g.isBlocked();
1975 if (g.getColor().isPresent()) {
1976 syncGroup.color = g.getColor().get();
1977 }
1978
1979 if (g.getAvatar().isPresent()) {
1980 retrieveGroupAvatarAttachment(g.getAvatar().get(), syncGroup.getGroupId());
1981 }
1982 syncGroup.inboxPosition = g.getInboxPosition().orNull();
1983 syncGroup.archived = g.isArchived();
1984 account.getGroupStore().updateGroup(syncGroup);
1985 }
1986 }
1987 }
1988 } catch (Exception e) {
1989 logger.warn("Failed to handle received sync groups “{}”, ignoring: {}",
1990 tmpFile,
1991 e.getMessage());
1992 e.printStackTrace();
1993 } finally {
1994 if (tmpFile != null) {
1995 try {
1996 Files.delete(tmpFile.toPath());
1997 } catch (IOException e) {
1998 logger.warn("Failed to delete received groups temp file “{}”, ignoring: {}",
1999 tmpFile,
2000 e.getMessage());
2001 }
2002 }
2003 }
2004 }
2005 if (syncMessage.getBlockedList().isPresent()) {
2006 final BlockedListMessage blockedListMessage = syncMessage.getBlockedList().get();
2007 for (SignalServiceAddress address : blockedListMessage.getAddresses()) {
2008 setContactBlocked(resolveSignalServiceAddress(address), true);
2009 }
2010 for (GroupId groupId : blockedListMessage.getGroupIds()
2011 .stream()
2012 .map(GroupId::unknownVersion)
2013 .collect(Collectors.toSet())) {
2014 try {
2015 setGroupBlocked(groupId, true);
2016 } catch (GroupNotFoundException e) {
2017 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
2018 groupId.toBase64());
2019 }
2020 }
2021 }
2022 if (syncMessage.getContacts().isPresent()) {
2023 File tmpFile = null;
2024 try {
2025 tmpFile = IOUtils.createTempFile();
2026 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
2027 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream()
2028 .asPointer(), tmpFile)) {
2029 DeviceContactsInputStream s = new DeviceContactsInputStream(attachmentAsStream);
2030 if (contactsMessage.isComplete()) {
2031 account.getContactStore().clear();
2032 }
2033 DeviceContact c;
2034 while ((c = s.read()) != null) {
2035 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
2036 account.setProfileKey(c.getProfileKey().get());
2037 }
2038 final SignalServiceAddress address = resolveSignalServiceAddress(c.getAddress());
2039 ContactInfo contact = account.getContactStore().getContact(address);
2040 if (contact == null) {
2041 contact = new ContactInfo(address);
2042 }
2043 if (c.getName().isPresent()) {
2044 contact.name = c.getName().get();
2045 }
2046 if (c.getColor().isPresent()) {
2047 contact.color = c.getColor().get();
2048 }
2049 if (c.getProfileKey().isPresent()) {
2050 account.getProfileStore().storeProfileKey(address, c.getProfileKey().get());
2051 }
2052 if (c.getVerified().isPresent()) {
2053 final VerifiedMessage verifiedMessage = c.getVerified().get();
2054 account.getSignalProtocolStore()
2055 .setIdentityTrustLevel(verifiedMessage.getDestination(),
2056 verifiedMessage.getIdentityKey(),
2057 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2058 }
2059 if (c.getExpirationTimer().isPresent()) {
2060 contact.messageExpirationTime = c.getExpirationTimer().get();
2061 }
2062 contact.blocked = c.isBlocked();
2063 contact.inboxPosition = c.getInboxPosition().orNull();
2064 contact.archived = c.isArchived();
2065 account.getContactStore().updateContact(contact);
2066
2067 if (c.getAvatar().isPresent()) {
2068 retrieveContactAvatarAttachment(c.getAvatar().get(), contact.getAddress());
2069 }
2070 }
2071 }
2072 } catch (Exception e) {
2073 e.printStackTrace();
2074 } finally {
2075 if (tmpFile != null) {
2076 try {
2077 Files.delete(tmpFile.toPath());
2078 } catch (IOException e) {
2079 logger.warn("Failed to delete received contacts temp file “{}”, ignoring: {}",
2080 tmpFile,
2081 e.getMessage());
2082 }
2083 }
2084 }
2085 }
2086 if (syncMessage.getVerified().isPresent()) {
2087 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
2088 account.getSignalProtocolStore()
2089 .setIdentityTrustLevel(resolveSignalServiceAddress(verifiedMessage.getDestination()),
2090 verifiedMessage.getIdentityKey(),
2091 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
2092 }
2093 if (syncMessage.getStickerPackOperations().isPresent()) {
2094 final List<StickerPackOperationMessage> stickerPackOperationMessages = syncMessage.getStickerPackOperations()
2095 .get();
2096 for (StickerPackOperationMessage m : stickerPackOperationMessages) {
2097 if (!m.getPackId().isPresent()) {
2098 continue;
2099 }
2100 Sticker sticker = account.getStickerStore().getSticker(m.getPackId().get());
2101 if (sticker == null) {
2102 if (!m.getPackKey().isPresent()) {
2103 continue;
2104 }
2105 sticker = new Sticker(m.getPackId().get(), m.getPackKey().get());
2106 }
2107 sticker.setInstalled(!m.getType().isPresent()
2108 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL);
2109 account.getStickerStore().updateSticker(sticker);
2110 }
2111 }
2112 if (syncMessage.getConfiguration().isPresent()) {
2113 // TODO
2114 }
2115 }
2116 }
2117 return actions;
2118 }
2119
2120 private void retrieveContactAvatarAttachment(
2121 SignalServiceAttachment attachment, SignalServiceAddress address
2122 ) throws IOException {
2123 avatarStore.storeContactAvatar(address, outputStream -> retrieveAttachment(attachment, outputStream));
2124 }
2125
2126 private void retrieveGroupAvatarAttachment(
2127 SignalServiceAttachment attachment, GroupId groupId
2128 ) throws IOException {
2129 avatarStore.storeGroupAvatar(groupId, outputStream -> retrieveAttachment(attachment, outputStream));
2130 }
2131
2132 private void retrieveGroupAvatar(
2133 GroupId groupId, GroupSecretParams groupSecretParams, String cdnKey
2134 ) throws IOException {
2135 GroupsV2Operations.GroupOperations groupOperations = groupsV2Operations.forGroup(groupSecretParams);
2136
2137 File tmpFile = IOUtils.createTempFile();
2138 try (InputStream input = messageReceiver.retrieveGroupsV2ProfileAvatar(cdnKey,
2139 tmpFile,
2140 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2141 byte[] encryptedData = IOUtils.readFully(input);
2142
2143 byte[] decryptedData = groupOperations.decryptAvatar(encryptedData);
2144 avatarStore.storeGroupAvatar(groupId, outputStream -> outputStream.write(decryptedData));
2145 } finally {
2146 try {
2147 Files.delete(tmpFile.toPath());
2148 } catch (IOException e) {
2149 logger.warn("Failed to delete received group avatar temp file “{}”, ignoring: {}",
2150 tmpFile,
2151 e.getMessage());
2152 }
2153 }
2154 }
2155
2156 private void retrieveProfileAvatar(
2157 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
2158 ) throws IOException {
2159 File tmpFile = IOUtils.createTempFile();
2160 try (InputStream input = messageReceiver.retrieveProfileAvatar(avatarPath,
2161 tmpFile,
2162 profileKey,
2163 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
2164 avatarStore.storeProfileAvatar(address, outputStream -> {
2165 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
2166 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
2167 });
2168 } finally {
2169 try {
2170 Files.delete(tmpFile.toPath());
2171 } catch (IOException e) {
2172 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
2173 tmpFile,
2174 e.getMessage());
2175 }
2176 }
2177 }
2178
2179 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
2180 return new File(pathConfig.getAttachmentsPath(), attachmentId.toString());
2181 }
2182
2183 private void retrieveAttachment(SignalServiceAttachmentPointer pointer) throws IOException {
2184 IOUtils.createPrivateDirectories(pathConfig.getAttachmentsPath());
2185 retrieveAttachment(pointer, getAttachmentFile(pointer.getRemoteId()));
2186 }
2187
2188 private void retrieveAttachment(
2189 SignalServiceAttachmentPointer pointer, File outputFile
2190 ) throws IOException {
2191 if (pointer.getPreview().isPresent()) {
2192 File previewFile = new File(outputFile + ".preview");
2193 try (OutputStream output = new FileOutputStream(previewFile)) {
2194 byte[] preview = pointer.getPreview().get();
2195 output.write(preview, 0, preview.length);
2196 } catch (FileNotFoundException e) {
2197 logger.warn("Failed to retrieve attachment preview, ignoring: {}", e.getMessage());
2198 }
2199 }
2200
2201 try (OutputStream output = new FileOutputStream(outputFile)) {
2202 retrieveAttachment(pointer, output);
2203 }
2204 }
2205
2206 private void retrieveAttachment(
2207 final SignalServiceAttachment attachment, final OutputStream outputStream
2208 ) throws IOException {
2209 if (attachment.isPointer()) {
2210 SignalServiceAttachmentPointer pointer = attachment.asPointer();
2211 retrieveAttachment(pointer, outputStream);
2212 } else {
2213 SignalServiceAttachmentStream stream = attachment.asStream();
2214 AttachmentUtils.retrieveAttachment(stream, outputStream);
2215 }
2216 }
2217
2218 private void retrieveAttachment(
2219 SignalServiceAttachmentPointer pointer, OutputStream outputStream
2220 ) throws IOException {
2221 File tmpFile = IOUtils.createTempFile();
2222 try (InputStream input = messageReceiver.retrieveAttachment(pointer,
2223 tmpFile,
2224 ServiceConfig.MAX_ATTACHMENT_SIZE)) {
2225 IOUtils.copyStream(input, outputStream);
2226 } catch (MissingConfigurationException | InvalidMessageException e) {
2227 throw new IOException(e);
2228 } finally {
2229 try {
2230 Files.delete(tmpFile.toPath());
2231 } catch (IOException e) {
2232 logger.warn("Failed to delete received attachment temp file “{}”, ignoring: {}",
2233 tmpFile,
2234 e.getMessage());
2235 }
2236 }
2237 }
2238
2239 private InputStream retrieveAttachmentAsStream(
2240 SignalServiceAttachmentPointer pointer, File tmpFile
2241 ) throws IOException, InvalidMessageException, MissingConfigurationException {
2242 return messageReceiver.retrieveAttachment(pointer, tmpFile, ServiceConfig.MAX_ATTACHMENT_SIZE);
2243 }
2244
2245 void sendGroups() throws IOException, UntrustedIdentityException {
2246 File groupsFile = IOUtils.createTempFile();
2247
2248 try {
2249 try (OutputStream fos = new FileOutputStream(groupsFile)) {
2250 DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(fos);
2251 for (GroupInfo record : getGroups()) {
2252 if (record instanceof GroupInfoV1) {
2253 GroupInfoV1 groupInfo = (GroupInfoV1) record;
2254 out.write(new DeviceGroup(groupInfo.getGroupId().serialize(),
2255 Optional.fromNullable(groupInfo.name),
2256 new ArrayList<>(groupInfo.getMembers()),
2257 createGroupAvatarAttachment(groupInfo.getGroupId()),
2258 groupInfo.isMember(account.getSelfAddress()),
2259 Optional.of(groupInfo.messageExpirationTime),
2260 Optional.fromNullable(groupInfo.color),
2261 groupInfo.blocked,
2262 Optional.fromNullable(groupInfo.inboxPosition),
2263 groupInfo.archived));
2264 }
2265 }
2266 }
2267
2268 if (groupsFile.exists() && groupsFile.length() > 0) {
2269 try (FileInputStream groupsFileStream = new FileInputStream(groupsFile)) {
2270 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
2271 .withStream(groupsFileStream)
2272 .withContentType("application/octet-stream")
2273 .withLength(groupsFile.length())
2274 .build();
2275
2276 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
2277 }
2278 }
2279 } finally {
2280 try {
2281 Files.delete(groupsFile.toPath());
2282 } catch (IOException e) {
2283 logger.warn("Failed to delete groups temp file “{}”, ignoring: {}", groupsFile, e.getMessage());
2284 }
2285 }
2286 }
2287
2288 public void sendContacts() throws IOException, UntrustedIdentityException {
2289 File contactsFile = IOUtils.createTempFile();
2290
2291 try {
2292 try (OutputStream fos = new FileOutputStream(contactsFile)) {
2293 DeviceContactsOutputStream out = new DeviceContactsOutputStream(fos);
2294 for (ContactInfo record : account.getContactStore().getContacts()) {
2295 VerifiedMessage verifiedMessage = null;
2296 IdentityInfo currentIdentity = account.getSignalProtocolStore().getIdentity(record.getAddress());
2297 if (currentIdentity != null) {
2298 verifiedMessage = new VerifiedMessage(record.getAddress(),
2299 currentIdentity.getIdentityKey(),
2300 currentIdentity.getTrustLevel().toVerifiedState(),
2301 currentIdentity.getDateAdded().getTime());
2302 }
2303
2304 ProfileKey profileKey = account.getProfileStore().getProfileKey(record.getAddress());
2305 out.write(new DeviceContact(record.getAddress(),
2306 Optional.fromNullable(record.name),
2307 createContactAvatarAttachment(record.getAddress()),
2308 Optional.fromNullable(record.color),
2309 Optional.fromNullable(verifiedMessage),
2310 Optional.fromNullable(profileKey),
2311 record.blocked,
2312 Optional.of(record.messageExpirationTime),
2313 Optional.fromNullable(record.inboxPosition),
2314 record.archived));
2315 }
2316
2317 if (account.getProfileKey() != null) {
2318 // Send our own profile key as well
2319 out.write(new DeviceContact(account.getSelfAddress(),
2320 Optional.absent(),
2321 Optional.absent(),
2322 Optional.absent(),
2323 Optional.absent(),
2324 Optional.of(account.getProfileKey()),
2325 false,
2326 Optional.absent(),
2327 Optional.absent(),
2328 false));
2329 }
2330 }
2331
2332 if (contactsFile.exists() && contactsFile.length() > 0) {
2333 try (FileInputStream contactsFileStream = new FileInputStream(contactsFile)) {
2334 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
2335 .withStream(contactsFileStream)
2336 .withContentType("application/octet-stream")
2337 .withLength(contactsFile.length())
2338 .build();
2339
2340 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
2341 }
2342 }
2343 } finally {
2344 try {
2345 Files.delete(contactsFile.toPath());
2346 } catch (IOException e) {
2347 logger.warn("Failed to delete contacts temp file “{}”, ignoring: {}", contactsFile, e.getMessage());
2348 }
2349 }
2350 }
2351
2352 void sendBlockedList() throws IOException, UntrustedIdentityException {
2353 List<SignalServiceAddress> addresses = new ArrayList<>();
2354 for (ContactInfo record : account.getContactStore().getContacts()) {
2355 if (record.blocked) {
2356 addresses.add(record.getAddress());
2357 }
2358 }
2359 List<byte[]> groupIds = new ArrayList<>();
2360 for (GroupInfo record : getGroups()) {
2361 if (record.isBlocked()) {
2362 groupIds.add(record.getGroupId().serialize());
2363 }
2364 }
2365 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
2366 }
2367
2368 private void sendVerifiedMessage(
2369 SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel
2370 ) throws IOException, UntrustedIdentityException {
2371 VerifiedMessage verifiedMessage = new VerifiedMessage(destination,
2372 identityKey,
2373 trustLevel.toVerifiedState(),
2374 System.currentTimeMillis());
2375 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
2376 }
2377
2378 public List<ContactInfo> getContacts() {
2379 return account.getContactStore().getContacts();
2380 }
2381
2382 public ContactInfo getContact(String number) {
2383 return account.getContactStore().getContact(Utils.getSignalServiceAddressFromIdentifier(number));
2384 }
2385
2386 public GroupInfo getGroup(GroupId groupId) {
2387 final GroupInfo group = account.getGroupStore().getGroup(groupId);
2388 if (group instanceof GroupInfoV2 && ((GroupInfoV2) group).getGroup() == null) {
2389 final GroupSecretParams groupSecretParams = GroupSecretParams.deriveFromMasterKey(((GroupInfoV2) group).getMasterKey());
2390 ((GroupInfoV2) group).setGroup(groupHelper.getDecryptedGroup(groupSecretParams));
2391 account.getGroupStore().updateGroup(group);
2392 }
2393 return group;
2394 }
2395
2396 public List<IdentityInfo> getIdentities() {
2397 return account.getSignalProtocolStore().getIdentities();
2398 }
2399
2400 public List<IdentityInfo> getIdentities(String number) throws InvalidNumberException {
2401 return account.getSignalProtocolStore().getIdentities(canonicalizeAndResolveSignalServiceAddress(number));
2402 }
2403
2404 /**
2405 * Trust this the identity with this fingerprint
2406 *
2407 * @param name username of the identity
2408 * @param fingerprint Fingerprint
2409 */
2410 public boolean trustIdentityVerified(String name, byte[] fingerprint) throws InvalidNumberException {
2411 SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(name);
2412 List<IdentityInfo> ids = account.getSignalProtocolStore().getIdentities(address);
2413 if (ids == null) {
2414 return false;
2415 }
2416 for (IdentityInfo id : ids) {
2417 if (!Arrays.equals(id.getIdentityKey().serialize(), fingerprint)) {
2418 continue;
2419 }
2420
2421 account.getSignalProtocolStore()
2422 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2423 try {
2424 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2425 } catch (IOException | UntrustedIdentityException e) {
2426 e.printStackTrace();
2427 }
2428 account.save();
2429 return true;
2430 }
2431 return false;
2432 }
2433
2434 /**
2435 * Trust this the identity with this safety number
2436 *
2437 * @param name username of the identity
2438 * @param safetyNumber Safety number
2439 */
2440 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) throws InvalidNumberException {
2441 SignalServiceAddress address = canonicalizeAndResolveSignalServiceAddress(name);
2442 List<IdentityInfo> ids = account.getSignalProtocolStore().getIdentities(address);
2443 if (ids == null) {
2444 return false;
2445 }
2446 for (IdentityInfo id : ids) {
2447 if (!safetyNumber.equals(computeSafetyNumber(address, id.getIdentityKey()))) {
2448 continue;
2449 }
2450
2451 account.getSignalProtocolStore()
2452 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2453 try {
2454 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
2455 } catch (IOException | UntrustedIdentityException e) {
2456 e.printStackTrace();
2457 }
2458 account.save();
2459 return true;
2460 }
2461 return false;
2462 }
2463
2464 /**
2465 * Trust all keys of this identity without verification
2466 *
2467 * @param name username of the identity
2468 */
2469 public boolean trustIdentityAllKeys(String name) {
2470 SignalServiceAddress address = resolveSignalServiceAddress(name);
2471 List<IdentityInfo> ids = account.getSignalProtocolStore().getIdentities(address);
2472 if (ids == null) {
2473 return false;
2474 }
2475 for (IdentityInfo id : ids) {
2476 if (id.getTrustLevel() == TrustLevel.UNTRUSTED) {
2477 account.getSignalProtocolStore()
2478 .setIdentityTrustLevel(address, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
2479 try {
2480 sendVerifiedMessage(address, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
2481 } catch (IOException | UntrustedIdentityException e) {
2482 e.printStackTrace();
2483 }
2484 }
2485 }
2486 account.save();
2487 return true;
2488 }
2489
2490 public String computeSafetyNumber(
2491 SignalServiceAddress theirAddress, IdentityKey theirIdentityKey
2492 ) {
2493 return Utils.computeSafetyNumber(ServiceConfig.capabilities.isUuid(),
2494 account.getSelfAddress(),
2495 getIdentityKeyPair().getPublicKey(),
2496 theirAddress,
2497 theirIdentityKey);
2498 }
2499
2500 public SignalServiceAddress canonicalizeAndResolveSignalServiceAddress(String identifier) throws InvalidNumberException {
2501 String canonicalizedNumber = UuidUtil.isUuid(identifier)
2502 ? identifier
2503 : PhoneNumberFormatter.formatNumber(identifier, account.getUsername());
2504 return resolveSignalServiceAddress(canonicalizedNumber);
2505 }
2506
2507 public SignalServiceAddress resolveSignalServiceAddress(String identifier) {
2508 SignalServiceAddress address = Utils.getSignalServiceAddressFromIdentifier(identifier);
2509
2510 return resolveSignalServiceAddress(address);
2511 }
2512
2513 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
2514 if (address.matches(account.getSelfAddress())) {
2515 return account.getSelfAddress();
2516 }
2517
2518 return account.getRecipientStore().resolveServiceAddress(address);
2519 }
2520
2521 @Override
2522 public void close() throws IOException {
2523 close(true);
2524 }
2525
2526 void close(boolean closeAccount) throws IOException {
2527 if (messagePipe != null) {
2528 messagePipe.shutdown();
2529 messagePipe = null;
2530 }
2531
2532 if (unidentifiedMessagePipe != null) {
2533 unidentifiedMessagePipe.shutdown();
2534 unidentifiedMessagePipe = null;
2535 }
2536
2537 if (closeAccount && account != null) {
2538 account.close();
2539 }
2540 account = null;
2541 }
2542
2543 public interface ReceiveMessageHandler {
2544
2545 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
2546 }
2547 }