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