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