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