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