1 package org
.asamk
.signal
.manager
.storage
.recipients
;
3 import com
.fasterxml
.jackson
.databind
.ObjectMapper
;
5 import org
.asamk
.signal
.manager
.api
.Pair
;
6 import org
.asamk
.signal
.manager
.api
.UnregisteredRecipientException
;
7 import org
.asamk
.signal
.manager
.storage
.Utils
;
8 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactsStore
;
9 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
10 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
11 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
12 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKeyCredential
;
13 import org
.slf4j
.Logger
;
14 import org
.slf4j
.LoggerFactory
;
15 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
16 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
17 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
18 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
20 import java
.io
.ByteArrayInputStream
;
21 import java
.io
.ByteArrayOutputStream
;
23 import java
.io
.FileInputStream
;
24 import java
.io
.FileNotFoundException
;
25 import java
.io
.FileOutputStream
;
26 import java
.io
.IOException
;
27 import java
.util
.ArrayList
;
28 import java
.util
.Base64
;
29 import java
.util
.Collection
;
30 import java
.util
.HashMap
;
31 import java
.util
.List
;
33 import java
.util
.Objects
;
34 import java
.util
.Optional
;
36 import java
.util
.UUID
;
37 import java
.util
.function
.Supplier
;
38 import java
.util
.stream
.Collectors
;
40 public class RecipientStore
implements RecipientResolver
, ContactsStore
, ProfileStore
{
42 private final static Logger logger
= LoggerFactory
.getLogger(RecipientStore
.class);
44 private final ObjectMapper objectMapper
;
45 private final File file
;
46 private final RecipientMergeHandler recipientMergeHandler
;
47 private final SelfAddressProvider selfAddressProvider
;
49 private final Map
<RecipientId
, Recipient
> recipients
;
50 private final Map
<Long
, Long
> recipientsMerged
= new HashMap
<>();
53 private boolean isBulkUpdating
;
55 public static RecipientStore
load(
56 File file
, RecipientMergeHandler recipientMergeHandler
, SelfAddressProvider selfAddressProvider
58 final var objectMapper
= Utils
.createStorageObjectMapper();
59 try (var inputStream
= new FileInputStream(file
)) {
60 final var storage
= objectMapper
.readValue(inputStream
, Storage
.class);
62 final var recipientStore
= new RecipientStore(objectMapper
,
64 recipientMergeHandler
,
68 final var recipients
= storage
.recipients
.stream().map(r
-> {
69 final var recipientId
= new RecipientId(r
.id
, recipientStore
);
70 final var address
= new RecipientAddress(Optional
.ofNullable(r
.uuid
).map(UuidUtil
::parseOrThrow
),
71 Optional
.ofNullable(r
.number
));
73 Contact contact
= null;
74 if (r
.contact
!= null) {
75 contact
= new Contact(r
.contact
.name
,
77 r
.contact
.messageExpirationTime
,
80 r
.contact
.profileSharingEnabled
);
83 ProfileKey profileKey
= null;
84 if (r
.profileKey
!= null) {
86 profileKey
= new ProfileKey(Base64
.getDecoder().decode(r
.profileKey
));
87 } catch (InvalidInputException ignored
) {
91 ProfileKeyCredential profileKeyCredential
= null;
92 if (r
.profileKeyCredential
!= null) {
94 profileKeyCredential
= new ProfileKeyCredential(Base64
.getDecoder()
95 .decode(r
.profileKeyCredential
));
96 } catch (Throwable ignored
) {
100 Profile profile
= null;
101 if (r
.profile
!= null) {
102 profile
= new Profile(r
.profile
.lastUpdateTimestamp
,
104 r
.profile
.familyName
,
106 r
.profile
.aboutEmoji
,
107 r
.profile
.avatarUrlPath
,
108 r
.profile
.mobileCoinAddress
== null
110 : Base64
.getDecoder().decode(r
.profile
.mobileCoinAddress
),
111 Profile
.UnidentifiedAccessMode
.valueOfOrUnknown(r
.profile
.unidentifiedAccessMode
),
112 r
.profile
.capabilities
.stream()
113 .map(Profile
.Capability
::valueOfOrNull
)
114 .filter(Objects
::nonNull
)
115 .collect(Collectors
.toSet()));
118 return new Recipient(recipientId
, address
, contact
, profileKey
, profileKeyCredential
, profile
);
119 }).collect(Collectors
.toMap(Recipient
::getRecipientId
, r
-> r
));
121 recipientStore
.addRecipients(recipients
);
123 return recipientStore
;
124 } catch (FileNotFoundException e
) {
125 logger
.trace("Creating new recipient store.");
126 return new RecipientStore(objectMapper
,
128 recipientMergeHandler
,
132 } catch (IOException e
) {
133 logger
.warn("Failed to load recipient store", e
);
134 throw new RuntimeException(e
);
138 private RecipientStore(
139 final ObjectMapper objectMapper
,
141 final RecipientMergeHandler recipientMergeHandler
,
142 final SelfAddressProvider selfAddressProvider
,
143 final Map
<RecipientId
, Recipient
> recipients
,
146 this.objectMapper
= objectMapper
;
148 this.recipientMergeHandler
= recipientMergeHandler
;
149 this.selfAddressProvider
= selfAddressProvider
;
150 this.recipients
= recipients
;
151 this.lastId
= lastId
;
154 public void setBulkUpdating(final boolean bulkUpdating
) {
155 isBulkUpdating
= bulkUpdating
;
157 synchronized (recipients
) {
163 public RecipientAddress
resolveRecipientAddress(RecipientId recipientId
) {
164 synchronized (recipients
) {
165 return getRecipient(recipientId
).getAddress();
169 public Recipient
getRecipient(RecipientId recipientId
) {
170 synchronized (recipients
) {
171 return recipients
.get(recipientId
);
175 public Collection
<RecipientId
> getRecipientIdsWithEnabledProfileSharing() {
176 synchronized (recipients
) {
177 return recipients
.values().stream().filter(r
-> {
178 final var contact
= r
.getContact();
179 return contact
!= null && !contact
.isBlocked() && contact
.isProfileSharingEnabled();
180 }).map(Recipient
::getRecipientId
).toList();
185 public RecipientId
resolveRecipient(ServiceId serviceId
) {
186 return resolveRecipient(new RecipientAddress(serviceId
.uuid()), false, false);
190 public RecipientId
resolveRecipient(final long recipientId
) {
191 final var recipient
= getRecipient(new RecipientId(recipientId
, this));
192 return recipient
== null ?
null : recipient
.getRecipientId();
196 public RecipientId
resolveRecipient(final String identifier
) {
197 return resolveRecipient(Utils
.getRecipientAddressFromIdentifier(identifier
), false, false);
200 public RecipientId
resolveRecipient(
201 final String number
, Supplier
<ACI
> aciSupplier
202 ) throws UnregisteredRecipientException
{
203 final Optional
<Recipient
> byNumber
;
204 synchronized (recipients
) {
205 byNumber
= findByNumberLocked(number
);
207 if (byNumber
.isEmpty() || byNumber
.get().getAddress().uuid().isEmpty()) {
208 final var aci
= aciSupplier
.get();
210 throw new UnregisteredRecipientException(new RecipientAddress(null, number
));
213 return resolveRecipient(new RecipientAddress(aci
.uuid(), number
), false, false);
215 return byNumber
.get().getRecipientId();
218 public RecipientId
resolveRecipient(RecipientAddress address
) {
219 return resolveRecipient(address
, false, false);
223 public RecipientId
resolveRecipient(final SignalServiceAddress address
) {
224 return resolveRecipient(new RecipientAddress(address
), false, false);
227 public RecipientId
resolveSelfRecipientTrusted(RecipientAddress address
) {
228 return resolveRecipient(address
, true, true);
231 public RecipientId
resolveRecipientTrusted(RecipientAddress address
) {
232 return resolveRecipient(address
, true, false);
235 public RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
236 return resolveRecipient(new RecipientAddress(address
), true, false);
239 public List
<RecipientId
> resolveRecipientsTrusted(List
<RecipientAddress
> addresses
) {
240 final List
<RecipientId
> recipientIds
;
241 final List
<Pair
<RecipientId
, RecipientId
>> toBeMerged
= new ArrayList
<>();
242 synchronized (recipients
) {
243 recipientIds
= addresses
.stream().map(address
-> {
244 final var pair
= resolveRecipientLocked(address
, true, false);
245 if (pair
.second().isPresent()) {
246 toBeMerged
.add(new Pair
<>(pair
.first(), pair
.second().get()));
251 for (var pair
: toBeMerged
) {
252 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second());
258 public void storeContact(RecipientId recipientId
, final Contact contact
) {
259 synchronized (recipients
) {
260 final var recipient
= recipients
.get(recipientId
);
261 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withContact(contact
).build());
266 public Contact
getContact(RecipientId recipientId
) {
267 final var recipient
= getRecipient(recipientId
);
268 return recipient
== null ?
null : recipient
.getContact();
272 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
273 return recipients
.entrySet()
275 .filter(e
-> e
.getValue().getContact() != null)
276 .map(e
-> new Pair
<>(e
.getKey(), e
.getValue().getContact()))
280 public List
<Recipient
> getRecipients(
281 boolean onlyContacts
, Optional
<Boolean
> blocked
, Set
<RecipientId
> recipientIds
, Optional
<String
> name
283 return recipients
.values()
285 .filter(r
-> !onlyContacts
|| r
.getContact() != null)
286 .filter(r
-> blocked
.isEmpty() || (
288 r
.getContact() != null && r
.getContact().isBlocked()
291 .filter(r
-> recipientIds
.isEmpty() || (recipientIds
.contains(r
.getRecipientId())))
292 .filter(r
-> name
.isEmpty()
293 || (r
.getContact() != null && name
.get().equals(r
.getContact().getName()))
294 || (r
.getProfile() != null && name
.get().equals(r
.getProfile().getDisplayName())))
299 public void deleteContact(RecipientId recipientId
) {
300 synchronized (recipients
) {
301 final var recipient
= recipients
.get(recipientId
);
302 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withContact(null).build());
306 public void deleteRecipientData(RecipientId recipientId
) {
307 synchronized (recipients
) {
308 logger
.debug("Deleting recipient data for {}", recipientId
);
309 final var recipient
= recipients
.get(recipientId
);
310 recipient
.getAddress()
312 .ifPresent(uuid
-> storeRecipientLocked(recipientId
,
313 Recipient
.newBuilder()
314 .withRecipientId(recipientId
)
315 .withAddress(new RecipientAddress(uuid
))
321 public Profile
getProfile(final RecipientId recipientId
) {
322 final var recipient
= getRecipient(recipientId
);
323 return recipient
== null ?
null : recipient
.getProfile();
327 public ProfileKey
getProfileKey(final RecipientId recipientId
) {
328 final var recipient
= getRecipient(recipientId
);
329 return recipient
== null ?
null : recipient
.getProfileKey();
333 public ProfileKeyCredential
getProfileKeyCredential(final RecipientId recipientId
) {
334 final var recipient
= getRecipient(recipientId
);
335 return recipient
== null ?
null : recipient
.getProfileKeyCredential();
339 public void storeProfile(RecipientId recipientId
, final Profile profile
) {
340 synchronized (recipients
) {
341 final var recipient
= recipients
.get(recipientId
);
342 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withProfile(profile
).build());
347 public void storeSelfProfileKey(final RecipientId recipientId
, final ProfileKey profileKey
) {
348 storeProfileKey(recipientId
, profileKey
, false);
352 public void storeProfileKey(RecipientId recipientId
, final ProfileKey profileKey
) {
353 storeProfileKey(recipientId
, profileKey
, true);
356 private void storeProfileKey(RecipientId recipientId
, final ProfileKey profileKey
, boolean resetProfile
) {
357 synchronized (recipients
) {
358 final var recipient
= recipients
.get(recipientId
);
359 if (profileKey
!= null && profileKey
.equals(recipient
.getProfileKey()) && (
360 recipient
.getProfile() == null || (
361 recipient
.getProfile().getUnidentifiedAccessMode() != Profile
.UnidentifiedAccessMode
.UNKNOWN
362 && recipient
.getProfile().getUnidentifiedAccessMode()
363 != Profile
.UnidentifiedAccessMode
.DISABLED
369 final var builder
= Recipient
.newBuilder(recipient
)
370 .withProfileKey(profileKey
)
371 .withProfileKeyCredential(null);
373 builder
.withProfile(recipient
.getProfile() == null
375 : Profile
.newBuilder(recipient
.getProfile()).withLastUpdateTimestamp(0).build());
377 final var newRecipient
= builder
.build();
378 storeRecipientLocked(recipientId
, newRecipient
);
383 public void storeProfileKeyCredential(RecipientId recipientId
, final ProfileKeyCredential profileKeyCredential
) {
384 synchronized (recipients
) {
385 final var recipient
= recipients
.get(recipientId
);
386 storeRecipientLocked(recipientId
,
387 Recipient
.newBuilder(recipient
).withProfileKeyCredential(profileKeyCredential
).build());
391 public boolean isEmpty() {
392 synchronized (recipients
) {
393 return recipients
.isEmpty();
397 private void addRecipients(final Map
<RecipientId
, Recipient
> recipients
) {
398 this.recipients
.putAll(recipients
);
402 * @param isHighTrust true, if the number/uuid connection was obtained from a trusted source.
403 * Has no effect, if the address contains only a number or a uuid.
405 private RecipientId
resolveRecipient(RecipientAddress address
, boolean isHighTrust
, boolean isSelf
) {
406 final Pair
<RecipientId
, Optional
<RecipientId
>> pair
;
407 synchronized (recipients
) {
408 pair
= resolveRecipientLocked(address
, isHighTrust
, isSelf
);
411 if (pair
.second().isPresent()) {
412 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second().get());
417 private Pair
<RecipientId
, Optional
<RecipientId
>> resolveRecipientLocked(
418 RecipientAddress address
, boolean isHighTrust
, boolean isSelf
420 if (isHighTrust
&& !isSelf
) {
421 if (selfAddressProvider
.getSelfAddress().matches(address
)) {
425 final var byNumber
= address
.number().isEmpty()
426 ? Optional
.<Recipient
>empty()
427 : findByNumberLocked(address
.number().get());
428 final var byUuid
= address
.uuid().isEmpty()
429 ? Optional
.<Recipient
>empty()
430 : findByUuidLocked(address
.uuid().get());
432 if (byNumber
.isEmpty() && byUuid
.isEmpty()) {
433 logger
.debug("Got new recipient, both uuid and number are unknown");
435 if (isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty()) {
436 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
439 return new Pair
<>(addNewRecipientLocked(new RecipientAddress(address
.uuid().get())), Optional
.empty());
442 if (!isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty() || byNumber
.equals(byUuid
)) {
443 return new Pair
<>(byUuid
.or(() -> byNumber
).map(Recipient
::getRecipientId
).get(), Optional
.empty());
446 if (byNumber
.isEmpty()) {
447 logger
.debug("Got recipient {} existing with uuid, updating with high trust number",
448 byUuid
.get().getRecipientId());
449 updateRecipientAddressLocked(byUuid
.get().getRecipientId(), address
);
450 return new Pair
<>(byUuid
.get().getRecipientId(), Optional
.empty());
453 final var byNumberRecipient
= byNumber
.get();
455 if (byUuid
.isEmpty()) {
456 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
458 "Got recipient {} existing with number, but different uuid, so stripping its number and adding new recipient",
459 byNumberRecipient
.getRecipientId());
461 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
462 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
463 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
466 logger
.debug("Got recipient {} existing with number and no uuid, updating with high trust uuid",
467 byNumberRecipient
.getRecipientId());
468 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(), address
);
469 return new Pair
<>(byNumberRecipient
.getRecipientId(), Optional
.empty());
472 final var byUuidRecipient
= byUuid
.get();
474 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
476 "Got separate recipients for high trust number {} and uuid {}, recipient for number has different uuid, so stripping its number",
477 byNumberRecipient
.getRecipientId(),
478 byUuidRecipient
.getRecipientId());
480 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
481 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
482 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
483 return new Pair
<>(byUuidRecipient
.getRecipientId(), Optional
.empty());
486 logger
.debug("Got separate recipients for high trust number {} and uuid {}, need to merge them",
487 byNumberRecipient
.getRecipientId(),
488 byUuidRecipient
.getRecipientId());
489 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
490 // Create a fixed RecipientId that won't update its id after merge
491 final var toBeMergedRecipientId
= new RecipientId(byNumberRecipient
.getRecipientId().id(), null);
492 mergeRecipientsLocked(byUuidRecipient
.getRecipientId(), toBeMergedRecipientId
);
493 return new Pair
<>(byUuidRecipient
.getRecipientId(), Optional
.of(toBeMergedRecipientId
));
496 private RecipientId
addNewRecipientLocked(final RecipientAddress address
) {
497 final var nextRecipientId
= nextIdLocked();
498 logger
.debug("Adding new recipient {} with address {}", nextRecipientId
, address
);
499 storeRecipientLocked(nextRecipientId
, new Recipient(nextRecipientId
, address
, null, null, null, null));
500 return nextRecipientId
;
503 private void updateRecipientAddressLocked(RecipientId recipientId
, final RecipientAddress address
) {
504 final var recipient
= recipients
.get(recipientId
);
505 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withAddress(address
).build());
508 long getActualRecipientId(long recipientId
) {
509 while (recipientsMerged
.containsKey(recipientId
)) {
510 final var newRecipientId
= recipientsMerged
.get(recipientId
);
511 logger
.debug("Using {} instead of {}, because recipients have been merged", newRecipientId
, recipientId
);
512 recipientId
= newRecipientId
;
517 private void storeRecipientLocked(final RecipientId recipientId
, final Recipient recipient
) {
518 final var existingRecipient
= recipients
.get(recipientId
);
519 if (existingRecipient
== null || !existingRecipient
.equals(recipient
)) {
520 recipients
.put(recipientId
, recipient
);
525 private void mergeRecipientsLocked(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
526 final var recipient
= recipients
.get(recipientId
);
527 final var toBeMergedRecipient
= recipients
.get(toBeMergedRecipientId
);
528 recipients
.put(recipientId
,
529 new Recipient(recipientId
,
530 recipient
.getAddress(),
531 recipient
.getContact() != null ? recipient
.getContact() : toBeMergedRecipient
.getContact(),
532 recipient
.getProfileKey() != null
533 ? recipient
.getProfileKey()
534 : toBeMergedRecipient
.getProfileKey(),
535 recipient
.getProfileKeyCredential() != null
536 ? recipient
.getProfileKeyCredential()
537 : toBeMergedRecipient
.getProfileKeyCredential(),
538 recipient
.getProfile() != null ? recipient
.getProfile() : toBeMergedRecipient
.getProfile()));
539 recipients
.remove(toBeMergedRecipientId
);
540 recipientsMerged
.put(toBeMergedRecipientId
.id(), recipientId
.id());
544 private Optional
<Recipient
> findByNumberLocked(final String number
) {
545 return recipients
.entrySet()
547 .filter(entry
-> entry
.getValue().getAddress().number().isPresent() && number
.equals(entry
.getValue()
552 .map(Map
.Entry
::getValue
);
555 private Optional
<Recipient
> findByUuidLocked(final UUID uuid
) {
556 return recipients
.entrySet()
558 .filter(entry
-> entry
.getValue().getAddress().uuid().isPresent() && uuid
.equals(entry
.getValue()
563 .map(Map
.Entry
::getValue
);
566 private RecipientId
nextIdLocked() {
567 return new RecipientId(++this.lastId
, this);
570 private void saveLocked() {
571 if (isBulkUpdating
) {
574 final var base64
= Base64
.getEncoder();
575 var storage
= new Storage(recipients
.entrySet().stream().map(pair
-> {
576 final var recipient
= pair
.getValue();
577 final var recipientContact
= recipient
.getContact();
578 final var contact
= recipientContact
== null
580 : new Storage
.Recipient
.Contact(recipientContact
.getName(),
581 recipientContact
.getColor(),
582 recipientContact
.getMessageExpirationTime(),
583 recipientContact
.isBlocked(),
584 recipientContact
.isArchived(),
585 recipientContact
.isProfileSharingEnabled());
586 final var recipientProfile
= recipient
.getProfile();
587 final var profile
= recipientProfile
== null
589 : new Storage
.Recipient
.Profile(recipientProfile
.getLastUpdateTimestamp(),
590 recipientProfile
.getGivenName(),
591 recipientProfile
.getFamilyName(),
592 recipientProfile
.getAbout(),
593 recipientProfile
.getAboutEmoji(),
594 recipientProfile
.getAvatarUrlPath(),
595 recipientProfile
.getMobileCoinAddress() == null
597 : base64
.encodeToString(recipientProfile
.getMobileCoinAddress()),
598 recipientProfile
.getUnidentifiedAccessMode().name(),
599 recipientProfile
.getCapabilities().stream().map(Enum
::name
).collect(Collectors
.toSet()));
600 return new Storage
.Recipient(pair
.getKey().id(),
601 recipient
.getAddress().number().orElse(null),
602 recipient
.getAddress().uuid().map(UUID
::toString
).orElse(null),
603 recipient
.getProfileKey() == null
605 : base64
.encodeToString(recipient
.getProfileKey().serialize()),
606 recipient
.getProfileKeyCredential() == null
608 : base64
.encodeToString(recipient
.getProfileKeyCredential().serialize()),
611 }).toList(), lastId
);
613 // Write to memory first to prevent corrupting the file in case of serialization errors
614 try (var inMemoryOutput
= new ByteArrayOutputStream()) {
615 objectMapper
.writeValue(inMemoryOutput
, storage
);
617 var input
= new ByteArrayInputStream(inMemoryOutput
.toByteArray());
618 try (var outputStream
= new FileOutputStream(file
)) {
619 input
.transferTo(outputStream
);
621 } catch (Exception e
) {
622 logger
.error("Error saving recipient store file: {}", e
.getMessage());
626 private record Storage(List
<Recipient
> recipients
, long lastId
) {
628 private record Recipient(
633 String profileKeyCredential
,
634 Storage
.Recipient
.Contact contact
,
635 Storage
.Recipient
.Profile profile
638 private record Contact(
641 int messageExpirationTime
,
644 boolean profileSharingEnabled
647 private record Profile(
648 long lastUpdateTimestamp
,
653 String avatarUrlPath
,
654 String mobileCoinAddress
,
655 String unidentifiedAccessMode
,
656 Set
<String
> capabilities
661 public interface RecipientMergeHandler
{
663 void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
);