]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/ProfileHelper.java
7a492d9f98dba0291ef7ea67f28d0ed69af999cf
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / helper / ProfileHelper.java
1 package org.asamk.signal.manager.helper;
2
3 import org.asamk.signal.manager.AvatarStore;
4 import org.asamk.signal.manager.SignalDependencies;
5 import org.asamk.signal.manager.config.ServiceConfig;
6 import org.asamk.signal.manager.storage.SignalAccount;
7 import org.asamk.signal.manager.storage.recipients.Profile;
8 import org.asamk.signal.manager.storage.recipients.RecipientId;
9 import org.asamk.signal.manager.util.IOUtils;
10 import org.asamk.signal.manager.util.ProfileUtils;
11 import org.asamk.signal.manager.util.Utils;
12 import org.signal.zkgroup.profiles.ProfileKey;
13 import org.signal.zkgroup.profiles.ProfileKeyCredential;
14 import org.slf4j.Logger;
15 import org.slf4j.LoggerFactory;
16 import org.whispersystems.libsignal.IdentityKey;
17 import org.whispersystems.libsignal.InvalidKeyException;
18 import org.whispersystems.libsignal.util.guava.Optional;
19 import org.whispersystems.signalservice.api.crypto.UnidentifiedAccess;
20 import org.whispersystems.signalservice.api.profiles.ProfileAndCredential;
21 import org.whispersystems.signalservice.api.profiles.SignalServiceProfile;
22 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
23 import org.whispersystems.signalservice.api.push.exceptions.NotFoundException;
24 import org.whispersystems.signalservice.api.push.exceptions.PushNetworkException;
25 import org.whispersystems.signalservice.api.services.ProfileService;
26 import org.whispersystems.signalservice.internal.ServiceResponse;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.io.OutputStream;
31 import java.nio.file.Files;
32 import java.util.Base64;
33 import java.util.Date;
34 import java.util.HashSet;
35 import java.util.List;
36 import java.util.Objects;
37 import java.util.Set;
38
39 import io.reactivex.rxjava3.core.Single;
40
41 public final class ProfileHelper {
42
43 private final static Logger logger = LoggerFactory.getLogger(ProfileHelper.class);
44
45 private final SignalAccount account;
46 private final SignalDependencies dependencies;
47 private final AvatarStore avatarStore;
48 private final UnidentifiedAccessProvider unidentifiedAccessProvider;
49 private final SignalServiceAddressResolver addressResolver;
50
51 public ProfileHelper(
52 final SignalAccount account,
53 final SignalDependencies dependencies,
54 final AvatarStore avatarStore,
55 final UnidentifiedAccessProvider unidentifiedAccessProvider,
56 final SignalServiceAddressResolver addressResolver
57 ) {
58 this.account = account;
59 this.dependencies = dependencies;
60 this.avatarStore = avatarStore;
61 this.unidentifiedAccessProvider = unidentifiedAccessProvider;
62 this.addressResolver = addressResolver;
63 }
64
65 public Profile getRecipientProfile(RecipientId recipientId) {
66 return getRecipientProfile(recipientId, false);
67 }
68
69 public void refreshRecipientProfile(RecipientId recipientId) {
70 getRecipientProfile(recipientId, true);
71 }
72
73 public ProfileKeyCredential getRecipientProfileKeyCredential(RecipientId recipientId) {
74 var profileKeyCredential = account.getProfileStore().getProfileKeyCredential(recipientId);
75 if (profileKeyCredential != null) {
76 return profileKeyCredential;
77 }
78
79 ProfileAndCredential profileAndCredential;
80 try {
81 profileAndCredential = retrieveProfileAndCredential(recipientId,
82 SignalServiceProfile.RequestType.PROFILE_AND_CREDENTIAL);
83 } catch (IOException e) {
84 logger.warn("Failed to retrieve profile key credential, ignoring: {}", e.getMessage());
85 return null;
86 }
87
88 profileKeyCredential = profileAndCredential.getProfileKeyCredential().orNull();
89 account.getProfileStore().storeProfileKeyCredential(recipientId, profileKeyCredential);
90
91 var profileKey = account.getProfileStore().getProfileKey(recipientId);
92 if (profileKey != null) {
93 final var profile = decryptProfileAndDownloadAvatar(recipientId,
94 profileKey,
95 profileAndCredential.getProfile());
96 account.getProfileStore().storeProfile(recipientId, profile);
97 }
98
99 return profileKeyCredential;
100 }
101
102 /**
103 * @param givenName if null, the previous givenName will be kept
104 * @param familyName if null, the previous familyName will be kept
105 * @param about if null, the previous about text will be kept
106 * @param aboutEmoji if null, the previous about emoji will be kept
107 * @param avatar if avatar is null the image from the local avatar store is used (if present),
108 */
109 public void setProfile(
110 String givenName, final String familyName, String about, String aboutEmoji, Optional<File> avatar
111 ) throws IOException {
112 setProfile(true, givenName, familyName, about, aboutEmoji, avatar);
113 }
114
115 public void setProfile(
116 boolean uploadProfile,
117 String givenName,
118 final String familyName,
119 String about,
120 String aboutEmoji,
121 Optional<File> avatar
122 ) throws IOException {
123 var profile = getRecipientProfile(account.getSelfRecipientId());
124 var builder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
125 if (givenName != null) {
126 builder.withGivenName(givenName);
127 }
128 if (familyName != null) {
129 builder.withFamilyName(familyName);
130 }
131 if (about != null) {
132 builder.withAbout(about);
133 }
134 if (aboutEmoji != null) {
135 builder.withAboutEmoji(aboutEmoji);
136 }
137 var newProfile = builder.build();
138
139 if (uploadProfile) {
140 try (final var streamDetails = avatar == null
141 ? avatarStore.retrieveProfileAvatar(account.getSelfAddress())
142 : avatar.isPresent() ? Utils.createStreamDetailsFromFile(avatar.get()) : null) {
143 final var avatarPath = dependencies.getAccountManager()
144 .setVersionedProfile(account.getUuid(),
145 account.getProfileKey(),
146 newProfile.getInternalServiceName(),
147 newProfile.getAbout() == null ? "" : newProfile.getAbout(),
148 newProfile.getAboutEmoji() == null ? "" : newProfile.getAboutEmoji(),
149 Optional.absent(),
150 streamDetails,
151 List.of(/* TODO */));
152 builder.withAvatarUrlPath(avatarPath.orNull());
153 newProfile = builder.build();
154 }
155 }
156
157 if (avatar != null) {
158 if (avatar.isPresent()) {
159 avatarStore.storeProfileAvatar(account.getSelfAddress(),
160 outputStream -> IOUtils.copyFileToStream(avatar.get(), outputStream));
161 } else {
162 avatarStore.deleteProfileAvatar(account.getSelfAddress());
163 }
164 }
165 account.getProfileStore().storeProfile(account.getSelfRecipientId(), newProfile);
166 }
167
168 private final Set<RecipientId> pendingProfileRequest = new HashSet<>();
169
170 private Profile getRecipientProfile(RecipientId recipientId, boolean force) {
171 var profile = account.getProfileStore().getProfile(recipientId);
172
173 var now = System.currentTimeMillis();
174 // Profiles are cached for 24h before retrieving them again, unless forced
175 if (!force && profile != null && now - profile.getLastUpdateTimestamp() < 24 * 60 * 60 * 1000) {
176 return profile;
177 }
178
179 synchronized (pendingProfileRequest) {
180 if (pendingProfileRequest.contains(recipientId)) {
181 return profile;
182 }
183 pendingProfileRequest.add(recipientId);
184 }
185 final SignalServiceProfile encryptedProfile;
186 try {
187 encryptedProfile = retrieveEncryptedProfile(recipientId);
188 } finally {
189 synchronized (pendingProfileRequest) {
190 pendingProfileRequest.remove(recipientId);
191 }
192 }
193 if (encryptedProfile == null) {
194 return null;
195 }
196
197 profile = decryptProfileIfKeyKnown(recipientId, encryptedProfile);
198 account.getProfileStore().storeProfile(recipientId, profile);
199
200 return profile;
201 }
202
203 private Profile decryptProfileIfKeyKnown(
204 final RecipientId recipientId, final SignalServiceProfile encryptedProfile
205 ) {
206 var profileKey = account.getProfileStore().getProfileKey(recipientId);
207 if (profileKey == null) {
208 return new Profile(System.currentTimeMillis(),
209 null,
210 null,
211 null,
212 null,
213 null,
214 ProfileUtils.getUnidentifiedAccessMode(encryptedProfile, null),
215 ProfileUtils.getCapabilities(encryptedProfile));
216 }
217
218 return decryptProfileAndDownloadAvatar(recipientId, profileKey, encryptedProfile);
219 }
220
221 private SignalServiceProfile retrieveEncryptedProfile(RecipientId recipientId) {
222 try {
223 return retrieveProfileAndCredential(recipientId, SignalServiceProfile.RequestType.PROFILE).getProfile();
224 } catch (IOException e) {
225 logger.warn("Failed to retrieve profile, ignoring: {}", e.getMessage());
226 return null;
227 }
228 }
229
230 private SignalServiceProfile retrieveProfileSync(String username) throws IOException {
231 return dependencies.getMessageReceiver().retrieveProfileByUsername(username, Optional.absent());
232 }
233
234 private ProfileAndCredential retrieveProfileAndCredential(
235 final RecipientId recipientId, final SignalServiceProfile.RequestType requestType
236 ) throws IOException {
237 final var profileAndCredential = retrieveProfileSync(recipientId, requestType);
238 final var profile = profileAndCredential.getProfile();
239
240 try {
241 var newIdentity = account.getIdentityKeyStore()
242 .saveIdentity(recipientId,
243 new IdentityKey(Base64.getDecoder().decode(profile.getIdentityKey())),
244 new Date());
245
246 if (newIdentity) {
247 account.getSessionStore().archiveSessions(recipientId);
248 }
249 } catch (InvalidKeyException ignored) {
250 logger.warn("Got invalid identity key in profile for {}",
251 addressResolver.resolveSignalServiceAddress(recipientId).getIdentifier());
252 }
253 return profileAndCredential;
254 }
255
256 private Profile decryptProfileAndDownloadAvatar(
257 final RecipientId recipientId, final ProfileKey profileKey, final SignalServiceProfile encryptedProfile
258 ) {
259 final var avatarPath = encryptedProfile.getAvatar();
260 downloadProfileAvatar(recipientId, avatarPath, profileKey);
261
262 return ProfileUtils.decryptProfile(profileKey, encryptedProfile);
263 }
264
265 public void downloadProfileAvatar(
266 final RecipientId recipientId, final String avatarPath, final ProfileKey profileKey
267 ) {
268 var profile = account.getProfileStore().getProfile(recipientId);
269 if (profile == null || !Objects.equals(avatarPath, profile.getAvatarUrlPath())) {
270 downloadProfileAvatar(addressResolver.resolveSignalServiceAddress(recipientId), avatarPath, profileKey);
271 var builder = profile == null ? Profile.newBuilder() : Profile.newBuilder(profile);
272 account.getProfileStore().storeProfile(recipientId, builder.withAvatarUrlPath(avatarPath).build());
273 }
274 }
275
276 private ProfileAndCredential retrieveProfileSync(
277 RecipientId recipientId, SignalServiceProfile.RequestType requestType
278 ) throws IOException {
279 try {
280 return retrieveProfile(recipientId, requestType).blockingGet();
281 } catch (RuntimeException e) {
282 if (e.getCause() instanceof PushNetworkException) {
283 throw (PushNetworkException) e.getCause();
284 } else if (e.getCause() instanceof NotFoundException) {
285 throw (NotFoundException) e.getCause();
286 } else {
287 throw new IOException(e);
288 }
289 }
290 }
291
292 private Single<ProfileAndCredential> retrieveProfile(
293 RecipientId recipientId, SignalServiceProfile.RequestType requestType
294 ) {
295 var unidentifiedAccess = getUnidentifiedAccess(recipientId);
296 var profileKey = Optional.fromNullable(account.getProfileStore().getProfileKey(recipientId));
297
298 final var address = addressResolver.resolveSignalServiceAddress(recipientId);
299 return retrieveProfile(address, profileKey, unidentifiedAccess, requestType);
300 }
301
302 private Single<ProfileAndCredential> retrieveProfile(
303 SignalServiceAddress address,
304 Optional<ProfileKey> profileKey,
305 Optional<UnidentifiedAccess> unidentifiedAccess,
306 SignalServiceProfile.RequestType requestType
307 ) {
308 var profileService = dependencies.getProfileService();
309
310 Single<ServiceResponse<ProfileAndCredential>> responseSingle;
311 try {
312 responseSingle = profileService.getProfile(address, profileKey, unidentifiedAccess, requestType);
313 } catch (NoClassDefFoundError e) {
314 // Native zkgroup lib not available for ProfileKey
315 responseSingle = profileService.getProfile(address, Optional.absent(), unidentifiedAccess, requestType);
316 }
317
318 return responseSingle.map(pair -> {
319 var processor = new ProfileService.ProfileResponseProcessor(pair);
320 if (processor.hasResult()) {
321 return processor.getResult();
322 } else if (processor.notFound()) {
323 throw new NotFoundException("Profile not found");
324 } else {
325 throw pair.getExecutionError()
326 .or(pair.getApplicationError())
327 .or(new IOException("Unknown error while retrieving profile"));
328 }
329 });
330 }
331
332 private void downloadProfileAvatar(
333 SignalServiceAddress address, String avatarPath, ProfileKey profileKey
334 ) {
335 if (avatarPath == null) {
336 try {
337 avatarStore.deleteProfileAvatar(address);
338 } catch (IOException e) {
339 logger.warn("Failed to delete local profile avatar, ignoring: {}", e.getMessage());
340 }
341 return;
342 }
343
344 try {
345 avatarStore.storeProfileAvatar(address,
346 outputStream -> retrieveProfileAvatar(avatarPath, profileKey, outputStream));
347 } catch (Throwable e) {
348 if (e instanceof AssertionError && e.getCause() instanceof InterruptedException) {
349 Thread.currentThread().interrupt();
350 }
351 logger.warn("Failed to download profile avatar, ignoring: {}", e.getMessage());
352 }
353 }
354
355 private void retrieveProfileAvatar(
356 String avatarPath, ProfileKey profileKey, OutputStream outputStream
357 ) throws IOException {
358 var tmpFile = IOUtils.createTempFile();
359 try (var input = dependencies.getMessageReceiver()
360 .retrieveProfileAvatar(avatarPath,
361 tmpFile,
362 profileKey,
363 ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE)) {
364 // Use larger buffer size to prevent AssertionError: Need: 12272 but only have: 8192 ...
365 IOUtils.copyStream(input, outputStream, (int) ServiceConfig.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
366 } finally {
367 try {
368 Files.delete(tmpFile.toPath());
369 } catch (IOException e) {
370 logger.warn("Failed to delete received profile avatar temp file “{}”, ignoring: {}",
371 tmpFile,
372 e.getMessage());
373 }
374 }
375 }
376
377 private Optional<UnidentifiedAccess> getUnidentifiedAccess(RecipientId recipientId) {
378 var unidentifiedAccess = unidentifiedAccessProvider.getAccessFor(recipientId);
379
380 if (unidentifiedAccess.isPresent()) {
381 return unidentifiedAccess.get().getTargetUnidentifiedAccess();
382 }
383
384 return Optional.absent();
385 }
386 }