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