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
.zkgroup
.InvalidInputException
;
11 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
12 import org
.signal
.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
.HashMap
;
30 import java
.util
.List
;
32 import java
.util
.Objects
;
33 import java
.util
.Optional
;
35 import java
.util
.UUID
;
36 import java
.util
.function
.Supplier
;
37 import java
.util
.stream
.Collectors
;
39 public class RecipientStore
implements RecipientResolver
, ContactsStore
, ProfileStore
{
41 private final static Logger logger
= LoggerFactory
.getLogger(RecipientStore
.class);
43 private final ObjectMapper objectMapper
;
44 private final File file
;
45 private final RecipientMergeHandler recipientMergeHandler
;
46 private final SelfAddressProvider selfAddressProvider
;
48 private final Map
<RecipientId
, Recipient
> recipients
;
49 private final Map
<Long
, Long
> recipientsMerged
= new HashMap
<>();
52 private boolean isBulkUpdating
;
54 public static RecipientStore
load(
55 File file
, RecipientMergeHandler recipientMergeHandler
, SelfAddressProvider selfAddressProvider
57 final var objectMapper
= Utils
.createStorageObjectMapper();
58 try (var inputStream
= new FileInputStream(file
)) {
59 final var storage
= objectMapper
.readValue(inputStream
, Storage
.class);
61 final var recipientStore
= new RecipientStore(objectMapper
,
63 recipientMergeHandler
,
67 final var recipients
= storage
.recipients
.stream().map(r
-> {
68 final var recipientId
= new RecipientId(r
.id
, recipientStore
);
69 final var address
= new RecipientAddress(Optional
.ofNullable(r
.uuid
).map(UuidUtil
::parseOrThrow
),
70 Optional
.ofNullable(r
.number
));
72 Contact contact
= null;
73 if (r
.contact
!= null) {
74 contact
= new Contact(r
.contact
.name
,
76 r
.contact
.messageExpirationTime
,
81 ProfileKey profileKey
= null;
82 if (r
.profileKey
!= null) {
84 profileKey
= new ProfileKey(Base64
.getDecoder().decode(r
.profileKey
));
85 } catch (InvalidInputException ignored
) {
89 ProfileKeyCredential profileKeyCredential
= null;
90 if (r
.profileKeyCredential
!= null) {
92 profileKeyCredential
= new ProfileKeyCredential(Base64
.getDecoder()
93 .decode(r
.profileKeyCredential
));
94 } catch (Throwable ignored
) {
98 Profile profile
= null;
99 if (r
.profile
!= null) {
100 profile
= new Profile(r
.profile
.lastUpdateTimestamp
,
102 r
.profile
.familyName
,
104 r
.profile
.aboutEmoji
,
105 r
.profile
.avatarUrlPath
,
106 Profile
.UnidentifiedAccessMode
.valueOfOrUnknown(r
.profile
.unidentifiedAccessMode
),
107 r
.profile
.capabilities
.stream()
108 .map(Profile
.Capability
::valueOfOrNull
)
109 .filter(Objects
::nonNull
)
110 .collect(Collectors
.toSet()));
113 return new Recipient(recipientId
, address
, contact
, profileKey
, profileKeyCredential
, profile
);
114 }).collect(Collectors
.toMap(Recipient
::getRecipientId
, r
-> r
));
116 recipientStore
.addRecipients(recipients
);
118 return recipientStore
;
119 } catch (FileNotFoundException e
) {
120 logger
.trace("Creating new recipient store.");
121 return new RecipientStore(objectMapper
,
123 recipientMergeHandler
,
127 } catch (IOException e
) {
128 logger
.warn("Failed to load recipient store", e
);
129 throw new RuntimeException(e
);
133 private RecipientStore(
134 final ObjectMapper objectMapper
,
136 final RecipientMergeHandler recipientMergeHandler
,
137 final SelfAddressProvider selfAddressProvider
,
138 final Map
<RecipientId
, Recipient
> recipients
,
141 this.objectMapper
= objectMapper
;
143 this.recipientMergeHandler
= recipientMergeHandler
;
144 this.selfAddressProvider
= selfAddressProvider
;
145 this.recipients
= recipients
;
146 this.lastId
= lastId
;
149 public boolean isBulkUpdating() {
150 return isBulkUpdating
;
153 public void setBulkUpdating(final boolean bulkUpdating
) {
154 isBulkUpdating
= bulkUpdating
;
156 synchronized (recipients
) {
162 public RecipientAddress
resolveRecipientAddress(RecipientId recipientId
) {
163 synchronized (recipients
) {
164 return getRecipient(recipientId
).getAddress();
168 public Recipient
getRecipient(RecipientId recipientId
) {
169 synchronized (recipients
) {
170 return recipients
.get(recipientId
);
175 public RecipientId
resolveRecipient(ServiceId serviceId
) {
176 return resolveRecipient(new RecipientAddress(serviceId
.uuid()), false, false);
180 public RecipientId
resolveRecipient(final long recipientId
) {
181 final var recipient
= getRecipient(new RecipientId(recipientId
, this));
182 return recipient
== null ?
null : recipient
.getRecipientId();
186 public RecipientId
resolveRecipient(final String identifier
) {
187 return resolveRecipient(Utils
.getRecipientAddressFromIdentifier(identifier
), false, false);
190 public RecipientId
resolveRecipient(
191 final String number
, Supplier
<ACI
> aciSupplier
192 ) throws UnregisteredRecipientException
{
193 final Optional
<Recipient
> byNumber
;
194 synchronized (recipients
) {
195 byNumber
= findByNumberLocked(number
);
197 if (byNumber
.isEmpty() || byNumber
.get().getAddress().uuid().isEmpty()) {
198 final var aci
= aciSupplier
.get();
200 throw new UnregisteredRecipientException(new RecipientAddress(null, number
));
203 return resolveRecipient(new RecipientAddress(aci
.uuid(), number
), false, false);
205 return byNumber
.get().getRecipientId();
208 public RecipientId
resolveRecipient(RecipientAddress address
) {
209 return resolveRecipient(address
, false, false);
213 public RecipientId
resolveRecipient(final SignalServiceAddress address
) {
214 return resolveRecipient(new RecipientAddress(address
), false, false);
217 public RecipientId
resolveSelfRecipientTrusted(RecipientAddress address
) {
218 return resolveRecipient(address
, true, true);
221 public RecipientId
resolveRecipientTrusted(RecipientAddress address
) {
222 return resolveRecipient(address
, true, false);
225 public RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
226 return resolveRecipient(new RecipientAddress(address
), true, false);
229 public List
<RecipientId
> resolveRecipientsTrusted(List
<RecipientAddress
> addresses
) {
230 final List
<RecipientId
> recipientIds
;
231 final List
<Pair
<RecipientId
, RecipientId
>> toBeMerged
= new ArrayList
<>();
232 synchronized (recipients
) {
233 recipientIds
= addresses
.stream().map(address
-> {
234 final var pair
= resolveRecipientLocked(address
, true, false);
235 if (pair
.second().isPresent()) {
236 toBeMerged
.add(new Pair
<>(pair
.first(), pair
.second().get()));
241 for (var pair
: toBeMerged
) {
242 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second());
248 public void storeContact(RecipientId recipientId
, final Contact contact
) {
249 synchronized (recipients
) {
250 final var recipient
= recipients
.get(recipientId
);
251 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withContact(contact
).build());
256 public Contact
getContact(RecipientId recipientId
) {
257 final var recipient
= getRecipient(recipientId
);
258 return recipient
== null ?
null : recipient
.getContact();
262 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
263 return recipients
.entrySet()
265 .filter(e
-> e
.getValue().getContact() != null)
266 .map(e
-> new Pair
<>(e
.getKey(), e
.getValue().getContact()))
271 public void deleteContact(RecipientId recipientId
) {
272 synchronized (recipients
) {
273 final var recipient
= recipients
.get(recipientId
);
274 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withContact(null).build());
278 public void deleteRecipientData(RecipientId recipientId
) {
279 synchronized (recipients
) {
280 logger
.debug("Deleting recipient data for {}", recipientId
);
281 final var recipient
= recipients
.get(recipientId
);
282 storeRecipientLocked(recipientId
,
283 Recipient
.newBuilder()
284 .withRecipientId(recipientId
)
285 .withAddress(new RecipientAddress(recipient
.getAddress().uuid().orElse(null)))
291 public Profile
getProfile(final RecipientId recipientId
) {
292 final var recipient
= getRecipient(recipientId
);
293 return recipient
== null ?
null : recipient
.getProfile();
297 public ProfileKey
getProfileKey(final RecipientId recipientId
) {
298 final var recipient
= getRecipient(recipientId
);
299 return recipient
== null ?
null : recipient
.getProfileKey();
303 public ProfileKeyCredential
getProfileKeyCredential(final RecipientId recipientId
) {
304 final var recipient
= getRecipient(recipientId
);
305 return recipient
== null ?
null : recipient
.getProfileKeyCredential();
309 public void storeProfile(RecipientId recipientId
, final Profile profile
) {
310 synchronized (recipients
) {
311 final var recipient
= recipients
.get(recipientId
);
312 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withProfile(profile
).build());
317 public void storeProfileKey(RecipientId recipientId
, final ProfileKey profileKey
) {
318 synchronized (recipients
) {
319 final var recipient
= recipients
.get(recipientId
);
320 if (profileKey
!= null && profileKey
.equals(recipient
.getProfileKey()) && (
321 recipient
.getProfile() == null || (
322 recipient
.getProfile().getUnidentifiedAccessMode() != Profile
.UnidentifiedAccessMode
.UNKNOWN
323 && recipient
.getProfile().getUnidentifiedAccessMode()
324 != Profile
.UnidentifiedAccessMode
.DISABLED
330 final var newRecipient
= Recipient
.newBuilder(recipient
)
331 .withProfileKey(profileKey
)
332 .withProfileKeyCredential(null)
333 .withProfile(recipient
.getProfile() == null
335 : Profile
.newBuilder(recipient
.getProfile()).withLastUpdateTimestamp(0).build())
337 storeRecipientLocked(recipientId
, newRecipient
);
342 public void storeProfileKeyCredential(RecipientId recipientId
, final ProfileKeyCredential profileKeyCredential
) {
343 synchronized (recipients
) {
344 final var recipient
= recipients
.get(recipientId
);
345 storeRecipientLocked(recipientId
,
346 Recipient
.newBuilder(recipient
).withProfileKeyCredential(profileKeyCredential
).build());
350 public boolean isEmpty() {
351 synchronized (recipients
) {
352 return recipients
.isEmpty();
356 private void addRecipients(final Map
<RecipientId
, Recipient
> recipients
) {
357 this.recipients
.putAll(recipients
);
361 * @param isHighTrust true, if the number/uuid connection was obtained from a trusted source.
362 * Has no effect, if the address contains only a number or a uuid.
364 private RecipientId
resolveRecipient(RecipientAddress address
, boolean isHighTrust
, boolean isSelf
) {
365 final Pair
<RecipientId
, Optional
<RecipientId
>> pair
;
366 synchronized (recipients
) {
367 pair
= resolveRecipientLocked(address
, isHighTrust
, isSelf
);
370 if (pair
.second().isPresent()) {
371 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second().get());
376 private Pair
<RecipientId
, Optional
<RecipientId
>> resolveRecipientLocked(
377 RecipientAddress address
, boolean isHighTrust
, boolean isSelf
379 if (isHighTrust
&& !isSelf
) {
380 if (selfAddressProvider
.getSelfAddress().matches(address
)) {
384 final var byNumber
= address
.number().isEmpty()
385 ? Optional
.<Recipient
>empty()
386 : findByNumberLocked(address
.number().get());
387 final var byUuid
= address
.uuid().isEmpty()
388 ? Optional
.<Recipient
>empty()
389 : findByUuidLocked(address
.uuid().get());
391 if (byNumber
.isEmpty() && byUuid
.isEmpty()) {
392 logger
.debug("Got new recipient, both uuid and number are unknown");
394 if (isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty()) {
395 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
398 return new Pair
<>(addNewRecipientLocked(new RecipientAddress(address
.uuid().get())), Optional
.empty());
401 if (!isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty() || byNumber
.equals(byUuid
)) {
402 return new Pair
<>(byUuid
.or(() -> byNumber
).map(Recipient
::getRecipientId
).get(), Optional
.empty());
405 if (byNumber
.isEmpty()) {
406 logger
.debug("Got recipient {} existing with uuid, updating with high trust number",
407 byUuid
.get().getRecipientId());
408 updateRecipientAddressLocked(byUuid
.get().getRecipientId(), address
);
409 return new Pair
<>(byUuid
.get().getRecipientId(), Optional
.empty());
412 final var byNumberRecipient
= byNumber
.get();
414 if (byUuid
.isEmpty()) {
415 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
417 "Got recipient {} existing with number, but different uuid, so stripping its number and adding new recipient",
418 byNumberRecipient
.getRecipientId());
420 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
421 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
422 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
425 logger
.debug("Got recipient {} existing with number and no uuid, updating with high trust uuid",
426 byNumberRecipient
.getRecipientId());
427 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(), address
);
428 return new Pair
<>(byNumberRecipient
.getRecipientId(), Optional
.empty());
431 final var byUuidRecipient
= byUuid
.get();
433 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
435 "Got separate recipients for high trust number {} and uuid {}, recipient for number has different uuid, so stripping its number",
436 byNumberRecipient
.getRecipientId(),
437 byUuidRecipient
.getRecipientId());
439 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
440 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
441 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
442 return new Pair
<>(byUuidRecipient
.getRecipientId(), Optional
.empty());
445 logger
.debug("Got separate recipients for high trust number {} and uuid {}, need to merge them",
446 byNumberRecipient
.getRecipientId(),
447 byUuidRecipient
.getRecipientId());
448 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
449 // Create a fixed RecipientId that won't update its id after merge
450 final var toBeMergedRecipientId
= new RecipientId(byNumberRecipient
.getRecipientId().id(), null);
451 mergeRecipientsLocked(byUuidRecipient
.getRecipientId(), toBeMergedRecipientId
);
452 return new Pair
<>(byUuidRecipient
.getRecipientId(), Optional
.of(toBeMergedRecipientId
));
455 private RecipientId
addNewRecipientLocked(final RecipientAddress address
) {
456 final var nextRecipientId
= nextIdLocked();
457 logger
.debug("Adding new recipient {} with address {}", nextRecipientId
, address
);
458 storeRecipientLocked(nextRecipientId
, new Recipient(nextRecipientId
, address
, null, null, null, null));
459 return nextRecipientId
;
462 private void updateRecipientAddressLocked(RecipientId recipientId
, final RecipientAddress address
) {
463 final var recipient
= recipients
.get(recipientId
);
464 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withAddress(address
).build());
467 long getActualRecipientId(long recipientId
) {
468 while (recipientsMerged
.containsKey(recipientId
)) {
469 final var newRecipientId
= recipientsMerged
.get(recipientId
);
470 logger
.debug("Using {} instead of {}, because recipients have been merged", newRecipientId
, recipientId
);
471 recipientId
= newRecipientId
;
476 private void storeRecipientLocked(final RecipientId recipientId
, final Recipient recipient
) {
477 final var existingRecipient
= recipients
.get(recipientId
);
478 if (existingRecipient
== null || !existingRecipient
.equals(recipient
)) {
479 recipients
.put(recipientId
, recipient
);
484 private void mergeRecipientsLocked(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
485 final var recipient
= recipients
.get(recipientId
);
486 final var toBeMergedRecipient
= recipients
.get(toBeMergedRecipientId
);
487 recipients
.put(recipientId
,
488 new Recipient(recipientId
,
489 recipient
.getAddress(),
490 recipient
.getContact() != null ? recipient
.getContact() : toBeMergedRecipient
.getContact(),
491 recipient
.getProfileKey() != null
492 ? recipient
.getProfileKey()
493 : toBeMergedRecipient
.getProfileKey(),
494 recipient
.getProfileKeyCredential() != null
495 ? recipient
.getProfileKeyCredential()
496 : toBeMergedRecipient
.getProfileKeyCredential(),
497 recipient
.getProfile() != null ? recipient
.getProfile() : toBeMergedRecipient
.getProfile()));
498 recipients
.remove(toBeMergedRecipientId
);
499 recipientsMerged
.put(toBeMergedRecipientId
.id(), recipientId
.id());
503 private Optional
<Recipient
> findByNumberLocked(final String number
) {
504 return recipients
.entrySet()
506 .filter(entry
-> entry
.getValue().getAddress().number().isPresent() && number
.equals(entry
.getValue()
511 .map(Map
.Entry
::getValue
);
514 private Optional
<Recipient
> findByUuidLocked(final UUID uuid
) {
515 return recipients
.entrySet()
517 .filter(entry
-> entry
.getValue().getAddress().uuid().isPresent() && uuid
.equals(entry
.getValue()
522 .map(Map
.Entry
::getValue
);
525 private RecipientId
nextIdLocked() {
526 return new RecipientId(++this.lastId
, this);
529 private void saveLocked() {
530 if (isBulkUpdating
) {
533 final var base64
= Base64
.getEncoder();
534 var storage
= new Storage(recipients
.entrySet().stream().map(pair
-> {
535 final var recipient
= pair
.getValue();
536 final var contact
= recipient
.getContact() == null
538 : new Storage
.Recipient
.Contact(recipient
.getContact().getName(),
539 recipient
.getContact().getColor(),
540 recipient
.getContact().getMessageExpirationTime(),
541 recipient
.getContact().isBlocked(),
542 recipient
.getContact().isArchived());
543 final var profile
= recipient
.getProfile() == null
545 : new Storage
.Recipient
.Profile(recipient
.getProfile().getLastUpdateTimestamp(),
546 recipient
.getProfile().getGivenName(),
547 recipient
.getProfile().getFamilyName(),
548 recipient
.getProfile().getAbout(),
549 recipient
.getProfile().getAboutEmoji(),
550 recipient
.getProfile().getAvatarUrlPath(),
551 recipient
.getProfile().getUnidentifiedAccessMode().name(),
552 recipient
.getProfile()
556 .collect(Collectors
.toSet()));
557 return new Storage
.Recipient(pair
.getKey().id(),
558 recipient
.getAddress().number().orElse(null),
559 recipient
.getAddress().uuid().map(UUID
::toString
).orElse(null),
560 recipient
.getProfileKey() == null
562 : base64
.encodeToString(recipient
.getProfileKey().serialize()),
563 recipient
.getProfileKeyCredential() == null
565 : base64
.encodeToString(recipient
.getProfileKeyCredential().serialize()),
568 }).toList(), lastId
);
570 // Write to memory first to prevent corrupting the file in case of serialization errors
571 try (var inMemoryOutput
= new ByteArrayOutputStream()) {
572 objectMapper
.writeValue(inMemoryOutput
, storage
);
574 var input
= new ByteArrayInputStream(inMemoryOutput
.toByteArray());
575 try (var outputStream
= new FileOutputStream(file
)) {
576 input
.transferTo(outputStream
);
578 } catch (Exception e
) {
579 logger
.error("Error saving recipient store file: {}", e
.getMessage());
583 private record Storage(List
<Recipient
> recipients
, long lastId
) {
585 private record Recipient(
590 String profileKeyCredential
,
591 Storage
.Recipient
.Contact contact
,
592 Storage
.Recipient
.Profile profile
595 private record Contact(
596 String name
, String color
, int messageExpirationTime
, boolean blocked
, boolean archived
599 private record Profile(
600 long lastUpdateTimestamp
,
605 String avatarUrlPath
,
606 String unidentifiedAccessMode
,
607 Set
<String
> capabilities
612 public interface RecipientMergeHandler
{
614 void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
);