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
.SignalServiceAddress
;
17 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
19 import java
.io
.ByteArrayInputStream
;
20 import java
.io
.ByteArrayOutputStream
;
22 import java
.io
.FileInputStream
;
23 import java
.io
.FileNotFoundException
;
24 import java
.io
.FileOutputStream
;
25 import java
.io
.IOException
;
26 import java
.util
.ArrayList
;
27 import java
.util
.Base64
;
28 import java
.util
.HashMap
;
29 import java
.util
.List
;
31 import java
.util
.Objects
;
32 import java
.util
.Optional
;
34 import java
.util
.UUID
;
35 import java
.util
.function
.Supplier
;
36 import java
.util
.stream
.Collectors
;
38 public class RecipientStore
implements RecipientResolver
, ContactsStore
, ProfileStore
{
40 private final static Logger logger
= LoggerFactory
.getLogger(RecipientStore
.class);
42 private final ObjectMapper objectMapper
;
43 private final File file
;
44 private final RecipientMergeHandler recipientMergeHandler
;
46 private final Map
<RecipientId
, Recipient
> recipients
;
47 private final Map
<Long
, Long
> recipientsMerged
= new HashMap
<>();
50 private boolean isBulkUpdating
;
52 public static RecipientStore
load(File file
, RecipientMergeHandler recipientMergeHandler
) throws IOException
{
53 final var objectMapper
= Utils
.createStorageObjectMapper();
54 try (var inputStream
= new FileInputStream(file
)) {
55 final var storage
= objectMapper
.readValue(inputStream
, Storage
.class);
57 final var recipientStore
= new RecipientStore(objectMapper
,
59 recipientMergeHandler
,
62 final var recipients
= storage
.recipients
.stream().map(r
-> {
63 final var recipientId
= new RecipientId(r
.id
, recipientStore
);
64 final var address
= new RecipientAddress(Optional
.ofNullable(r
.uuid
).map(UuidUtil
::parseOrThrow
),
65 Optional
.ofNullable(r
.number
));
67 Contact contact
= null;
68 if (r
.contact
!= null) {
69 contact
= new Contact(r
.contact
.name
,
71 r
.contact
.messageExpirationTime
,
76 ProfileKey profileKey
= null;
77 if (r
.profileKey
!= null) {
79 profileKey
= new ProfileKey(Base64
.getDecoder().decode(r
.profileKey
));
80 } catch (InvalidInputException ignored
) {
84 ProfileKeyCredential profileKeyCredential
= null;
85 if (r
.profileKeyCredential
!= null) {
87 profileKeyCredential
= new ProfileKeyCredential(Base64
.getDecoder()
88 .decode(r
.profileKeyCredential
));
89 } catch (Throwable ignored
) {
93 Profile profile
= null;
94 if (r
.profile
!= null) {
95 profile
= new Profile(r
.profile
.lastUpdateTimestamp
,
100 r
.profile
.avatarUrlPath
,
101 Profile
.UnidentifiedAccessMode
.valueOfOrUnknown(r
.profile
.unidentifiedAccessMode
),
102 r
.profile
.capabilities
.stream()
103 .map(Profile
.Capability
::valueOfOrNull
)
104 .filter(Objects
::nonNull
)
105 .collect(Collectors
.toSet()));
108 return new Recipient(recipientId
, address
, contact
, profileKey
, profileKeyCredential
, profile
);
109 }).collect(Collectors
.toMap(Recipient
::getRecipientId
, r
-> r
));
111 recipientStore
.addRecipients(recipients
);
113 return recipientStore
;
114 } catch (FileNotFoundException e
) {
115 logger
.trace("Creating new recipient store.");
116 return new RecipientStore(objectMapper
, file
, recipientMergeHandler
, new HashMap
<>(), 0);
120 private RecipientStore(
121 final ObjectMapper objectMapper
,
123 final RecipientMergeHandler recipientMergeHandler
,
124 final Map
<RecipientId
, Recipient
> recipients
,
127 this.objectMapper
= objectMapper
;
129 this.recipientMergeHandler
= recipientMergeHandler
;
130 this.recipients
= recipients
;
131 this.lastId
= lastId
;
134 public boolean isBulkUpdating() {
135 return isBulkUpdating
;
138 public void setBulkUpdating(final boolean bulkUpdating
) {
139 isBulkUpdating
= bulkUpdating
;
141 synchronized (recipients
) {
147 public RecipientAddress
resolveRecipientAddress(RecipientId recipientId
) {
148 synchronized (recipients
) {
149 return getRecipient(recipientId
).getAddress();
153 public Recipient
getRecipient(RecipientId recipientId
) {
154 synchronized (recipients
) {
155 return recipients
.get(recipientId
);
160 public RecipientId
resolveRecipient(ACI aci
) {
161 return resolveRecipient(new RecipientAddress(aci
.uuid()), false);
165 public RecipientId
resolveRecipient(final long recipientId
) {
166 final var recipient
= getRecipient(new RecipientId(recipientId
, this));
167 return recipient
== null ?
null : recipient
.getRecipientId();
171 public RecipientId
resolveRecipient(final String identifier
) {
172 return resolveRecipient(Utils
.getRecipientAddressFromIdentifier(identifier
), false);
175 public RecipientId
resolveRecipient(
176 final String number
, Supplier
<ACI
> aciSupplier
177 ) throws UnregisteredRecipientException
{
178 final Optional
<Recipient
> byNumber
;
179 synchronized (recipients
) {
180 byNumber
= findByNumberLocked(number
);
182 if (byNumber
.isEmpty() || byNumber
.get().getAddress().uuid().isEmpty()) {
183 final var aci
= aciSupplier
.get();
185 throw new UnregisteredRecipientException(new RecipientAddress(null, number
));
188 return resolveRecipient(new RecipientAddress(aci
.uuid(), number
), false);
190 return byNumber
.get().getRecipientId();
193 public RecipientId
resolveRecipient(RecipientAddress address
) {
194 return resolveRecipient(address
, false);
198 public RecipientId
resolveRecipient(final SignalServiceAddress address
) {
199 return resolveRecipient(new RecipientAddress(address
), false);
202 public RecipientId
resolveRecipientTrusted(RecipientAddress address
) {
203 return resolveRecipient(address
, true);
206 public RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
207 return resolveRecipient(new RecipientAddress(address
), true);
210 public List
<RecipientId
> resolveRecipientsTrusted(List
<RecipientAddress
> addresses
) {
211 final List
<RecipientId
> recipientIds
;
212 final List
<Pair
<RecipientId
, RecipientId
>> toBeMerged
= new ArrayList
<>();
213 synchronized (recipients
) {
214 recipientIds
= addresses
.stream().map(address
-> {
215 final var pair
= resolveRecipientLocked(address
, true);
216 if (pair
.second().isPresent()) {
217 toBeMerged
.add(new Pair
<>(pair
.first(), pair
.second().get()));
222 for (var pair
: toBeMerged
) {
223 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second());
229 public void storeContact(RecipientId recipientId
, final Contact contact
) {
230 synchronized (recipients
) {
231 final var recipient
= recipients
.get(recipientId
);
232 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withContact(contact
).build());
237 public Contact
getContact(RecipientId recipientId
) {
238 final var recipient
= getRecipient(recipientId
);
239 return recipient
== null ?
null : recipient
.getContact();
243 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
244 return recipients
.entrySet()
246 .filter(e
-> e
.getValue().getContact() != null)
247 .map(e
-> new Pair
<>(e
.getKey(), e
.getValue().getContact()))
252 public void deleteContact(RecipientId recipientId
) {
253 synchronized (recipients
) {
254 final var recipient
= recipients
.get(recipientId
);
255 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withContact(null).build());
259 public void deleteRecipientData(RecipientId recipientId
) {
260 synchronized (recipients
) {
261 logger
.debug("Deleting recipient data for {}", recipientId
);
262 final var recipient
= recipients
.get(recipientId
);
263 storeRecipientLocked(recipientId
,
264 Recipient
.newBuilder()
265 .withRecipientId(recipientId
)
266 .withAddress(new RecipientAddress(recipient
.getAddress().uuid().orElse(null)))
272 public Profile
getProfile(final RecipientId recipientId
) {
273 final var recipient
= getRecipient(recipientId
);
274 return recipient
== null ?
null : recipient
.getProfile();
278 public ProfileKey
getProfileKey(final RecipientId recipientId
) {
279 final var recipient
= getRecipient(recipientId
);
280 return recipient
== null ?
null : recipient
.getProfileKey();
284 public ProfileKeyCredential
getProfileKeyCredential(final RecipientId recipientId
) {
285 final var recipient
= getRecipient(recipientId
);
286 return recipient
== null ?
null : recipient
.getProfileKeyCredential();
290 public void storeProfile(RecipientId recipientId
, final Profile profile
) {
291 synchronized (recipients
) {
292 final var recipient
= recipients
.get(recipientId
);
293 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withProfile(profile
).build());
298 public void storeProfileKey(RecipientId recipientId
, final ProfileKey profileKey
) {
299 synchronized (recipients
) {
300 final var recipient
= recipients
.get(recipientId
);
301 if (profileKey
!= null && profileKey
.equals(recipient
.getProfileKey())) {
305 final var newRecipient
= Recipient
.newBuilder(recipient
)
306 .withProfileKey(profileKey
)
307 .withProfileKeyCredential(null)
308 .withProfile(recipient
.getProfile() == null
310 : Profile
.newBuilder(recipient
.getProfile()).withLastUpdateTimestamp(0).build())
312 storeRecipientLocked(recipientId
, newRecipient
);
317 public void storeProfileKeyCredential(RecipientId recipientId
, final ProfileKeyCredential profileKeyCredential
) {
318 synchronized (recipients
) {
319 final var recipient
= recipients
.get(recipientId
);
320 storeRecipientLocked(recipientId
,
321 Recipient
.newBuilder(recipient
).withProfileKeyCredential(profileKeyCredential
).build());
325 public boolean isEmpty() {
326 synchronized (recipients
) {
327 return recipients
.isEmpty();
331 private void addRecipients(final Map
<RecipientId
, Recipient
> recipients
) {
332 this.recipients
.putAll(recipients
);
336 * @param isHighTrust true, if the number/uuid connection was obtained from a trusted source.
337 * Has no effect, if the address contains only a number or a uuid.
339 private RecipientId
resolveRecipient(RecipientAddress address
, boolean isHighTrust
) {
340 final Pair
<RecipientId
, Optional
<RecipientId
>> pair
;
341 synchronized (recipients
) {
342 pair
= resolveRecipientLocked(address
, isHighTrust
);
345 if (pair
.second().isPresent()) {
346 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second().get());
351 private Pair
<RecipientId
, Optional
<RecipientId
>> resolveRecipientLocked(
352 RecipientAddress address
, boolean isHighTrust
354 final var byNumber
= address
.number().isEmpty()
355 ? Optional
.<Recipient
>empty()
356 : findByNumberLocked(address
.number().get());
357 final var byUuid
= address
.uuid().isEmpty()
358 ? Optional
.<Recipient
>empty()
359 : findByUuidLocked(address
.uuid().get());
361 if (byNumber
.isEmpty() && byUuid
.isEmpty()) {
362 logger
.debug("Got new recipient, both uuid and number are unknown");
364 if (isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty()) {
365 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
368 return new Pair
<>(addNewRecipientLocked(new RecipientAddress(address
.uuid().get())), Optional
.empty());
371 if (!isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty() || byNumber
.equals(byUuid
)) {
372 return new Pair
<>(byUuid
.or(() -> byNumber
).map(Recipient
::getRecipientId
).get(), Optional
.empty());
375 if (byNumber
.isEmpty()) {
376 logger
.debug("Got recipient {} existing with uuid, updating with high trust number",
377 byUuid
.get().getRecipientId());
378 updateRecipientAddressLocked(byUuid
.get().getRecipientId(), address
);
379 return new Pair
<>(byUuid
.get().getRecipientId(), Optional
.empty());
382 final var byNumberRecipient
= byNumber
.get();
384 if (byUuid
.isEmpty()) {
385 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
387 "Got recipient {} existing with number, but different uuid, so stripping its number and adding new recipient",
388 byNumberRecipient
.getRecipientId());
390 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
391 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
392 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
395 logger
.debug("Got recipient {} existing with number and no uuid, updating with high trust uuid",
396 byNumberRecipient
.getRecipientId());
397 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(), address
);
398 return new Pair
<>(byNumberRecipient
.getRecipientId(), Optional
.empty());
401 final var byUuidRecipient
= byUuid
.get();
403 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
405 "Got separate recipients for high trust number {} and uuid {}, recipient for number has different uuid, so stripping its number",
406 byNumberRecipient
.getRecipientId(),
407 byUuidRecipient
.getRecipientId());
409 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
410 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
411 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
412 return new Pair
<>(byUuidRecipient
.getRecipientId(), Optional
.empty());
415 logger
.debug("Got separate recipients for high trust number {} and uuid {}, need to merge them",
416 byNumberRecipient
.getRecipientId(),
417 byUuidRecipient
.getRecipientId());
418 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
419 // Create a fixed RecipientId that won't update its id after merge
420 final var toBeMergedRecipientId
= new RecipientId(byNumberRecipient
.getRecipientId().id(), null);
421 mergeRecipientsLocked(byUuidRecipient
.getRecipientId(), toBeMergedRecipientId
);
422 return new Pair
<>(byUuidRecipient
.getRecipientId(), Optional
.of(toBeMergedRecipientId
));
425 private RecipientId
addNewRecipientLocked(final RecipientAddress address
) {
426 final var nextRecipientId
= nextIdLocked();
427 logger
.debug("Adding new recipient {} with address {}", nextRecipientId
, address
);
428 storeRecipientLocked(nextRecipientId
, new Recipient(nextRecipientId
, address
, null, null, null, null));
429 return nextRecipientId
;
432 private void updateRecipientAddressLocked(RecipientId recipientId
, final RecipientAddress address
) {
433 final var recipient
= recipients
.get(recipientId
);
434 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withAddress(address
).build());
437 long getActualRecipientId(long recipientId
) {
438 while (recipientsMerged
.containsKey(recipientId
)) {
439 final var newRecipientId
= recipientsMerged
.get(recipientId
);
440 logger
.debug("Using {} instead of {}, because recipients have been merged", newRecipientId
, recipientId
);
441 recipientId
= newRecipientId
;
446 private void storeRecipientLocked(final RecipientId recipientId
, final Recipient recipient
) {
447 final var existingRecipient
= recipients
.get(recipientId
);
448 if (existingRecipient
== null || !existingRecipient
.equals(recipient
)) {
449 recipients
.put(recipientId
, recipient
);
454 private void mergeRecipientsLocked(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
455 final var recipient
= recipients
.get(recipientId
);
456 final var toBeMergedRecipient
= recipients
.get(toBeMergedRecipientId
);
457 recipients
.put(recipientId
,
458 new Recipient(recipientId
,
459 recipient
.getAddress(),
460 recipient
.getContact() != null ? recipient
.getContact() : toBeMergedRecipient
.getContact(),
461 recipient
.getProfileKey() != null
462 ? recipient
.getProfileKey()
463 : toBeMergedRecipient
.getProfileKey(),
464 recipient
.getProfileKeyCredential() != null
465 ? recipient
.getProfileKeyCredential()
466 : toBeMergedRecipient
.getProfileKeyCredential(),
467 recipient
.getProfile() != null ? recipient
.getProfile() : toBeMergedRecipient
.getProfile()));
468 recipients
.remove(toBeMergedRecipientId
);
469 recipientsMerged
.put(toBeMergedRecipientId
.id(), recipientId
.id());
473 private Optional
<Recipient
> findByNumberLocked(final String number
) {
474 return recipients
.entrySet()
476 .filter(entry
-> entry
.getValue().getAddress().number().isPresent() && number
.equals(entry
.getValue()
481 .map(Map
.Entry
::getValue
);
484 private Optional
<Recipient
> findByUuidLocked(final UUID uuid
) {
485 return recipients
.entrySet()
487 .filter(entry
-> entry
.getValue().getAddress().uuid().isPresent() && uuid
.equals(entry
.getValue()
492 .map(Map
.Entry
::getValue
);
495 private RecipientId
nextIdLocked() {
496 return new RecipientId(++this.lastId
, this);
499 private void saveLocked() {
500 if (isBulkUpdating
) {
503 final var base64
= Base64
.getEncoder();
504 var storage
= new Storage(recipients
.entrySet().stream().map(pair
-> {
505 final var recipient
= pair
.getValue();
506 final var contact
= recipient
.getContact() == null
508 : new Storage
.Recipient
.Contact(recipient
.getContact().getName(),
509 recipient
.getContact().getColor(),
510 recipient
.getContact().getMessageExpirationTime(),
511 recipient
.getContact().isBlocked(),
512 recipient
.getContact().isArchived());
513 final var profile
= recipient
.getProfile() == null
515 : new Storage
.Recipient
.Profile(recipient
.getProfile().getLastUpdateTimestamp(),
516 recipient
.getProfile().getGivenName(),
517 recipient
.getProfile().getFamilyName(),
518 recipient
.getProfile().getAbout(),
519 recipient
.getProfile().getAboutEmoji(),
520 recipient
.getProfile().getAvatarUrlPath(),
521 recipient
.getProfile().getUnidentifiedAccessMode().name(),
522 recipient
.getProfile()
526 .collect(Collectors
.toSet()));
527 return new Storage
.Recipient(pair
.getKey().id(),
528 recipient
.getAddress().number().orElse(null),
529 recipient
.getAddress().uuid().map(UUID
::toString
).orElse(null),
530 recipient
.getProfileKey() == null
532 : base64
.encodeToString(recipient
.getProfileKey().serialize()),
533 recipient
.getProfileKeyCredential() == null
535 : base64
.encodeToString(recipient
.getProfileKeyCredential().serialize()),
538 }).toList(), lastId
);
540 // Write to memory first to prevent corrupting the file in case of serialization errors
541 try (var inMemoryOutput
= new ByteArrayOutputStream()) {
542 objectMapper
.writeValue(inMemoryOutput
, storage
);
544 var input
= new ByteArrayInputStream(inMemoryOutput
.toByteArray());
545 try (var outputStream
= new FileOutputStream(file
)) {
546 input
.transferTo(outputStream
);
548 } catch (Exception e
) {
549 logger
.error("Error saving recipient store file: {}", e
.getMessage());
553 private record Storage(List
<Recipient
> recipients
, long lastId
) {
555 private record Recipient(
560 String profileKeyCredential
,
561 Storage
.Recipient
.Contact contact
,
562 Storage
.Recipient
.Profile profile
565 private record Contact(
566 String name
, String color
, int messageExpirationTime
, boolean blocked
, boolean archived
569 private record Profile(
570 long lastUpdateTimestamp
,
575 String avatarUrlPath
,
576 String unidentifiedAccessMode
,
577 Set
<String
> capabilities
582 public interface RecipientMergeHandler
{
584 void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
);