]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/IncomingMessageHandler.java
Extend logging
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / helper / IncomingMessageHandler.java
1 package org.asamk.signal.manager.helper;
2
3 import org.asamk.signal.manager.Manager;
4 import org.asamk.signal.manager.actions.HandleAction;
5 import org.asamk.signal.manager.actions.RefreshPreKeysAction;
6 import org.asamk.signal.manager.actions.RenewSessionAction;
7 import org.asamk.signal.manager.actions.ResendMessageAction;
8 import org.asamk.signal.manager.actions.RetrieveProfileAction;
9 import org.asamk.signal.manager.actions.RetrieveStorageDataAction;
10 import org.asamk.signal.manager.actions.SendGroupInfoAction;
11 import org.asamk.signal.manager.actions.SendGroupInfoRequestAction;
12 import org.asamk.signal.manager.actions.SendProfileKeyAction;
13 import org.asamk.signal.manager.actions.SendReceiptAction;
14 import org.asamk.signal.manager.actions.SendRetryMessageRequestAction;
15 import org.asamk.signal.manager.actions.SendSyncBlockedListAction;
16 import org.asamk.signal.manager.actions.SendSyncConfigurationAction;
17 import org.asamk.signal.manager.actions.SendSyncContactsAction;
18 import org.asamk.signal.manager.actions.SendSyncGroupsAction;
19 import org.asamk.signal.manager.actions.SendSyncKeysAction;
20 import org.asamk.signal.manager.actions.UpdateAccountAttributesAction;
21 import org.asamk.signal.manager.api.GroupId;
22 import org.asamk.signal.manager.api.GroupNotFoundException;
23 import org.asamk.signal.manager.api.MessageEnvelope;
24 import org.asamk.signal.manager.api.Pair;
25 import org.asamk.signal.manager.api.Profile;
26 import org.asamk.signal.manager.api.ReceiveConfig;
27 import org.asamk.signal.manager.api.StickerPackId;
28 import org.asamk.signal.manager.api.TrustLevel;
29 import org.asamk.signal.manager.api.UntrustedIdentityException;
30 import org.asamk.signal.manager.groups.GroupUtils;
31 import org.asamk.signal.manager.internal.SignalDependencies;
32 import org.asamk.signal.manager.jobs.RetrieveStickerPackJob;
33 import org.asamk.signal.manager.storage.SignalAccount;
34 import org.asamk.signal.manager.storage.groups.GroupInfoV1;
35 import org.asamk.signal.manager.storage.recipients.RecipientId;
36 import org.asamk.signal.manager.storage.stickers.StickerPack;
37 import org.signal.libsignal.metadata.ProtocolInvalidKeyException;
38 import org.signal.libsignal.metadata.ProtocolInvalidKeyIdException;
39 import org.signal.libsignal.metadata.ProtocolInvalidMessageException;
40 import org.signal.libsignal.metadata.ProtocolNoSessionException;
41 import org.signal.libsignal.metadata.ProtocolUntrustedIdentityException;
42 import org.signal.libsignal.metadata.SelfSendException;
43 import org.signal.libsignal.protocol.IdentityKeyPair;
44 import org.signal.libsignal.protocol.InvalidMessageException;
45 import org.signal.libsignal.protocol.groups.GroupSessionBuilder;
46 import org.signal.libsignal.protocol.message.DecryptionErrorMessage;
47 import org.signal.libsignal.protocol.state.KyberPreKeyRecord;
48 import org.signal.libsignal.protocol.state.SignedPreKeyRecord;
49 import org.signal.libsignal.zkgroup.InvalidInputException;
50 import org.signal.libsignal.zkgroup.profiles.ProfileKey;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.whispersystems.signalservice.api.InvalidMessageStructureException;
54 import org.whispersystems.signalservice.api.crypto.SignalGroupSessionBuilder;
55 import org.whispersystems.signalservice.api.crypto.SignalServiceCipherResult;
56 import org.whispersystems.signalservice.api.messages.EnvelopeContentValidator;
57 import org.whispersystems.signalservice.api.messages.SignalServiceContent;
58 import org.whispersystems.signalservice.api.messages.SignalServiceDataMessage;
59 import org.whispersystems.signalservice.api.messages.SignalServiceEnvelope;
60 import org.whispersystems.signalservice.api.messages.SignalServiceGroup;
61 import org.whispersystems.signalservice.api.messages.SignalServiceGroupContext;
62 import org.whispersystems.signalservice.api.messages.SignalServiceGroupV2;
63 import org.whispersystems.signalservice.api.messages.SignalServiceMetadata;
64 import org.whispersystems.signalservice.api.messages.SignalServicePniSignatureMessage;
65 import org.whispersystems.signalservice.api.messages.SignalServiceReceiptMessage;
66 import org.whispersystems.signalservice.api.messages.SignalServiceStoryMessage;
67 import org.whispersystems.signalservice.api.messages.multidevice.SignalServiceSyncMessage;
68 import org.whispersystems.signalservice.api.messages.multidevice.StickerPackOperationMessage;
69 import org.whispersystems.signalservice.api.push.ServiceId;
70 import org.whispersystems.signalservice.api.push.ServiceId.ACI;
71 import org.whispersystems.signalservice.api.push.ServiceId.PNI;
72 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
73 import org.whispersystems.signalservice.internal.push.SignalServiceProtos;
74 import org.whispersystems.signalservice.internal.push.UnsupportedDataMessageException;
75 import org.whispersystems.signalservice.internal.serialize.SignalServiceAddressProtobufSerializer;
76 import org.whispersystems.signalservice.internal.serialize.SignalServiceMetadataProtobufSerializer;
77 import org.whispersystems.signalservice.internal.serialize.protos.SignalServiceContentProto;
78
79 import java.util.ArrayList;
80 import java.util.List;
81 import java.util.Optional;
82 import java.util.stream.Collectors;
83
84 public final class IncomingMessageHandler {
85
86 private final static Logger logger = LoggerFactory.getLogger(IncomingMessageHandler.class);
87
88 private final SignalAccount account;
89 private final SignalDependencies dependencies;
90 private final Context context;
91
92 public IncomingMessageHandler(final Context context) {
93 this.account = context.getAccount();
94 this.dependencies = context.getDependencies();
95 this.context = context;
96 }
97
98 public Pair<List<HandleAction>, Exception> handleRetryEnvelope(
99 final SignalServiceEnvelope envelope,
100 final ReceiveConfig receiveConfig,
101 final Manager.ReceiveMessageHandler handler
102 ) {
103 final List<HandleAction> actions = new ArrayList<>();
104 if (envelope.isPreKeySignalMessage()) {
105 actions.add(RefreshPreKeysAction.create());
106 }
107
108 SignalServiceContent content = null;
109 if (!envelope.isReceipt()) {
110 account.getIdentityKeyStore().setRetryingDecryption(true);
111 try {
112 final var cipherResult = dependencies.getCipher()
113 .decrypt(envelope.getProto(), envelope.getServerDeliveredTimestamp());
114 content = validate(envelope.getProto(), cipherResult, envelope.getServerDeliveredTimestamp());
115 if (content == null) {
116 return new Pair<>(List.of(), null);
117 }
118 } catch (ProtocolUntrustedIdentityException e) {
119 final var recipientId = account.getRecipientResolver().resolveRecipient(e.getSender());
120 final var exception = new UntrustedIdentityException(account.getRecipientAddressResolver()
121 .resolveRecipientAddress(recipientId)
122 .toApiRecipientAddress(), e.getSenderDevice());
123 return new Pair<>(List.of(), exception);
124 } catch (Exception e) {
125 return new Pair<>(List.of(), e);
126 } finally {
127 account.getIdentityKeyStore().setRetryingDecryption(false);
128 }
129 }
130 actions.addAll(checkAndHandleMessage(envelope, content, receiveConfig, handler, null));
131 return new Pair<>(actions, null);
132 }
133
134 public Pair<List<HandleAction>, Exception> handleEnvelope(
135 final SignalServiceEnvelope envelope,
136 final ReceiveConfig receiveConfig,
137 final Manager.ReceiveMessageHandler handler
138 ) {
139 final var actions = new ArrayList<HandleAction>();
140 if (envelope.hasSourceServiceId()) {
141 // Store uuid if we don't have it already
142 // uuid in envelope is sent by server
143 account.getRecipientTrustedResolver().resolveRecipientTrusted(envelope.getSourceAddress());
144 }
145 SignalServiceContent content = null;
146 Exception exception = null;
147 if (!envelope.isReceipt()) {
148 try {
149 final var cipherResult = dependencies.getCipher()
150 .decrypt(envelope.getProto(), envelope.getServerDeliveredTimestamp());
151 content = validate(envelope.getProto(), cipherResult, envelope.getServerDeliveredTimestamp());
152 if (content == null) {
153 return new Pair<>(List.of(), null);
154 }
155 } catch (ProtocolUntrustedIdentityException e) {
156 final var recipientId = account.getRecipientResolver().resolveRecipient(e.getSender());
157 actions.add(new RetrieveProfileAction(recipientId));
158 exception = new UntrustedIdentityException(account.getRecipientAddressResolver()
159 .resolveRecipientAddress(recipientId)
160 .toApiRecipientAddress(), e.getSenderDevice());
161 } catch (ProtocolInvalidKeyIdException | ProtocolInvalidKeyException | ProtocolNoSessionException |
162 ProtocolInvalidMessageException e) {
163 logger.debug("Failed to decrypt incoming message", e);
164 final var sender = account.getRecipientResolver().resolveRecipient(e.getSender());
165 if (context.getContactHelper().isContactBlocked(sender)) {
166 logger.debug("Received invalid message from blocked contact, ignoring.");
167 } else {
168 final var senderProfile = context.getProfileHelper().getRecipientProfile(sender);
169 final var selfProfile = context.getProfileHelper().getSelfProfile();
170 var serviceId = ServiceId.parseOrNull(e.getSender());
171 if (serviceId == null) {
172 // Workaround for libsignal-client issue #492
173 serviceId = account.getRecipientAddressResolver()
174 .resolveRecipientAddress(sender)
175 .serviceId()
176 .orElse(null);
177 }
178 if (serviceId != null) {
179 final var isSelf = sender.equals(account.getSelfRecipientId())
180 && e.getSenderDevice() == account.getDeviceId();
181 final var isSenderSenderKeyCapable = senderProfile != null && senderProfile.getCapabilities()
182 .contains(Profile.Capability.senderKey);
183 final var isSelfSenderKeyCapable = selfProfile != null && selfProfile.getCapabilities()
184 .contains(Profile.Capability.senderKey);
185 final var destination = getDestination(envelope).serviceId();
186 if (!isSelf && isSenderSenderKeyCapable && isSelfSenderKeyCapable) {
187 logger.debug("Received invalid message, requesting message resend.");
188 actions.add(new SendRetryMessageRequestAction(sender, serviceId, e, envelope, destination));
189 } else {
190 logger.debug("Received invalid message, queuing renew session action.");
191 actions.add(new RenewSessionAction(sender, serviceId, destination));
192 }
193 } else {
194 logger.debug("Received invalid message from invalid sender: {}", e.getSender());
195 }
196 }
197 exception = e;
198 } catch (SelfSendException e) {
199 logger.debug("Dropping unidentified message from self.");
200 return new Pair<>(List.of(), null);
201 } catch (Exception e) {
202 logger.debug("Failed to handle incoming message", e);
203 exception = e;
204 }
205 }
206
207 actions.addAll(checkAndHandleMessage(envelope, content, receiveConfig, handler, exception));
208 return new Pair<>(actions, exception);
209 }
210
211 private SignalServiceContent validate(
212 SignalServiceProtos.Envelope envelope, SignalServiceCipherResult cipherResult, long serverDeliveredTimestamp
213 ) throws ProtocolInvalidKeyException, ProtocolInvalidMessageException, UnsupportedDataMessageException, InvalidMessageStructureException {
214 final var content = cipherResult.getContent();
215 final var envelopeMetadata = cipherResult.getMetadata();
216 final var validationResult = EnvelopeContentValidator.INSTANCE.validate(envelope, content);
217
218 if (validationResult instanceof EnvelopeContentValidator.Result.Invalid v) {
219 logger.warn("Invalid content! {}", v.getReason(), v.getThrowable());
220 return null;
221 }
222
223 if (validationResult instanceof EnvelopeContentValidator.Result.UnsupportedDataMessage v) {
224 logger.warn("Unsupported DataMessage! Our version: {}, their version: {}",
225 v.getOurVersion(),
226 v.getTheirVersion());
227 return null;
228 }
229
230 final var localAddress = new SignalServiceAddress(envelopeMetadata.getDestinationServiceId(),
231 Optional.ofNullable(account.getNumber()));
232 final var metadata = new SignalServiceMetadata(new SignalServiceAddress(envelopeMetadata.getSourceServiceId(),
233 Optional.ofNullable(envelopeMetadata.getSourceE164())),
234 envelopeMetadata.getSourceDeviceId(),
235 envelope.getTimestamp(),
236 envelope.getServerTimestamp(),
237 serverDeliveredTimestamp,
238 envelopeMetadata.getSealedSender(),
239 envelope.getServerGuid(),
240 Optional.ofNullable(envelopeMetadata.getGroupId()),
241 envelopeMetadata.getDestinationServiceId().toString());
242
243 final var contentProto = SignalServiceContentProto.newBuilder()
244 .setLocalAddress(SignalServiceAddressProtobufSerializer.toProtobuf(localAddress))
245 .setMetadata(SignalServiceMetadataProtobufSerializer.toProtobuf(metadata))
246 .setContent(content)
247 .build();
248
249 return SignalServiceContent.createFromProto(contentProto);
250 }
251
252 private List<HandleAction> checkAndHandleMessage(
253 final SignalServiceEnvelope envelope,
254 final SignalServiceContent content,
255 final ReceiveConfig receiveConfig,
256 final Manager.ReceiveMessageHandler handler,
257 final Exception exception
258 ) {
259 if (content != null) {
260 // Store uuid if we don't have it already
261 // address/uuid is validated by unidentified sender certificate
262
263 boolean handledPniSignature = false;
264 if (content.getPniSignatureMessage().isPresent()) {
265 final var message = content.getPniSignatureMessage().get();
266 final var senderAddress = getSenderAddress(envelope, content);
267 if (senderAddress != null) {
268 handledPniSignature = handlePniSignatureMessage(message, senderAddress);
269 }
270 }
271 if (!handledPniSignature) {
272 account.getRecipientTrustedResolver().resolveRecipientTrusted(content.getSender());
273 }
274 }
275 if (envelope.isReceipt()) {
276 final var senderDeviceAddress = getSender(envelope, content);
277 final var sender = senderDeviceAddress.serviceId();
278 final var senderDeviceId = senderDeviceAddress.deviceId();
279 account.getMessageSendLogStore().deleteEntryForRecipient(envelope.getTimestamp(), sender, senderDeviceId);
280 }
281
282 var notAllowedToSendToGroup = isNotAllowedToSendToGroup(envelope, content);
283 final var groupContext = getGroupContext(content);
284 if (groupContext != null && groupContext.getGroupV2().isPresent()) {
285 handleGroupV2Context(groupContext.getGroupV2().get());
286 }
287 // Check again in case the user just joined the group
288 notAllowedToSendToGroup = notAllowedToSendToGroup && isNotAllowedToSendToGroup(envelope, content);
289
290 if (isMessageBlocked(envelope, content)) {
291 logger.info("Ignoring a message from blocked user/group: {}", envelope.getTimestamp());
292 return List.of();
293 } else if (notAllowedToSendToGroup) {
294 final var senderAddress = getSenderAddress(envelope, content);
295 logger.info("Ignoring a group message from an unauthorized sender (no member or admin): {} {}",
296 senderAddress == null ? null : senderAddress.getIdentifier(),
297 envelope.getTimestamp());
298 return List.of();
299 } else {
300 List<HandleAction> actions;
301 if (content != null) {
302 actions = handleMessage(envelope, content, receiveConfig);
303 } else {
304 actions = List.of();
305 }
306 handler.handleMessage(MessageEnvelope.from(envelope,
307 content,
308 account.getRecipientResolver(),
309 account.getRecipientAddressResolver(),
310 context.getAttachmentHelper()::getAttachmentFile,
311 exception), exception);
312 return actions;
313 }
314 }
315
316 public List<HandleAction> handleMessage(
317 SignalServiceEnvelope envelope, SignalServiceContent content, ReceiveConfig receiveConfig
318 ) {
319 var actions = new ArrayList<HandleAction>();
320 final var senderDeviceAddress = getSender(envelope, content);
321 final var sender = senderDeviceAddress.recipientId();
322 final var senderServiceId = senderDeviceAddress.serviceId();
323 final var senderDeviceId = senderDeviceAddress.deviceId();
324 final var destination = getDestination(envelope);
325
326 if (content.getReceiptMessage().isPresent()) {
327 final var message = content.getReceiptMessage().get();
328 if (message.isDeliveryReceipt()) {
329 account.getMessageSendLogStore()
330 .deleteEntriesForRecipient(message.getTimestamps(), senderServiceId, senderDeviceId);
331 }
332 }
333
334 if (content.getSenderKeyDistributionMessage().isPresent()) {
335 final var message = content.getSenderKeyDistributionMessage().get();
336 final var protocolAddress = senderServiceId.toProtocolAddress(senderDeviceId);
337 logger.debug("Received a sender key distribution message for distributionId {} from {}",
338 message.getDistributionId(),
339 protocolAddress);
340 new SignalGroupSessionBuilder(dependencies.getSessionLock(),
341 new GroupSessionBuilder(account.getSenderKeyStore())).process(protocolAddress, message);
342 }
343
344 if (content.getDecryptionErrorMessage().isPresent()) {
345 var message = content.getDecryptionErrorMessage().get();
346 logger.debug("Received a decryption error message from {}.{} (resend request for {})",
347 sender,
348 senderDeviceId,
349 message.getTimestamp());
350 if (message.getDeviceId() == account.getDeviceId()) {
351 handleDecryptionErrorMessage(actions,
352 sender,
353 senderServiceId,
354 senderDeviceId,
355 message,
356 destination.serviceId());
357 } else {
358 logger.debug("Request is for another one of our devices");
359 }
360 }
361
362 if (content.getDataMessage().isPresent()) {
363 var message = content.getDataMessage().get();
364
365 if (content.isNeedsReceipt()) {
366 actions.add(new SendReceiptAction(sender,
367 SignalServiceReceiptMessage.Type.DELIVERY,
368 message.getTimestamp()));
369 } else {
370 // Message wasn't sent as unidentified sender message
371 final var contact = context.getAccount().getContactStore().getContact(sender);
372 if (account.isPrimaryDevice()
373 && contact != null
374 && !contact.isBlocked()
375 && contact.isProfileSharingEnabled()) {
376 actions.add(UpdateAccountAttributesAction.create());
377 actions.add(new SendProfileKeyAction(sender));
378 }
379 }
380 if (receiveConfig.sendReadReceipts()) {
381 actions.add(new SendReceiptAction(sender,
382 SignalServiceReceiptMessage.Type.READ,
383 message.getTimestamp()));
384 }
385
386 actions.addAll(handleSignalServiceDataMessage(message,
387 false,
388 senderDeviceAddress,
389 destination,
390 receiveConfig.ignoreAttachments()));
391 }
392
393 if (content.getStoryMessage().isPresent()) {
394 final var message = content.getStoryMessage().get();
395 actions.addAll(handleSignalServiceStoryMessage(message, sender, receiveConfig.ignoreAttachments()));
396 }
397
398 if (content.getSyncMessage().isPresent()) {
399 var syncMessage = content.getSyncMessage().get();
400 actions.addAll(handleSyncMessage(envelope,
401 syncMessage,
402 senderDeviceAddress,
403 receiveConfig.ignoreAttachments()));
404 }
405
406 return actions;
407 }
408
409 private boolean handlePniSignatureMessage(
410 final SignalServicePniSignatureMessage message, final SignalServiceAddress senderAddress
411 ) {
412 final var aci = senderAddress.getServiceId();
413 final var aciIdentity = account.getIdentityKeyStore().getIdentityInfo(aci);
414 final var pni = message.getPni();
415 final var pniIdentity = account.getIdentityKeyStore().getIdentityInfo(pni);
416
417 if (aciIdentity == null || pniIdentity == null || aci.equals(pni)) {
418 return false;
419 }
420
421 final var verified = pniIdentity.getIdentityKey()
422 .verifyAlternateIdentity(aciIdentity.getIdentityKey(), message.getSignature());
423
424 if (!verified) {
425 logger.debug("Invalid PNI signature of ACI {} with PNI {}", aci, pni);
426 return false;
427 }
428
429 logger.debug("Verified association of ACI {} with PNI {}", aci, pni);
430 account.getRecipientTrustedResolver()
431 .resolveRecipientTrusted(Optional.of(ACI.from(aci.getRawUuid())),
432 Optional.of(pni),
433 senderAddress.getNumber());
434 return true;
435 }
436
437 private void handleDecryptionErrorMessage(
438 final List<HandleAction> actions,
439 final RecipientId sender,
440 final ServiceId senderServiceId,
441 final int senderDeviceId,
442 final DecryptionErrorMessage message,
443 final ServiceId destination
444 ) {
445 final var logEntries = account.getMessageSendLogStore()
446 .findMessages(senderServiceId,
447 senderDeviceId,
448 message.getTimestamp(),
449 message.getRatchetKey().isEmpty());
450
451 for (final var logEntry : logEntries) {
452 actions.add(new ResendMessageAction(sender, message.getTimestamp(), logEntry));
453 }
454
455 if (message.getRatchetKey().isPresent()) {
456 final var sessionStore = account.getAccountData(destination).getSessionStore();
457 if (sessionStore.isCurrentRatchetKey(senderServiceId, senderDeviceId, message.getRatchetKey().get())) {
458 if (logEntries.isEmpty()) {
459 logger.debug("Renewing the session with sender");
460 actions.add(new RenewSessionAction(sender, senderServiceId, destination));
461 } else {
462 logger.trace("Archiving the session with sender, a resend message has already been queued");
463 sessionStore.archiveSessions(senderServiceId);
464 }
465 }
466 return;
467 }
468
469 var found = false;
470 for (final var logEntry : logEntries) {
471 if (logEntry.groupId().isEmpty()) {
472 continue;
473 }
474 final var group = account.getGroupStore().getGroup(logEntry.groupId().get());
475 if (group == null) {
476 continue;
477 }
478 found = true;
479 logger.trace("Deleting shared sender key with {} ({}): {}",
480 sender,
481 senderDeviceId,
482 group.getDistributionId());
483 account.getSenderKeyStore().deleteSharedWith(senderServiceId, senderDeviceId, group.getDistributionId());
484 }
485 if (!found) {
486 logger.debug("Reset all shared sender keys with this recipient, no related message found in send log");
487 account.getSenderKeyStore().deleteSharedWith(senderServiceId);
488 }
489 }
490
491 private List<HandleAction> handleSyncMessage(
492 final SignalServiceEnvelope envelope,
493 final SignalServiceSyncMessage syncMessage,
494 final DeviceAddress sender,
495 final boolean ignoreAttachments
496 ) {
497 var actions = new ArrayList<HandleAction>();
498 account.setMultiDevice(true);
499 if (syncMessage.getSent().isPresent()) {
500 var message = syncMessage.getSent().get();
501 final var destination = message.getDestination().orElse(null);
502 if (message.getDataMessage().isPresent()) {
503 actions.addAll(handleSignalServiceDataMessage(message.getDataMessage().get(),
504 true,
505 sender,
506 destination == null
507 ? null
508 : new DeviceAddress(context.getRecipientHelper().resolveRecipient(destination),
509 destination.getServiceId(),
510 0),
511 ignoreAttachments));
512 }
513 if (message.getStoryMessage().isPresent()) {
514 actions.addAll(handleSignalServiceStoryMessage(message.getStoryMessage().get(),
515 sender.recipientId(),
516 ignoreAttachments));
517 }
518 }
519 if (syncMessage.getRequest().isPresent() && account.isPrimaryDevice()) {
520 var rm = syncMessage.getRequest().get();
521 if (rm.isContactsRequest()) {
522 actions.add(SendSyncContactsAction.create());
523 }
524 if (rm.isGroupsRequest()) {
525 actions.add(SendSyncGroupsAction.create());
526 }
527 if (rm.isBlockedListRequest()) {
528 actions.add(SendSyncBlockedListAction.create());
529 }
530 if (rm.isKeysRequest()) {
531 actions.add(SendSyncKeysAction.create());
532 }
533 if (rm.isConfigurationRequest()) {
534 actions.add(SendSyncConfigurationAction.create());
535 }
536 }
537 if (syncMessage.getGroups().isPresent()) {
538 try {
539 final var groupsMessage = syncMessage.getGroups().get();
540 context.getAttachmentHelper()
541 .retrieveAttachment(groupsMessage, context.getSyncHelper()::handleSyncDeviceGroups);
542 } catch (Exception e) {
543 logger.warn("Failed to handle received sync groups, ignoring: {}", e.getMessage());
544 }
545 }
546 if (syncMessage.getBlockedList().isPresent()) {
547 final var blockedListMessage = syncMessage.getBlockedList().get();
548 for (var address : blockedListMessage.getAddresses()) {
549 context.getContactHelper()
550 .setContactBlocked(context.getRecipientHelper().resolveRecipient(address), true);
551 }
552 for (var groupId : blockedListMessage.getGroupIds()
553 .stream()
554 .map(GroupId::unknownVersion)
555 .collect(Collectors.toSet())) {
556 try {
557 context.getGroupHelper().setGroupBlocked(groupId, true);
558 } catch (GroupNotFoundException e) {
559 logger.warn("BlockedListMessage contained groupID that was not found in GroupStore: {}",
560 groupId.toBase64());
561 }
562 }
563 }
564 if (syncMessage.getContacts().isPresent()) {
565 try {
566 final var contactsMessage = syncMessage.getContacts().get();
567 context.getAttachmentHelper()
568 .retrieveAttachment(contactsMessage.getContactsStream(),
569 context.getSyncHelper()::handleSyncDeviceContacts);
570 } catch (Exception e) {
571 logger.warn("Failed to handle received sync contacts, ignoring: {}", e.getMessage());
572 }
573 }
574 if (syncMessage.getVerified().isPresent()) {
575 final var verifiedMessage = syncMessage.getVerified().get();
576 account.getIdentityKeyStore()
577 .setIdentityTrustLevel(verifiedMessage.getDestination().getServiceId(),
578 verifiedMessage.getIdentityKey(),
579 TrustLevel.fromVerifiedState(verifiedMessage.getVerified()));
580 }
581 if (syncMessage.getStickerPackOperations().isPresent()) {
582 final var stickerPackOperationMessages = syncMessage.getStickerPackOperations().get();
583 for (var m : stickerPackOperationMessages) {
584 if (m.getPackId().isEmpty()) {
585 continue;
586 }
587 final var stickerPackId = StickerPackId.deserialize(m.getPackId().get());
588 final var stickerPackKey = m.getPackKey().orElse(null);
589 final var installed = m.getType().isEmpty()
590 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL;
591
592 final var sticker = context.getStickerHelper()
593 .addOrUpdateStickerPack(stickerPackId, stickerPackKey, installed);
594
595 if (sticker != null && installed) {
596 context.getJobExecutor().enqueueJob(new RetrieveStickerPackJob(stickerPackId, sticker.packKey()));
597 }
598 }
599 }
600 if (syncMessage.getFetchType().isPresent()) {
601 switch (syncMessage.getFetchType().get()) {
602 case LOCAL_PROFILE -> actions.add(new RetrieveProfileAction(account.getSelfRecipientId()));
603 case STORAGE_MANIFEST -> actions.add(RetrieveStorageDataAction.create());
604 }
605 }
606 if (syncMessage.getKeys().isPresent()) {
607 final var keysMessage = syncMessage.getKeys().get();
608 if (keysMessage.getStorageService().isPresent()) {
609 final var storageKey = keysMessage.getStorageService().get();
610 account.setStorageKey(storageKey);
611 actions.add(RetrieveStorageDataAction.create());
612 }
613 }
614 if (syncMessage.getConfiguration().isPresent()) {
615 final var configurationMessage = syncMessage.getConfiguration().get();
616 final var configurationStore = account.getConfigurationStore();
617 if (configurationMessage.getReadReceipts().isPresent()) {
618 configurationStore.setReadReceipts(configurationMessage.getReadReceipts().get());
619 }
620 if (configurationMessage.getLinkPreviews().isPresent()) {
621 configurationStore.setLinkPreviews(configurationMessage.getLinkPreviews().get());
622 }
623 if (configurationMessage.getTypingIndicators().isPresent()) {
624 configurationStore.setTypingIndicators(configurationMessage.getTypingIndicators().get());
625 }
626 if (configurationMessage.getUnidentifiedDeliveryIndicators().isPresent()) {
627 configurationStore.setUnidentifiedDeliveryIndicators(configurationMessage.getUnidentifiedDeliveryIndicators()
628 .get());
629 }
630 }
631 if (syncMessage.getPniChangeNumber().isPresent()) {
632 final var pniChangeNumber = syncMessage.getPniChangeNumber().get();
633 logger.debug("Received PNI change number sync message, applying.");
634 if (pniChangeNumber.hasIdentityKeyPair()
635 && pniChangeNumber.hasRegistrationId()
636 && pniChangeNumber.hasSignedPreKey()
637 && !envelope.getUpdatedPni().isEmpty()) {
638 logger.debug("New PNI: {}", envelope.getUpdatedPni());
639 try {
640 final var updatedPni = PNI.parseOrThrow(envelope.getUpdatedPni());
641 context.getAccountHelper()
642 .setPni(updatedPni,
643 new IdentityKeyPair(pniChangeNumber.getIdentityKeyPair().toByteArray()),
644 pniChangeNumber.hasNewE164() ? pniChangeNumber.getNewE164() : null,
645 pniChangeNumber.getRegistrationId(),
646 new SignedPreKeyRecord(pniChangeNumber.getSignedPreKey().toByteArray()),
647 pniChangeNumber.hasLastResortKyberPreKey()
648 ? new KyberPreKeyRecord(pniChangeNumber.getLastResortKyberPreKey()
649 .toByteArray())
650 : null);
651 } catch (Exception e) {
652 logger.warn("Failed to handle change number message", e);
653 }
654 }
655 }
656 return actions;
657 }
658
659 private SignalServiceGroupContext getGroupContext(SignalServiceContent content) {
660 if (content == null) {
661 return null;
662 }
663
664 if (content.getDataMessage().isPresent()) {
665 var message = content.getDataMessage().get();
666 if (message.getGroupContext().isPresent()) {
667 return message.getGroupContext().get();
668 }
669 }
670
671 if (content.getStoryMessage().isPresent()) {
672 var message = content.getStoryMessage().get();
673 if (message.getGroupContext().isPresent()) {
674 try {
675 return SignalServiceGroupContext.create(null, message.getGroupContext().get());
676 } catch (InvalidMessageException e) {
677 throw new AssertionError(e);
678 }
679 }
680 }
681
682 return null;
683 }
684
685 private boolean isMessageBlocked(SignalServiceEnvelope envelope, SignalServiceContent content) {
686 SignalServiceAddress source = getSenderAddress(envelope, content);
687 if (source == null) {
688 return false;
689 }
690 final var recipientId = context.getRecipientHelper().resolveRecipient(source);
691 if (context.getContactHelper().isContactBlocked(recipientId)) {
692 return true;
693 }
694
695 final var groupContext = getGroupContext(content);
696 if (groupContext != null) {
697 var groupId = GroupUtils.getGroupId(groupContext);
698 return context.getGroupHelper().isGroupBlocked(groupId);
699 }
700
701 return false;
702 }
703
704 private boolean isNotAllowedToSendToGroup(SignalServiceEnvelope envelope, SignalServiceContent content) {
705 SignalServiceAddress source = getSenderAddress(envelope, content);
706 if (source == null) {
707 return false;
708 }
709
710 final var groupContext = getGroupContext(content);
711 if (groupContext == null) {
712 return false;
713 }
714
715 if (groupContext.getGroupV1().isPresent()) {
716 var groupInfo = groupContext.getGroupV1().get();
717 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
718 return false;
719 }
720 }
721
722 var groupId = GroupUtils.getGroupId(groupContext);
723 var group = context.getGroupHelper().getGroup(groupId);
724 if (group == null) {
725 return false;
726 }
727
728 final var message = content.getDataMessage().orElse(null);
729
730 final var recipientId = context.getRecipientHelper().resolveRecipient(source);
731 if (!group.isMember(recipientId) && !(
732 group.isPendingMember(recipientId) && message != null && message.isGroupV2Update()
733 )) {
734 return true;
735 }
736
737 if (group.isAnnouncementGroup() && !group.isAdmin(recipientId)) {
738 return message == null
739 || message.getBody().isPresent()
740 || message.getAttachments().isPresent()
741 || message.getQuote().isPresent()
742 || message.getPreviews().isPresent()
743 || message.getMentions().isPresent()
744 || message.getSticker().isPresent();
745 }
746 return false;
747 }
748
749 private List<HandleAction> handleSignalServiceDataMessage(
750 SignalServiceDataMessage message,
751 boolean isSync,
752 DeviceAddress source,
753 DeviceAddress destination,
754 boolean ignoreAttachments
755 ) {
756 var actions = new ArrayList<HandleAction>();
757 if (message.getGroupContext().isPresent()) {
758 final var groupContext = message.getGroupContext().get();
759 if (groupContext.getGroupV1().isPresent()) {
760 var groupInfo = groupContext.getGroupV1().get();
761 var groupId = GroupId.v1(groupInfo.getGroupId());
762 var group = context.getGroupHelper().getGroup(groupId);
763 if (group == null || group instanceof GroupInfoV1) {
764 var groupV1 = (GroupInfoV1) group;
765 switch (groupInfo.getType()) {
766 case UPDATE -> {
767 if (groupV1 == null) {
768 groupV1 = new GroupInfoV1(groupId);
769 }
770
771 if (groupInfo.getAvatar().isPresent()) {
772 var avatar = groupInfo.getAvatar().get();
773 context.getGroupHelper().downloadGroupAvatar(groupV1.getGroupId(), avatar);
774 }
775
776 if (groupInfo.getName().isPresent()) {
777 groupV1.name = groupInfo.getName().get();
778 }
779
780 if (groupInfo.getMembers().isPresent()) {
781 groupV1.addMembers(groupInfo.getMembers()
782 .get()
783 .stream()
784 .map(context.getRecipientHelper()::resolveRecipient)
785 .collect(Collectors.toSet()));
786 }
787
788 account.getGroupStore().updateGroup(groupV1);
789 }
790 case DELIVER -> {
791 if (groupV1 == null && !isSync) {
792 actions.add(new SendGroupInfoRequestAction(source.recipientId(), groupId));
793 }
794 }
795 case QUIT -> {
796 if (groupV1 != null) {
797 groupV1.removeMember(source.recipientId());
798 account.getGroupStore().updateGroup(groupV1);
799 }
800 }
801 case REQUEST_INFO -> {
802 if (groupV1 != null && !isSync) {
803 actions.add(new SendGroupInfoAction(source.recipientId(), groupV1.getGroupId()));
804 }
805 }
806 }
807 } else {
808 // Received a group v1 message for a v2 group
809 }
810 }
811 if (groupContext.getGroupV2().isPresent()) {
812 handleGroupV2Context(groupContext.getGroupV2().get());
813 }
814 }
815
816 final var selfAddress = isSync ? source : destination;
817 final var conversationPartnerAddress = isSync ? destination : source;
818 if (conversationPartnerAddress != null && message.isEndSession()) {
819 account.getAccountData(selfAddress.serviceId())
820 .getSessionStore()
821 .deleteAllSessions(conversationPartnerAddress.serviceId());
822 }
823 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
824 if (message.getGroupContext().isPresent()) {
825 final var groupContext = message.getGroupContext().get();
826 if (groupContext.getGroupV1().isPresent()) {
827 var groupInfo = groupContext.getGroupV1().get();
828 var group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
829 if (group != null) {
830 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
831 group.messageExpirationTime = message.getExpiresInSeconds();
832 account.getGroupStore().updateGroup(group);
833 }
834 }
835 } else if (groupContext.getGroupV2().isPresent()) {
836 // disappearing message timer already stored in the DecryptedGroup
837 }
838 } else if (conversationPartnerAddress != null) {
839 context.getContactHelper()
840 .setExpirationTimer(conversationPartnerAddress.recipientId(), message.getExpiresInSeconds());
841 }
842 }
843 if (!ignoreAttachments) {
844 if (message.getAttachments().isPresent()) {
845 for (var attachment : message.getAttachments().get()) {
846 context.getAttachmentHelper().downloadAttachment(attachment);
847 }
848 }
849 if (message.getSharedContacts().isPresent()) {
850 for (var contact : message.getSharedContacts().get()) {
851 if (contact.getAvatar().isPresent()) {
852 context.getAttachmentHelper().downloadAttachment(contact.getAvatar().get().getAttachment());
853 }
854 }
855 }
856 if (message.getPreviews().isPresent()) {
857 final var previews = message.getPreviews().get();
858 for (var preview : previews) {
859 if (preview.getImage().isPresent()) {
860 context.getAttachmentHelper().downloadAttachment(preview.getImage().get());
861 }
862 }
863 }
864 if (message.getQuote().isPresent()) {
865 final var quote = message.getQuote().get();
866
867 if (quote.getAttachments() != null) {
868 for (var quotedAttachment : quote.getAttachments()) {
869 final var thumbnail = quotedAttachment.getThumbnail();
870 if (thumbnail != null) {
871 context.getAttachmentHelper().downloadAttachment(thumbnail);
872 }
873 }
874 }
875 }
876 }
877 if (message.getGiftBadge().isPresent()) {
878 handleIncomingGiftBadge(message.getGiftBadge().get());
879 }
880 if (message.getProfileKey().isPresent()) {
881 handleIncomingProfileKey(message.getProfileKey().get(), source.recipientId());
882 }
883 if (message.getSticker().isPresent()) {
884 final var messageSticker = message.getSticker().get();
885 final var stickerPackId = StickerPackId.deserialize(messageSticker.getPackId());
886 var sticker = account.getStickerStore().getStickerPack(stickerPackId);
887 if (sticker == null) {
888 sticker = new StickerPack(stickerPackId, messageSticker.getPackKey());
889 account.getStickerStore().addStickerPack(sticker);
890 }
891 context.getJobExecutor().enqueueJob(new RetrieveStickerPackJob(stickerPackId, messageSticker.getPackKey()));
892 }
893 return actions;
894 }
895
896 private void handleIncomingGiftBadge(final SignalServiceDataMessage.GiftBadge giftBadge) {
897 // TODO
898 }
899
900 private List<HandleAction> handleSignalServiceStoryMessage(
901 SignalServiceStoryMessage message, RecipientId source, boolean ignoreAttachments
902 ) {
903 var actions = new ArrayList<HandleAction>();
904 if (message.getGroupContext().isPresent()) {
905 handleGroupV2Context(message.getGroupContext().get());
906 }
907
908 if (!ignoreAttachments) {
909 if (message.getFileAttachment().isPresent()) {
910 context.getAttachmentHelper().downloadAttachment(message.getFileAttachment().get());
911 }
912 if (message.getTextAttachment().isPresent()) {
913 final var textAttachment = message.getTextAttachment().get();
914 if (textAttachment.getPreview().isPresent()) {
915 final var preview = textAttachment.getPreview().get();
916 if (preview.getImage().isPresent()) {
917 context.getAttachmentHelper().downloadAttachment(preview.getImage().get());
918 }
919 }
920 }
921 }
922
923 if (message.getProfileKey().isPresent()) {
924 handleIncomingProfileKey(message.getProfileKey().get(), source);
925 }
926
927 return actions;
928 }
929
930 private void handleGroupV2Context(final SignalServiceGroupV2 groupContext) {
931 final var groupMasterKey = groupContext.getMasterKey();
932
933 context.getGroupHelper()
934 .getOrMigrateGroup(groupMasterKey,
935 groupContext.getRevision(),
936 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
937 }
938
939 private void handleIncomingProfileKey(final byte[] profileKeyBytes, final RecipientId source) {
940 if (profileKeyBytes.length != 32) {
941 logger.debug("Received invalid profile key of length {}", profileKeyBytes.length);
942 return;
943 }
944 final ProfileKey profileKey;
945 try {
946 profileKey = new ProfileKey(profileKeyBytes);
947 } catch (InvalidInputException e) {
948 throw new AssertionError(e);
949 }
950 if (account.getSelfRecipientId().equals(source)) {
951 this.account.setProfileKey(profileKey);
952 }
953 this.account.getProfileStore().storeProfileKey(source, profileKey);
954 }
955
956 private SignalServiceAddress getSenderAddress(SignalServiceEnvelope envelope, SignalServiceContent content) {
957 if (!envelope.isUnidentifiedSender() && envelope.hasSourceServiceId()) {
958 return envelope.getSourceAddress();
959 } else if (content != null) {
960 return content.getSender();
961 } else {
962 return null;
963 }
964 }
965
966 private DeviceAddress getSender(SignalServiceEnvelope envelope, SignalServiceContent content) {
967 if (!envelope.isUnidentifiedSender() && envelope.hasSourceServiceId()) {
968 return new DeviceAddress(context.getRecipientHelper().resolveRecipient(envelope.getSourceAddress()),
969 envelope.getSourceAddress().getServiceId(),
970 envelope.getSourceDevice());
971 } else {
972 return new DeviceAddress(context.getRecipientHelper().resolveRecipient(content.getSender()),
973 content.getSender().getServiceId(),
974 content.getSenderDevice());
975 }
976 }
977
978 private DeviceAddress getDestination(SignalServiceEnvelope envelope) {
979 if (!envelope.hasDestinationUuid()) {
980 return new DeviceAddress(account.getSelfRecipientId(), account.getAci(), account.getDeviceId());
981 }
982 final var addressOptional = SignalServiceAddress.fromRaw(envelope.getDestinationServiceId(), null);
983 if (addressOptional.isEmpty()) {
984 return new DeviceAddress(account.getSelfRecipientId(), account.getAci(), account.getDeviceId());
985 }
986 final var address = addressOptional.get();
987 return new DeviceAddress(context.getRecipientHelper().resolveRecipient(address),
988 address.getServiceId(),
989 account.getDeviceId());
990 }
991
992 private record DeviceAddress(RecipientId recipientId, ServiceId serviceId, int deviceId) {}
993 }