]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/manager/Manager.java
Store contact uuids in contact store
[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(new SignalServiceAddress(null, 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 final SignalServiceAddress address = new SignalServiceAddress(null, canonicalizedNumber);
757 ContactInfo contact = account.getContactStore().getContact(address);
758 if (contact == null) {
759 contact = new ContactInfo(address);
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 final SignalServiceAddress address = new SignalServiceAddress(null, number);
773 ContactInfo contact = account.getContactStore().getContact(address);
774 if (contact == null) {
775 contact = new ContactInfo(address);
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);
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);
1343 if (contact == null) {
1344 contact = new ContactInfo(source);
1345 }
1346 contact.profileKey = Base64.encodeBytes(message.getProfileKey().get());
1347 account.getContactStore().updateContact(contact);
1348 }
1349 if (message.getPreviews().isPresent()) {
1350 final List<SignalServiceDataMessage.Preview> previews = message.getPreviews().get();
1351 for (SignalServiceDataMessage.Preview preview : previews) {
1352 if (preview.getImage().isPresent() && preview.getImage().get().isPointer()) {
1353 SignalServiceAttachmentPointer attachment = preview.getImage().get().asPointer();
1354 try {
1355 retrieveAttachment(attachment);
1356 } catch (IOException | InvalidMessageException e) {
1357 System.err.println("Failed to retrieve attachment (" + attachment.getId() + "): " + e.getMessage());
1358 }
1359 }
1360 }
1361 }
1362 }
1363
1364 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1365 final File cachePath = new File(getMessageCachePath());
1366 if (!cachePath.exists()) {
1367 return;
1368 }
1369 for (final File dir : Objects.requireNonNull(cachePath.listFiles())) {
1370 if (!dir.isDirectory()) {
1371 continue;
1372 }
1373
1374 for (final File fileEntry : Objects.requireNonNull(dir.listFiles())) {
1375 if (!fileEntry.isFile()) {
1376 continue;
1377 }
1378 SignalServiceEnvelope envelope;
1379 try {
1380 envelope = Utils.loadEnvelope(fileEntry);
1381 if (envelope == null) {
1382 continue;
1383 }
1384 } catch (IOException e) {
1385 e.printStackTrace();
1386 continue;
1387 }
1388 SignalServiceContent content = null;
1389 if (!envelope.isReceipt()) {
1390 try {
1391 content = decryptMessage(envelope);
1392 } catch (Exception e) {
1393 continue;
1394 }
1395 handleMessage(envelope, content, ignoreAttachments);
1396 }
1397 account.save();
1398 handler.handleMessage(envelope, content, null);
1399 try {
1400 Files.delete(fileEntry.toPath());
1401 } catch (IOException e) {
1402 System.err.println("Failed to delete cached message file “" + fileEntry + "”: " + e.getMessage());
1403 }
1404 }
1405 // Try to delete directory if empty
1406 dir.delete();
1407 }
1408 }
1409
1410 public void receiveMessages(long timeout, TimeUnit unit, boolean returnOnTimeout, boolean ignoreAttachments, ReceiveMessageHandler handler) throws IOException {
1411 retryFailedReceivedMessages(handler, ignoreAttachments);
1412 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1413
1414 try {
1415 if (messagePipe == null) {
1416 messagePipe = messageReceiver.createMessagePipe();
1417 }
1418
1419 while (true) {
1420 SignalServiceEnvelope envelope;
1421 SignalServiceContent content = null;
1422 Exception exception = null;
1423 final long now = new Date().getTime();
1424 try {
1425 envelope = messagePipe.read(timeout, unit, envelope1 -> {
1426 // store message on disk, before acknowledging receipt to the server
1427 try {
1428 File cacheFile = getMessageCacheFile(envelope1.getSourceE164().get(), now, envelope1.getTimestamp());
1429 Utils.storeEnvelope(envelope1, cacheFile);
1430 } catch (IOException e) {
1431 System.err.println("Failed to store encrypted message in disk cache, ignoring: " + e.getMessage());
1432 }
1433 });
1434 } catch (TimeoutException e) {
1435 if (returnOnTimeout)
1436 return;
1437 continue;
1438 } catch (InvalidVersionException e) {
1439 System.err.println("Ignoring error: " + e.getMessage());
1440 continue;
1441 }
1442 if (!envelope.isReceipt()) {
1443 try {
1444 content = decryptMessage(envelope);
1445 } catch (Exception e) {
1446 exception = e;
1447 }
1448 handleMessage(envelope, content, ignoreAttachments);
1449 }
1450 account.save();
1451 if (!isMessageBlocked(envelope, content)) {
1452 handler.handleMessage(envelope, content, exception);
1453 }
1454 if (!(exception instanceof ProtocolUntrustedIdentityException)) {
1455 File cacheFile = null;
1456 try {
1457 cacheFile = getMessageCacheFile(envelope.getSourceE164().get(), now, envelope.getTimestamp());
1458 Files.delete(cacheFile.toPath());
1459 // Try to delete directory if empty
1460 new File(getMessageCachePath()).delete();
1461 } catch (IOException e) {
1462 System.err.println("Failed to delete cached message file “" + cacheFile + "”: " + e.getMessage());
1463 }
1464 }
1465 }
1466 } finally {
1467 if (messagePipe != null) {
1468 messagePipe.shutdown();
1469 messagePipe = null;
1470 }
1471 }
1472 }
1473
1474 private boolean isMessageBlocked(SignalServiceEnvelope envelope, SignalServiceContent content) {
1475 SignalServiceAddress source;
1476 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1477 source = envelope.getSourceAddress();
1478 } else if (content != null) {
1479 source = content.getSender();
1480 } else {
1481 return false;
1482 }
1483 ContactInfo sourceContact = getContact(source.getNumber().get());
1484 if (sourceContact != null && sourceContact.blocked) {
1485 return true;
1486 }
1487
1488 if (content != null && content.getDataMessage().isPresent()) {
1489 SignalServiceDataMessage message = content.getDataMessage().get();
1490 if (message.getGroupInfo().isPresent()) {
1491 SignalServiceGroup groupInfo = message.getGroupInfo().get();
1492 GroupInfo group = getGroup(groupInfo.getGroupId());
1493 if (groupInfo.getType() == SignalServiceGroup.Type.DELIVER && group != null && group.blocked) {
1494 return true;
1495 }
1496 }
1497 }
1498 return false;
1499 }
1500
1501 private void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments) {
1502 if (content != null) {
1503 SignalServiceAddress sender;
1504 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1505 sender = envelope.getSourceAddress();
1506 } else {
1507 sender = content.getSender();
1508 }
1509 if (content.getDataMessage().isPresent()) {
1510 SignalServiceDataMessage message = content.getDataMessage().get();
1511 handleSignalServiceDataMessage(message, false, sender, account.getSelfAddress(), ignoreAttachments);
1512 }
1513 if (content.getSyncMessage().isPresent()) {
1514 account.setMultiDevice(true);
1515 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
1516 if (syncMessage.getSent().isPresent()) {
1517 SentTranscriptMessage message = syncMessage.getSent().get();
1518 handleSignalServiceDataMessage(message.getMessage(), true, sender, message.getDestination().orNull(), ignoreAttachments);
1519 }
1520 if (syncMessage.getRequest().isPresent()) {
1521 RequestMessage rm = syncMessage.getRequest().get();
1522 if (rm.isContactsRequest()) {
1523 try {
1524 sendContacts();
1525 } catch (UntrustedIdentityException | IOException e) {
1526 e.printStackTrace();
1527 }
1528 }
1529 if (rm.isGroupsRequest()) {
1530 try {
1531 sendGroups();
1532 } catch (UntrustedIdentityException | IOException e) {
1533 e.printStackTrace();
1534 }
1535 }
1536 if (rm.isBlockedListRequest()) {
1537 try {
1538 sendBlockedList();
1539 } catch (UntrustedIdentityException | IOException e) {
1540 e.printStackTrace();
1541 }
1542 }
1543 // TODO Handle rm.isConfigurationRequest();
1544 }
1545 if (syncMessage.getGroups().isPresent()) {
1546 File tmpFile = null;
1547 try {
1548 tmpFile = IOUtils.createTempFile();
1549 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(syncMessage.getGroups().get().asPointer(), tmpFile)) {
1550 DeviceGroupsInputStream s = new DeviceGroupsInputStream(attachmentAsStream);
1551 DeviceGroup g;
1552 while ((g = s.read()) != null) {
1553 GroupInfo syncGroup = account.getGroupStore().getGroup(g.getId());
1554 if (syncGroup == null) {
1555 syncGroup = new GroupInfo(g.getId());
1556 }
1557 if (g.getName().isPresent()) {
1558 syncGroup.name = g.getName().get();
1559 }
1560 syncGroup.addMembers(g.getMembers());
1561 if (!g.isActive()) {
1562 syncGroup.members.remove(account.getUsername());
1563 } else {
1564 // Add ourself to the member set as it's marked as active
1565 syncGroup.members.add(account.getUsername());
1566 }
1567 syncGroup.blocked = g.isBlocked();
1568 if (g.getColor().isPresent()) {
1569 syncGroup.color = g.getColor().get();
1570 }
1571
1572 if (g.getAvatar().isPresent()) {
1573 retrieveGroupAvatarAttachment(g.getAvatar().get(), syncGroup.groupId);
1574 }
1575 syncGroup.inboxPosition = g.getInboxPosition().orNull();
1576 syncGroup.archived = g.isArchived();
1577 account.getGroupStore().updateGroup(syncGroup);
1578 }
1579 }
1580 } catch (Exception e) {
1581 e.printStackTrace();
1582 } finally {
1583 if (tmpFile != null) {
1584 try {
1585 Files.delete(tmpFile.toPath());
1586 } catch (IOException e) {
1587 System.err.println("Failed to delete received groups temp file “" + tmpFile + "”: " + e.getMessage());
1588 }
1589 }
1590 }
1591 }
1592 if (syncMessage.getBlockedList().isPresent()) {
1593 final BlockedListMessage blockedListMessage = syncMessage.getBlockedList().get();
1594 for (SignalServiceAddress address : blockedListMessage.getAddresses()) {
1595 if (address.getNumber().isPresent()) {
1596 try {
1597 setContactBlocked(address.getNumber().get(), true);
1598 } catch (InvalidNumberException e) {
1599 e.printStackTrace();
1600 }
1601 }
1602 }
1603 for (byte[] groupId : blockedListMessage.getGroupIds()) {
1604 try {
1605 setGroupBlocked(groupId, true);
1606 } catch (GroupNotFoundException e) {
1607 System.err.println("BlockedListMessage contained groupID that was not found in GroupStore: " + Base64.encodeBytes(groupId));
1608 }
1609 }
1610 }
1611 if (syncMessage.getContacts().isPresent()) {
1612 File tmpFile = null;
1613 try {
1614 tmpFile = IOUtils.createTempFile();
1615 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
1616 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream().asPointer(), tmpFile)) {
1617 DeviceContactsInputStream s = new DeviceContactsInputStream(attachmentAsStream);
1618 if (contactsMessage.isComplete()) {
1619 account.getContactStore().clear();
1620 }
1621 DeviceContact c;
1622 while ((c = s.read()) != null) {
1623 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
1624 account.setProfileKey(c.getProfileKey().get());
1625 }
1626 ContactInfo contact = account.getContactStore().getContact(c.getAddress());
1627 if (contact == null) {
1628 contact = new ContactInfo(c.getAddress());
1629 }
1630 if (c.getName().isPresent()) {
1631 contact.name = c.getName().get();
1632 }
1633 if (c.getColor().isPresent()) {
1634 contact.color = c.getColor().get();
1635 }
1636 if (c.getProfileKey().isPresent()) {
1637 contact.profileKey = Base64.encodeBytes(c.getProfileKey().get().serialize());
1638 }
1639 if (c.getVerified().isPresent()) {
1640 final VerifiedMessage verifiedMessage = c.getVerified().get();
1641 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination().getNumber().get(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1642 }
1643 if (c.getExpirationTimer().isPresent()) {
1644 ThreadInfo thread = account.getThreadStore().getThread(c.getAddress().getNumber().get());
1645 if (thread == null) {
1646 thread = new ThreadInfo();
1647 thread.id = c.getAddress().getNumber().get();
1648 }
1649 thread.messageExpirationTime = c.getExpirationTimer().get();
1650 account.getThreadStore().updateThread(thread);
1651 }
1652 contact.blocked = c.isBlocked();
1653 contact.inboxPosition = c.getInboxPosition().orNull();
1654 contact.archived = c.isArchived();
1655 account.getContactStore().updateContact(contact);
1656
1657 if (c.getAvatar().isPresent()) {
1658 retrieveContactAvatarAttachment(c.getAvatar().get(), contact.number);
1659 }
1660 }
1661 }
1662 } catch (Exception e) {
1663 e.printStackTrace();
1664 } finally {
1665 if (tmpFile != null) {
1666 try {
1667 Files.delete(tmpFile.toPath());
1668 } catch (IOException e) {
1669 System.err.println("Failed to delete received contacts temp file “" + tmpFile + "”: " + e.getMessage());
1670 }
1671 }
1672 }
1673 }
1674 if (syncMessage.getVerified().isPresent()) {
1675 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1676 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination().getNumber().get(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1677 }
1678 if (syncMessage.getConfiguration().isPresent()) {
1679 // TODO
1680 }
1681 }
1682 }
1683 }
1684
1685 private File getContactAvatarFile(String number) {
1686 return new File(avatarsPath, "contact-" + number);
1687 }
1688
1689 private File retrieveContactAvatarAttachment(SignalServiceAttachment attachment, String number) throws IOException, InvalidMessageException {
1690 IOUtils.createPrivateDirectories(avatarsPath);
1691 if (attachment.isPointer()) {
1692 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1693 return retrieveAttachment(pointer, getContactAvatarFile(number), false);
1694 } else {
1695 SignalServiceAttachmentStream stream = attachment.asStream();
1696 return Utils.retrieveAttachment(stream, getContactAvatarFile(number));
1697 }
1698 }
1699
1700 private File getGroupAvatarFile(byte[] groupId) {
1701 return new File(avatarsPath, "group-" + Base64.encodeBytes(groupId).replace("/", "_"));
1702 }
1703
1704 private File retrieveGroupAvatarAttachment(SignalServiceAttachment attachment, byte[] groupId) throws IOException, InvalidMessageException {
1705 IOUtils.createPrivateDirectories(avatarsPath);
1706 if (attachment.isPointer()) {
1707 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1708 return retrieveAttachment(pointer, getGroupAvatarFile(groupId), false);
1709 } else {
1710 SignalServiceAttachmentStream stream = attachment.asStream();
1711 return Utils.retrieveAttachment(stream, getGroupAvatarFile(groupId));
1712 }
1713 }
1714
1715 public File getAttachmentFile(long attachmentId) {
1716 return new File(attachmentsPath, attachmentId + "");
1717 }
1718
1719 private File retrieveAttachment(SignalServiceAttachmentPointer pointer) throws IOException, InvalidMessageException {
1720 IOUtils.createPrivateDirectories(attachmentsPath);
1721 return retrieveAttachment(pointer, getAttachmentFile(pointer.getId()), true);
1722 }
1723
1724 private File retrieveAttachment(SignalServiceAttachmentPointer pointer, File outputFile, boolean storePreview) throws IOException, InvalidMessageException {
1725 if (storePreview && pointer.getPreview().isPresent()) {
1726 File previewFile = new File(outputFile + ".preview");
1727 try (OutputStream output = new FileOutputStream(previewFile)) {
1728 byte[] preview = pointer.getPreview().get();
1729 output.write(preview, 0, preview.length);
1730 } catch (FileNotFoundException e) {
1731 e.printStackTrace();
1732 return null;
1733 }
1734 }
1735
1736 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1737
1738 File tmpFile = IOUtils.createTempFile();
1739 try (InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE)) {
1740 try (OutputStream output = new FileOutputStream(outputFile)) {
1741 byte[] buffer = new byte[4096];
1742 int read;
1743
1744 while ((read = input.read(buffer)) != -1) {
1745 output.write(buffer, 0, read);
1746 }
1747 } catch (FileNotFoundException e) {
1748 e.printStackTrace();
1749 return null;
1750 }
1751 } finally {
1752 try {
1753 Files.delete(tmpFile.toPath());
1754 } catch (IOException e) {
1755 System.err.println("Failed to delete received attachment temp file “" + tmpFile + "”: " + e.getMessage());
1756 }
1757 }
1758 return outputFile;
1759 }
1760
1761 private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer, File tmpFile) throws IOException, InvalidMessageException {
1762 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1763 return messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE);
1764 }
1765
1766 @Override
1767 public boolean isRemote() {
1768 return false;
1769 }
1770
1771 private void sendGroups() throws IOException, UntrustedIdentityException {
1772 File groupsFile = IOUtils.createTempFile();
1773
1774 try {
1775 try (OutputStream fos = new FileOutputStream(groupsFile)) {
1776 DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(fos);
1777 for (GroupInfo record : account.getGroupStore().getGroups()) {
1778 ThreadInfo info = account.getThreadStore().getThread(Base64.encodeBytes(record.groupId));
1779 out.write(new DeviceGroup(record.groupId, Optional.fromNullable(record.name),
1780 new ArrayList<>(record.getMembers()), createGroupAvatarAttachment(record.groupId),
1781 record.members.contains(account.getUsername()), Optional.fromNullable(info != null ? info.messageExpirationTime : null),
1782 Optional.fromNullable(record.color), record.blocked, Optional.fromNullable(record.inboxPosition), record.archived));
1783 }
1784 }
1785
1786 if (groupsFile.exists() && groupsFile.length() > 0) {
1787 try (FileInputStream groupsFileStream = new FileInputStream(groupsFile)) {
1788 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1789 .withStream(groupsFileStream)
1790 .withContentType("application/octet-stream")
1791 .withLength(groupsFile.length())
1792 .build();
1793
1794 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
1795 }
1796 }
1797 } finally {
1798 try {
1799 Files.delete(groupsFile.toPath());
1800 } catch (IOException e) {
1801 System.err.println("Failed to delete groups temp file “" + groupsFile + "”: " + e.getMessage());
1802 }
1803 }
1804 }
1805
1806 public void sendContacts() throws IOException, UntrustedIdentityException {
1807 File contactsFile = IOUtils.createTempFile();
1808
1809 try {
1810 try (OutputStream fos = new FileOutputStream(contactsFile)) {
1811 DeviceContactsOutputStream out = new DeviceContactsOutputStream(fos);
1812 for (ContactInfo record : account.getContactStore().getContacts()) {
1813 VerifiedMessage verifiedMessage = null;
1814 ThreadInfo info = account.getThreadStore().getThread(record.number);
1815 if (getIdentities().containsKey(record.number)) {
1816 JsonIdentityKeyStore.Identity currentIdentity = null;
1817 for (JsonIdentityKeyStore.Identity id : getIdentities().get(record.number)) {
1818 if (currentIdentity == null || id.getDateAdded().after(currentIdentity.getDateAdded())) {
1819 currentIdentity = id;
1820 }
1821 }
1822 if (currentIdentity != null) {
1823 verifiedMessage = new VerifiedMessage(record.getAddress(), currentIdentity.getIdentityKey(), currentIdentity.getTrustLevel().toVerifiedState(), currentIdentity.getDateAdded().getTime());
1824 }
1825 }
1826
1827 ProfileKey profileKey = null;
1828 try {
1829 profileKey = record.profileKey == null ? null : new ProfileKey(Base64.decode(record.profileKey));
1830 } catch (InvalidInputException ignored) {
1831 }
1832 out.write(new DeviceContact(record.getAddress(), Optional.fromNullable(record.name),
1833 createContactAvatarAttachment(record.number), Optional.fromNullable(record.color),
1834 Optional.fromNullable(verifiedMessage), Optional.fromNullable(profileKey), record.blocked,
1835 Optional.fromNullable(info != null ? info.messageExpirationTime : null),
1836 Optional.fromNullable(record.inboxPosition), record.archived));
1837 }
1838
1839 if (account.getProfileKey() != null) {
1840 // Send our own profile key as well
1841 out.write(new DeviceContact(account.getSelfAddress(),
1842 Optional.absent(), Optional.absent(),
1843 Optional.absent(), Optional.absent(),
1844 Optional.of(account.getProfileKey()),
1845 false, Optional.absent(), Optional.absent(), false));
1846 }
1847 }
1848
1849 if (contactsFile.exists() && contactsFile.length() > 0) {
1850 try (FileInputStream contactsFileStream = new FileInputStream(contactsFile)) {
1851 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1852 .withStream(contactsFileStream)
1853 .withContentType("application/octet-stream")
1854 .withLength(contactsFile.length())
1855 .build();
1856
1857 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
1858 }
1859 }
1860 } finally {
1861 try {
1862 Files.delete(contactsFile.toPath());
1863 } catch (IOException e) {
1864 System.err.println("Failed to delete contacts temp file “" + contactsFile + "”: " + e.getMessage());
1865 }
1866 }
1867 }
1868
1869 private void sendBlockedList() throws IOException, UntrustedIdentityException {
1870 List<SignalServiceAddress> addresses = new ArrayList<>();
1871 for (ContactInfo record : account.getContactStore().getContacts()) {
1872 if (record.blocked) {
1873 addresses.add(record.getAddress());
1874 }
1875 }
1876 List<byte[]> groupIds = new ArrayList<>();
1877 for (GroupInfo record : account.getGroupStore().getGroups()) {
1878 if (record.blocked) {
1879 groupIds.add(record.groupId);
1880 }
1881 }
1882 sendSyncMessage(SignalServiceSyncMessage.forBlocked(new BlockedListMessage(addresses, groupIds)));
1883 }
1884
1885 private void sendVerifiedMessage(SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel) throws IOException, UntrustedIdentityException {
1886 VerifiedMessage verifiedMessage = new VerifiedMessage(destination, identityKey, trustLevel.toVerifiedState(), System.currentTimeMillis());
1887 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
1888 }
1889
1890 public List<ContactInfo> getContacts() {
1891 return account.getContactStore().getContacts();
1892 }
1893
1894 public ContactInfo getContact(String number) {
1895 return account.getContactStore().getContact(new SignalServiceAddress(null, number));
1896 }
1897
1898 public GroupInfo getGroup(byte[] groupId) {
1899 return account.getGroupStore().getGroup(groupId);
1900 }
1901
1902 public Map<String, List<JsonIdentityKeyStore.Identity>> getIdentities() {
1903 return account.getSignalProtocolStore().getIdentities();
1904 }
1905
1906 public Pair<String, List<JsonIdentityKeyStore.Identity>> getIdentities(String number) throws InvalidNumberException {
1907 String canonicalizedNumber = Utils.canonicalizeNumber(number, account.getUsername());
1908 return new Pair<>(canonicalizedNumber, account.getSignalProtocolStore().getIdentities(canonicalizedNumber));
1909 }
1910
1911 /**
1912 * Trust this the identity with this fingerprint
1913 *
1914 * @param name username of the identity
1915 * @param fingerprint Fingerprint
1916 */
1917 public boolean trustIdentityVerified(String name, byte[] fingerprint) {
1918 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1919 if (ids == null) {
1920 return false;
1921 }
1922 for (JsonIdentityKeyStore.Identity id : ids) {
1923 if (!Arrays.equals(id.getIdentityKey().serialize(), fingerprint)) {
1924 continue;
1925 }
1926
1927 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1928 try {
1929 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1930 } catch (IOException | UntrustedIdentityException e) {
1931 e.printStackTrace();
1932 }
1933 account.save();
1934 return true;
1935 }
1936 return false;
1937 }
1938
1939 /**
1940 * Trust this the identity with this safety number
1941 *
1942 * @param name username of the identity
1943 * @param safetyNumber Safety number
1944 */
1945 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) {
1946 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1947 if (ids == null) {
1948 return false;
1949 }
1950 for (JsonIdentityKeyStore.Identity id : ids) {
1951 if (!safetyNumber.equals(computeSafetyNumber(name, id.getIdentityKey()))) {
1952 continue;
1953 }
1954
1955 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1956 try {
1957 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1958 } catch (IOException | UntrustedIdentityException e) {
1959 e.printStackTrace();
1960 }
1961 account.save();
1962 return true;
1963 }
1964 return false;
1965 }
1966
1967 /**
1968 * Trust all keys of this identity without verification
1969 *
1970 * @param name username of the identity
1971 */
1972 public boolean trustIdentityAllKeys(String name) {
1973 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1974 if (ids == null) {
1975 return false;
1976 }
1977 for (JsonIdentityKeyStore.Identity id : ids) {
1978 if (id.getTrustLevel() == TrustLevel.UNTRUSTED) {
1979 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1980 try {
1981 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1982 } catch (IOException | UntrustedIdentityException e) {
1983 e.printStackTrace();
1984 }
1985 }
1986 }
1987 account.save();
1988 return true;
1989 }
1990
1991 public String computeSafetyNumber(String theirUsername, IdentityKey theirIdentityKey) {
1992 return Utils.computeSafetyNumber(account.getUsername(), getIdentity(), theirUsername, theirIdentityKey);
1993 }
1994
1995 public interface ReceiveMessageHandler {
1996
1997 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
1998 }
1999 }