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