]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/ManagerImpl.java
d0fab3503330ae598ea6d157e76865073566d9d8
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / ManagerImpl.java
1 /*
2 Copyright (C) 2015-2021 AsamK and contributors
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package org.asamk.signal.manager;
18
19 import org.asamk.signal.manager.actions.HandleAction;
20 import org.asamk.signal.manager.api.Device;
21 import org.asamk.signal.manager.api.Message;
22 import org.asamk.signal.manager.api.RecipientIdentifier;
23 import org.asamk.signal.manager.api.SendGroupMessageResults;
24 import org.asamk.signal.manager.api.SendMessageResults;
25 import org.asamk.signal.manager.api.TypingAction;
26 import org.asamk.signal.manager.config.ServiceConfig;
27 import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
28 import org.asamk.signal.manager.groups.GroupId;
29 import org.asamk.signal.manager.groups.GroupInviteLinkUrl;
30 import org.asamk.signal.manager.groups.GroupLinkState;
31 import org.asamk.signal.manager.groups.GroupNotFoundException;
32 import org.asamk.signal.manager.groups.GroupPermission;
33 import org.asamk.signal.manager.groups.GroupSendingNotAllowedException;
34 import org.asamk.signal.manager.groups.LastGroupAdminException;
35 import org.asamk.signal.manager.groups.NotAGroupMemberException;
36 import org.asamk.signal.manager.helper.AttachmentHelper;
37 import org.asamk.signal.manager.helper.ContactHelper;
38 import org.asamk.signal.manager.helper.GroupHelper;
39 import org.asamk.signal.manager.helper.GroupV2Helper;
40 import org.asamk.signal.manager.helper.IncomingMessageHandler;
41 import org.asamk.signal.manager.helper.PinHelper;
42 import org.asamk.signal.manager.helper.PreKeyHelper;
43 import org.asamk.signal.manager.helper.ProfileHelper;
44 import org.asamk.signal.manager.helper.SendHelper;
45 import org.asamk.signal.manager.helper.StorageHelper;
46 import org.asamk.signal.manager.helper.SyncHelper;
47 import org.asamk.signal.manager.helper.UnidentifiedAccessHelper;
48 import org.asamk.signal.manager.jobs.Context;
49 import org.asamk.signal.manager.storage.SignalAccount;
50 import org.asamk.signal.manager.storage.groups.GroupInfo;
51 import org.asamk.signal.manager.storage.identities.IdentityInfo;
52 import org.asamk.signal.manager.storage.messageCache.CachedMessage;
53 import org.asamk.signal.manager.storage.recipients.Contact;
54 import org.asamk.signal.manager.storage.recipients.Profile;
55 import org.asamk.signal.manager.storage.recipients.RecipientId;
56 import org.asamk.signal.manager.storage.stickers.Sticker;
57 import org.asamk.signal.manager.storage.stickers.StickerPackId;
58 import org.asamk.signal.manager.util.KeyUtils;
59 import org.asamk.signal.manager.util.StickerUtils;
60 import org.asamk.signal.manager.util.Utils;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.whispersystems.libsignal.IdentityKey;
64 import org.whispersystems.libsignal.InvalidKeyException;
65 import org.whispersystems.libsignal.ecc.ECPublicKey;
66 import org.whispersystems.libsignal.fingerprint.Fingerprint;
67 import org.whispersystems.libsignal.fingerprint.FingerprintParsingException;
68 import org.whispersystems.libsignal.fingerprint.FingerprintVersionMismatchException;
69 import org.whispersystems.libsignal.util.Pair;
70 import org.whispersystems.libsignal.util.guava.Optional;
71 import org.whispersystems.signalservice.api.SignalSessionLock;
72 import org.whispersystems.signalservice.api.groupsv2.GroupLinkNotActiveException;
73 import org.whispersystems.signalservice.api.messages.SendMessageResult;
74 import org.whispersystems.signalservice.api.messages.SignalServiceAttachmentRemoteId;
75 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
76 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
77 import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
78 import org.whispersystems.signalservice.api.messages.SignalServiceTypingMessage;
79 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
80 import org.whispersystems.signalservice.api.push.exceptions.UnregisteredUserException;
81 import org.whispersystems.signalservice.api.util.DeviceNameUtil;
82 import org.whispersystems.signalservice.api.util.InvalidNumberException;
83 import org.whispersystems.signalservice.api.util.PhoneNumberFormatter;
84 import org.whispersystems.signalservice.api.websocket.WebSocketUnavailableException;
85 import org.whispersystems.signalservice.internal.contacts.crypto.Quote;
86 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedQuoteException;
87 import org.whispersystems.signalservice.internal.contacts.crypto.UnauthenticatedResponseException;
88 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
89 import org.whispersystems.signalservice.internal.util.Hex;
90 import org.whispersystems.signalservice.internal.util.Util;
91
92 import java.io.File;
93 import java.io.IOException;
94 import java.net.URI;
95 import java.net.URISyntaxException;
96 import java.net.URLEncoder;
97 import java.nio.charset.StandardCharsets;
98 import java.security.SignatureException;
99 import java.util.Arrays;
100 import java.util.Collection;
101 import java.util.Date;
102 import java.util.HashMap;
103 import java.util.HashSet;
104 import java.util.List;
105 import java.util.Map;
106 import java.util.Set;
107 import java.util.UUID;
108 import java.util.concurrent.ExecutorService;
109 import java.util.concurrent.Executors;
110 import java.util.concurrent.TimeUnit;
111 import java.util.concurrent.TimeoutException;
112 import java.util.concurrent.locks.ReentrantLock;
113 import java.util.function.Function;
114 import java.util.stream.Collectors;
115
116 import static org.asamk.signal.manager.config.ServiceConfig.capabilities;
117
118 public class ManagerImpl implements Manager {
119
120 private final static Logger logger = LoggerFactory.getLogger(ManagerImpl.class);
121
122 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
123 private final SignalDependencies dependencies;
124
125 private SignalAccount account;
126
127 private final ExecutorService executor = Executors.newCachedThreadPool();
128
129 private final ProfileHelper profileHelper;
130 private final PinHelper pinHelper;
131 private final StorageHelper storageHelper;
132 private final SendHelper sendHelper;
133 private final SyncHelper syncHelper;
134 private final AttachmentHelper attachmentHelper;
135 private final GroupHelper groupHelper;
136 private final ContactHelper contactHelper;
137 private final IncomingMessageHandler incomingMessageHandler;
138 private final PreKeyHelper preKeyHelper;
139
140 private final Context context;
141 private boolean hasCaughtUpWithOldMessages = false;
142
143 ManagerImpl(
144 SignalAccount account,
145 PathConfig pathConfig,
146 ServiceEnvironmentConfig serviceEnvironmentConfig,
147 String userAgent
148 ) {
149 this.account = account;
150 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
151
152 final var credentialsProvider = new DynamicCredentialsProvider(account.getUuid(),
153 account.getUsername(),
154 account.getPassword(),
155 account.getDeviceId());
156 final var sessionLock = new SignalSessionLock() {
157 private final ReentrantLock LEGACY_LOCK = new ReentrantLock();
158
159 @Override
160 public Lock acquire() {
161 LEGACY_LOCK.lock();
162 return LEGACY_LOCK::unlock;
163 }
164 };
165 this.dependencies = new SignalDependencies(serviceEnvironmentConfig,
166 userAgent,
167 credentialsProvider,
168 account.getSignalProtocolStore(),
169 executor,
170 sessionLock);
171 final var avatarStore = new AvatarStore(pathConfig.getAvatarsPath());
172 final var attachmentStore = new AttachmentStore(pathConfig.getAttachmentsPath());
173 final var stickerPackStore = new StickerPackStore(pathConfig.getStickerPacksPath());
174
175 this.attachmentHelper = new AttachmentHelper(dependencies, attachmentStore);
176 this.pinHelper = new PinHelper(dependencies.getKeyBackupService());
177 final var unidentifiedAccessHelper = new UnidentifiedAccessHelper(account::getProfileKey,
178 account.getProfileStore()::getProfileKey,
179 this::getRecipientProfile,
180 this::getSenderCertificate);
181 this.profileHelper = new ProfileHelper(account,
182 dependencies,
183 avatarStore,
184 account.getProfileStore()::getProfileKey,
185 unidentifiedAccessHelper::getAccessFor,
186 this::resolveSignalServiceAddress);
187 final GroupV2Helper groupV2Helper = new GroupV2Helper(profileHelper::getRecipientProfileKeyCredential,
188 this::getRecipientProfile,
189 account::getSelfRecipientId,
190 dependencies.getGroupsV2Operations(),
191 dependencies.getGroupsV2Api(),
192 this::resolveSignalServiceAddress);
193 this.sendHelper = new SendHelper(account,
194 dependencies,
195 unidentifiedAccessHelper,
196 this::resolveSignalServiceAddress,
197 account.getRecipientStore(),
198 this::handleIdentityFailure,
199 this::getGroup,
200 this::refreshRegisteredUser);
201 this.groupHelper = new GroupHelper(account,
202 dependencies,
203 attachmentHelper,
204 sendHelper,
205 groupV2Helper,
206 avatarStore,
207 this::resolveSignalServiceAddress,
208 account.getRecipientStore());
209 this.storageHelper = new StorageHelper(account, dependencies, groupHelper);
210 this.contactHelper = new ContactHelper(account);
211 this.syncHelper = new SyncHelper(account,
212 attachmentHelper,
213 sendHelper,
214 groupHelper,
215 avatarStore,
216 this::resolveSignalServiceAddress);
217 preKeyHelper = new PreKeyHelper(account, dependencies);
218
219 this.context = new Context(account,
220 dependencies,
221 stickerPackStore,
222 sendHelper,
223 groupHelper,
224 syncHelper,
225 profileHelper,
226 storageHelper,
227 preKeyHelper);
228 var jobExecutor = new JobExecutor(context);
229
230 this.incomingMessageHandler = new IncomingMessageHandler(account,
231 dependencies,
232 account.getRecipientStore(),
233 this::resolveSignalServiceAddress,
234 groupHelper,
235 contactHelper,
236 attachmentHelper,
237 syncHelper,
238 this::getRecipientProfile,
239 jobExecutor);
240 }
241
242 @Override
243 public String getUsername() {
244 return account.getUsername();
245 }
246
247 @Override
248 public RecipientId getSelfRecipientId() {
249 return account.getSelfRecipientId();
250 }
251
252 @Override
253 public int getDeviceId() {
254 return account.getDeviceId();
255 }
256
257 @Override
258 public void checkAccountState() throws IOException {
259 if (account.getLastReceiveTimestamp() == 0) {
260 logger.info("The Signal protocol expects that incoming messages are regularly received.");
261 } else {
262 var diffInMilliseconds = System.currentTimeMillis() - account.getLastReceiveTimestamp();
263 long days = TimeUnit.DAYS.convert(diffInMilliseconds, TimeUnit.MILLISECONDS);
264 if (days > 7) {
265 logger.warn(
266 "Messages have been last received {} days ago. The Signal protocol expects that incoming messages are regularly received.",
267 days);
268 }
269 }
270 preKeyHelper.refreshPreKeysIfNecessary();
271 if (account.getUuid() == null) {
272 account.setUuid(dependencies.getAccountManager().getOwnUuid());
273 }
274 updateAccountAttributes(null);
275 }
276
277 /**
278 * This is used for checking a set of phone numbers for registration on Signal
279 *
280 * @param numbers The set of phone number in question
281 * @return A map of numbers to canonicalized number and uuid. If a number is not registered the uuid is null.
282 * @throws IOException if its unable to get the contacts to check if they're registered
283 */
284 @Override
285 public Map<String, Pair<String, UUID>> areUsersRegistered(Set<String> numbers) throws IOException {
286 Map<String, String> canonicalizedNumbers = numbers.stream().collect(Collectors.toMap(n -> n, n -> {
287 try {
288 return PhoneNumberFormatter.formatNumber(n, account.getUsername());
289 } catch (InvalidNumberException e) {
290 return "";
291 }
292 }));
293
294 // Note "registeredUsers" has no optionals. It only gives us info on users who are registered
295 var registeredUsers = getRegisteredUsers(canonicalizedNumbers.values()
296 .stream()
297 .filter(s -> !s.isEmpty())
298 .collect(Collectors.toSet()));
299
300 return numbers.stream().collect(Collectors.toMap(n -> n, n -> {
301 final var number = canonicalizedNumbers.get(n);
302 final var uuid = registeredUsers.get(number);
303 return new Pair<>(number.isEmpty() ? null : number, uuid);
304 }));
305 }
306
307 @Override
308 public void updateAccountAttributes(String deviceName) throws IOException {
309 final String encryptedDeviceName;
310 if (deviceName == null) {
311 encryptedDeviceName = account.getEncryptedDeviceName();
312 } else {
313 final var privateKey = account.getIdentityKeyPair().getPrivateKey();
314 encryptedDeviceName = DeviceNameUtil.encryptDeviceName(deviceName, privateKey);
315 account.setEncryptedDeviceName(encryptedDeviceName);
316 }
317 dependencies.getAccountManager()
318 .setAccountAttributes(encryptedDeviceName,
319 null,
320 account.getLocalRegistrationId(),
321 true,
322 null,
323 account.getPinMasterKey() == null ? null : account.getPinMasterKey().deriveRegistrationLock(),
324 account.getSelfUnidentifiedAccessKey(),
325 account.isUnrestrictedUnidentifiedAccess(),
326 capabilities,
327 account.isDiscoverableByPhoneNumber());
328 }
329
330 /**
331 * @param givenName if null, the previous givenName will be kept
332 * @param familyName if null, the previous familyName will be kept
333 * @param about if null, the previous about text will be kept
334 * @param aboutEmoji if null, the previous about emoji will be kept
335 * @param avatar if avatar is null the image from the local avatar store is used (if present),
336 */
337 @Override
338 public void setProfile(
339 String givenName, final String familyName, String about, String aboutEmoji, Optional<File> avatar
340 ) throws IOException {
341 profileHelper.setProfile(givenName, familyName, about, aboutEmoji, avatar);
342 syncHelper.sendSyncFetchProfileMessage();
343 }
344
345 @Override
346 public void unregister() throws IOException {
347 // When setting an empty GCM id, the Signal-Server also sets the fetchesMessages property to false.
348 // If this is the master device, other users can't send messages to this number anymore.
349 // If this is a linked device, other users can still send messages, but this device doesn't receive them anymore.
350 dependencies.getAccountManager().setGcmId(Optional.absent());
351
352 account.setRegistered(false);
353 }
354
355 @Override
356 public void deleteAccount() throws IOException {
357 try {
358 pinHelper.removeRegistrationLockPin();
359 } catch (UnauthenticatedResponseException e) {
360 logger.warn("Failed to remove registration lock pin");
361 }
362 account.setRegistrationLockPin(null, null);
363
364 dependencies.getAccountManager().deleteAccount();
365
366 account.setRegistered(false);
367 }
368
369 @Override
370 public void submitRateLimitRecaptchaChallenge(String challenge, String captcha) throws IOException {
371 dependencies.getAccountManager().submitRateLimitRecaptchaChallenge(challenge, captcha);
372 }
373
374 @Override
375 public List<Device> getLinkedDevices() throws IOException {
376 var devices = dependencies.getAccountManager().getDevices();
377 account.setMultiDevice(devices.size() > 1);
378 var identityKey = account.getIdentityKeyPair().getPrivateKey();
379 return devices.stream().map(d -> {
380 String deviceName = d.getName();
381 if (deviceName != null) {
382 try {
383 deviceName = DeviceNameUtil.decryptDeviceName(deviceName, identityKey);
384 } catch (IOException e) {
385 logger.debug("Failed to decrypt device name, maybe plain text?", e);
386 }
387 }
388 return new Device(d.getId(), deviceName, d.getCreated(), d.getLastSeen());
389 }).collect(Collectors.toList());
390 }
391
392 @Override
393 public void removeLinkedDevices(int deviceId) throws IOException {
394 dependencies.getAccountManager().removeDevice(deviceId);
395 var devices = dependencies.getAccountManager().getDevices();
396 account.setMultiDevice(devices.size() > 1);
397 }
398
399 @Override
400 public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
401 var info = DeviceLinkInfo.parseDeviceLinkUri(linkUri);
402
403 addDevice(info.deviceIdentifier, info.deviceKey);
404 }
405
406 private void addDevice(String deviceIdentifier, ECPublicKey deviceKey) throws IOException, InvalidKeyException {
407 var identityKeyPair = account.getIdentityKeyPair();
408 var verificationCode = dependencies.getAccountManager().getNewDeviceVerificationCode();
409
410 dependencies.getAccountManager()
411 .addDevice(deviceIdentifier,
412 deviceKey,
413 identityKeyPair,
414 Optional.of(account.getProfileKey().serialize()),
415 verificationCode);
416 account.setMultiDevice(true);
417 }
418
419 @Override
420 public void setRegistrationLockPin(Optional<String> pin) throws IOException, UnauthenticatedResponseException {
421 if (!account.isMasterDevice()) {
422 throw new RuntimeException("Only master device can set a PIN");
423 }
424 if (pin.isPresent()) {
425 final var masterKey = account.getPinMasterKey() != null
426 ? account.getPinMasterKey()
427 : KeyUtils.createMasterKey();
428
429 pinHelper.setRegistrationLockPin(pin.get(), masterKey);
430
431 account.setRegistrationLockPin(pin.get(), masterKey);
432 } else {
433 // Remove KBS Pin
434 pinHelper.removeRegistrationLockPin();
435
436 account.setRegistrationLockPin(null, null);
437 }
438 }
439
440 void refreshPreKeys() throws IOException {
441 preKeyHelper.refreshPreKeys();
442 }
443
444 @Override
445 public Profile getRecipientProfile(RecipientId recipientId) {
446 return profileHelper.getRecipientProfile(recipientId);
447 }
448
449 @Override
450 public List<GroupInfo> getGroups() {
451 return account.getGroupStore().getGroups();
452 }
453
454 @Override
455 public SendGroupMessageResults quitGroup(
456 GroupId groupId, Set<RecipientIdentifier.Single> groupAdmins
457 ) throws GroupNotFoundException, IOException, NotAGroupMemberException, LastGroupAdminException {
458 final var newAdmins = resolveRecipients(groupAdmins);
459 return groupHelper.quitGroup(groupId, newAdmins);
460 }
461
462 @Override
463 public void deleteGroup(GroupId groupId) throws IOException {
464 groupHelper.deleteGroup(groupId);
465 }
466
467 @Override
468 public Pair<GroupId, SendGroupMessageResults> createGroup(
469 String name, Set<RecipientIdentifier.Single> members, File avatarFile
470 ) throws IOException, AttachmentInvalidException {
471 return groupHelper.createGroup(name, members == null ? null : resolveRecipients(members), avatarFile);
472 }
473
474 @Override
475 public SendGroupMessageResults updateGroup(
476 GroupId groupId,
477 String name,
478 String description,
479 Set<RecipientIdentifier.Single> members,
480 Set<RecipientIdentifier.Single> removeMembers,
481 Set<RecipientIdentifier.Single> admins,
482 Set<RecipientIdentifier.Single> removeAdmins,
483 boolean resetGroupLink,
484 GroupLinkState groupLinkState,
485 GroupPermission addMemberPermission,
486 GroupPermission editDetailsPermission,
487 File avatarFile,
488 Integer expirationTimer,
489 Boolean isAnnouncementGroup
490 ) throws IOException, GroupNotFoundException, AttachmentInvalidException, NotAGroupMemberException, GroupSendingNotAllowedException {
491 return groupHelper.updateGroup(groupId,
492 name,
493 description,
494 members == null ? null : resolveRecipients(members),
495 removeMembers == null ? null : resolveRecipients(removeMembers),
496 admins == null ? null : resolveRecipients(admins),
497 removeAdmins == null ? null : resolveRecipients(removeAdmins),
498 resetGroupLink,
499 groupLinkState,
500 addMemberPermission,
501 editDetailsPermission,
502 avatarFile,
503 expirationTimer,
504 isAnnouncementGroup);
505 }
506
507 @Override
508 public Pair<GroupId, SendGroupMessageResults> joinGroup(
509 GroupInviteLinkUrl inviteLinkUrl
510 ) throws IOException, GroupLinkNotActiveException {
511 return groupHelper.joinGroup(inviteLinkUrl);
512 }
513
514 private SendMessageResults sendMessage(
515 SignalServiceDataMessage.Builder messageBuilder, Set<RecipientIdentifier> recipients
516 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
517 var results = new HashMap<RecipientIdentifier, List<SendMessageResult>>();
518 long timestamp = System.currentTimeMillis();
519 messageBuilder.withTimestamp(timestamp);
520 for (final var recipient : recipients) {
521 if (recipient instanceof RecipientIdentifier.Single) {
522 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
523 final var result = sendHelper.sendMessage(messageBuilder, recipientId);
524 results.put(recipient, List.of(result));
525 } else if (recipient instanceof RecipientIdentifier.NoteToSelf) {
526 final var result = sendHelper.sendSelfMessage(messageBuilder);
527 results.put(recipient, List.of(result));
528 } else if (recipient instanceof RecipientIdentifier.Group) {
529 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
530 final var result = sendHelper.sendAsGroupMessage(messageBuilder, groupId);
531 results.put(recipient, result);
532 }
533 }
534 return new SendMessageResults(timestamp, results);
535 }
536
537 private void sendTypingMessage(
538 SignalServiceTypingMessage.Action action, Set<RecipientIdentifier> recipients
539 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
540 final var timestamp = System.currentTimeMillis();
541 for (var recipient : recipients) {
542 if (recipient instanceof RecipientIdentifier.Single) {
543 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.absent());
544 final var recipientId = resolveRecipient((RecipientIdentifier.Single) recipient);
545 sendHelper.sendTypingMessage(message, recipientId);
546 } else if (recipient instanceof RecipientIdentifier.Group) {
547 final var groupId = ((RecipientIdentifier.Group) recipient).groupId;
548 final var message = new SignalServiceTypingMessage(action, timestamp, Optional.of(groupId.serialize()));
549 sendHelper.sendGroupTypingMessage(message, groupId);
550 }
551 }
552 }
553
554 @Override
555 public void sendTypingMessage(
556 TypingAction action, Set<RecipientIdentifier> recipients
557 ) throws IOException, UntrustedIdentityException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
558 sendTypingMessage(action.toSignalService(), recipients);
559 }
560
561 @Override
562 public void sendReadReceipt(
563 RecipientIdentifier.Single sender, List<Long> messageIds
564 ) throws IOException, UntrustedIdentityException {
565 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.READ,
566 messageIds,
567 System.currentTimeMillis());
568
569 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
570 }
571
572 @Override
573 public void sendViewedReceipt(
574 RecipientIdentifier.Single sender, List<Long> messageIds
575 ) throws IOException, UntrustedIdentityException {
576 var receiptMessage = new SignalServiceReceiptMessage(SignalServiceReceiptMessage.Type.VIEWED,
577 messageIds,
578 System.currentTimeMillis());
579
580 sendHelper.sendReceiptMessage(receiptMessage, resolveRecipient(sender));
581 }
582
583 @Override
584 public SendMessageResults sendMessage(
585 Message message, Set<RecipientIdentifier> recipients
586 ) throws IOException, AttachmentInvalidException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
587 final var messageBuilder = SignalServiceDataMessage.newBuilder();
588 applyMessage(messageBuilder, message);
589 return sendMessage(messageBuilder, recipients);
590 }
591
592 private void applyMessage(
593 final SignalServiceDataMessage.Builder messageBuilder, final Message message
594 ) throws AttachmentInvalidException, IOException {
595 messageBuilder.withBody(message.getMessageText());
596 final var attachments = message.getAttachments();
597 if (attachments != null) {
598 messageBuilder.withAttachments(attachmentHelper.uploadAttachments(attachments));
599 }
600 }
601
602 @Override
603 public SendMessageResults sendRemoteDeleteMessage(
604 long targetSentTimestamp, Set<RecipientIdentifier> recipients
605 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
606 var delete = new SignalServiceDataMessage.RemoteDelete(targetSentTimestamp);
607 final var messageBuilder = SignalServiceDataMessage.newBuilder().withRemoteDelete(delete);
608 return sendMessage(messageBuilder, recipients);
609 }
610
611 @Override
612 public SendMessageResults sendMessageReaction(
613 String emoji,
614 boolean remove,
615 RecipientIdentifier.Single targetAuthor,
616 long targetSentTimestamp,
617 Set<RecipientIdentifier> recipients
618 ) throws IOException, NotAGroupMemberException, GroupNotFoundException, GroupSendingNotAllowedException {
619 var targetAuthorRecipientId = resolveRecipient(targetAuthor);
620 var reaction = new SignalServiceDataMessage.Reaction(emoji,
621 remove,
622 resolveSignalServiceAddress(targetAuthorRecipientId),
623 targetSentTimestamp);
624 final var messageBuilder = SignalServiceDataMessage.newBuilder().withReaction(reaction);
625 return sendMessage(messageBuilder, recipients);
626 }
627
628 @Override
629 public SendMessageResults sendEndSessionMessage(Set<RecipientIdentifier.Single> recipients) throws IOException {
630 var messageBuilder = SignalServiceDataMessage.newBuilder().asEndSessionMessage();
631
632 try {
633 return sendMessage(messageBuilder,
634 recipients.stream().map(RecipientIdentifier.class::cast).collect(Collectors.toSet()));
635 } catch (GroupNotFoundException | NotAGroupMemberException | GroupSendingNotAllowedException e) {
636 throw new AssertionError(e);
637 } finally {
638 for (var recipient : recipients) {
639 final var recipientId = resolveRecipient(recipient);
640 account.getSessionStore().deleteAllSessions(recipientId);
641 }
642 }
643 }
644
645 @Override
646 public void setContactName(
647 RecipientIdentifier.Single recipient, String name
648 ) throws NotMasterDeviceException, UnregisteredUserException {
649 if (!account.isMasterDevice()) {
650 throw new NotMasterDeviceException();
651 }
652 contactHelper.setContactName(resolveRecipient(recipient), name);
653 }
654
655 @Override
656 public void setContactBlocked(
657 RecipientIdentifier.Single recipient, boolean blocked
658 ) throws NotMasterDeviceException, IOException {
659 if (!account.isMasterDevice()) {
660 throw new NotMasterDeviceException();
661 }
662 contactHelper.setContactBlocked(resolveRecipient(recipient), blocked);
663 // TODO cycle our profile key
664 syncHelper.sendBlockedList();
665 }
666
667 @Override
668 public void setGroupBlocked(
669 final GroupId groupId, final boolean blocked
670 ) throws GroupNotFoundException, IOException {
671 groupHelper.setGroupBlocked(groupId, blocked);
672 // TODO cycle our profile key
673 syncHelper.sendBlockedList();
674 }
675
676 /**
677 * Change the expiration timer for a contact
678 */
679 @Override
680 public void setExpirationTimer(
681 RecipientIdentifier.Single recipient, int messageExpirationTimer
682 ) throws IOException {
683 var recipientId = resolveRecipient(recipient);
684 contactHelper.setExpirationTimer(recipientId, messageExpirationTimer);
685 final var messageBuilder = SignalServiceDataMessage.newBuilder().asExpirationUpdate();
686 try {
687 sendMessage(messageBuilder, Set.of(recipient));
688 } catch (NotAGroupMemberException | GroupNotFoundException | GroupSendingNotAllowedException e) {
689 throw new AssertionError(e);
690 }
691 }
692
693 /**
694 * Upload the sticker pack from path.
695 *
696 * @param path Path can be a path to a manifest.json file or to a zip file that contains a manifest.json file
697 * @return if successful, returns the URL to install the sticker pack in the signal app
698 */
699 @Override
700 public URI uploadStickerPack(File path) throws IOException, StickerPackInvalidException {
701 var manifest = StickerUtils.getSignalServiceStickerManifestUpload(path);
702
703 var messageSender = dependencies.getMessageSender();
704
705 var packKey = KeyUtils.createStickerUploadKey();
706 var packIdString = messageSender.uploadStickerManifest(manifest, packKey);
707 var packId = StickerPackId.deserialize(Hex.fromStringCondensed(packIdString));
708
709 var sticker = new Sticker(packId, packKey);
710 account.getStickerStore().updateSticker(sticker);
711
712 try {
713 return new URI("https",
714 "signal.art",
715 "/addstickers/",
716 "pack_id="
717 + URLEncoder.encode(Hex.toStringCondensed(packId.serialize()), StandardCharsets.UTF_8)
718 + "&pack_key="
719 + URLEncoder.encode(Hex.toStringCondensed(packKey), StandardCharsets.UTF_8));
720 } catch (URISyntaxException e) {
721 throw new AssertionError(e);
722 }
723 }
724
725 @Override
726 public void requestAllSyncData() throws IOException {
727 syncHelper.requestAllSyncData();
728 retrieveRemoteStorage();
729 }
730
731 void retrieveRemoteStorage() throws IOException {
732 if (account.getStorageKey() != null) {
733 storageHelper.readDataFromStorage();
734 }
735 }
736
737 private byte[] getSenderCertificate() {
738 byte[] certificate;
739 try {
740 if (account.isPhoneNumberShared()) {
741 certificate = dependencies.getAccountManager().getSenderCertificate();
742 } else {
743 certificate = dependencies.getAccountManager().getSenderCertificateForPhoneNumberPrivacy();
744 }
745 } catch (IOException e) {
746 logger.warn("Failed to get sender certificate, ignoring: {}", e.getMessage());
747 return null;
748 }
749 // TODO cache for a day
750 return certificate;
751 }
752
753 private RecipientId refreshRegisteredUser(RecipientId recipientId) throws IOException {
754 final var address = resolveSignalServiceAddress(recipientId);
755 if (!address.getNumber().isPresent()) {
756 return recipientId;
757 }
758 final var number = address.getNumber().get();
759 final var uuid = getRegisteredUser(number);
760 return resolveRecipientTrusted(new SignalServiceAddress(uuid, number));
761 }
762
763 private UUID getRegisteredUser(final String number) throws IOException {
764 final Map<String, UUID> uuidMap;
765 try {
766 uuidMap = getRegisteredUsers(Set.of(number));
767 } catch (NumberFormatException e) {
768 throw new UnregisteredUserException(number, e);
769 }
770 final var uuid = uuidMap.get(number);
771 if (uuid == null) {
772 throw new UnregisteredUserException(number, null);
773 }
774 return uuid;
775 }
776
777 private Map<String, UUID> getRegisteredUsers(final Set<String> numbers) throws IOException {
778 final Map<String, UUID> registeredUsers;
779 try {
780 registeredUsers = dependencies.getAccountManager()
781 .getRegisteredUsers(ServiceConfig.getIasKeyStore(),
782 numbers,
783 serviceEnvironmentConfig.getCdsMrenclave());
784 } catch (Quote.InvalidQuoteFormatException | UnauthenticatedQuoteException | SignatureException | UnauthenticatedResponseException | InvalidKeyException e) {
785 throw new IOException(e);
786 }
787
788 // Store numbers as recipients so we have the number/uuid association
789 registeredUsers.forEach((number, uuid) -> resolveRecipientTrusted(new SignalServiceAddress(uuid, number)));
790
791 return registeredUsers;
792 }
793
794 private void retryFailedReceivedMessages(ReceiveMessageHandler handler, boolean ignoreAttachments) {
795 Set<HandleAction> queuedActions = new HashSet<>();
796 for (var cachedMessage : account.getMessageCache().getCachedMessages()) {
797 var actions = retryFailedReceivedMessage(handler, ignoreAttachments, cachedMessage);
798 if (actions != null) {
799 queuedActions.addAll(actions);
800 }
801 }
802 handleQueuedActions(queuedActions);
803 }
804
805 private List<HandleAction> retryFailedReceivedMessage(
806 final ReceiveMessageHandler handler, final boolean ignoreAttachments, final CachedMessage cachedMessage
807 ) {
808 var envelope = cachedMessage.loadEnvelope();
809 if (envelope == null) {
810 cachedMessage.delete();
811 return null;
812 }
813
814 final var result = incomingMessageHandler.handleRetryEnvelope(envelope, ignoreAttachments, handler);
815 final var actions = result.first();
816 final var exception = result.second();
817
818 if (exception instanceof UntrustedIdentityException) {
819 if (System.currentTimeMillis() - envelope.getServerDeliveredTimestamp() > 1000L * 60 * 60 * 24 * 30) {
820 // Envelope is more than a month old, cleaning up.
821 cachedMessage.delete();
822 return null;
823 }
824 if (!envelope.hasSourceUuid()) {
825 final var identifier = ((UntrustedIdentityException) exception).getSender();
826 final var recipientId = account.getRecipientStore().resolveRecipient(identifier);
827 try {
828 account.getMessageCache().replaceSender(cachedMessage, recipientId);
829 } catch (IOException ioException) {
830 logger.warn("Failed to move cached message to recipient folder: {}", ioException.getMessage());
831 }
832 }
833 return null;
834 }
835
836 // If successful and for all other errors that are not recoverable, delete the cached message
837 cachedMessage.delete();
838 return actions;
839 }
840
841 @Override
842 public void receiveMessages(
843 long timeout,
844 TimeUnit unit,
845 boolean returnOnTimeout,
846 boolean ignoreAttachments,
847 ReceiveMessageHandler handler
848 ) throws IOException {
849 retryFailedReceivedMessages(handler, ignoreAttachments);
850
851 Set<HandleAction> queuedActions = new HashSet<>();
852
853 final var signalWebSocket = dependencies.getSignalWebSocket();
854 signalWebSocket.connect();
855
856 hasCaughtUpWithOldMessages = false;
857
858 while (!Thread.interrupted()) {
859 SignalServiceEnvelope envelope;
860 final CachedMessage[] cachedMessage = {null};
861 account.setLastReceiveTimestamp(System.currentTimeMillis());
862 logger.debug("Checking for new message from server");
863 try {
864 var result = signalWebSocket.readOrEmpty(unit.toMillis(timeout), envelope1 -> {
865 final var recipientId = envelope1.hasSourceUuid()
866 ? resolveRecipient(envelope1.getSourceAddress())
867 : null;
868 // store message on disk, before acknowledging receipt to the server
869 cachedMessage[0] = account.getMessageCache().cacheMessage(envelope1, recipientId);
870 });
871 if (result.isPresent()) {
872 envelope = result.get();
873 logger.debug("New message received from server");
874 } else {
875 logger.debug("Received indicator that server queue is empty");
876 handleQueuedActions(queuedActions);
877 queuedActions.clear();
878
879 hasCaughtUpWithOldMessages = true;
880 synchronized (this) {
881 this.notifyAll();
882 }
883
884 // Continue to wait another timeout for new messages
885 continue;
886 }
887 } catch (AssertionError e) {
888 if (e.getCause() instanceof InterruptedException) {
889 Thread.currentThread().interrupt();
890 break;
891 } else {
892 throw e;
893 }
894 } catch (WebSocketUnavailableException e) {
895 logger.debug("Pipe unexpectedly unavailable, connecting");
896 signalWebSocket.connect();
897 continue;
898 } catch (TimeoutException e) {
899 if (returnOnTimeout) return;
900 continue;
901 }
902
903 final var result = incomingMessageHandler.handleEnvelope(envelope, ignoreAttachments, handler);
904 queuedActions.addAll(result.first());
905 final var exception = result.second();
906
907 if (hasCaughtUpWithOldMessages) {
908 handleQueuedActions(queuedActions);
909 }
910 if (cachedMessage[0] != null) {
911 if (exception instanceof UntrustedIdentityException) {
912 final var address = ((UntrustedIdentityException) exception).getSender();
913 final var recipientId = resolveRecipient(address);
914 if (!envelope.hasSourceUuid()) {
915 try {
916 cachedMessage[0] = account.getMessageCache().replaceSender(cachedMessage[0], recipientId);
917 } catch (IOException ioException) {
918 logger.warn("Failed to move cached message to recipient folder: {}",
919 ioException.getMessage());
920 }
921 }
922 } else {
923 cachedMessage[0].delete();
924 }
925 }
926 }
927 handleQueuedActions(queuedActions);
928 }
929
930 @Override
931 public boolean hasCaughtUpWithOldMessages() {
932 return hasCaughtUpWithOldMessages;
933 }
934
935 private void handleQueuedActions(final Collection<HandleAction> queuedActions) {
936 var interrupted = false;
937 for (var action : queuedActions) {
938 try {
939 action.execute(context);
940 } catch (Throwable e) {
941 if ((e instanceof AssertionError || e instanceof RuntimeException)
942 && e.getCause() instanceof InterruptedException) {
943 interrupted = true;
944 continue;
945 }
946 logger.warn("Message action failed.", e);
947 }
948 }
949 if (interrupted) {
950 Thread.currentThread().interrupt();
951 }
952 }
953
954 @Override
955 public boolean isContactBlocked(final RecipientIdentifier.Single recipient) {
956 final RecipientId recipientId;
957 try {
958 recipientId = resolveRecipient(recipient);
959 } catch (UnregisteredUserException e) {
960 return false;
961 }
962 return contactHelper.isContactBlocked(recipientId);
963 }
964
965 @Override
966 public File getAttachmentFile(SignalServiceAttachmentRemoteId attachmentId) {
967 return attachmentHelper.getAttachmentFile(attachmentId);
968 }
969
970 @Override
971 public void sendContacts() throws IOException {
972 syncHelper.sendContacts();
973 }
974
975 @Override
976 public List<Pair<RecipientId, Contact>> getContacts() {
977 return account.getContactStore().getContacts();
978 }
979
980 @Override
981 public String getContactOrProfileName(RecipientIdentifier.Single recipientIdentifier) {
982 final RecipientId recipientId;
983 try {
984 recipientId = resolveRecipient(recipientIdentifier);
985 } catch (UnregisteredUserException e) {
986 return null;
987 }
988
989 final var contact = account.getContactStore().getContact(recipientId);
990 if (contact != null && !Util.isEmpty(contact.getName())) {
991 return contact.getName();
992 }
993
994 final var profile = getRecipientProfile(recipientId);
995 if (profile != null) {
996 return profile.getDisplayName();
997 }
998
999 return null;
1000 }
1001
1002 @Override
1003 public GroupInfo getGroup(GroupId groupId) {
1004 return groupHelper.getGroup(groupId);
1005 }
1006
1007 @Override
1008 public List<IdentityInfo> getIdentities() {
1009 return account.getIdentityKeyStore().getIdentities();
1010 }
1011
1012 @Override
1013 public List<IdentityInfo> getIdentities(RecipientIdentifier.Single recipient) {
1014 IdentityInfo identity;
1015 try {
1016 identity = account.getIdentityKeyStore().getIdentity(resolveRecipient(recipient));
1017 } catch (UnregisteredUserException e) {
1018 identity = null;
1019 }
1020 return identity == null ? List.of() : List.of(identity);
1021 }
1022
1023 /**
1024 * Trust this the identity with this fingerprint
1025 *
1026 * @param recipient username of the identity
1027 * @param fingerprint Fingerprint
1028 */
1029 @Override
1030 public boolean trustIdentityVerified(RecipientIdentifier.Single recipient, byte[] fingerprint) {
1031 RecipientId recipientId;
1032 try {
1033 recipientId = resolveRecipient(recipient);
1034 } catch (UnregisteredUserException e) {
1035 return false;
1036 }
1037 return trustIdentity(recipientId,
1038 identityKey -> Arrays.equals(identityKey.serialize(), fingerprint),
1039 TrustLevel.TRUSTED_VERIFIED);
1040 }
1041
1042 /**
1043 * Trust this the identity with this safety number
1044 *
1045 * @param recipient username of the identity
1046 * @param safetyNumber Safety number
1047 */
1048 @Override
1049 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, String safetyNumber) {
1050 RecipientId recipientId;
1051 try {
1052 recipientId = resolveRecipient(recipient);
1053 } catch (UnregisteredUserException e) {
1054 return false;
1055 }
1056 var address = resolveSignalServiceAddress(recipientId);
1057 return trustIdentity(recipientId,
1058 identityKey -> safetyNumber.equals(computeSafetyNumber(address, identityKey)),
1059 TrustLevel.TRUSTED_VERIFIED);
1060 }
1061
1062 /**
1063 * Trust this the identity with this scannable safety number
1064 *
1065 * @param recipient username of the identity
1066 * @param safetyNumber Scannable safety number
1067 */
1068 @Override
1069 public boolean trustIdentityVerifiedSafetyNumber(RecipientIdentifier.Single recipient, byte[] safetyNumber) {
1070 RecipientId recipientId;
1071 try {
1072 recipientId = resolveRecipient(recipient);
1073 } catch (UnregisteredUserException e) {
1074 return false;
1075 }
1076 var address = resolveSignalServiceAddress(recipientId);
1077 return trustIdentity(recipientId, identityKey -> {
1078 final var fingerprint = computeSafetyNumberFingerprint(address, identityKey);
1079 try {
1080 return fingerprint != null && fingerprint.getScannableFingerprint().compareTo(safetyNumber);
1081 } catch (FingerprintVersionMismatchException | FingerprintParsingException e) {
1082 return false;
1083 }
1084 }, TrustLevel.TRUSTED_VERIFIED);
1085 }
1086
1087 /**
1088 * Trust all keys of this identity without verification
1089 *
1090 * @param recipient username of the identity
1091 */
1092 @Override
1093 public boolean trustIdentityAllKeys(RecipientIdentifier.Single recipient) {
1094 RecipientId recipientId;
1095 try {
1096 recipientId = resolveRecipient(recipient);
1097 } catch (UnregisteredUserException e) {
1098 return false;
1099 }
1100 return trustIdentity(recipientId, identityKey -> true, TrustLevel.TRUSTED_UNVERIFIED);
1101 }
1102
1103 private boolean trustIdentity(
1104 RecipientId recipientId, Function<IdentityKey, Boolean> verifier, TrustLevel trustLevel
1105 ) {
1106 var identity = account.getIdentityKeyStore().getIdentity(recipientId);
1107 if (identity == null) {
1108 return false;
1109 }
1110
1111 if (!verifier.apply(identity.getIdentityKey())) {
1112 return false;
1113 }
1114
1115 account.getIdentityKeyStore().setIdentityTrustLevel(recipientId, identity.getIdentityKey(), trustLevel);
1116 try {
1117 var address = resolveSignalServiceAddress(recipientId);
1118 syncHelper.sendVerifiedMessage(address, identity.getIdentityKey(), trustLevel);
1119 } catch (IOException e) {
1120 logger.warn("Failed to send verification sync message: {}", e.getMessage());
1121 }
1122
1123 return true;
1124 }
1125
1126 private void handleIdentityFailure(
1127 final RecipientId recipientId, final SendMessageResult.IdentityFailure identityFailure
1128 ) {
1129 final var identityKey = identityFailure.getIdentityKey();
1130 if (identityKey != null) {
1131 final var newIdentity = account.getIdentityKeyStore().saveIdentity(recipientId, identityKey, new Date());
1132 if (newIdentity) {
1133 account.getSessionStore().archiveSessions(recipientId);
1134 }
1135 } else {
1136 // Retrieve profile to get the current identity key from the server
1137 profileHelper.refreshRecipientProfile(recipientId);
1138 }
1139 }
1140
1141 @Override
1142 public String computeSafetyNumber(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
1143 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
1144 return fingerprint == null ? null : fingerprint.getDisplayableFingerprint().getDisplayText();
1145 }
1146
1147 @Override
1148 public byte[] computeSafetyNumberForScanning(SignalServiceAddress theirAddress, IdentityKey theirIdentityKey) {
1149 final Fingerprint fingerprint = computeSafetyNumberFingerprint(theirAddress, theirIdentityKey);
1150 return fingerprint == null ? null : fingerprint.getScannableFingerprint().getSerialized();
1151 }
1152
1153 private Fingerprint computeSafetyNumberFingerprint(
1154 final SignalServiceAddress theirAddress, final IdentityKey theirIdentityKey
1155 ) {
1156 return Utils.computeSafetyNumber(capabilities.isUuid(),
1157 account.getSelfAddress(),
1158 account.getIdentityKeyPair().getPublicKey(),
1159 theirAddress,
1160 theirIdentityKey);
1161 }
1162
1163 @Override
1164 public SignalServiceAddress resolveSignalServiceAddress(SignalServiceAddress address) {
1165 return resolveSignalServiceAddress(resolveRecipient(address));
1166 }
1167
1168 @Override
1169 public SignalServiceAddress resolveSignalServiceAddress(UUID uuid) {
1170 return resolveSignalServiceAddress(account.getRecipientStore().resolveRecipient(uuid));
1171 }
1172
1173 @Override
1174 public SignalServiceAddress resolveSignalServiceAddress(RecipientId recipientId) {
1175 final var address = account.getRecipientStore().resolveRecipientAddress(recipientId);
1176 if (address.getUuid().isPresent()) {
1177 return address.toSignalServiceAddress();
1178 }
1179
1180 // Address in recipient store doesn't have a uuid, this shouldn't happen
1181 // Try to retrieve the uuid from the server
1182 final var number = address.getNumber().get();
1183 try {
1184 return resolveSignalServiceAddress(getRegisteredUser(number));
1185 } catch (IOException e) {
1186 logger.warn("Failed to get uuid for e164 number: {}", number, e);
1187 // Return SignalServiceAddress with unknown UUID
1188 return address.toSignalServiceAddress();
1189 }
1190 }
1191
1192 private Set<RecipientId> resolveRecipients(Collection<RecipientIdentifier.Single> recipients) throws UnregisteredUserException {
1193 final var recipientIds = new HashSet<RecipientId>(recipients.size());
1194 for (var number : recipients) {
1195 final var recipientId = resolveRecipient(number);
1196 recipientIds.add(recipientId);
1197 }
1198 return recipientIds;
1199 }
1200
1201 private RecipientId resolveRecipient(final RecipientIdentifier.Single recipient) throws UnregisteredUserException {
1202 if (recipient instanceof RecipientIdentifier.Uuid) {
1203 return account.getRecipientStore().resolveRecipient(((RecipientIdentifier.Uuid) recipient).uuid);
1204 } else {
1205 final var number = ((RecipientIdentifier.Number) recipient).number;
1206 return account.getRecipientStore().resolveRecipient(number, () -> {
1207 try {
1208 return getRegisteredUser(number);
1209 } catch (IOException e) {
1210 return null;
1211 }
1212 });
1213 }
1214 }
1215
1216 private RecipientId resolveRecipient(SignalServiceAddress address) {
1217 return account.getRecipientStore().resolveRecipient(address);
1218 }
1219
1220 private RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
1221 return account.getRecipientStore().resolveRecipientTrusted(address);
1222 }
1223
1224 @Override
1225 public void close() throws IOException {
1226 close(true);
1227 }
1228
1229 private void close(boolean closeAccount) throws IOException {
1230 executor.shutdown();
1231
1232 dependencies.getSignalWebSocket().disconnect();
1233
1234 if (closeAccount && account != null) {
1235 account.close();
1236 }
1237 account = null;
1238 }
1239
1240 }