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 while (recipientsMerged
.containsKey(recipientId
)) {
134 recipientId
= recipientsMerged
.get(recipientId
);
136 return recipients
.get(recipientId
);
141 public RecipientId
resolveRecipient(ACI aci
) {
142 return resolveRecipient(new RecipientAddress(aci
== null ?
null : aci
.uuid()), false);
146 public RecipientId
resolveRecipient(final String identifier
) {
147 return resolveRecipient(Utils
.getRecipientAddressFromIdentifier(identifier
), false);
150 public RecipientId
resolveRecipient(
151 final String number
, Supplier
<ACI
> aciSupplier
152 ) throws UnregisteredUserException
{
153 final Optional
<Recipient
> byNumber
;
154 synchronized (recipients
) {
155 byNumber
= findByNumberLocked(number
);
157 if (byNumber
.isEmpty() || byNumber
.get().getAddress().getUuid().isEmpty()) {
158 final var aci
= aciSupplier
.get();
160 throw new UnregisteredUserException(number
, null);
163 return resolveRecipient(new RecipientAddress(aci
.uuid(), number
), false);
165 return byNumber
.get().getRecipientId();
168 public RecipientId
resolveRecipient(RecipientAddress address
) {
169 return resolveRecipient(address
, false);
173 public RecipientId
resolveRecipient(final SignalServiceAddress address
) {
174 return resolveRecipient(new RecipientAddress(address
), false);
177 public RecipientId
resolveRecipientTrusted(RecipientAddress address
) {
178 return resolveRecipient(address
, true);
181 public RecipientId
resolveRecipientTrusted(SignalServiceAddress address
) {
182 return resolveRecipient(new RecipientAddress(address
), true);
185 public List
<RecipientId
> resolveRecipientsTrusted(List
<RecipientAddress
> addresses
) {
186 final List
<RecipientId
> recipientIds
;
187 final List
<Pair
<RecipientId
, RecipientId
>> toBeMerged
= new ArrayList
<>();
188 synchronized (recipients
) {
189 recipientIds
= addresses
.stream().map(address
-> {
190 final var pair
= resolveRecipientLocked(address
, true);
191 if (pair
.second().isPresent()) {
192 toBeMerged
.add(new Pair
<>(pair
.first(), pair
.second().get()));
195 }).collect(Collectors
.toList());
197 for (var pair
: toBeMerged
) {
198 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second());
204 public void storeContact(final RecipientId recipientId
, final Contact contact
) {
205 synchronized (recipients
) {
206 final var recipient
= recipients
.get(recipientId
);
207 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withContact(contact
).build());
212 public Contact
getContact(final RecipientId recipientId
) {
213 final var recipient
= getRecipient(recipientId
);
214 return recipient
== null ?
null : recipient
.getContact();
218 public List
<Pair
<RecipientId
, Contact
>> getContacts() {
219 return recipients
.entrySet()
221 .filter(e
-> e
.getValue().getContact() != null)
222 .map(e
-> new Pair
<>(e
.getKey(), e
.getValue().getContact()))
223 .collect(Collectors
.toList());
227 public Profile
getProfile(final RecipientId recipientId
) {
228 final var recipient
= getRecipient(recipientId
);
229 return recipient
== null ?
null : recipient
.getProfile();
233 public ProfileKey
getProfileKey(final RecipientId recipientId
) {
234 final var recipient
= getRecipient(recipientId
);
235 return recipient
== null ?
null : recipient
.getProfileKey();
239 public ProfileKeyCredential
getProfileKeyCredential(final RecipientId recipientId
) {
240 final var recipient
= getRecipient(recipientId
);
241 return recipient
== null ?
null : recipient
.getProfileKeyCredential();
245 public void storeProfile(final RecipientId recipientId
, final Profile profile
) {
246 synchronized (recipients
) {
247 final var recipient
= recipients
.get(recipientId
);
248 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withProfile(profile
).build());
253 public void storeProfileKey(final RecipientId recipientId
, final ProfileKey profileKey
) {
254 synchronized (recipients
) {
255 final var recipient
= recipients
.get(recipientId
);
256 if (profileKey
!= null && profileKey
.equals(recipient
.getProfileKey())) {
260 final var newRecipient
= Recipient
.newBuilder(recipient
)
261 .withProfileKey(profileKey
)
262 .withProfileKeyCredential(null)
263 .withProfile(recipient
.getProfile() == null
265 : Profile
.newBuilder(recipient
.getProfile()).withLastUpdateTimestamp(0).build())
267 storeRecipientLocked(recipientId
, newRecipient
);
272 public void storeProfileKeyCredential(
273 final RecipientId recipientId
, final ProfileKeyCredential profileKeyCredential
275 synchronized (recipients
) {
276 final var recipient
= recipients
.get(recipientId
);
277 storeRecipientLocked(recipientId
,
278 Recipient
.newBuilder(recipient
).withProfileKeyCredential(profileKeyCredential
).build());
282 public boolean isEmpty() {
283 synchronized (recipients
) {
284 return recipients
.isEmpty();
289 * @param isHighTrust true, if the number/uuid connection was obtained from a trusted source.
290 * Has no effect, if the address contains only a number or a uuid.
292 private RecipientId
resolveRecipient(RecipientAddress address
, boolean isHighTrust
) {
293 final Pair
<RecipientId
, Optional
<RecipientId
>> pair
;
294 synchronized (recipients
) {
295 pair
= resolveRecipientLocked(address
, isHighTrust
);
296 if (pair
.second().isPresent()) {
297 recipientsMerged
.put(pair
.second().get(), pair
.first());
301 if (pair
.second().isPresent()) {
302 recipientMergeHandler
.mergeRecipients(pair
.first(), pair
.second().get());
307 private Pair
<RecipientId
, Optional
<RecipientId
>> resolveRecipientLocked(
308 RecipientAddress address
, boolean isHighTrust
310 final var byNumber
= address
.getNumber().isEmpty()
311 ? Optional
.<Recipient
>empty()
312 : findByNumberLocked(address
.getNumber().get());
313 final var byUuid
= address
.getUuid().isEmpty()
314 ? Optional
.<Recipient
>empty()
315 : findByUuidLocked(address
.getUuid().get());
317 if (byNumber
.isEmpty() && byUuid
.isEmpty()) {
318 logger
.debug("Got new recipient, both uuid and number are unknown");
320 if (isHighTrust
|| address
.getUuid().isEmpty() || address
.getNumber().isEmpty()) {
321 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
324 return new Pair
<>(addNewRecipientLocked(new RecipientAddress(address
.getUuid().get())), Optional
.empty());
327 if (!isHighTrust
|| address
.getUuid().isEmpty() || address
.getNumber().isEmpty() || byNumber
.equals(byUuid
)) {
328 return new Pair
<>(byUuid
.or(() -> byNumber
).map(Recipient
::getRecipientId
).get(), Optional
.empty());
331 if (byNumber
.isEmpty()) {
332 logger
.debug("Got recipient existing with uuid, updating with high trust number");
333 updateRecipientAddressLocked(byUuid
.get().getRecipientId(), address
);
334 return new Pair
<>(byUuid
.get().getRecipientId(), Optional
.empty());
337 if (byUuid
.isEmpty()) {
338 if (byNumber
.get().getAddress().getUuid().isPresent()) {
340 "Got recipient existing with number, but different uuid, so stripping its number and adding new recipient");
342 updateRecipientAddressLocked(byNumber
.get().getRecipientId(),
343 new RecipientAddress(byNumber
.get().getAddress().getUuid().get()));
344 return new Pair
<>(addNewRecipientLocked(address
), Optional
.empty());
347 logger
.debug("Got recipient existing with number and no uuid, updating with high trust uuid");
348 updateRecipientAddressLocked(byNumber
.get().getRecipientId(), address
);
349 return new Pair
<>(byNumber
.get().getRecipientId(), Optional
.empty());
352 if (byNumber
.get().getAddress().getUuid().isPresent()) {
354 "Got separate recipients for high trust number and uuid, recipient for number has different uuid, so stripping its number");
356 updateRecipientAddressLocked(byNumber
.get().getRecipientId(),
357 new RecipientAddress(byNumber
.get().getAddress().getUuid().get()));
358 updateRecipientAddressLocked(byUuid
.get().getRecipientId(), address
);
359 return new Pair
<>(byUuid
.get().getRecipientId(), Optional
.empty());
362 logger
.debug("Got separate recipients for high trust number and uuid, need to merge them");
363 updateRecipientAddressLocked(byUuid
.get().getRecipientId(), address
);
364 mergeRecipientsLocked(byUuid
.get().getRecipientId(), byNumber
.get().getRecipientId());
365 return new Pair
<>(byUuid
.get().getRecipientId(), byNumber
.map(Recipient
::getRecipientId
));
368 private RecipientId
addNewRecipientLocked(final RecipientAddress address
) {
369 final var nextRecipientId
= nextIdLocked();
370 storeRecipientLocked(nextRecipientId
, new Recipient(nextRecipientId
, address
, null, null, null, null));
371 return nextRecipientId
;
374 private void updateRecipientAddressLocked(
375 final RecipientId recipientId
, final RecipientAddress address
377 final var recipient
= recipients
.get(recipientId
);
378 storeRecipientLocked(recipientId
, Recipient
.newBuilder(recipient
).withAddress(address
).build());
381 private void storeRecipientLocked(
382 final RecipientId recipientId
, final Recipient recipient
384 recipients
.put(recipientId
, recipient
);
388 private void mergeRecipientsLocked(RecipientId recipientId
, RecipientId toBeMergedRecipientId
) {
389 final var recipient
= recipients
.get(recipientId
);
390 final var toBeMergedRecipient
= recipients
.get(toBeMergedRecipientId
);
391 recipients
.put(recipientId
,
392 new Recipient(recipientId
,
393 recipient
.getAddress(),
394 recipient
.getContact() != null ? recipient
.getContact() : toBeMergedRecipient
.getContact(),
395 recipient
.getProfileKey() != null
396 ? recipient
.getProfileKey()
397 : toBeMergedRecipient
.getProfileKey(),
398 recipient
.getProfileKeyCredential() != null
399 ? recipient
.getProfileKeyCredential()
400 : toBeMergedRecipient
.getProfileKeyCredential(),
401 recipient
.getProfile() != null ? recipient
.getProfile() : toBeMergedRecipient
.getProfile()));
402 recipients
.remove(toBeMergedRecipientId
);
406 private Optional
<Recipient
> findByNumberLocked(final String number
) {
407 return recipients
.entrySet()
409 .filter(entry
-> entry
.getValue().getAddress().getNumber().isPresent() && number
.equals(entry
.getValue()
414 .map(Map
.Entry
::getValue
);
417 private Optional
<Recipient
> findByUuidLocked(final UUID uuid
) {
418 return recipients
.entrySet()
420 .filter(entry
-> entry
.getValue().getAddress().getUuid().isPresent() && uuid
.equals(entry
.getValue()
425 .map(Map
.Entry
::getValue
);
428 private RecipientId
nextIdLocked() {
429 return new RecipientId(++this.lastId
);
432 private void saveLocked() {
433 final var base64
= Base64
.getEncoder();
434 var storage
= new Storage(recipients
.entrySet().stream().map(pair
-> {
435 final var recipient
= pair
.getValue();
436 final var contact
= recipient
.getContact() == null
438 : new Storage
.Recipient
.Contact(recipient
.getContact().getName(),
439 recipient
.getContact().getColor(),
440 recipient
.getContact().getMessageExpirationTime(),
441 recipient
.getContact().isBlocked(),
442 recipient
.getContact().isArchived());
443 final var profile
= recipient
.getProfile() == null
445 : new Storage
.Recipient
.Profile(recipient
.getProfile().getLastUpdateTimestamp(),
446 recipient
.getProfile().getGivenName(),
447 recipient
.getProfile().getFamilyName(),
448 recipient
.getProfile().getAbout(),
449 recipient
.getProfile().getAboutEmoji(),
450 recipient
.getProfile().getAvatarUrlPath(),
451 recipient
.getProfile().getUnidentifiedAccessMode().name(),
452 recipient
.getProfile()
456 .collect(Collectors
.toSet()));
457 return new Storage
.Recipient(pair
.getKey().id(),
458 recipient
.getAddress().getNumber().orElse(null),
459 recipient
.getAddress().getUuid().map(UUID
::toString
).orElse(null),
460 recipient
.getProfileKey() == null
462 : base64
.encodeToString(recipient
.getProfileKey().serialize()),
463 recipient
.getProfileKeyCredential() == null
465 : base64
.encodeToString(recipient
.getProfileKeyCredential().serialize()),
468 }).collect(Collectors
.toList()), lastId
);
470 // Write to memory first to prevent corrupting the file in case of serialization errors
471 try (var inMemoryOutput
= new ByteArrayOutputStream()) {
472 objectMapper
.writeValue(inMemoryOutput
, storage
);
474 var input
= new ByteArrayInputStream(inMemoryOutput
.toByteArray());
475 try (var outputStream
= new FileOutputStream(file
)) {
476 input
.transferTo(outputStream
);
478 } catch (Exception e
) {
479 logger
.error("Error saving recipient store file: {}", e
.getMessage());
483 private record Storage(List
<Recipient
> recipients
, long lastId
) {
485 private record Recipient(
490 String profileKeyCredential
,
491 Storage
.Recipient
.Contact contact
,
492 Storage
.Recipient
.Profile profile
495 private record Contact(
496 String name
, String color
, int messageExpirationTime
, boolean blocked
, boolean archived
499 private record Profile(
500 long lastUpdateTimestamp
,
505 String avatarUrlPath
,
506 String unidentifiedAccessMode
,
507 Set
<String
> capabilities
512 public interface RecipientMergeHandler
{
514 void mergeRecipients(RecipientId recipientId
, RecipientId toBeMergedRecipientId
);