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