]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/storage/recipients/RecipientStore.java
9c13459b8707d39b4314341658784b59a15ff466
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / storage / recipients / RecipientStore.java
1 package org.asamk.signal.manager.storage.recipients;
2
3 import org.asamk.signal.manager.api.Contact;
4 import org.asamk.signal.manager.api.Pair;
5 import org.asamk.signal.manager.api.Profile;
6 import org.asamk.signal.manager.api.UnregisteredRecipientException;
7 import org.asamk.signal.manager.storage.Database;
8 import org.asamk.signal.manager.storage.Utils;
9 import org.asamk.signal.manager.storage.contacts.ContactsStore;
10 import org.asamk.signal.manager.storage.profiles.ProfileStore;
11 import org.signal.libsignal.zkgroup.InvalidInputException;
12 import org.signal.libsignal.zkgroup.profiles.ExpiringProfileKeyCredential;
13 import org.signal.libsignal.zkgroup.profiles.ProfileKey;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16 import org.whispersystems.signalservice.api.push.ACI;
17 import org.whispersystems.signalservice.api.push.PNI;
18 import org.whispersystems.signalservice.api.push.ServiceId;
19 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
20 import org.whispersystems.signalservice.api.util.UuidUtil;
21
22 import java.sql.Connection;
23 import java.sql.ResultSet;
24 import java.sql.SQLException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Objects;
32 import java.util.Optional;
33 import java.util.Set;
34 import java.util.function.Supplier;
35 import java.util.stream.Collectors;
36
37 public class RecipientStore implements RecipientIdCreator, RecipientResolver, RecipientTrustedResolver, ContactsStore, ProfileStore {
38
39 private final static Logger logger = LoggerFactory.getLogger(RecipientStore.class);
40 private static final String TABLE_RECIPIENT = "recipient";
41 private static final String SQL_IS_CONTACT = "r.given_name IS NOT NULL OR r.family_name IS NOT NULL OR r.expiration_time > 0 OR r.profile_sharing = TRUE OR r.color IS NOT NULL OR r.blocked = TRUE OR r.archived = TRUE";
42
43 private final RecipientMergeHandler recipientMergeHandler;
44 private final SelfAddressProvider selfAddressProvider;
45 private final Database database;
46
47 private final Object recipientsLock = new Object();
48 private final Map<Long, Long> recipientsMerged = new HashMap<>();
49
50 public static void createSql(Connection connection) throws SQLException {
51 // When modifying the CREATE statement here, also add a migration in AccountDatabase.java
52 try (final var statement = connection.createStatement()) {
53 statement.executeUpdate("""
54 CREATE TABLE recipient (
55 _id INTEGER PRIMARY KEY AUTOINCREMENT,
56 number TEXT UNIQUE,
57 username TEXT UNIQUE,
58 uuid BLOB UNIQUE,
59 pni BLOB UNIQUE,
60 profile_key BLOB,
61 profile_key_credential BLOB,
62
63 given_name TEXT,
64 family_name TEXT,
65 color TEXT,
66
67 expiration_time INTEGER NOT NULL DEFAULT 0,
68 blocked INTEGER NOT NULL DEFAULT FALSE,
69 archived INTEGER NOT NULL DEFAULT FALSE,
70 profile_sharing INTEGER NOT NULL DEFAULT FALSE,
71
72 profile_last_update_timestamp INTEGER NOT NULL DEFAULT 0,
73 profile_given_name TEXT,
74 profile_family_name TEXT,
75 profile_about TEXT,
76 profile_about_emoji TEXT,
77 profile_avatar_url_path TEXT,
78 profile_mobile_coin_address BLOB,
79 profile_unidentified_access_mode TEXT,
80 profile_capabilities TEXT
81 ) STRICT;
82 """);
83 }
84 }
85
86 public RecipientStore(
87 final RecipientMergeHandler recipientMergeHandler,
88 final SelfAddressProvider selfAddressProvider,
89 final Database database
90 ) {
91 this.recipientMergeHandler = recipientMergeHandler;
92 this.selfAddressProvider = selfAddressProvider;
93 this.database = database;
94 }
95
96 public RecipientAddress resolveRecipientAddress(RecipientId recipientId) {
97 final var sql = (
98 """
99 SELECT r.number, r.uuid, r.pni, r.username
100 FROM %s r
101 WHERE r._id = ?
102 """
103 ).formatted(TABLE_RECIPIENT);
104 try (final var connection = database.getConnection()) {
105 try (final var statement = connection.prepareStatement(sql)) {
106 statement.setLong(1, recipientId.id());
107 return Utils.executeQuerySingleRow(statement, this::getRecipientAddressFromResultSet);
108 }
109 } catch (SQLException e) {
110 throw new RuntimeException("Failed read from recipient store", e);
111 }
112 }
113
114 public Collection<RecipientId> getRecipientIdsWithEnabledProfileSharing() {
115 final var sql = (
116 """
117 SELECT r._id
118 FROM %s r
119 WHERE r.blocked = FALSE AND r.profile_sharing = TRUE
120 """
121 ).formatted(TABLE_RECIPIENT);
122 try (final var connection = database.getConnection()) {
123 try (final var statement = connection.prepareStatement(sql)) {
124 try (var result = Utils.executeQueryForStream(statement, this::getRecipientIdFromResultSet)) {
125 return result.toList();
126 }
127 }
128 } catch (SQLException e) {
129 throw new RuntimeException("Failed read from recipient store", e);
130 }
131 }
132
133 @Override
134 public RecipientId resolveRecipient(final long rawRecipientId) {
135 final var sql = (
136 """
137 SELECT r._id
138 FROM %s r
139 WHERE r._id = ?
140 """
141 ).formatted(TABLE_RECIPIENT);
142 try (final var connection = database.getConnection()) {
143 try (final var statement = connection.prepareStatement(sql)) {
144 statement.setLong(1, rawRecipientId);
145 return Utils.executeQueryForOptional(statement, this::getRecipientIdFromResultSet).orElse(null);
146 }
147 } catch (SQLException e) {
148 throw new RuntimeException("Failed read from recipient store", e);
149 }
150 }
151
152 @Override
153 public RecipientId resolveRecipient(final String identifier) {
154 if (UuidUtil.isUuid(identifier)) {
155 return resolveRecipient(ServiceId.parseOrThrow(identifier));
156 } else {
157 return resolveRecipientByNumber(identifier);
158 }
159 }
160
161 private RecipientId resolveRecipientByNumber(final String number) {
162 synchronized (recipientsLock) {
163 final RecipientId recipientId;
164 try (final var connection = database.getConnection()) {
165 connection.setAutoCommit(false);
166 recipientId = resolveRecipientLocked(connection, number);
167 connection.commit();
168 } catch (SQLException e) {
169 throw new RuntimeException("Failed read recipient store", e);
170 }
171 return recipientId;
172 }
173 }
174
175 @Override
176 public RecipientId resolveRecipient(final ServiceId serviceId) {
177 synchronized (recipientsLock) {
178 final RecipientId recipientId;
179 try (final var connection = database.getConnection()) {
180 connection.setAutoCommit(false);
181 recipientId = resolveRecipientLocked(connection, serviceId);
182 connection.commit();
183 } catch (SQLException e) {
184 throw new RuntimeException("Failed read recipient store", e);
185 }
186 return recipientId;
187 }
188 }
189
190 /**
191 * Should only be used for recipientIds from the database.
192 * Where the foreign key relations ensure a valid recipientId.
193 */
194 @Override
195 public RecipientId create(final long recipientId) {
196 return new RecipientId(recipientId, this);
197 }
198
199 public RecipientId resolveRecipientByNumber(
200 final String number, Supplier<ServiceId> serviceIdSupplier
201 ) throws UnregisteredRecipientException {
202 final Optional<RecipientWithAddress> byNumber;
203 try (final var connection = database.getConnection()) {
204 byNumber = findByNumber(connection, number);
205 } catch (SQLException e) {
206 throw new RuntimeException("Failed read from recipient store", e);
207 }
208 if (byNumber.isEmpty() || byNumber.get().address().serviceId().isEmpty()) {
209 final var serviceId = serviceIdSupplier.get();
210 if (serviceId == null) {
211 throw new UnregisteredRecipientException(new org.asamk.signal.manager.api.RecipientAddress(null,
212 number));
213 }
214
215 return resolveRecipient(serviceId);
216 }
217 return byNumber.get().id();
218 }
219
220 public Optional<RecipientId> resolveRecipientByNumberOptional(final String number) {
221 final Optional<RecipientWithAddress> byNumber;
222 try (final var connection = database.getConnection()) {
223 byNumber = findByNumber(connection, number);
224 } catch (SQLException e) {
225 throw new RuntimeException("Failed read from recipient store", e);
226 }
227 return byNumber.map(RecipientWithAddress::id);
228 }
229
230 public RecipientId resolveRecipientByUsername(
231 final String username, Supplier<ServiceId> serviceIdSupplier
232 ) throws UnregisteredRecipientException {
233 final Optional<RecipientWithAddress> byUsername;
234 try (final var connection = database.getConnection()) {
235 byUsername = findByUsername(connection, username);
236 } catch (SQLException e) {
237 throw new RuntimeException("Failed read from recipient store", e);
238 }
239 if (byUsername.isEmpty() || byUsername.get().address().serviceId().isEmpty()) {
240 final var serviceId = serviceIdSupplier.get();
241 if (serviceId == null) {
242 throw new UnregisteredRecipientException(new org.asamk.signal.manager.api.RecipientAddress(null,
243 null,
244 username));
245 }
246
247 return resolveRecipient(serviceId);
248 }
249 return byUsername.get().id();
250 }
251
252 public RecipientId resolveRecipient(RecipientAddress address) {
253 synchronized (recipientsLock) {
254 final RecipientId recipientId;
255 try (final var connection = database.getConnection()) {
256 connection.setAutoCommit(false);
257 recipientId = resolveRecipientLocked(connection, address);
258 connection.commit();
259 } catch (SQLException e) {
260 throw new RuntimeException("Failed read recipient store", e);
261 }
262 return recipientId;
263 }
264 }
265
266 @Override
267 public RecipientId resolveSelfRecipientTrusted(RecipientAddress address) {
268 return resolveRecipientTrusted(address, true);
269 }
270
271 public RecipientId resolveRecipientTrusted(RecipientAddress address) {
272 return resolveRecipientTrusted(address, false);
273 }
274
275 @Override
276 public RecipientId resolveRecipientTrusted(SignalServiceAddress address) {
277 return resolveRecipientTrusted(new RecipientAddress(address), false);
278 }
279
280 @Override
281 public RecipientId resolveRecipientTrusted(
282 final Optional<ACI> aci, final Optional<PNI> pni, final Optional<String> number
283 ) {
284 final var serviceId = aci.map(a -> (ServiceId) a).or(() -> pni);
285 return resolveRecipientTrusted(new RecipientAddress(serviceId, pni, number, Optional.empty()), false);
286 }
287
288 @Override
289 public RecipientId resolveRecipientTrusted(final ServiceId serviceId, final String username) {
290 return resolveRecipientTrusted(new RecipientAddress(serviceId, null, null, username), false);
291 }
292
293 public RecipientId resolveRecipientTrusted(
294 final ACI aci, final String username
295 ) {
296 return resolveRecipientTrusted(new RecipientAddress(Optional.of(aci),
297 Optional.empty(),
298 Optional.empty(),
299 Optional.of(username)), false);
300 }
301
302 @Override
303 public void storeContact(RecipientId recipientId, final Contact contact) {
304 try (final var connection = database.getConnection()) {
305 storeContact(connection, recipientId, contact);
306 } catch (SQLException e) {
307 throw new RuntimeException("Failed update recipient store", e);
308 }
309 }
310
311 @Override
312 public Contact getContact(RecipientId recipientId) {
313 try (final var connection = database.getConnection()) {
314 return getContact(connection, recipientId);
315 } catch (SQLException e) {
316 throw new RuntimeException("Failed read from recipient store", e);
317 }
318 }
319
320 @Override
321 public List<Pair<RecipientId, Contact>> getContacts() {
322 final var sql = (
323 """
324 SELECT r._id, r.given_name, r.family_name, r.expiration_time, r.profile_sharing, r.color, r.blocked, r.archived
325 FROM %s r
326 WHERE (r.number IS NOT NULL OR r.uuid IS NOT NULL) AND %s
327 """
328 ).formatted(TABLE_RECIPIENT, SQL_IS_CONTACT);
329 try (final var connection = database.getConnection()) {
330 try (final var statement = connection.prepareStatement(sql)) {
331 try (var result = Utils.executeQueryForStream(statement,
332 resultSet -> new Pair<>(getRecipientIdFromResultSet(resultSet),
333 getContactFromResultSet(resultSet)))) {
334 return result.toList();
335 }
336 }
337 } catch (SQLException e) {
338 throw new RuntimeException("Failed read from recipient store", e);
339 }
340 }
341
342 public List<Recipient> getRecipients(
343 boolean onlyContacts, Optional<Boolean> blocked, Set<RecipientId> recipientIds, Optional<String> name
344 ) {
345 final var sqlWhere = new ArrayList<String>();
346 if (onlyContacts) {
347 sqlWhere.add("(" + SQL_IS_CONTACT + ")");
348 }
349 if (blocked.isPresent()) {
350 sqlWhere.add("r.blocked = ?");
351 }
352 if (!recipientIds.isEmpty()) {
353 final var recipientIdsCommaSeparated = recipientIds.stream()
354 .map(recipientId -> String.valueOf(recipientId.id()))
355 .collect(Collectors.joining(","));
356 sqlWhere.add("r._id IN (" + recipientIdsCommaSeparated + ")");
357 }
358 final var sql = (
359 """
360 SELECT r._id,
361 r.number, r.uuid, r.pni, r.username,
362 r.profile_key, r.profile_key_credential,
363 r.given_name, r.family_name, r.expiration_time, r.profile_sharing, r.color, r.blocked, r.archived,
364 r.profile_last_update_timestamp, r.profile_given_name, r.profile_family_name, r.profile_about, r.profile_about_emoji, r.profile_avatar_url_path, r.profile_mobile_coin_address, r.profile_unidentified_access_mode, r.profile_capabilities
365 FROM %s r
366 WHERE (r.number IS NOT NULL OR r.uuid IS NOT NULL) AND %s
367 """
368 ).formatted(TABLE_RECIPIENT, sqlWhere.size() == 0 ? "TRUE" : String.join(" AND ", sqlWhere));
369 try (final var connection = database.getConnection()) {
370 try (final var statement = connection.prepareStatement(sql)) {
371 if (blocked.isPresent()) {
372 statement.setBoolean(1, blocked.get());
373 }
374 try (var result = Utils.executeQueryForStream(statement, this::getRecipientFromResultSet)) {
375 return result.filter(r -> name.isEmpty() || (
376 r.getContact() != null && name.get().equals(r.getContact().getName())
377 ) || (r.getProfile() != null && name.get().equals(r.getProfile().getDisplayName()))).toList();
378 }
379 }
380 } catch (SQLException e) {
381 throw new RuntimeException("Failed read from recipient store", e);
382 }
383 }
384
385 public Map<ServiceId, ProfileKey> getServiceIdToProfileKeyMap() {
386 final var sql = (
387 """
388 SELECT r.uuid, r.profile_key
389 FROM %s r
390 WHERE r.uuid IS NOT NULL AND r.profile_key IS NOT NULL
391 """
392 ).formatted(TABLE_RECIPIENT);
393 try (final var connection = database.getConnection()) {
394 try (final var statement = connection.prepareStatement(sql)) {
395 return Utils.executeQueryForStream(statement, resultSet -> {
396 final var serviceId = ServiceId.parseOrThrow(resultSet.getBytes("uuid"));
397 final var profileKey = getProfileKeyFromResultSet(resultSet);
398 return new Pair<>(serviceId, profileKey);
399 }).filter(Objects::nonNull).collect(Collectors.toMap(Pair::first, Pair::second));
400 }
401 } catch (SQLException e) {
402 throw new RuntimeException("Failed read from recipient store", e);
403 }
404 }
405
406 @Override
407 public void deleteContact(RecipientId recipientId) {
408 storeContact(recipientId, null);
409 }
410
411 public void deleteRecipientData(RecipientId recipientId) {
412 logger.debug("Deleting recipient data for {}", recipientId);
413 try (final var connection = database.getConnection()) {
414 connection.setAutoCommit(false);
415 storeContact(connection, recipientId, null);
416 storeProfile(connection, recipientId, null);
417 storeProfileKey(connection, recipientId, null, false);
418 storeExpiringProfileKeyCredential(connection, recipientId, null);
419 deleteRecipient(connection, recipientId);
420 connection.commit();
421 } catch (SQLException e) {
422 throw new RuntimeException("Failed update recipient store", e);
423 }
424 }
425
426 @Override
427 public Profile getProfile(final RecipientId recipientId) {
428 try (final var connection = database.getConnection()) {
429 return getProfile(connection, recipientId);
430 } catch (SQLException e) {
431 throw new RuntimeException("Failed read from recipient store", e);
432 }
433 }
434
435 @Override
436 public ProfileKey getProfileKey(final RecipientId recipientId) {
437 try (final var connection = database.getConnection()) {
438 return getProfileKey(connection, recipientId);
439 } catch (SQLException e) {
440 throw new RuntimeException("Failed read from recipient store", e);
441 }
442 }
443
444 @Override
445 public ExpiringProfileKeyCredential getExpiringProfileKeyCredential(final RecipientId recipientId) {
446 try (final var connection = database.getConnection()) {
447 return getExpiringProfileKeyCredential(connection, recipientId);
448 } catch (SQLException e) {
449 throw new RuntimeException("Failed read from recipient store", e);
450 }
451 }
452
453 @Override
454 public void storeProfile(RecipientId recipientId, final Profile profile) {
455 try (final var connection = database.getConnection()) {
456 storeProfile(connection, recipientId, profile);
457 } catch (SQLException e) {
458 throw new RuntimeException("Failed update recipient store", e);
459 }
460 }
461
462 @Override
463 public void storeSelfProfileKey(final RecipientId recipientId, final ProfileKey profileKey) {
464 try (final var connection = database.getConnection()) {
465 storeProfileKey(connection, recipientId, profileKey, false);
466 } catch (SQLException e) {
467 throw new RuntimeException("Failed update recipient store", e);
468 }
469 }
470
471 @Override
472 public void storeProfileKey(RecipientId recipientId, final ProfileKey profileKey) {
473 try (final var connection = database.getConnection()) {
474 storeProfileKey(connection, recipientId, profileKey, true);
475 } catch (SQLException e) {
476 throw new RuntimeException("Failed update recipient store", e);
477 }
478 }
479
480 @Override
481 public void storeExpiringProfileKeyCredential(
482 RecipientId recipientId, final ExpiringProfileKeyCredential profileKeyCredential
483 ) {
484 try (final var connection = database.getConnection()) {
485 storeExpiringProfileKeyCredential(connection, recipientId, profileKeyCredential);
486 } catch (SQLException e) {
487 throw new RuntimeException("Failed update recipient store", e);
488 }
489 }
490
491 void addLegacyRecipients(final Map<RecipientId, Recipient> recipients) {
492 logger.debug("Migrating legacy recipients to database");
493 long start = System.nanoTime();
494 final var sql = (
495 """
496 INSERT INTO %s (_id, number, uuid)
497 VALUES (?, ?, ?)
498 """
499 ).formatted(TABLE_RECIPIENT);
500 try (final var connection = database.getConnection()) {
501 connection.setAutoCommit(false);
502 try (final var statement = connection.prepareStatement("DELETE FROM %s".formatted(TABLE_RECIPIENT))) {
503 statement.executeUpdate();
504 }
505 try (final var statement = connection.prepareStatement(sql)) {
506 for (final var recipient : recipients.values()) {
507 statement.setLong(1, recipient.getRecipientId().id());
508 statement.setString(2, recipient.getAddress().number().orElse(null));
509 statement.setBytes(3,
510 recipient.getAddress()
511 .serviceId()
512 .map(ServiceId::uuid)
513 .map(UuidUtil::toByteArray)
514 .orElse(null));
515 statement.executeUpdate();
516 }
517 }
518 logger.debug("Initial inserts took {}ms", (System.nanoTime() - start) / 1000000);
519
520 for (final var recipient : recipients.values()) {
521 if (recipient.getContact() != null) {
522 storeContact(connection, recipient.getRecipientId(), recipient.getContact());
523 }
524 if (recipient.getProfile() != null) {
525 storeProfile(connection, recipient.getRecipientId(), recipient.getProfile());
526 }
527 if (recipient.getProfileKey() != null) {
528 storeProfileKey(connection, recipient.getRecipientId(), recipient.getProfileKey(), false);
529 }
530 if (recipient.getExpiringProfileKeyCredential() != null) {
531 storeExpiringProfileKeyCredential(connection,
532 recipient.getRecipientId(),
533 recipient.getExpiringProfileKeyCredential());
534 }
535 }
536 connection.commit();
537 } catch (SQLException e) {
538 throw new RuntimeException("Failed update recipient store", e);
539 }
540 logger.debug("Complete recipients migration took {}ms", (System.nanoTime() - start) / 1000000);
541 }
542
543 long getActualRecipientId(long recipientId) {
544 while (recipientsMerged.containsKey(recipientId)) {
545 final var newRecipientId = recipientsMerged.get(recipientId);
546 logger.debug("Using {} instead of {}, because recipients have been merged", newRecipientId, recipientId);
547 recipientId = newRecipientId;
548 }
549 return recipientId;
550 }
551
552 private void storeContact(
553 final Connection connection, final RecipientId recipientId, final Contact contact
554 ) throws SQLException {
555 final var sql = (
556 """
557 UPDATE %s
558 SET given_name = ?, family_name = ?, expiration_time = ?, profile_sharing = ?, color = ?, blocked = ?, archived = ?
559 WHERE _id = ?
560 """
561 ).formatted(TABLE_RECIPIENT);
562 try (final var statement = connection.prepareStatement(sql)) {
563 statement.setString(1, contact == null ? null : contact.getGivenName());
564 statement.setString(2, contact == null ? null : contact.getFamilyName());
565 statement.setInt(3, contact == null ? 0 : contact.getMessageExpirationTime());
566 statement.setBoolean(4, contact != null && contact.isProfileSharingEnabled());
567 statement.setString(5, contact == null ? null : contact.getColor());
568 statement.setBoolean(6, contact != null && contact.isBlocked());
569 statement.setBoolean(7, contact != null && contact.isArchived());
570 statement.setLong(8, recipientId.id());
571 statement.executeUpdate();
572 }
573 }
574
575 private void storeExpiringProfileKeyCredential(
576 final Connection connection,
577 final RecipientId recipientId,
578 final ExpiringProfileKeyCredential profileKeyCredential
579 ) throws SQLException {
580 final var sql = (
581 """
582 UPDATE %s
583 SET profile_key_credential = ?
584 WHERE _id = ?
585 """
586 ).formatted(TABLE_RECIPIENT);
587 try (final var statement = connection.prepareStatement(sql)) {
588 statement.setBytes(1, profileKeyCredential == null ? null : profileKeyCredential.serialize());
589 statement.setLong(2, recipientId.id());
590 statement.executeUpdate();
591 }
592 }
593
594 private void storeProfile(
595 final Connection connection, final RecipientId recipientId, final Profile profile
596 ) throws SQLException {
597 final var sql = (
598 """
599 UPDATE %s
600 SET profile_last_update_timestamp = ?, profile_given_name = ?, profile_family_name = ?, profile_about = ?, profile_about_emoji = ?, profile_avatar_url_path = ?, profile_mobile_coin_address = ?, profile_unidentified_access_mode = ?, profile_capabilities = ?
601 WHERE _id = ?
602 """
603 ).formatted(TABLE_RECIPIENT);
604 try (final var statement = connection.prepareStatement(sql)) {
605 statement.setLong(1, profile == null ? 0 : profile.getLastUpdateTimestamp());
606 statement.setString(2, profile == null ? null : profile.getGivenName());
607 statement.setString(3, profile == null ? null : profile.getFamilyName());
608 statement.setString(4, profile == null ? null : profile.getAbout());
609 statement.setString(5, profile == null ? null : profile.getAboutEmoji());
610 statement.setString(6, profile == null ? null : profile.getAvatarUrlPath());
611 statement.setBytes(7, profile == null ? null : profile.getMobileCoinAddress());
612 statement.setString(8, profile == null ? null : profile.getUnidentifiedAccessMode().name());
613 statement.setString(9,
614 profile == null
615 ? null
616 : profile.getCapabilities().stream().map(Enum::name).collect(Collectors.joining(",")));
617 statement.setLong(10, recipientId.id());
618 statement.executeUpdate();
619 }
620 }
621
622 private void storeProfileKey(
623 Connection connection, RecipientId recipientId, final ProfileKey profileKey, boolean resetProfile
624 ) throws SQLException {
625 if (profileKey != null) {
626 final var recipientProfileKey = getProfileKey(recipientId);
627 if (profileKey.equals(recipientProfileKey)) {
628 final var recipientProfile = getProfile(recipientId);
629 if (recipientProfile == null || (
630 recipientProfile.getUnidentifiedAccessMode() != Profile.UnidentifiedAccessMode.UNKNOWN
631 && recipientProfile.getUnidentifiedAccessMode()
632 != Profile.UnidentifiedAccessMode.DISABLED
633 )) {
634 return;
635 }
636 }
637 }
638
639 final var sql = (
640 """
641 UPDATE %s
642 SET profile_key = ?, profile_key_credential = NULL%s
643 WHERE _id = ?
644 """
645 ).formatted(TABLE_RECIPIENT, resetProfile ? ", profile_last_update_timestamp = 0" : "");
646 try (final var statement = connection.prepareStatement(sql)) {
647 statement.setBytes(1, profileKey == null ? null : profileKey.serialize());
648 statement.setLong(2, recipientId.id());
649 statement.executeUpdate();
650 }
651 }
652
653 private RecipientId resolveRecipientTrusted(RecipientAddress address, boolean isSelf) {
654 final Pair<RecipientId, List<RecipientId>> pair;
655 synchronized (recipientsLock) {
656 try (final var connection = database.getConnection()) {
657 connection.setAutoCommit(false);
658 if (address.hasSingleIdentifier() || (
659 !isSelf && selfAddressProvider.getSelfAddress().matches(address)
660 )) {
661 pair = new Pair<>(resolveRecipientLocked(connection, address), List.of());
662 } else {
663 pair = MergeRecipientHelper.resolveRecipientTrustedLocked(new HelperStore(connection), address);
664
665 for (final var toBeMergedRecipientId : pair.second()) {
666 mergeRecipientsLocked(connection, pair.first(), toBeMergedRecipientId);
667 }
668 }
669 connection.commit();
670 } catch (SQLException e) {
671 throw new RuntimeException("Failed update recipient store", e);
672 }
673 }
674
675 if (pair.second().size() > 0) {
676 try (final var connection = database.getConnection()) {
677 for (final var toBeMergedRecipientId : pair.second()) {
678 recipientMergeHandler.mergeRecipients(connection, pair.first(), toBeMergedRecipientId);
679 deleteRecipient(connection, toBeMergedRecipientId);
680 }
681 } catch (SQLException e) {
682 throw new RuntimeException("Failed update recipient store", e);
683 }
684 }
685 return pair.first();
686 }
687
688 private RecipientId resolveRecipientLocked(
689 Connection connection, RecipientAddress address
690 ) throws SQLException {
691 final var byServiceId = address.serviceId().isEmpty()
692 ? Optional.<RecipientWithAddress>empty()
693 : findByServiceId(connection, address.serviceId().get());
694
695 if (byServiceId.isPresent()) {
696 return byServiceId.get().id();
697 }
698
699 final var byPni = address.pni().isEmpty()
700 ? Optional.<RecipientWithAddress>empty()
701 : findByServiceId(connection, address.pni().get());
702
703 if (byPni.isPresent()) {
704 return byPni.get().id();
705 }
706
707 final var byNumber = address.number().isEmpty()
708 ? Optional.<RecipientWithAddress>empty()
709 : findByNumber(connection, address.number().get());
710
711 if (byNumber.isPresent()) {
712 return byNumber.get().id();
713 }
714
715 logger.debug("Got new recipient, both serviceId and number are unknown");
716
717 if (address.serviceId().isEmpty()) {
718 return addNewRecipient(connection, address);
719 }
720
721 return addNewRecipient(connection, new RecipientAddress(address.serviceId().get()));
722 }
723
724 private RecipientId resolveRecipientLocked(Connection connection, ServiceId serviceId) throws SQLException {
725 final var recipient = findByServiceId(connection, serviceId);
726
727 if (recipient.isEmpty()) {
728 logger.debug("Got new recipient, serviceId is unknown");
729 return addNewRecipient(connection, new RecipientAddress(serviceId));
730 }
731
732 return recipient.get().id();
733 }
734
735 private RecipientId resolveRecipientLocked(Connection connection, String number) throws SQLException {
736 final var recipient = findByNumber(connection, number);
737
738 if (recipient.isEmpty()) {
739 logger.debug("Got new recipient, number is unknown");
740 return addNewRecipient(connection, new RecipientAddress(null, number));
741 }
742
743 return recipient.get().id();
744 }
745
746 private RecipientId addNewRecipient(
747 final Connection connection, final RecipientAddress address
748 ) throws SQLException {
749 final var sql = (
750 """
751 INSERT INTO %s (number, uuid, pni)
752 VALUES (?, ?, ?)
753 """
754 ).formatted(TABLE_RECIPIENT);
755 try (final var statement = connection.prepareStatement(sql)) {
756 statement.setString(1, address.number().orElse(null));
757 statement.setBytes(2, address.serviceId().map(ServiceId::uuid).map(UuidUtil::toByteArray).orElse(null));
758 statement.setBytes(3, address.pni().map(PNI::uuid).map(UuidUtil::toByteArray).orElse(null));
759 statement.executeUpdate();
760 final var generatedKeys = statement.getGeneratedKeys();
761 if (generatedKeys.next()) {
762 final var recipientId = new RecipientId(generatedKeys.getLong(1), this);
763 logger.debug("Added new recipient {} with address {}", recipientId, address);
764 return recipientId;
765 } else {
766 throw new RuntimeException("Failed to add new recipient to database");
767 }
768 }
769 }
770
771 private void removeRecipientAddress(Connection connection, RecipientId recipientId) throws SQLException {
772 final var sql = (
773 """
774 UPDATE %s
775 SET number = NULL, uuid = NULL, pni = NULL
776 WHERE _id = ?
777 """
778 ).formatted(TABLE_RECIPIENT);
779 try (final var statement = connection.prepareStatement(sql)) {
780 statement.setLong(1, recipientId.id());
781 statement.executeUpdate();
782 }
783 }
784
785 private void updateRecipientAddress(
786 Connection connection, RecipientId recipientId, final RecipientAddress address
787 ) throws SQLException {
788 final var sql = (
789 """
790 UPDATE %s
791 SET number = ?, uuid = ?, pni = ?, username = ?
792 WHERE _id = ?
793 """
794 ).formatted(TABLE_RECIPIENT);
795 try (final var statement = connection.prepareStatement(sql)) {
796 statement.setString(1, address.number().orElse(null));
797 statement.setBytes(2, address.serviceId().map(ServiceId::uuid).map(UuidUtil::toByteArray).orElse(null));
798 statement.setBytes(3, address.pni().map(PNI::uuid).map(UuidUtil::toByteArray).orElse(null));
799 statement.setString(4, address.username().orElse(null));
800 statement.setLong(5, recipientId.id());
801 statement.executeUpdate();
802 }
803 }
804
805 private void deleteRecipient(final Connection connection, final RecipientId recipientId) throws SQLException {
806 final var sql = (
807 """
808 DELETE FROM %s
809 WHERE _id = ?
810 """
811 ).formatted(TABLE_RECIPIENT);
812 try (final var statement = connection.prepareStatement(sql)) {
813 statement.setLong(1, recipientId.id());
814 statement.executeUpdate();
815 }
816 }
817
818 private void mergeRecipientsLocked(
819 Connection connection, RecipientId recipientId, RecipientId toBeMergedRecipientId
820 ) throws SQLException {
821 final var contact = getContact(connection, recipientId);
822 if (contact == null) {
823 final var toBeMergedContact = getContact(connection, toBeMergedRecipientId);
824 storeContact(connection, recipientId, toBeMergedContact);
825 }
826
827 final var profileKey = getProfileKey(connection, recipientId);
828 if (profileKey == null) {
829 final var toBeMergedProfileKey = getProfileKey(connection, toBeMergedRecipientId);
830 storeProfileKey(connection, recipientId, toBeMergedProfileKey, false);
831 }
832
833 final var profileKeyCredential = getExpiringProfileKeyCredential(connection, recipientId);
834 if (profileKeyCredential == null) {
835 final var toBeMergedProfileKeyCredential = getExpiringProfileKeyCredential(connection,
836 toBeMergedRecipientId);
837 storeExpiringProfileKeyCredential(connection, recipientId, toBeMergedProfileKeyCredential);
838 }
839
840 final var profile = getProfile(connection, recipientId);
841 if (profile == null) {
842 final var toBeMergedProfile = getProfile(connection, toBeMergedRecipientId);
843 storeProfile(connection, recipientId, toBeMergedProfile);
844 }
845
846 recipientsMerged.put(toBeMergedRecipientId.id(), recipientId.id());
847 }
848
849 private Optional<RecipientWithAddress> findByNumber(
850 final Connection connection, final String number
851 ) throws SQLException {
852 final var sql = """
853 SELECT r._id, r.number, r.uuid, r.pni, r.username
854 FROM %s r
855 WHERE r.number = ?
856 LIMIT 1
857 """.formatted(TABLE_RECIPIENT);
858 try (final var statement = connection.prepareStatement(sql)) {
859 statement.setString(1, number);
860 return Utils.executeQueryForOptional(statement, this::getRecipientWithAddressFromResultSet);
861 }
862 }
863
864 private Optional<RecipientWithAddress> findByUsername(
865 final Connection connection, final String username
866 ) throws SQLException {
867 final var sql = """
868 SELECT r._id, r.number, r.uuid, r.pni, r.username
869 FROM %s r
870 WHERE r.username = ?
871 LIMIT 1
872 """.formatted(TABLE_RECIPIENT);
873 try (final var statement = connection.prepareStatement(sql)) {
874 statement.setString(1, username);
875 return Utils.executeQueryForOptional(statement, this::getRecipientWithAddressFromResultSet);
876 }
877 }
878
879 private Optional<RecipientWithAddress> findByServiceId(
880 final Connection connection, final ServiceId serviceId
881 ) throws SQLException {
882 final var sql = """
883 SELECT r._id, r.number, r.uuid, r.pni, r.username
884 FROM %s r
885 WHERE r.uuid = ? OR r.pni = ?
886 LIMIT 1
887 """.formatted(TABLE_RECIPIENT);
888 try (final var statement = connection.prepareStatement(sql)) {
889 statement.setBytes(1, UuidUtil.toByteArray(serviceId.uuid()));
890 return Utils.executeQueryForOptional(statement, this::getRecipientWithAddressFromResultSet);
891 }
892 }
893
894 private Set<RecipientWithAddress> findAllByAddress(
895 final Connection connection, final RecipientAddress address
896 ) throws SQLException {
897 final var sql = """
898 SELECT r._id, r.number, r.uuid, r.pni, r.username
899 FROM %s r
900 WHERE r.uuid = ?1 OR r.pni = ?1 OR
901 r.uuid = ?2 OR r.pni = ?2 OR
902 r.number = ?3 OR
903 r.username = ?4
904 """.formatted(TABLE_RECIPIENT);
905 try (final var statement = connection.prepareStatement(sql)) {
906 statement.setBytes(1, address.serviceId().map(ServiceId::uuid).map(UuidUtil::toByteArray).orElse(null));
907 statement.setBytes(2, address.pni().map(ServiceId::uuid).map(UuidUtil::toByteArray).orElse(null));
908 statement.setString(3, address.number().orElse(null));
909 statement.setString(4, address.username().orElse(null));
910 return Utils.executeQueryForStream(statement, this::getRecipientWithAddressFromResultSet)
911 .collect(Collectors.toSet());
912 }
913 }
914
915 private Contact getContact(final Connection connection, final RecipientId recipientId) throws SQLException {
916 final var sql = (
917 """
918 SELECT r.given_name, r.family_name, r.expiration_time, r.profile_sharing, r.color, r.blocked, r.archived
919 FROM %s r
920 WHERE r._id = ? AND (%s)
921 """
922 ).formatted(TABLE_RECIPIENT, SQL_IS_CONTACT);
923 try (final var statement = connection.prepareStatement(sql)) {
924 statement.setLong(1, recipientId.id());
925 return Utils.executeQueryForOptional(statement, this::getContactFromResultSet).orElse(null);
926 }
927 }
928
929 private ProfileKey getProfileKey(final Connection connection, final RecipientId recipientId) throws SQLException {
930 final var sql = (
931 """
932 SELECT r.profile_key
933 FROM %s r
934 WHERE r._id = ?
935 """
936 ).formatted(TABLE_RECIPIENT);
937 try (final var statement = connection.prepareStatement(sql)) {
938 statement.setLong(1, recipientId.id());
939 return Utils.executeQueryForOptional(statement, this::getProfileKeyFromResultSet).orElse(null);
940 }
941 }
942
943 private ExpiringProfileKeyCredential getExpiringProfileKeyCredential(
944 final Connection connection, final RecipientId recipientId
945 ) throws SQLException {
946 final var sql = (
947 """
948 SELECT r.profile_key_credential
949 FROM %s r
950 WHERE r._id = ?
951 """
952 ).formatted(TABLE_RECIPIENT);
953 try (final var statement = connection.prepareStatement(sql)) {
954 statement.setLong(1, recipientId.id());
955 return Utils.executeQueryForOptional(statement, this::getExpiringProfileKeyCredentialFromResultSet)
956 .orElse(null);
957 }
958 }
959
960 private Profile getProfile(final Connection connection, final RecipientId recipientId) throws SQLException {
961 final var sql = (
962 """
963 SELECT r.profile_last_update_timestamp, r.profile_given_name, r.profile_family_name, r.profile_about, r.profile_about_emoji, r.profile_avatar_url_path, r.profile_mobile_coin_address, r.profile_unidentified_access_mode, r.profile_capabilities
964 FROM %s r
965 WHERE r._id = ? AND r.profile_capabilities IS NOT NULL
966 """
967 ).formatted(TABLE_RECIPIENT);
968 try (final var statement = connection.prepareStatement(sql)) {
969 statement.setLong(1, recipientId.id());
970 return Utils.executeQueryForOptional(statement, this::getProfileFromResultSet).orElse(null);
971 }
972 }
973
974 private RecipientAddress getRecipientAddressFromResultSet(ResultSet resultSet) throws SQLException {
975 final var serviceId = Optional.ofNullable(resultSet.getBytes("uuid")).map(ServiceId::parseOrNull);
976 final var pni = Optional.ofNullable(resultSet.getBytes("pni")).map(PNI::parseOrNull);
977 final var number = Optional.ofNullable(resultSet.getString("number"));
978 final var username = Optional.ofNullable(resultSet.getString("username"));
979 return new RecipientAddress(serviceId, pni, number, username);
980 }
981
982 private RecipientId getRecipientIdFromResultSet(ResultSet resultSet) throws SQLException {
983 return new RecipientId(resultSet.getLong("_id"), this);
984 }
985
986 private RecipientWithAddress getRecipientWithAddressFromResultSet(final ResultSet resultSet) throws SQLException {
987 return new RecipientWithAddress(getRecipientIdFromResultSet(resultSet),
988 getRecipientAddressFromResultSet(resultSet));
989 }
990
991 private Recipient getRecipientFromResultSet(final ResultSet resultSet) throws SQLException {
992 return new Recipient(getRecipientIdFromResultSet(resultSet),
993 getRecipientAddressFromResultSet(resultSet),
994 getContactFromResultSet(resultSet),
995 getProfileKeyFromResultSet(resultSet),
996 getExpiringProfileKeyCredentialFromResultSet(resultSet),
997 getProfileFromResultSet(resultSet));
998 }
999
1000 private Contact getContactFromResultSet(ResultSet resultSet) throws SQLException {
1001 return new Contact(resultSet.getString("given_name"),
1002 resultSet.getString("family_name"),
1003 resultSet.getString("color"),
1004 resultSet.getInt("expiration_time"),
1005 resultSet.getBoolean("blocked"),
1006 resultSet.getBoolean("archived"),
1007 resultSet.getBoolean("profile_sharing"));
1008 }
1009
1010 private Profile getProfileFromResultSet(ResultSet resultSet) throws SQLException {
1011 final var profileCapabilities = resultSet.getString("profile_capabilities");
1012 final var profileUnidentifiedAccessMode = resultSet.getString("profile_unidentified_access_mode");
1013 return new Profile(resultSet.getLong("profile_last_update_timestamp"),
1014 resultSet.getString("profile_given_name"),
1015 resultSet.getString("profile_family_name"),
1016 resultSet.getString("profile_about"),
1017 resultSet.getString("profile_about_emoji"),
1018 resultSet.getString("profile_avatar_url_path"),
1019 resultSet.getBytes("profile_mobile_coin_address"),
1020 profileUnidentifiedAccessMode == null
1021 ? Profile.UnidentifiedAccessMode.UNKNOWN
1022 : Profile.UnidentifiedAccessMode.valueOfOrUnknown(profileUnidentifiedAccessMode),
1023 profileCapabilities == null
1024 ? Set.of()
1025 : Arrays.stream(profileCapabilities.split(","))
1026 .map(Profile.Capability::valueOfOrNull)
1027 .filter(Objects::nonNull)
1028 .collect(Collectors.toSet()));
1029 }
1030
1031 private ProfileKey getProfileKeyFromResultSet(ResultSet resultSet) throws SQLException {
1032 final var profileKey = resultSet.getBytes("profile_key");
1033
1034 if (profileKey == null) {
1035 return null;
1036 }
1037 try {
1038 return new ProfileKey(profileKey);
1039 } catch (InvalidInputException ignored) {
1040 return null;
1041 }
1042 }
1043
1044 private ExpiringProfileKeyCredential getExpiringProfileKeyCredentialFromResultSet(ResultSet resultSet) throws SQLException {
1045 final var profileKeyCredential = resultSet.getBytes("profile_key_credential");
1046
1047 if (profileKeyCredential == null) {
1048 return null;
1049 }
1050 try {
1051 return new ExpiringProfileKeyCredential(profileKeyCredential);
1052 } catch (Throwable ignored) {
1053 return null;
1054 }
1055 }
1056
1057 public interface RecipientMergeHandler {
1058
1059 void mergeRecipients(
1060 final Connection connection, RecipientId recipientId, RecipientId toBeMergedRecipientId
1061 ) throws SQLException;
1062 }
1063
1064 private class HelperStore implements MergeRecipientHelper.Store {
1065
1066 private final Connection connection;
1067
1068 public HelperStore(final Connection connection) {
1069 this.connection = connection;
1070 }
1071
1072 @Override
1073 public Set<RecipientWithAddress> findAllByAddress(final RecipientAddress address) throws SQLException {
1074 return RecipientStore.this.findAllByAddress(connection, address);
1075 }
1076
1077 @Override
1078 public RecipientId addNewRecipient(final RecipientAddress address) throws SQLException {
1079 return RecipientStore.this.addNewRecipient(connection, address);
1080 }
1081
1082 @Override
1083 public void updateRecipientAddress(
1084 final RecipientId recipientId, final RecipientAddress address
1085 ) throws SQLException {
1086 RecipientStore.this.updateRecipientAddress(connection, recipientId, address);
1087 }
1088
1089 @Override
1090 public void removeRecipientAddress(final RecipientId recipientId) throws SQLException {
1091 RecipientStore.this.removeRecipientAddress(connection, recipientId);
1092 }
1093 }
1094 }