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