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
.storage
.Utils
;
7 import org
.asamk
.signal
.manager
.storage
.contacts
.ContactsStore
;
8 import org
.asamk
.signal
.manager
.storage
.profiles
.ProfileStore
;
9 import org
.signal
.zkgroup
.InvalidInputException
;
10 import org
.signal
.zkgroup
.profiles
.ProfileKey
;
11 import org
.signal
.zkgroup
.profiles
.ProfileKeyCredential
;
12 import org
.slf4j
.Logger
;
13 import org
.slf4j
.LoggerFactory
;
14 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
15 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
16 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.UnregisteredUserException
;
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
<RecipientId
, RecipientId
> recipientsMerged
= new HashMap
<>();
51 public static RecipientStore
load(File file
, RecipientMergeHandler recipientMergeHandler
) throws IOException
{
52 final var objectMapper
= Utils
.createStorageObjectMapper();
53 try (var inputStream
= new FileInputStream(file
)) {
54 final var storage
= objectMapper
.readValue(inputStream
, Storage
.class);
55 final var recipients
= storage
.recipients
.stream().map(r
-> {
56 final var recipientId
= new RecipientId(r
.id
);
57 final var address
= new RecipientAddress(Optional
.ofNullable(r
.uuid
).map(UuidUtil
::parseOrThrow
),
58 Optional
.ofNullable(r
.number
));
60 Contact contact
= null;
61 if (r
.contact
!= null) {
62 contact
= new Contact(r
.contact
.name
,
64 r
.contact
.messageExpirationTime
,
69 ProfileKey profileKey
= null;
70 if (r
.profileKey
!= null) {
72 profileKey
= new ProfileKey(Base64
.getDecoder().decode(r
.profileKey
));
73 } catch (InvalidInputException ignored
) {
77 ProfileKeyCredential profileKeyCredential
= null;
78 if (r
.profileKeyCredential
!= null) {
80 profileKeyCredential
= new ProfileKeyCredential(Base64
.getDecoder()
81 .decode(r
.profileKeyCredential
));
82 } catch (Throwable ignored
) {
86 Profile profile
= null;
87 if (r
.profile
!= null) {
88 profile
= new Profile(r
.profile
.lastUpdateTimestamp
,
93 r
.profile
.avatarUrlPath
,
94 Profile
.UnidentifiedAccessMode
.valueOfOrUnknown(r
.profile
.unidentifiedAccessMode
),
95 r
.profile
.capabilities
.stream()
96 .map(Profile
.Capability
::valueOfOrNull
)
97 .filter(Objects
::nonNull
)
98 .collect(Collectors
.toSet()));
101 return new Recipient(recipientId
, address
, contact
, profileKey
, profileKeyCredential
, profile
);
102 }).collect(Collectors
.toMap(Recipient
::getRecipientId
, r
-> r
));
104 return new RecipientStore(objectMapper
, file
, recipientMergeHandler
, recipients
, storage
.lastId
);
105 } catch (FileNotFoundException e
) {
106 logger
.debug("Creating new recipient store.");
107 return new RecipientStore(objectMapper
, file
, recipientMergeHandler
, new HashMap
<>(), 0);
111 private RecipientStore(
112 final ObjectMapper objectMapper
,
114 final RecipientMergeHandler recipientMergeHandler
,
115 final Map
<RecipientId
, Recipient
> recipients
,
118 this.objectMapper
= objectMapper
;
120 this.recipientMergeHandler
= recipientMergeHandler
;
121 this.recipients
= recipients
;
122 this.lastId
= lastId
;
125 public RecipientAddress
resolveRecipientAddress(RecipientId recipientId
) {
126 synchronized (recipients
) {
127 return getRecipient(recipientId
).getAddress();
131 public Recipient
getRecipient(RecipientId recipientId
) {
132 synchronized (recipients
) {
133 return getRecipientLocked(recipientId
);
138 public RecipientId
resolveRecipient(ACI aci
) {
139 return resolveRecipient(new RecipientAddress(aci
== null ?
null : aci
.uuid()), false);
143 public RecipientId
resolveRecipient(final String identifier
) {
144 return resolveRecipient(Utils
.getRecipientAddressFromIdentifier(identifier
), false);
147 public RecipientId
resolveRecipient(
148 final String number
, Supplier
<ACI
> aciSupplier
149 ) throws UnregisteredUserException
{
150 final Optional
<Recipient
> byNumber
;
151 synchronized (recipients
) {
152 byNumber
= findByNumberLocked(number
);
154 if (byNumber
.isEmpty() || byNumber
.get().getAddress().uuid().isEmpty()) {
155 final var aci
= aciSupplier
.get();
157 throw new UnregisteredUserException(number
, null);
160 return resolveRecipient(new RecipientAddress(aci
.uuid(), number
), false);
162 return byNumber
.get().getRecipientId();
165 public RecipientId
resolveRecipient(RecipientAddress address
) {
166 return resolveRecipient(address
, false);
170 public RecipientId
resolveRecipient(final SignalServiceAddress address
) {
171 return resolveRecipient(new RecipientAddress(address
), false);
174 public RecipientId
resolveRecipientTrusted(RecipientAddress address
) {
175 return resolveRecipient(address
, true);
178 public RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
179 return resolveRecipient(new RecipientAddress(address
), true);
182 public List
<RecipientId
> resolveRecipientsTrusted(List
<RecipientAddress
> addresses
) {
183 final List
<RecipientId
> recipientIds
;
184 final List
<Pair
<RecipientId
, RecipientId
>> toBeMerged
= new ArrayList
<>();
185 synchronized (recipients
) {
186 recipientIds
= addresses
.stream().map(address
-> {
187 final var pair
= resolveRecipientLocked(address
, true);
188 if (pair
.second().isPresent()) {
189 toBeMerged
.add(new Pair
<>(pair
.first(), pair
.second().get()));
192 }).collect(Collectors
.toList());
194 for (var pair
: toBeMerged
) {
195 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second());
201 public void storeContact(final RecipientId recipientId
, final Contact contact
) {
202 synchronized (recipients
) {
203 final var recipient
= recipients
.get(recipientId
);
204 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withContact(contact
).build());
209 public Contact
getContact(final RecipientId recipientId
) {
210 final var recipient
= getRecipient(recipientId
);
211 return recipient
== null ?
null : recipient
.getContact();
215 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
216 return recipients
.entrySet()
218 .filter(e
-> e
.getValue().getContact() != null)
219 .map(e
-> new Pair
<>(e
.getKey(), e
.getValue().getContact()))
220 .collect(Collectors
.toList());
224 public void deleteContact(final RecipientId recipientId
) {
225 synchronized (recipients
) {
226 final var recipient
= recipients
.get(recipientId
);
227 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withContact(null).build());
231 public void deleteRecipientData(final RecipientId recipientId
) {
232 synchronized (recipients
) {
233 logger
.debug("Deleting recipient data for {}", recipientId
);
234 final var recipient
= recipients
.get(recipientId
);
235 storeRecipientLocked(recipientId
,
236 Recipient
.newBuilder()
237 .withRecipientId(recipientId
)
238 .withAddress(new RecipientAddress(recipient
.getAddress().uuid().orElse(null)))
244 public Profile
getProfile(final RecipientId recipientId
) {
245 final var recipient
= getRecipient(recipientId
);
246 return recipient
== null ?
null : recipient
.getProfile();
250 public ProfileKey
getProfileKey(final RecipientId recipientId
) {
251 final var recipient
= getRecipient(recipientId
);
252 return recipient
== null ?
null : recipient
.getProfileKey();
256 public ProfileKeyCredential
getProfileKeyCredential(final RecipientId recipientId
) {
257 final var recipient
= getRecipient(recipientId
);
258 return recipient
== null ?
null : recipient
.getProfileKeyCredential();
262 public void storeProfile(final RecipientId recipientId
, final Profile profile
) {
263 synchronized (recipients
) {
264 final var recipient
= recipients
.get(recipientId
);
265 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withProfile(profile
).build());
270 public void storeProfileKey(final RecipientId recipientId
, final ProfileKey profileKey
) {
271 synchronized (recipients
) {
272 final var recipient
= recipients
.get(recipientId
);
273 if (profileKey
!= null && profileKey
.equals(recipient
.getProfileKey())) {
277 final var newRecipient
= Recipient
.newBuilder(recipient
)
278 .withProfileKey(profileKey
)
279 .withProfileKeyCredential(null)
280 .withProfile(recipient
.getProfile() == null
282 : Profile
.newBuilder(recipient
.getProfile()).withLastUpdateTimestamp(0).build())
284 storeRecipientLocked(recipientId
, newRecipient
);
289 public void storeProfileKeyCredential(
290 final RecipientId recipientId
, final ProfileKeyCredential profileKeyCredential
292 synchronized (recipients
) {
293 final var recipient
= recipients
.get(recipientId
);
294 storeRecipientLocked(recipientId
,
295 Recipient
.newBuilder(recipient
).withProfileKeyCredential(profileKeyCredential
).build());
299 public boolean isEmpty() {
300 synchronized (recipients
) {
301 return recipients
.isEmpty();
306 * @param isHighTrust true, if the number/uuid connection was obtained from a trusted source.
307 * Has no effect, if the address contains only a number or a uuid.
309 private RecipientId
resolveRecipient(RecipientAddress address
, boolean isHighTrust
) {
310 final Pair
<RecipientId
, Optional
<RecipientId
>> pair
;
311 synchronized (recipients
) {
312 pair
= resolveRecipientLocked(address
, isHighTrust
);
315 if (pair
.second().isPresent()) {
316 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second().get());
321 private Pair
<RecipientId
, Optional
<RecipientId
>> resolveRecipientLocked(
322 RecipientAddress address
, boolean isHighTrust
324 final var byNumber
= address
.number().isEmpty()
325 ? Optional
.<Recipient
>empty()
326 : findByNumberLocked(address
.number().get());
327 final var byUuid
= address
.uuid().isEmpty()
328 ? Optional
.<Recipient
>empty()
329 : findByUuidLocked(address
.uuid().get());
331 if (byNumber
.isEmpty() && byUuid
.isEmpty()) {
332 logger
.debug("Got new recipient, both uuid and number are unknown");
334 if (isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty()) {
335 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
338 return new Pair
<>(addNewRecipientLocked(new RecipientAddress(address
.uuid().get())), Optional
.empty());
341 if (!isHighTrust
|| address
.uuid().isEmpty() || address
.number().isEmpty() || byNumber
.equals(byUuid
)) {
342 return new Pair
<>(byUuid
.or(() -> byNumber
).map(Recipient
::getRecipientId
).get(), Optional
.empty());
345 if (byNumber
.isEmpty()) {
346 logger
.debug("Got recipient {} existing with uuid, updating with high trust number",
347 byUuid
.get().getRecipientId());
348 updateRecipientAddressLocked(byUuid
.get().getRecipientId(), address
);
349 return new Pair
<>(byUuid
.get().getRecipientId(), Optional
.empty());
352 final var byNumberRecipient
= byNumber
.get();
354 if (byUuid
.isEmpty()) {
355 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
357 "Got recipient {} existing with number, but different uuid, so stripping its number and adding new recipient",
358 byNumberRecipient
.getRecipientId());
360 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
361 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
362 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
365 logger
.debug("Got recipient {} existing with number and no uuid, updating with high trust uuid",
366 byNumberRecipient
.getRecipientId());
367 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(), address
);
368 return new Pair
<>(byNumberRecipient
.getRecipientId(), Optional
.empty());
371 final var byUuidRecipient
= byUuid
.get();
373 if (byNumberRecipient
.getAddress().uuid().isPresent()) {
375 "Got separate recipients for high trust number {} and uuid {}, recipient for number has different uuid, so stripping its number",
376 byNumberRecipient
.getRecipientId(),
377 byUuidRecipient
.getRecipientId());
379 updateRecipientAddressLocked(byNumberRecipient
.getRecipientId(),
380 new RecipientAddress(byNumberRecipient
.getAddress().uuid().get()));
381 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
382 return new Pair
<>(byUuidRecipient
.getRecipientId(), Optional
.empty());
385 logger
.debug("Got separate recipients for high trust number {} and uuid {}, need to merge them",
386 byNumberRecipient
.getRecipientId(),
387 byUuidRecipient
.getRecipientId());
388 updateRecipientAddressLocked(byUuidRecipient
.getRecipientId(), address
);
389 mergeRecipientsLocked(byUuidRecipient
.getRecipientId(), byNumberRecipient
.getRecipientId());
390 recipientsMerged
.put(byNumberRecipient
.getRecipientId(), byUuidRecipient
.getRecipientId());
391 return new Pair
<>(byUuidRecipient
.getRecipientId(), byNumber
.map(Recipient
::getRecipientId
));
394 private RecipientId
addNewRecipientLocked(final RecipientAddress address
) {
395 final var nextRecipientId
= nextIdLocked();
396 logger
.debug("Adding new recipient {} with address {}", nextRecipientId
, address
);
397 storeRecipientLocked(nextRecipientId
, new Recipient(nextRecipientId
, address
, null, null, null, null));
398 return nextRecipientId
;
401 private void updateRecipientAddressLocked(
402 final RecipientId recipientId
, final RecipientAddress address
404 final var recipient
= recipients
.get(recipientId
);
405 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withAddress(address
).build());
408 private Recipient
getRecipientLocked(RecipientId recipientId
) {
409 while (recipientsMerged
.containsKey(recipientId
)) {
410 final var newRecipientId
= recipientsMerged
.get(recipientId
);
411 logger
.debug("Using {} instead of {}, because recipients have been merged", newRecipientId
, recipientId
);
412 recipientId
= newRecipientId
;
414 return recipients
.get(recipientId
);
417 private void storeRecipientLocked(
418 final RecipientId recipientId
, final Recipient recipient
420 final var existingRecipient
= getRecipientLocked(recipientId
);
421 if (existingRecipient
== null || !existingRecipient
.equals(recipient
)) {
422 recipients
.put(recipientId
, recipient
);
427 private void mergeRecipientsLocked(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
428 final var recipient
= recipients
.get(recipientId
);
429 final var toBeMergedRecipient
= recipients
.get(toBeMergedRecipientId
);
430 recipients
.put(recipientId
,
431 new Recipient(recipientId
,
432 recipient
.getAddress(),
433 recipient
.getContact() != null ? recipient
.getContact() : toBeMergedRecipient
.getContact(),
434 recipient
.getProfileKey() != null
435 ? recipient
.getProfileKey()
436 : toBeMergedRecipient
.getProfileKey(),
437 recipient
.getProfileKeyCredential() != null
438 ? recipient
.getProfileKeyCredential()
439 : toBeMergedRecipient
.getProfileKeyCredential(),
440 recipient
.getProfile() != null ? recipient
.getProfile() : toBeMergedRecipient
.getProfile()));
441 recipients
.remove(toBeMergedRecipientId
);
445 private Optional
<Recipient
> findByNumberLocked(final String number
) {
446 return recipients
.entrySet()
448 .filter(entry
-> entry
.getValue().getAddress().number().isPresent() && number
.equals(entry
.getValue()
453 .map(Map
.Entry
::getValue
);
456 private Optional
<Recipient
> findByUuidLocked(final UUID uuid
) {
457 return recipients
.entrySet()
459 .filter(entry
-> entry
.getValue().getAddress().uuid().isPresent() && uuid
.equals(entry
.getValue()
464 .map(Map
.Entry
::getValue
);
467 private RecipientId
nextIdLocked() {
468 return new RecipientId(++this.lastId
);
471 private void saveLocked() {
472 final var base64
= Base64
.getEncoder();
473 var storage
= new Storage(recipients
.entrySet().stream().map(pair
-> {
474 final var recipient
= pair
.getValue();
475 final var contact
= recipient
.getContact() == null
477 : new Storage
.Recipient
.Contact(recipient
.getContact().getName(),
478 recipient
.getContact().getColor(),
479 recipient
.getContact().getMessageExpirationTime(),
480 recipient
.getContact().isBlocked(),
481 recipient
.getContact().isArchived());
482 final var profile
= recipient
.getProfile() == null
484 : new Storage
.Recipient
.Profile(recipient
.getProfile().getLastUpdateTimestamp(),
485 recipient
.getProfile().getGivenName(),
486 recipient
.getProfile().getFamilyName(),
487 recipient
.getProfile().getAbout(),
488 recipient
.getProfile().getAboutEmoji(),
489 recipient
.getProfile().getAvatarUrlPath(),
490 recipient
.getProfile().getUnidentifiedAccessMode().name(),
491 recipient
.getProfile()
495 .collect(Collectors
.toSet()));
496 return new Storage
.Recipient(pair
.getKey().id(),
497 recipient
.getAddress().number().orElse(null),
498 recipient
.getAddress().uuid().map(UUID
::toString
).orElse(null),
499 recipient
.getProfileKey() == null
501 : base64
.encodeToString(recipient
.getProfileKey().serialize()),
502 recipient
.getProfileKeyCredential() == null
504 : base64
.encodeToString(recipient
.getProfileKeyCredential().serialize()),
507 }).collect(Collectors
.toList()), lastId
);
509 // Write to memory first to prevent corrupting the file in case of serialization errors
510 try (var inMemoryOutput
= new ByteArrayOutputStream()) {
511 objectMapper
.writeValue(inMemoryOutput
, storage
);
513 var input
= new ByteArrayInputStream(inMemoryOutput
.toByteArray());
514 try (var outputStream
= new FileOutputStream(file
)) {
515 input
.transferTo(outputStream
);
517 } catch (Exception e
) {
518 logger
.error("Error saving recipient store file: {}", e
.getMessage());
522 private record Storage(List
<Recipient
> recipients
, long lastId
) {
524 private record Recipient(
529 String profileKeyCredential
,
530 Storage
.Recipient
.Contact contact
,
531 Storage
.Recipient
.Profile profile
534 private record Contact(
535 String name
, String color
, int messageExpirationTime
, boolean blocked
, boolean archived
538 private record Profile(
539 long lastUpdateTimestamp
,
544 String avatarUrlPath
,
545 String unidentifiedAccessMode
,
546 Set
<String
> capabilities
551 public interface RecipientMergeHandler
{
553 void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
);