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