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