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