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
.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 recipient
.getAddress()
284 .ifPresent(uuid
-> storeRecipientLocked(recipientId
,
285 Recipient
.newBuilder()
286 .withRecipientId(recipientId
)
287 .withAddress(new RecipientAddress(uuid
))
293 public Profile
getProfile(final RecipientId recipientId
) {
294 final var recipient
= getRecipient(recipientId
);
295 return recipient
== null ?
null : recipient
.getProfile();
299 public ProfileKey
getProfileKey(final RecipientId recipientId
) {
300 final var recipient
= getRecipient(recipientId
);
301 return recipient
== null ?
null : recipient
.getProfileKey();
305 public ProfileKeyCredential
getProfileKeyCredential(final RecipientId recipientId
) {
306 final var recipient
= getRecipient(recipientId
);
307 return recipient
== null ?
null : recipient
.getProfileKeyCredential();
311 public void storeProfile(RecipientId recipientId
, final Profile profile
) {
312 synchronized (recipients
) {
313 final var recipient
= recipients
.get(recipientId
);
314 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withProfile(profile
).build());
319 public void storeProfileKey(RecipientId recipientId
, final ProfileKey profileKey
) {
320 synchronized (recipients
) {
321 final var recipient
= recipients
.get(recipientId
);
322 if (profileKey
!= null && profileKey
.equals(recipient
.getProfileKey()) && (
323 recipient
.getProfile() == null || (
324 recipient
.getProfile().getUnidentifiedAccessMode() != Profile
.UnidentifiedAccessMode
.UNKNOWN
325 && recipient
.getProfile().getUnidentifiedAccessMode()
326 != Profile
.UnidentifiedAccessMode
.DISABLED
332 final var newRecipient
= Recipient
.newBuilder(recipient
)
333 .withProfileKey(profileKey
)
334 .withProfileKeyCredential(null)
335 .withProfile(recipient
.getProfile() == null
337 : Profile
.newBuilder(recipient
.getProfile()).withLastUpdateTimestamp(0).build())
339 storeRecipientLocked(recipientId
, newRecipient
);
344 public void storeProfileKeyCredential(RecipientId recipientId
, final ProfileKeyCredential profileKeyCredential
) {
345 synchronized (recipients
) {
346 final var recipient
= recipients
.get(recipientId
);
347 storeRecipientLocked(recipientId
,
348 Recipient
.newBuilder(recipient
).withProfileKeyCredential(profileKeyCredential
).build());
352 public boolean isEmpty() {
353 synchronized (recipients
) {
354 return recipients
.isEmpty();
358 private void addRecipients(final Map
<RecipientId
, Recipient
> recipients
) {
359 this.recipients
.putAll(recipients
);
363 * @param isHighTrust true, if the number/uuid connection was obtained from a trusted source.
364 * Has no effect, if the address contains only a number or a uuid.
366 private RecipientId
resolveRecipient(RecipientAddress address
, boolean isHighTrust
, boolean isSelf
) {
367 final Pair
<RecipientId
, Optional
<RecipientId
>> pair
;
368 synchronized (recipients
) {
369 pair
= resolveRecipientLocked(address
, isHighTrust
, isSelf
);
372 if (pair
.second().isPresent()) {
373 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second().get());
378 private Pair
<RecipientId
, Optional
<RecipientId
>> resolveRecipientLocked(
379 RecipientAddress address
, boolean isHighTrust
, boolean isSelf
381 if (isHighTrust
&& !isSelf
) {
382 if (selfAddressProvider
.getSelfAddress().matches(address
)) {
386 final var byNumber
= address
.number().isEmpty()
387 ? Optional
.<Recipient
>empty()
388 : findByNumberLocked(address
.number().get());
389 final var byUuid
= address
.uuid().isEmpty()
390 ? Optional
.<Recipient
>empty()
391 : findByUuidLocked(address
.uuid().get());
393 if (byNumber
.isEmpty() && byUuid
.isEmpty()) {
394 logger
.debug("Got new recipient, both uuid and number are unknown");
396 if (isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty()) {
397 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
400 return new Pair
<>(addNewRecipientLocked(new RecipientAddress(address
.uuid().get())), Optional
.empty());
403 if (!isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty() || byNumber
.equals(byUuid
)) {
404 return new Pair
<>(byUuid
.or(() -> byNumber
).map(Recipient
::getRecipientId
).get(), Optional
.empty());
407 if (byNumber
.isEmpty()) {
408 logger
.debug("Got recipient {} existing with uuid, updating with high trust number",
409 byUuid
.get().getRecipientId());
410 updateRecipientAddressLocked(byUuid
.get().getRecipientId(), address
);
411 return new Pair
<>(byUuid
.get().getRecipientId(), Optional
.empty());
414 final var byNumberRecipient
= byNumber
.get();
416 if (byUuid
.isEmpty()) {
417 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
419 "Got recipient {} existing with number, but different uuid, so stripping its number and adding new recipient",
420 byNumberRecipient
.getRecipientId());
422 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
423 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
424 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
427 logger
.debug("Got recipient {} existing with number and no uuid, updating with high trust uuid",
428 byNumberRecipient
.getRecipientId());
429 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(), address
);
430 return new Pair
<>(byNumberRecipient
.getRecipientId(), Optional
.empty());
433 final var byUuidRecipient
= byUuid
.get();
435 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
437 "Got separate recipients for high trust number {} and uuid {}, recipient for number has different uuid, so stripping its number",
438 byNumberRecipient
.getRecipientId(),
439 byUuidRecipient
.getRecipientId());
441 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
442 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
443 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
444 return new Pair
<>(byUuidRecipient
.getRecipientId(), Optional
.empty());
447 logger
.debug("Got separate recipients for high trust number {} and uuid {}, need to merge them",
448 byNumberRecipient
.getRecipientId(),
449 byUuidRecipient
.getRecipientId());
450 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
451 // Create a fixed RecipientId that won't update its id after merge
452 final var toBeMergedRecipientId
= new RecipientId(byNumberRecipient
.getRecipientId().id(), null);
453 mergeRecipientsLocked(byUuidRecipient
.getRecipientId(), toBeMergedRecipientId
);
454 return new Pair
<>(byUuidRecipient
.getRecipientId(), Optional
.of(toBeMergedRecipientId
));
457 private RecipientId
addNewRecipientLocked(final RecipientAddress address
) {
458 final var nextRecipientId
= nextIdLocked();
459 logger
.debug("Adding new recipient {} with address {}", nextRecipientId
, address
);
460 storeRecipientLocked(nextRecipientId
, new Recipient(nextRecipientId
, address
, null, null, null, null));
461 return nextRecipientId
;
464 private void updateRecipientAddressLocked(RecipientId recipientId
, final RecipientAddress address
) {
465 final var recipient
= recipients
.get(recipientId
);
466 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withAddress(address
).build());
469 long getActualRecipientId(long recipientId
) {
470 while (recipientsMerged
.containsKey(recipientId
)) {
471 final var newRecipientId
= recipientsMerged
.get(recipientId
);
472 logger
.debug("Using {} instead of {}, because recipients have been merged", newRecipientId
, recipientId
);
473 recipientId
= newRecipientId
;
478 private void storeRecipientLocked(final RecipientId recipientId
, final Recipient recipient
) {
479 final var existingRecipient
= recipients
.get(recipientId
);
480 if (existingRecipient
== null || !existingRecipient
.equals(recipient
)) {
481 recipients
.put(recipientId
, recipient
);
486 private void mergeRecipientsLocked(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
487 final var recipient
= recipients
.get(recipientId
);
488 final var toBeMergedRecipient
= recipients
.get(toBeMergedRecipientId
);
489 recipients
.put(recipientId
,
490 new Recipient(recipientId
,
491 recipient
.getAddress(),
492 recipient
.getContact() != null ? recipient
.getContact() : toBeMergedRecipient
.getContact(),
493 recipient
.getProfileKey() != null
494 ? recipient
.getProfileKey()
495 : toBeMergedRecipient
.getProfileKey(),
496 recipient
.getProfileKeyCredential() != null
497 ? recipient
.getProfileKeyCredential()
498 : toBeMergedRecipient
.getProfileKeyCredential(),
499 recipient
.getProfile() != null ? recipient
.getProfile() : toBeMergedRecipient
.getProfile()));
500 recipients
.remove(toBeMergedRecipientId
);
501 recipientsMerged
.put(toBeMergedRecipientId
.id(), recipientId
.id());
505 private Optional
<Recipient
> findByNumberLocked(final String number
) {
506 return recipients
.entrySet()
508 .filter(entry
-> entry
.getValue().getAddress().number().isPresent() && number
.equals(entry
.getValue()
513 .map(Map
.Entry
::getValue
);
516 private Optional
<Recipient
> findByUuidLocked(final UUID uuid
) {
517 return recipients
.entrySet()
519 .filter(entry
-> entry
.getValue().getAddress().uuid().isPresent() && uuid
.equals(entry
.getValue()
524 .map(Map
.Entry
::getValue
);
527 private RecipientId
nextIdLocked() {
528 return new RecipientId(++this.lastId
, this);
531 private void saveLocked() {
532 if (isBulkUpdating
) {
535 final var base64
= Base64
.getEncoder();
536 var storage
= new Storage(recipients
.entrySet().stream().map(pair
-> {
537 final var recipient
= pair
.getValue();
538 final var contact
= recipient
.getContact() == null
540 : new Storage
.Recipient
.Contact(recipient
.getContact().getName(),
541 recipient
.getContact().getColor(),
542 recipient
.getContact().getMessageExpirationTime(),
543 recipient
.getContact().isBlocked(),
544 recipient
.getContact().isArchived());
545 final var profile
= recipient
.getProfile() == null
547 : new Storage
.Recipient
.Profile(recipient
.getProfile().getLastUpdateTimestamp(),
548 recipient
.getProfile().getGivenName(),
549 recipient
.getProfile().getFamilyName(),
550 recipient
.getProfile().getAbout(),
551 recipient
.getProfile().getAboutEmoji(),
552 recipient
.getProfile().getAvatarUrlPath(),
553 recipient
.getProfile().getUnidentifiedAccessMode().name(),
554 recipient
.getProfile()
558 .collect(Collectors
.toSet()));
559 return new Storage
.Recipient(pair
.getKey().id(),
560 recipient
.getAddress().number().orElse(null),
561 recipient
.getAddress().uuid().map(UUID
::toString
).orElse(null),
562 recipient
.getProfileKey() == null
564 : base64
.encodeToString(recipient
.getProfileKey().serialize()),
565 recipient
.getProfileKeyCredential() == null
567 : base64
.encodeToString(recipient
.getProfileKeyCredential().serialize()),
570 }).toList(), lastId
);
572 // Write to memory first to prevent corrupting the file in case of serialization errors
573 try (var inMemoryOutput
= new ByteArrayOutputStream()) {
574 objectMapper
.writeValue(inMemoryOutput
, storage
);
576 var input
= new ByteArrayInputStream(inMemoryOutput
.toByteArray());
577 try (var outputStream
= new FileOutputStream(file
)) {
578 input
.transferTo(outputStream
);
580 } catch (Exception e
) {
581 logger
.error("Error saving recipient store file: {}", e
.getMessage());
585 private record Storage(List
<Recipient
> recipients
, long lastId
) {
587 private record Recipient(
592 String profileKeyCredential
,
593 Storage
.Recipient
.Contact contact
,
594 Storage
.Recipient
.Profile profile
597 private record Contact(
598 String name
, String color
, int messageExpirationTime
, boolean blocked
, boolean archived
601 private record Profile(
602 long lastUpdateTimestamp
,
607 String avatarUrlPath
,
608 String unidentifiedAccessMode
,
609 Set
<String
> capabilities
614 public interface RecipientMergeHandler
{
616 void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
);