]> nmode's Git Repositories - signal-cli/blob - src/main/java/org/asamk/signal/manager/Manager.java
50da5f23f748c725e6764d5b7e5357eb6273b5da
[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) throws InvalidNumberException {
679 String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
680 ContactInfo contact = account.getContactStore().getContact(canonicalizedNumber);
681 if (contact == null) {
682 return "";
683 } else {
684 return contact.name;
685 }
686 }
687
688 @Override
689 public void setContactName(String number, String name) throws InvalidNumberException {
690 String canonicalizedNumber = Utils.canonicalizeNumber(number, username);
691 ContactInfo contact = account.getContactStore().getContact(canonicalizedNumber);
692 if (contact == null) {
693 contact = new ContactInfo();
694 contact.number = canonicalizedNumber;
695 System.err.println("Add contact " + canonicalizedNumber + " named " + name);
696 } else {
697 System.err.println("Updating contact " + canonicalizedNumber + " name " + contact.name + " -> " + name);
698 }
699 contact.name = name;
700 account.getContactStore().updateContact(contact);
701 account.save();
702 }
703
704 @Override
705 public List<byte[]> getGroupIds() {
706 List<GroupInfo> groups = getGroups();
707 List<byte[]> ids = new ArrayList<>(groups.size());
708 for (GroupInfo group : groups) {
709 ids.add(group.groupId);
710 }
711 return ids;
712 }
713
714 @Override
715 public String getGroupName(byte[] groupId) {
716 GroupInfo group = getGroup(groupId);
717 if (group == null) {
718 return "";
719 } else {
720 return group.name;
721 }
722 }
723
724 @Override
725 public List<String> getGroupMembers(byte[] groupId) {
726 GroupInfo group = getGroup(groupId);
727 if (group == null) {
728 return new ArrayList<>();
729 } else {
730 return new ArrayList<>(group.members);
731 }
732 }
733
734 @Override
735 public byte[] updateGroup(byte[] groupId, String name, List<String> members, String avatar) throws IOException, EncapsulatedExceptions, GroupNotFoundException, AttachmentInvalidException {
736 if (groupId.length == 0) {
737 groupId = null;
738 }
739 if (name.isEmpty()) {
740 name = null;
741 }
742 if (members.size() == 0) {
743 members = null;
744 }
745 if (avatar.isEmpty()) {
746 avatar = null;
747 }
748 return sendUpdateGroupMessage(groupId, name, members, avatar);
749 }
750
751 /**
752 * Change the expiration timer for a thread (number of groupId)
753 *
754 * @param numberOrGroupId
755 * @param messageExpirationTimer
756 */
757 public void setExpirationTimer(String numberOrGroupId, int messageExpirationTimer) {
758 ThreadInfo thread = account.getThreadStore().getThread(numberOrGroupId);
759 thread.messageExpirationTime = messageExpirationTimer;
760 account.getThreadStore().updateThread(thread);
761 }
762
763 private void requestSyncGroups() throws IOException {
764 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.GROUPS).build();
765 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
766 try {
767 sendSyncMessage(message);
768 } catch (UntrustedIdentityException e) {
769 e.printStackTrace();
770 }
771 }
772
773 private void requestSyncContacts() throws IOException {
774 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONTACTS).build();
775 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
776 try {
777 sendSyncMessage(message);
778 } catch (UntrustedIdentityException e) {
779 e.printStackTrace();
780 }
781 }
782
783 private void requestSyncBlocked() throws IOException {
784 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.BLOCKED).build();
785 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
786 try {
787 sendSyncMessage(message);
788 } catch (UntrustedIdentityException e) {
789 e.printStackTrace();
790 }
791 }
792
793 private void requestSyncConfiguration() throws IOException {
794 SignalServiceProtos.SyncMessage.Request r = SignalServiceProtos.SyncMessage.Request.newBuilder().setType(SignalServiceProtos.SyncMessage.Request.Type.CONFIGURATION).build();
795 SignalServiceSyncMessage message = SignalServiceSyncMessage.forRequest(new RequestMessage(r));
796 try {
797 sendSyncMessage(message);
798 } catch (UntrustedIdentityException e) {
799 e.printStackTrace();
800 }
801 }
802
803 private byte[] getSelfUnidentifiedAccessKey() {
804 return UnidentifiedAccess.deriveAccessKeyFrom(account.getProfileKey());
805 }
806
807 private byte[] getTargetUnidentifiedAccessKey(SignalServiceAddress recipient) {
808 // TODO implement
809 return null;
810 }
811
812 private Optional<UnidentifiedAccessPair> getAccessForSync() {
813 // TODO implement
814 return Optional.absent();
815 }
816
817 private List<Optional<UnidentifiedAccessPair>> getAccessFor(Collection<SignalServiceAddress> recipients) {
818 List<Optional<UnidentifiedAccessPair>> result = new ArrayList<>(recipients.size());
819 for (SignalServiceAddress recipient : recipients) {
820 result.add(Optional.<UnidentifiedAccessPair>absent());
821 }
822 return result;
823 }
824
825 private Optional<UnidentifiedAccessPair> getAccessFor(SignalServiceAddress recipient) {
826 // TODO implement
827 return Optional.absent();
828 }
829
830 private void sendSyncMessage(SignalServiceSyncMessage message)
831 throws IOException, UntrustedIdentityException {
832 SignalServiceMessageSender messageSender = getMessageSender();
833 try {
834 messageSender.sendMessage(message, getAccessForSync());
835 } catch (UntrustedIdentityException e) {
836 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
837 throw e;
838 }
839 }
840
841 /**
842 * This method throws an EncapsulatedExceptions exception instead of returning a list of SendMessageResult.
843 */
844 private void sendMessageLegacy(SignalServiceDataMessage.Builder messageBuilder, Collection<String> recipients)
845 throws EncapsulatedExceptions, IOException {
846 List<SendMessageResult> results = sendMessage(messageBuilder, recipients);
847
848 List<UntrustedIdentityException> untrustedIdentities = new LinkedList<>();
849 List<UnregisteredUserException> unregisteredUsers = new LinkedList<>();
850 List<NetworkFailureException> networkExceptions = new LinkedList<>();
851
852 for (SendMessageResult result : results) {
853 if (result.isUnregisteredFailure()) {
854 unregisteredUsers.add(new UnregisteredUserException(result.getAddress().getNumber().get(), null));
855 } else if (result.isNetworkFailure()) {
856 networkExceptions.add(new NetworkFailureException(result.getAddress().getNumber().get(), null));
857 } else if (result.getIdentityFailure() != null) {
858 untrustedIdentities.add(new UntrustedIdentityException("Untrusted", result.getAddress().getNumber().get(), result.getIdentityFailure().getIdentityKey()));
859 }
860 }
861 if (!untrustedIdentities.isEmpty() || !unregisteredUsers.isEmpty() || !networkExceptions.isEmpty()) {
862 throw new EncapsulatedExceptions(untrustedIdentities, unregisteredUsers, networkExceptions);
863 }
864 }
865
866 private List<SendMessageResult> sendMessage(SignalServiceDataMessage.Builder messageBuilder, Collection<String> recipients)
867 throws IOException {
868 Set<SignalServiceAddress> recipientsTS = Utils.getSignalServiceAddresses(recipients, username);
869 if (recipientsTS == null) {
870 account.save();
871 return Collections.emptyList();
872 }
873
874 SignalServiceDataMessage message = null;
875 try {
876 SignalServiceMessageSender messageSender = getMessageSender();
877
878 message = messageBuilder.build();
879 if (message.getGroupInfo().isPresent()) {
880 try {
881 final boolean isRecipientUpdate = false;
882 List<SendMessageResult> result = messageSender.sendMessage(new ArrayList<>(recipientsTS), getAccessFor(recipientsTS), isRecipientUpdate, message);
883 for (SendMessageResult r : result) {
884 if (r.getIdentityFailure() != null) {
885 account.getSignalProtocolStore().saveIdentity(r.getAddress().getNumber().get(), r.getIdentityFailure().getIdentityKey(), TrustLevel.UNTRUSTED);
886 }
887 }
888 return result;
889 } catch (UntrustedIdentityException e) {
890 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
891 return Collections.emptyList();
892 }
893 } else if (recipientsTS.size() == 1 && recipientsTS.contains(getSelfAddress())) {
894 SignalServiceAddress recipient = getSelfAddress();
895 final Optional<UnidentifiedAccessPair> unidentifiedAccess = getAccessFor(recipient);
896 SentTranscriptMessage transcript = new SentTranscriptMessage(Optional.of(recipient),
897 message.getTimestamp(),
898 message,
899 message.getExpiresInSeconds(),
900 Collections.singletonMap(recipient, unidentifiedAccess.isPresent()),
901 false);
902 SignalServiceSyncMessage syncMessage = SignalServiceSyncMessage.forSentTranscript(transcript);
903
904 List<SendMessageResult> results = new ArrayList<>(recipientsTS.size());
905 try {
906 messageSender.sendMessage(syncMessage, unidentifiedAccess);
907 } catch (UntrustedIdentityException e) {
908 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
909 results.add(SendMessageResult.identityFailure(recipient, e.getIdentityKey()));
910 }
911 return results;
912 } else {
913 // Send to all individually, so sync messages are sent correctly
914 List<SendMessageResult> results = new ArrayList<>(recipientsTS.size());
915 for (SignalServiceAddress address : recipientsTS) {
916 ThreadInfo thread = account.getThreadStore().getThread(address.getNumber().get());
917 if (thread != null) {
918 messageBuilder.withExpiration(thread.messageExpirationTime);
919 } else {
920 messageBuilder.withExpiration(0);
921 }
922 message = messageBuilder.build();
923 try {
924 SendMessageResult result = messageSender.sendMessage(address, getAccessFor(address), message);
925 results.add(result);
926 } catch (UntrustedIdentityException e) {
927 account.getSignalProtocolStore().saveIdentity(e.getIdentifier(), e.getIdentityKey(), TrustLevel.UNTRUSTED);
928 results.add(SendMessageResult.identityFailure(address, e.getIdentityKey()));
929 }
930 }
931 return results;
932 }
933 } finally {
934 if (message != null && message.isEndSession()) {
935 for (SignalServiceAddress recipient : recipientsTS) {
936 handleEndSession(recipient.getNumber().get());
937 }
938 }
939 account.save();
940 }
941 }
942
943 private SignalServiceContent decryptMessage(SignalServiceEnvelope envelope) throws InvalidMetadataMessageException, ProtocolInvalidMessageException, ProtocolDuplicateMessageException, ProtocolLegacyMessageException, ProtocolInvalidKeyIdException, InvalidMetadataVersionException, ProtocolInvalidVersionException, ProtocolNoSessionException, ProtocolInvalidKeyException, ProtocolUntrustedIdentityException, SelfSendException, UnsupportedDataMessageException {
944 SignalServiceCipher cipher = new SignalServiceCipher(getSelfAddress(), account.getSignalProtocolStore(), Utils.getCertificateValidator());
945 try {
946 return cipher.decrypt(envelope);
947 } catch (ProtocolUntrustedIdentityException e) {
948 // TODO We don't get the new untrusted identity from ProtocolUntrustedIdentityException anymore ... we need to get it from somewhere else
949 // account.getSignalProtocolStore().saveIdentity(e.getSender(), e.getUntrustedIdentity(), TrustLevel.UNTRUSTED);
950 throw e;
951 }
952 }
953
954 private void handleEndSession(String source) {
955 account.getSignalProtocolStore().deleteAllSessions(source);
956 }
957
958 private void handleSignalServiceDataMessage(SignalServiceDataMessage message, boolean isSync, String source, SignalServiceAddress destination, boolean ignoreAttachments) {
959 String threadId;
960 if (message.getGroupInfo().isPresent()) {
961 SignalServiceGroup groupInfo = message.getGroupInfo().get();
962 threadId = Base64.encodeBytes(groupInfo.getGroupId());
963 GroupInfo group = account.getGroupStore().getGroup(groupInfo.getGroupId());
964 switch (groupInfo.getType()) {
965 case UPDATE:
966 if (group == null) {
967 group = new GroupInfo(groupInfo.getGroupId());
968 }
969
970 if (groupInfo.getAvatar().isPresent()) {
971 SignalServiceAttachment avatar = groupInfo.getAvatar().get();
972 if (avatar.isPointer()) {
973 try {
974 retrieveGroupAvatarAttachment(avatar.asPointer(), group.groupId);
975 } catch (IOException | InvalidMessageException e) {
976 System.err.println("Failed to retrieve group avatar (" + avatar.asPointer().getId() + "): " + e.getMessage());
977 }
978 }
979 }
980
981 if (groupInfo.getName().isPresent()) {
982 group.name = groupInfo.getName().get();
983 }
984
985 if (groupInfo.getMembers().isPresent()) {
986 group.addMembers(groupInfo.getMembers().get());
987 }
988
989 account.getGroupStore().updateGroup(group);
990 break;
991 case DELIVER:
992 if (group == null) {
993 try {
994 sendGroupInfoRequest(groupInfo.getGroupId(), source);
995 } catch (IOException | EncapsulatedExceptions e) {
996 e.printStackTrace();
997 }
998 }
999 break;
1000 case QUIT:
1001 if (group == null) {
1002 try {
1003 sendGroupInfoRequest(groupInfo.getGroupId(), source);
1004 } catch (IOException | EncapsulatedExceptions e) {
1005 e.printStackTrace();
1006 }
1007 } else {
1008 group.members.remove(source);
1009 account.getGroupStore().updateGroup(group);
1010 }
1011 break;
1012 case REQUEST_INFO:
1013 if (group != null) {
1014 try {
1015 sendUpdateGroupMessage(groupInfo.getGroupId(), source);
1016 } catch (IOException | EncapsulatedExceptions e) {
1017 e.printStackTrace();
1018 } catch (NotAGroupMemberException e) {
1019 // We have left this group, so don't send a group update message
1020 }
1021 }
1022 break;
1023 }
1024 } else {
1025 if (isSync) {
1026 threadId = destination.getNumber().get();
1027 } else {
1028 threadId = source;
1029 }
1030 }
1031 if (message.isEndSession()) {
1032 handleEndSession(isSync ? destination.getNumber().get() : source);
1033 }
1034 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
1035 ThreadInfo thread = account.getThreadStore().getThread(threadId);
1036 if (thread == null) {
1037 thread = new ThreadInfo();
1038 thread.id = threadId;
1039 }
1040 if (thread.messageExpirationTime != message.getExpiresInSeconds()) {
1041 thread.messageExpirationTime = message.getExpiresInSeconds();
1042 account.getThreadStore().updateThread(thread);
1043 }
1044 }
1045 if (message.getAttachments().isPresent() && !ignoreAttachments) {
1046 for (SignalServiceAttachment attachment : message.getAttachments().get()) {
1047 if (attachment.isPointer()) {
1048 try {
1049 retrieveAttachment(attachment.asPointer());
1050 } catch (IOException | InvalidMessageException e) {
1051 System.err.println("Failed to retrieve attachment (" + attachment.asPointer().getId() + "): " + e.getMessage());
1052 }
1053 }
1054 }
1055 }
1056 if (message.getProfileKey().isPresent() && message.getProfileKey().get().length == 32) {
1057 if (source.equals(username)) {
1058 this.account.setProfileKey(message.getProfileKey().get());
1059 }
1060 ContactInfo contact = account.getContactStore().getContact(source);
1061 if (contact == null) {
1062 contact = new ContactInfo();
1063 contact.number = source;
1064 }
1065 contact.profileKey = Base64.encodeBytes(message.getProfileKey().get());
1066 }
1067 if (message.getPreviews().isPresent()) {
1068 final List<SignalServiceDataMessage.Preview> previews = message.getPreviews().get();
1069 for (SignalServiceDataMessage.Preview preview : previews) {
1070 if (preview.getImage().isPresent() && preview.getImage().get().isPointer()) {
1071 SignalServiceAttachmentPointer attachment = preview.getImage().get().asPointer();
1072 try {
1073 retrieveAttachment(attachment);
1074 } catch (IOException | InvalidMessageException e) {
1075 System.err.println("Failed to retrieve attachment (" + attachment.getId() + "): " + e.getMessage());
1076 }
1077 }
1078 }
1079 }
1080 }
1081
1082 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
1083 final File cachePath = new File(getMessageCachePath());
1084 if (!cachePath.exists()) {
1085 return;
1086 }
1087 for (final File dir : Objects.requireNonNull(cachePath.listFiles())) {
1088 if (!dir.isDirectory()) {
1089 continue;
1090 }
1091
1092 for (final File fileEntry : Objects.requireNonNull(dir.listFiles())) {
1093 if (!fileEntry.isFile()) {
1094 continue;
1095 }
1096 SignalServiceEnvelope envelope;
1097 try {
1098 envelope = Utils.loadEnvelope(fileEntry);
1099 if (envelope == null) {
1100 continue;
1101 }
1102 } catch (IOException e) {
1103 e.printStackTrace();
1104 continue;
1105 }
1106 SignalServiceContent content = null;
1107 if (!envelope.isReceipt()) {
1108 try {
1109 content = decryptMessage(envelope);
1110 } catch (Exception e) {
1111 continue;
1112 }
1113 handleMessage(envelope, content, ignoreAttachments);
1114 }
1115 account.save();
1116 handler.handleMessage(envelope, content, null);
1117 try {
1118 Files.delete(fileEntry.toPath());
1119 } catch (IOException e) {
1120 System.err.println("Failed to delete cached message file “" + fileEntry + "”: " + e.getMessage());
1121 }
1122 }
1123 // Try to delete directory if empty
1124 dir.delete();
1125 }
1126 }
1127
1128 public void receiveMessages(long timeout, TimeUnit unit, boolean returnOnTimeout, boolean ignoreAttachments, ReceiveMessageHandler handler) throws IOException {
1129 retryFailedReceivedMessages(handler, ignoreAttachments);
1130 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1131
1132 try {
1133 if (messagePipe == null) {
1134 messagePipe = messageReceiver.createMessagePipe();
1135 }
1136
1137 while (true) {
1138 SignalServiceEnvelope envelope;
1139 SignalServiceContent content = null;
1140 Exception exception = null;
1141 final long now = new Date().getTime();
1142 try {
1143 envelope = messagePipe.read(timeout, unit, new SignalServiceMessagePipe.MessagePipeCallback() {
1144 @Override
1145 public void onMessage(SignalServiceEnvelope envelope) {
1146 // store message on disk, before acknowledging receipt to the server
1147 try {
1148 File cacheFile = getMessageCacheFile(envelope.getSourceE164().get(), now, envelope.getTimestamp());
1149 Utils.storeEnvelope(envelope, cacheFile);
1150 } catch (IOException e) {
1151 System.err.println("Failed to store encrypted message in disk cache, ignoring: " + e.getMessage());
1152 }
1153 }
1154 });
1155 } catch (TimeoutException e) {
1156 if (returnOnTimeout)
1157 return;
1158 continue;
1159 } catch (InvalidVersionException e) {
1160 System.err.println("Ignoring error: " + e.getMessage());
1161 continue;
1162 }
1163 if (!envelope.isReceipt()) {
1164 try {
1165 content = decryptMessage(envelope);
1166 } catch (Exception e) {
1167 exception = e;
1168 }
1169 handleMessage(envelope, content, ignoreAttachments);
1170 }
1171 account.save();
1172 handler.handleMessage(envelope, content, exception);
1173 if (!(exception instanceof ProtocolUntrustedIdentityException)) {
1174 File cacheFile = null;
1175 try {
1176 cacheFile = getMessageCacheFile(envelope.getSourceE164().get(), now, envelope.getTimestamp());
1177 Files.delete(cacheFile.toPath());
1178 // Try to delete directory if empty
1179 new File(getMessageCachePath()).delete();
1180 } catch (IOException e) {
1181 System.err.println("Failed to delete cached message file “" + cacheFile + "”: " + e.getMessage());
1182 }
1183 }
1184 }
1185 } finally {
1186 if (messagePipe != null) {
1187 messagePipe.shutdown();
1188 messagePipe = null;
1189 }
1190 }
1191 }
1192
1193 private void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent content, boolean ignoreAttachments) {
1194 if (content != null) {
1195 SignalServiceAddress sender;
1196 if (!envelope.isUnidentifiedSender() && envelope.hasSource()) {
1197 sender = envelope.getSourceAddress();
1198 } else {
1199 sender = content.getSender();
1200 }
1201 if (content.getDataMessage().isPresent()) {
1202 SignalServiceDataMessage message = content.getDataMessage().get();
1203 handleSignalServiceDataMessage(message, false, sender.getNumber().get(), getSelfAddress(), ignoreAttachments);
1204 }
1205 if (content.getSyncMessage().isPresent()) {
1206 account.setMultiDevice(true);
1207 SignalServiceSyncMessage syncMessage = content.getSyncMessage().get();
1208 if (syncMessage.getSent().isPresent()) {
1209 SentTranscriptMessage message = syncMessage.getSent().get();
1210 handleSignalServiceDataMessage(message.getMessage(), true, sender.getNumber().get(), message.getDestination().orNull(), ignoreAttachments);
1211 }
1212 if (syncMessage.getRequest().isPresent()) {
1213 RequestMessage rm = syncMessage.getRequest().get();
1214 if (rm.isContactsRequest()) {
1215 try {
1216 sendContacts();
1217 } catch (UntrustedIdentityException | IOException e) {
1218 e.printStackTrace();
1219 }
1220 }
1221 if (rm.isGroupsRequest()) {
1222 try {
1223 sendGroups();
1224 } catch (UntrustedIdentityException | IOException e) {
1225 e.printStackTrace();
1226 }
1227 }
1228 // TODO Handle rm.isBlockedListRequest(); rm.isConfigurationRequest();
1229 }
1230 if (syncMessage.getGroups().isPresent()) {
1231 File tmpFile = null;
1232 try {
1233 tmpFile = IOUtils.createTempFile();
1234 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(syncMessage.getGroups().get().asPointer(), tmpFile)) {
1235 DeviceGroupsInputStream s = new DeviceGroupsInputStream(attachmentAsStream);
1236 DeviceGroup g;
1237 while ((g = s.read()) != null) {
1238 GroupInfo syncGroup = account.getGroupStore().getGroup(g.getId());
1239 if (syncGroup == null) {
1240 syncGroup = new GroupInfo(g.getId());
1241 }
1242 if (g.getName().isPresent()) {
1243 syncGroup.name = g.getName().get();
1244 }
1245 syncGroup.addMembers(g.getMembers());
1246 syncGroup.active = g.isActive();
1247 if (g.getColor().isPresent()) {
1248 syncGroup.color = g.getColor().get();
1249 }
1250
1251 if (g.getAvatar().isPresent()) {
1252 retrieveGroupAvatarAttachment(g.getAvatar().get(), syncGroup.groupId);
1253 }
1254 account.getGroupStore().updateGroup(syncGroup);
1255 }
1256 }
1257 } catch (Exception e) {
1258 e.printStackTrace();
1259 } finally {
1260 if (tmpFile != null) {
1261 try {
1262 Files.delete(tmpFile.toPath());
1263 } catch (IOException e) {
1264 System.err.println("Failed to delete received groups temp file “" + tmpFile + "”: " + e.getMessage());
1265 }
1266 }
1267 }
1268 }
1269 if (syncMessage.getBlockedList().isPresent()) {
1270 // TODO store list of blocked numbers
1271 }
1272 if (syncMessage.getContacts().isPresent()) {
1273 File tmpFile = null;
1274 try {
1275 tmpFile = IOUtils.createTempFile();
1276 final ContactsMessage contactsMessage = syncMessage.getContacts().get();
1277 try (InputStream attachmentAsStream = retrieveAttachmentAsStream(contactsMessage.getContactsStream().asPointer(), tmpFile)) {
1278 DeviceContactsInputStream s = new DeviceContactsInputStream(attachmentAsStream);
1279 if (contactsMessage.isComplete()) {
1280 account.getContactStore().clear();
1281 }
1282 DeviceContact c;
1283 while ((c = s.read()) != null) {
1284 if (c.getAddress().matches(account.getSelfAddress()) && c.getProfileKey().isPresent()) {
1285 account.setProfileKey(c.getProfileKey().get());
1286 }
1287 ContactInfo contact = account.getContactStore().getContact(c.getAddress().getNumber().get());
1288 if (contact == null) {
1289 contact = new ContactInfo();
1290 contact.number = c.getAddress().getNumber().get();
1291 }
1292 if (c.getName().isPresent()) {
1293 contact.name = c.getName().get();
1294 }
1295 if (c.getColor().isPresent()) {
1296 contact.color = c.getColor().get();
1297 }
1298 if (c.getProfileKey().isPresent()) {
1299 contact.profileKey = Base64.encodeBytes(c.getProfileKey().get());
1300 }
1301 if (c.getVerified().isPresent()) {
1302 final VerifiedMessage verifiedMessage = c.getVerified().get();
1303 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination().getNumber().get(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1304 }
1305 if (c.getExpirationTimer().isPresent()) {
1306 ThreadInfo thread = account.getThreadStore().getThread(c.getAddress().getNumber().get());
1307 if (thread == null) {
1308 thread = new ThreadInfo();
1309 thread.id = c.getAddress().getNumber().get();
1310 }
1311 thread.messageExpirationTime = c.getExpirationTimer().get();
1312 account.getThreadStore().updateThread(thread);
1313 }
1314 if (c.isBlocked()) {
1315 // TODO store list of blocked numbers
1316 }
1317 account.getContactStore().updateContact(contact);
1318
1319 if (c.getAvatar().isPresent()) {
1320 retrieveContactAvatarAttachment(c.getAvatar().get(), contact.number);
1321 }
1322 }
1323 }
1324 } catch (Exception e) {
1325 e.printStackTrace();
1326 } finally {
1327 if (tmpFile != null) {
1328 try {
1329 Files.delete(tmpFile.toPath());
1330 } catch (IOException e) {
1331 System.err.println("Failed to delete received contacts temp file “" + tmpFile + "”: " + e.getMessage());
1332 }
1333 }
1334 }
1335 }
1336 if (syncMessage.getVerified().isPresent()) {
1337 final VerifiedMessage verifiedMessage = syncMessage.getVerified().get();
1338 account.getSignalProtocolStore().saveIdentity(verifiedMessage.getDestination().getNumber().get(), verifiedMessage.getIdentityKey(), TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
1339 }
1340 if (syncMessage.getConfiguration().isPresent()) {
1341 // TODO
1342 }
1343 }
1344 }
1345 }
1346
1347 private File getContactAvatarFile(String number) {
1348 return new File(avatarsPath, "contact-" + number);
1349 }
1350
1351 private File retrieveContactAvatarAttachment(SignalServiceAttachment attachment, String number) throws IOException, InvalidMessageException {
1352 IOUtils.createPrivateDirectories(avatarsPath);
1353 if (attachment.isPointer()) {
1354 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1355 return retrieveAttachment(pointer, getContactAvatarFile(number), false);
1356 } else {
1357 SignalServiceAttachmentStream stream = attachment.asStream();
1358 return Utils.retrieveAttachment(stream, getContactAvatarFile(number));
1359 }
1360 }
1361
1362 private File getGroupAvatarFile(byte[] groupId) {
1363 return new File(avatarsPath, "group-" + Base64.encodeBytes(groupId).replace("/", "_"));
1364 }
1365
1366 private File retrieveGroupAvatarAttachment(SignalServiceAttachment attachment, byte[] groupId) throws IOException, InvalidMessageException {
1367 IOUtils.createPrivateDirectories(avatarsPath);
1368 if (attachment.isPointer()) {
1369 SignalServiceAttachmentPointer pointer = attachment.asPointer();
1370 return retrieveAttachment(pointer, getGroupAvatarFile(groupId), false);
1371 } else {
1372 SignalServiceAttachmentStream stream = attachment.asStream();
1373 return Utils.retrieveAttachment(stream, getGroupAvatarFile(groupId));
1374 }
1375 }
1376
1377 public File getAttachmentFile(long attachmentId) {
1378 return new File(attachmentsPath, attachmentId + "");
1379 }
1380
1381 private File retrieveAttachment(SignalServiceAttachmentPointer pointer) throws IOException, InvalidMessageException {
1382 IOUtils.createPrivateDirectories(attachmentsPath);
1383 return retrieveAttachment(pointer, getAttachmentFile(pointer.getId()), true);
1384 }
1385
1386 private File retrieveAttachment(SignalServiceAttachmentPointer pointer, File outputFile, boolean storePreview) throws IOException, InvalidMessageException {
1387 if (storePreview && pointer.getPreview().isPresent()) {
1388 File previewFile = new File(outputFile + ".preview");
1389 try (OutputStream output = new FileOutputStream(previewFile)) {
1390 byte[] preview = pointer.getPreview().get();
1391 output.write(preview, 0, preview.length);
1392 } catch (FileNotFoundException e) {
1393 e.printStackTrace();
1394 return null;
1395 }
1396 }
1397
1398 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1399
1400 File tmpFile = IOUtils.createTempFile();
1401 try (InputStream input = messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE)) {
1402 try (OutputStream output = new FileOutputStream(outputFile)) {
1403 byte[] buffer = new byte[4096];
1404 int read;
1405
1406 while ((read = input.read(buffer)) != -1) {
1407 output.write(buffer, 0, read);
1408 }
1409 } catch (FileNotFoundException e) {
1410 e.printStackTrace();
1411 return null;
1412 }
1413 } finally {
1414 try {
1415 Files.delete(tmpFile.toPath());
1416 } catch (IOException e) {
1417 System.err.println("Failed to delete received attachment temp file “" + tmpFile + "”: " + e.getMessage());
1418 }
1419 }
1420 return outputFile;
1421 }
1422
1423 private InputStream retrieveAttachmentAsStream(SignalServiceAttachmentPointer pointer, File tmpFile) throws IOException, InvalidMessageException {
1424 final SignalServiceMessageReceiver messageReceiver = getMessageReceiver();
1425 return messageReceiver.retrieveAttachment(pointer, tmpFile, BaseConfig.MAX_ATTACHMENT_SIZE);
1426 }
1427
1428 @Override
1429 public boolean isRemote() {
1430 return false;
1431 }
1432
1433 private void sendGroups() throws IOException, UntrustedIdentityException {
1434 File groupsFile = IOUtils.createTempFile();
1435
1436 try {
1437 try (OutputStream fos = new FileOutputStream(groupsFile)) {
1438 DeviceGroupsOutputStream out = new DeviceGroupsOutputStream(fos);
1439 for (GroupInfo record : account.getGroupStore().getGroups()) {
1440 ThreadInfo info = account.getThreadStore().getThread(Base64.encodeBytes(record.groupId));
1441 out.write(new DeviceGroup(record.groupId, Optional.fromNullable(record.name),
1442 new ArrayList<>(record.getMembers()), createGroupAvatarAttachment(record.groupId),
1443 record.active, Optional.fromNullable(info != null ? info.messageExpirationTime : null),
1444 Optional.fromNullable(record.color), false));
1445 }
1446 }
1447
1448 if (groupsFile.exists() && groupsFile.length() > 0) {
1449 try (FileInputStream groupsFileStream = new FileInputStream(groupsFile)) {
1450 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1451 .withStream(groupsFileStream)
1452 .withContentType("application/octet-stream")
1453 .withLength(groupsFile.length())
1454 .build();
1455
1456 sendSyncMessage(SignalServiceSyncMessage.forGroups(attachmentStream));
1457 }
1458 }
1459 } finally {
1460 try {
1461 Files.delete(groupsFile.toPath());
1462 } catch (IOException e) {
1463 System.err.println("Failed to delete groups temp file “" + groupsFile + "”: " + e.getMessage());
1464 }
1465 }
1466 }
1467
1468 public void sendContacts() throws IOException, UntrustedIdentityException {
1469 File contactsFile = IOUtils.createTempFile();
1470
1471 try {
1472 try (OutputStream fos = new FileOutputStream(contactsFile)) {
1473 DeviceContactsOutputStream out = new DeviceContactsOutputStream(fos);
1474 for (ContactInfo record : account.getContactStore().getContacts()) {
1475 VerifiedMessage verifiedMessage = null;
1476 ThreadInfo info = account.getThreadStore().getThread(record.number);
1477 if (getIdentities().containsKey(record.number)) {
1478 JsonIdentityKeyStore.Identity currentIdentity = null;
1479 for (JsonIdentityKeyStore.Identity id : getIdentities().get(record.number)) {
1480 if (currentIdentity == null || id.getDateAdded().after(currentIdentity.getDateAdded())) {
1481 currentIdentity = id;
1482 }
1483 }
1484 if (currentIdentity != null) {
1485 verifiedMessage = new VerifiedMessage(record.getAddress(), currentIdentity.getIdentityKey(), currentIdentity.getTrustLevel().toVerifiedState(), currentIdentity.getDateAdded().getTime());
1486 }
1487 }
1488
1489 byte[] profileKey = record.profileKey == null ? null : Base64.decode(record.profileKey);
1490 // TODO store list of blocked numbers
1491 boolean blocked = false;
1492 out.write(new DeviceContact(record.getAddress(), Optional.fromNullable(record.name),
1493 createContactAvatarAttachment(record.number), Optional.fromNullable(record.color),
1494 Optional.fromNullable(verifiedMessage), Optional.fromNullable(profileKey), blocked, Optional.fromNullable(info != null ? info.messageExpirationTime : null)));
1495 }
1496
1497 if (account.getProfileKey() != null) {
1498 // Send our own profile key as well
1499 out.write(new DeviceContact(account.getSelfAddress(),
1500 Optional.<String>absent(), Optional.<SignalServiceAttachmentStream>absent(),
1501 Optional.<String>absent(), Optional.<VerifiedMessage>absent(),
1502 Optional.of(account.getProfileKey()),
1503 false, Optional.<Integer>absent()));
1504 }
1505 }
1506
1507 if (contactsFile.exists() && contactsFile.length() > 0) {
1508 try (FileInputStream contactsFileStream = new FileInputStream(contactsFile)) {
1509 SignalServiceAttachmentStream attachmentStream = SignalServiceAttachment.newStreamBuilder()
1510 .withStream(contactsFileStream)
1511 .withContentType("application/octet-stream")
1512 .withLength(contactsFile.length())
1513 .build();
1514
1515 sendSyncMessage(SignalServiceSyncMessage.forContacts(new ContactsMessage(attachmentStream, true)));
1516 }
1517 }
1518 } finally {
1519 try {
1520 Files.delete(contactsFile.toPath());
1521 } catch (IOException e) {
1522 System.err.println("Failed to delete contacts temp file “" + contactsFile + "”: " + e.getMessage());
1523 }
1524 }
1525 }
1526
1527 private void sendVerifiedMessage(SignalServiceAddress destination, IdentityKey identityKey, TrustLevel trustLevel) throws IOException, UntrustedIdentityException {
1528 VerifiedMessage verifiedMessage = new VerifiedMessage(destination, identityKey, trustLevel.toVerifiedState(), System.currentTimeMillis());
1529 sendSyncMessage(SignalServiceSyncMessage.forVerified(verifiedMessage));
1530 }
1531
1532 public List<ContactInfo> getContacts() {
1533 return account.getContactStore().getContacts();
1534 }
1535
1536 public ContactInfo getContact(String number) {
1537 return account.getContactStore().getContact(number);
1538 }
1539
1540 public GroupInfo getGroup(byte[] groupId) {
1541 return account.getGroupStore().getGroup(groupId);
1542 }
1543
1544 public Map<String, List<JsonIdentityKeyStore.Identity>> getIdentities() {
1545 return account.getSignalProtocolStore().getIdentities();
1546 }
1547
1548 public List<JsonIdentityKeyStore.Identity> getIdentities(String number) {
1549 return account.getSignalProtocolStore().getIdentities(number);
1550 }
1551
1552 /**
1553 * Trust this the identity with this fingerprint
1554 *
1555 * @param name username of the identity
1556 * @param fingerprint Fingerprint
1557 */
1558 public boolean trustIdentityVerified(String name, byte[] fingerprint) {
1559 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1560 if (ids == null) {
1561 return false;
1562 }
1563 for (JsonIdentityKeyStore.Identity id : ids) {
1564 if (!Arrays.equals(id.getIdentityKey().serialize(), fingerprint)) {
1565 continue;
1566 }
1567
1568 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1569 try {
1570 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1571 } catch (IOException | UntrustedIdentityException e) {
1572 e.printStackTrace();
1573 }
1574 account.save();
1575 return true;
1576 }
1577 return false;
1578 }
1579
1580 /**
1581 * Trust this the identity with this safety number
1582 *
1583 * @param name username of the identity
1584 * @param safetyNumber Safety number
1585 */
1586 public boolean trustIdentityVerifiedSafetyNumber(String name, String safetyNumber) {
1587 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1588 if (ids == null) {
1589 return false;
1590 }
1591 for (JsonIdentityKeyStore.Identity id : ids) {
1592 if (!safetyNumber.equals(computeSafetyNumber(name, id.getIdentityKey()))) {
1593 continue;
1594 }
1595
1596 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1597 try {
1598 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_VERIFIED);
1599 } catch (IOException | UntrustedIdentityException e) {
1600 e.printStackTrace();
1601 }
1602 account.save();
1603 return true;
1604 }
1605 return false;
1606 }
1607
1608 /**
1609 * Trust all keys of this identity without verification
1610 *
1611 * @param name username of the identity
1612 */
1613 public boolean trustIdentityAllKeys(String name) {
1614 List<JsonIdentityKeyStore.Identity> ids = account.getSignalProtocolStore().getIdentities(name);
1615 if (ids == null) {
1616 return false;
1617 }
1618 for (JsonIdentityKeyStore.Identity id : ids) {
1619 if (id.getTrustLevel() == TrustLevel.UNTRUSTED) {
1620 account.getSignalProtocolStore().saveIdentity(name, id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1621 try {
1622 sendVerifiedMessage(new SignalServiceAddress(null, name), id.getIdentityKey(), TrustLevel.TRUSTED_UNVERIFIED);
1623 } catch (IOException | UntrustedIdentityException e) {
1624 e.printStackTrace();
1625 }
1626 }
1627 }
1628 account.save();
1629 return true;
1630 }
1631
1632 public String computeSafetyNumber(String theirUsername, IdentityKey theirIdentityKey) {
1633 return Utils.computeSafetyNumber(username, getIdentity(), theirUsername, theirIdentityKey);
1634 }
1635
1636 public interface ReceiveMessageHandler {
1637
1638 void handleMessage(SignalServiceEnvelope envelope, SignalServiceContent decryptedContent, Throwable e);
1639 }
1640 }