]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/IncomingMessageHandler.java
Update libsignal-service
[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 installed = m.getType().isEmpty()
589 || m.getType().get() == StickerPackOperationMessage.Type.INSTALL;
590
591 var sticker = account.getStickerStore().getStickerPack(stickerPackId);
592 if (m.getPackKey().isPresent()) {
593 if (sticker == null) {
594 sticker = new StickerPack(-1, stickerPackId, m.getPackKey().get(), installed);
595 account.getStickerStore().addStickerPack(sticker);
596 }
597 if (installed) {
598 context.getJobExecutor()
599 .enqueueJob(new RetrieveStickerPackJob(stickerPackId, m.getPackKey().get()));
600 }
601 }
602
603 if (sticker != null && sticker.isInstalled() != installed) {
604 account.getStickerStore().updateStickerPackInstalled(sticker.packId(), installed);
605 }
606 }
607 }
608 if (syncMessage.getFetchType().isPresent()) {
609 switch (syncMessage.getFetchType().get()) {
610 case LOCAL_PROFILE -> actions.add(new RetrieveProfileAction(account.getSelfRecipientId()));
611 case STORAGE_MANIFEST -> actions.add(RetrieveStorageDataAction.create());
612 }
613 }
614 if (syncMessage.getKeys().isPresent()) {
615 final var keysMessage = syncMessage.getKeys().get();
616 if (keysMessage.getStorageService().isPresent()) {
617 final var storageKey = keysMessage.getStorageService().get();
618 account.setStorageKey(storageKey);
619 actions.add(RetrieveStorageDataAction.create());
620 }
621 }
622 if (syncMessage.getConfiguration().isPresent()) {
623 final var configurationMessage = syncMessage.getConfiguration().get();
624 final var configurationStore = account.getConfigurationStore();
625 if (configurationMessage.getReadReceipts().isPresent()) {
626 configurationStore.setReadReceipts(configurationMessage.getReadReceipts().get());
627 }
628 if (configurationMessage.getLinkPreviews().isPresent()) {
629 configurationStore.setLinkPreviews(configurationMessage.getLinkPreviews().get());
630 }
631 if (configurationMessage.getTypingIndicators().isPresent()) {
632 configurationStore.setTypingIndicators(configurationMessage.getTypingIndicators().get());
633 }
634 if (configurationMessage.getUnidentifiedDeliveryIndicators().isPresent()) {
635 configurationStore.setUnidentifiedDeliveryIndicators(configurationMessage.getUnidentifiedDeliveryIndicators()
636 .get());
637 }
638 }
639 if (syncMessage.getPniChangeNumber().isPresent()) {
640 final var pniChangeNumber = syncMessage.getPniChangeNumber().get();
641 logger.debug("Received PNI change number sync message, applying.");
642 if (pniChangeNumber.hasIdentityKeyPair()
643 && pniChangeNumber.hasRegistrationId()
644 && pniChangeNumber.hasSignedPreKey()
645 && !envelope.getUpdatedPni().isEmpty()) {
646 logger.debug("New PNI: {}", envelope.getUpdatedPni());
647 try {
648 final var updatedPni = PNI.parseOrThrow(envelope.getUpdatedPni());
649 context.getAccountHelper()
650 .setPni(updatedPni,
651 new IdentityKeyPair(pniChangeNumber.getIdentityKeyPair().toByteArray()),
652 pniChangeNumber.hasNewE164() ? pniChangeNumber.getNewE164() : null,
653 pniChangeNumber.getRegistrationId(),
654 new SignedPreKeyRecord(pniChangeNumber.getSignedPreKey().toByteArray()),
655 pniChangeNumber.hasLastResortKyberPreKey()
656 ? new KyberPreKeyRecord(pniChangeNumber.getLastResortKyberPreKey()
657 .toByteArray())
658 : null);
659 } catch (Exception e) {
660 logger.warn("Failed to handle change number message", e);
661 }
662 }
663 }
664 return actions;
665 }
666
667 private SignalServiceGroupContext getGroupContext(SignalServiceContent content) {
668 if (content == null) {
669 return null;
670 }
671
672 if (content.getDataMessage().isPresent()) {
673 var message = content.getDataMessage().get();
674 if (message.getGroupContext().isPresent()) {
675 return message.getGroupContext().get();
676 }
677 }
678
679 if (content.getStoryMessage().isPresent()) {
680 var message = content.getStoryMessage().get();
681 if (message.getGroupContext().isPresent()) {
682 try {
683 return SignalServiceGroupContext.create(null, message.getGroupContext().get());
684 } catch (InvalidMessageException e) {
685 throw new AssertionError(e);
686 }
687 }
688 }
689
690 return null;
691 }
692
693 private boolean isMessageBlocked(SignalServiceEnvelope envelope, SignalServiceContent content) {
694 SignalServiceAddress source = getSenderAddress(envelope, content);
695 if (source == null) {
696 return false;
697 }
698 final var recipientId = context.getRecipientHelper().resolveRecipient(source);
699 if (context.getContactHelper().isContactBlocked(recipientId)) {
700 return true;
701 }
702
703 final var groupContext = getGroupContext(content);
704 if (groupContext != null) {
705 var groupId = GroupUtils.getGroupId(groupContext);
706 return context.getGroupHelper().isGroupBlocked(groupId);
707 }
708
709 return false;
710 }
711
712 private boolean isNotAllowedToSendToGroup(SignalServiceEnvelope envelope, SignalServiceContent content) {
713 SignalServiceAddress source = getSenderAddress(envelope, content);
714 if (source == null) {
715 return false;
716 }
717
718 final var groupContext = getGroupContext(content);
719 if (groupContext == null) {
720 return false;
721 }
722
723 if (groupContext.getGroupV1().isPresent()) {
724 var groupInfo = groupContext.getGroupV1().get();
725 if (groupInfo.getType() == SignalServiceGroup.Type.QUIT) {
726 return false;
727 }
728 }
729
730 var groupId = GroupUtils.getGroupId(groupContext);
731 var group = context.getGroupHelper().getGroup(groupId);
732 if (group == null) {
733 return false;
734 }
735
736 final var message = content.getDataMessage().orElse(null);
737
738 final var recipientId = context.getRecipientHelper().resolveRecipient(source);
739 if (!group.isMember(recipientId) && !(
740 group.isPendingMember(recipientId) && message != null && message.isGroupV2Update()
741 )) {
742 return true;
743 }
744
745 if (group.isAnnouncementGroup() && !group.isAdmin(recipientId)) {
746 return message == null
747 || message.getBody().isPresent()
748 || message.getAttachments().isPresent()
749 || message.getQuote().isPresent()
750 || message.getPreviews().isPresent()
751 || message.getMentions().isPresent()
752 || message.getSticker().isPresent();
753 }
754 return false;
755 }
756
757 private List<HandleAction> handleSignalServiceDataMessage(
758 SignalServiceDataMessage message,
759 boolean isSync,
760 DeviceAddress source,
761 DeviceAddress destination,
762 boolean ignoreAttachments
763 ) {
764 var actions = new ArrayList<HandleAction>();
765 if (message.getGroupContext().isPresent()) {
766 final var groupContext = message.getGroupContext().get();
767 if (groupContext.getGroupV1().isPresent()) {
768 var groupInfo = groupContext.getGroupV1().get();
769 var groupId = GroupId.v1(groupInfo.getGroupId());
770 var group = context.getGroupHelper().getGroup(groupId);
771 if (group == null || group instanceof GroupInfoV1) {
772 var groupV1 = (GroupInfoV1) group;
773 switch (groupInfo.getType()) {
774 case UPDATE -> {
775 if (groupV1 == null) {
776 groupV1 = new GroupInfoV1(groupId);
777 }
778
779 if (groupInfo.getAvatar().isPresent()) {
780 var avatar = groupInfo.getAvatar().get();
781 context.getGroupHelper().downloadGroupAvatar(groupV1.getGroupId(), avatar);
782 }
783
784 if (groupInfo.getName().isPresent()) {
785 groupV1.name = groupInfo.getName().get();
786 }
787
788 if (groupInfo.getMembers().isPresent()) {
789 groupV1.addMembers(groupInfo.getMembers()
790 .get()
791 .stream()
792 .map(context.getRecipientHelper()::resolveRecipient)
793 .collect(Collectors.toSet()));
794 }
795
796 account.getGroupStore().updateGroup(groupV1);
797 }
798 case DELIVER -> {
799 if (groupV1 == null && !isSync) {
800 actions.add(new SendGroupInfoRequestAction(source.recipientId(), groupId));
801 }
802 }
803 case QUIT -> {
804 if (groupV1 != null) {
805 groupV1.removeMember(source.recipientId());
806 account.getGroupStore().updateGroup(groupV1);
807 }
808 }
809 case REQUEST_INFO -> {
810 if (groupV1 != null && !isSync) {
811 actions.add(new SendGroupInfoAction(source.recipientId(), groupV1.getGroupId()));
812 }
813 }
814 }
815 } else {
816 // Received a group v1 message for a v2 group
817 }
818 }
819 if (groupContext.getGroupV2().isPresent()) {
820 handleGroupV2Context(groupContext.getGroupV2().get());
821 }
822 }
823
824 final var selfAddress = isSync ? source : destination;
825 final var conversationPartnerAddress = isSync ? destination : source;
826 if (conversationPartnerAddress != null && message.isEndSession()) {
827 account.getAccountData(selfAddress.serviceId())
828 .getSessionStore()
829 .deleteAllSessions(conversationPartnerAddress.serviceId());
830 }
831 if (message.isExpirationUpdate() || message.getBody().isPresent()) {
832 if (message.getGroupContext().isPresent()) {
833 final var groupContext = message.getGroupContext().get();
834 if (groupContext.getGroupV1().isPresent()) {
835 var groupInfo = groupContext.getGroupV1().get();
836 var group = account.getGroupStore().getOrCreateGroupV1(GroupId.v1(groupInfo.getGroupId()));
837 if (group != null) {
838 if (group.messageExpirationTime != message.getExpiresInSeconds()) {
839 group.messageExpirationTime = message.getExpiresInSeconds();
840 account.getGroupStore().updateGroup(group);
841 }
842 }
843 } else if (groupContext.getGroupV2().isPresent()) {
844 // disappearing message timer already stored in the DecryptedGroup
845 }
846 } else if (conversationPartnerAddress != null) {
847 context.getContactHelper()
848 .setExpirationTimer(conversationPartnerAddress.recipientId(), message.getExpiresInSeconds());
849 }
850 }
851 if (!ignoreAttachments) {
852 if (message.getAttachments().isPresent()) {
853 for (var attachment : message.getAttachments().get()) {
854 context.getAttachmentHelper().downloadAttachment(attachment);
855 }
856 }
857 if (message.getSharedContacts().isPresent()) {
858 for (var contact : message.getSharedContacts().get()) {
859 if (contact.getAvatar().isPresent()) {
860 context.getAttachmentHelper().downloadAttachment(contact.getAvatar().get().getAttachment());
861 }
862 }
863 }
864 if (message.getPreviews().isPresent()) {
865 final var previews = message.getPreviews().get();
866 for (var preview : previews) {
867 if (preview.getImage().isPresent()) {
868 context.getAttachmentHelper().downloadAttachment(preview.getImage().get());
869 }
870 }
871 }
872 if (message.getQuote().isPresent()) {
873 final var quote = message.getQuote().get();
874
875 if (quote.getAttachments() != null) {
876 for (var quotedAttachment : quote.getAttachments()) {
877 final var thumbnail = quotedAttachment.getThumbnail();
878 if (thumbnail != null) {
879 context.getAttachmentHelper().downloadAttachment(thumbnail);
880 }
881 }
882 }
883 }
884 }
885 if (message.getGiftBadge().isPresent()) {
886 handleIncomingGiftBadge(message.getGiftBadge().get());
887 }
888 if (message.getProfileKey().isPresent()) {
889 handleIncomingProfileKey(message.getProfileKey().get(), source.recipientId());
890 }
891 if (message.getSticker().isPresent()) {
892 final var messageSticker = message.getSticker().get();
893 final var stickerPackId = StickerPackId.deserialize(messageSticker.getPackId());
894 var sticker = account.getStickerStore().getStickerPack(stickerPackId);
895 if (sticker == null) {
896 sticker = new StickerPack(stickerPackId, messageSticker.getPackKey());
897 account.getStickerStore().addStickerPack(sticker);
898 }
899 context.getJobExecutor().enqueueJob(new RetrieveStickerPackJob(stickerPackId, messageSticker.getPackKey()));
900 }
901 return actions;
902 }
903
904 private void handleIncomingGiftBadge(final SignalServiceDataMessage.GiftBadge giftBadge) {
905 // TODO
906 }
907
908 private List<HandleAction> handleSignalServiceStoryMessage(
909 SignalServiceStoryMessage message, RecipientId source, boolean ignoreAttachments
910 ) {
911 var actions = new ArrayList<HandleAction>();
912 if (message.getGroupContext().isPresent()) {
913 handleGroupV2Context(message.getGroupContext().get());
914 }
915
916 if (!ignoreAttachments) {
917 if (message.getFileAttachment().isPresent()) {
918 context.getAttachmentHelper().downloadAttachment(message.getFileAttachment().get());
919 }
920 if (message.getTextAttachment().isPresent()) {
921 final var textAttachment = message.getTextAttachment().get();
922 if (textAttachment.getPreview().isPresent()) {
923 final var preview = textAttachment.getPreview().get();
924 if (preview.getImage().isPresent()) {
925 context.getAttachmentHelper().downloadAttachment(preview.getImage().get());
926 }
927 }
928 }
929 }
930
931 if (message.getProfileKey().isPresent()) {
932 handleIncomingProfileKey(message.getProfileKey().get(), source);
933 }
934
935 return actions;
936 }
937
938 private void handleGroupV2Context(final SignalServiceGroupV2 groupContext) {
939 final var groupMasterKey = groupContext.getMasterKey();
940
941 context.getGroupHelper()
942 .getOrMigrateGroup(groupMasterKey,
943 groupContext.getRevision(),
944 groupContext.hasSignedGroupChange() ? groupContext.getSignedGroupChange() : null);
945 }
946
947 private void handleIncomingProfileKey(final byte[] profileKeyBytes, final RecipientId source) {
948 if (profileKeyBytes.length != 32) {
949 logger.debug("Received invalid profile key of length {}", profileKeyBytes.length);
950 return;
951 }
952 final ProfileKey profileKey;
953 try {
954 profileKey = new ProfileKey(profileKeyBytes);
955 } catch (InvalidInputException e) {
956 throw new AssertionError(e);
957 }
958 if (account.getSelfRecipientId().equals(source)) {
959 this.account.setProfileKey(profileKey);
960 }
961 this.account.getProfileStore().storeProfileKey(source, profileKey);
962 }
963
964 private SignalServiceAddress getSenderAddress(SignalServiceEnvelope envelope, SignalServiceContent content) {
965 if (!envelope.isUnidentifiedSender() && envelope.hasSourceServiceId()) {
966 return envelope.getSourceAddress();
967 } else if (content != null) {
968 return content.getSender();
969 } else {
970 return null;
971 }
972 }
973
974 private DeviceAddress getSender(SignalServiceEnvelope envelope, SignalServiceContent content) {
975 if (!envelope.isUnidentifiedSender() && envelope.hasSourceServiceId()) {
976 return new DeviceAddress(context.getRecipientHelper().resolveRecipient(envelope.getSourceAddress()),
977 envelope.getSourceAddress().getServiceId(),
978 envelope.getSourceDevice());
979 } else {
980 return new DeviceAddress(context.getRecipientHelper().resolveRecipient(content.getSender()),
981 content.getSender().getServiceId(),
982 content.getSenderDevice());
983 }
984 }
985
986 private DeviceAddress getDestination(SignalServiceEnvelope envelope) {
987 if (!envelope.hasDestinationUuid()) {
988 return new DeviceAddress(account.getSelfRecipientId(), account.getAci(), account.getDeviceId());
989 }
990 final var addressOptional = SignalServiceAddress.fromRaw(envelope.getDestinationServiceId(), null);
991 if (addressOptional.isEmpty()) {
992 return new DeviceAddress(account.getSelfRecipientId(), account.getAci(), account.getDeviceId());
993 }
994 final var address = addressOptional.get();
995 return new DeviceAddress(context.getRecipientHelper().resolveRecipient(address),
996 address.getServiceId(),
997 account.getDeviceId());
998 }
999
1000 private record DeviceAddress(RecipientId recipientId, ServiceId serviceId, int deviceId) {}
1001 }