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