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