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