]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/internal/RegistrationManagerImpl.java
Update libsignal-service-java
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / internal / RegistrationManagerImpl.java
1 /*
2 Copyright (C) 2015-2022 AsamK and contributors
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17 package org.asamk.signal.manager.internal;
18
19 import org.asamk.signal.manager.Manager;
20 import org.asamk.signal.manager.RegistrationManager;
21 import org.asamk.signal.manager.api.CaptchaRequiredException;
22 import org.asamk.signal.manager.api.IncorrectPinException;
23 import org.asamk.signal.manager.api.NonNormalizedPhoneNumberException;
24 import org.asamk.signal.manager.api.PinLockedException;
25 import org.asamk.signal.manager.api.RateLimitException;
26 import org.asamk.signal.manager.api.UpdateProfile;
27 import org.asamk.signal.manager.api.VerificationMethodNotAvailableException;
28 import org.asamk.signal.manager.config.ServiceConfig;
29 import org.asamk.signal.manager.config.ServiceEnvironmentConfig;
30 import org.asamk.signal.manager.helper.AccountFileUpdater;
31 import org.asamk.signal.manager.helper.PinHelper;
32 import org.asamk.signal.manager.storage.SignalAccount;
33 import org.asamk.signal.manager.util.KeyUtils;
34 import org.asamk.signal.manager.util.NumberVerificationUtils;
35 import org.asamk.signal.manager.util.Utils;
36 import org.signal.libsignal.usernames.BaseUsernameException;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
40 import org.whispersystems.signalservice.api.account.PreKeyCollection;
41 import org.whispersystems.signalservice.api.groupsv2.ClientZkOperations;
42 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
43 import org.whispersystems.signalservice.api.kbs.MasterKey;
44 import org.whispersystems.signalservice.api.push.ServiceId.ACI;
45 import org.whispersystems.signalservice.api.push.ServiceId.PNI;
46 import org.whispersystems.signalservice.api.push.ServiceIdType;
47 import org.whispersystems.signalservice.api.push.SignalServiceAddress;
48 import org.whispersystems.signalservice.api.push.exceptions.AlreadyVerifiedException;
49 import org.whispersystems.signalservice.api.push.exceptions.DeprecatedVersionException;
50 import org.whispersystems.signalservice.api.svr.SecureValueRecovery;
51 import org.whispersystems.signalservice.internal.push.VerifyAccountResponse;
52 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
53
54 import java.io.IOException;
55 import java.util.function.Consumer;
56
57 import static org.asamk.signal.manager.util.KeyUtils.generatePreKeysForType;
58
59 public class RegistrationManagerImpl implements RegistrationManager {
60
61 private static final Logger logger = LoggerFactory.getLogger(RegistrationManagerImpl.class);
62
63 private SignalAccount account;
64 private final PathConfig pathConfig;
65 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
66 private final String userAgent;
67 private final Consumer<Manager> newManagerListener;
68 private final GroupsV2Operations groupsV2Operations;
69
70 private final SignalServiceAccountManager accountManager;
71 private final PinHelper pinHelper;
72 private final AccountFileUpdater accountFileUpdater;
73
74 public RegistrationManagerImpl(
75 SignalAccount account,
76 PathConfig pathConfig,
77 ServiceEnvironmentConfig serviceEnvironmentConfig,
78 String userAgent,
79 Consumer<Manager> newManagerListener,
80 AccountFileUpdater accountFileUpdater
81 ) {
82 this.account = account;
83 this.pathConfig = pathConfig;
84 this.accountFileUpdater = accountFileUpdater;
85 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
86 this.userAgent = userAgent;
87 this.newManagerListener = newManagerListener;
88
89 groupsV2Operations = new GroupsV2Operations(ClientZkOperations.create(serviceEnvironmentConfig.signalServiceConfiguration()),
90 ServiceConfig.GROUP_MAX_SIZE);
91 this.accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.signalServiceConfiguration(),
92 new DynamicCredentialsProvider(
93 // Using empty UUID, because registering doesn't work otherwise
94 null, null, account.getNumber(), account.getPassword(), SignalServiceAddress.DEFAULT_DEVICE_ID),
95 userAgent,
96 groupsV2Operations,
97 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
98 final var secureValueRecoveryV2 = serviceEnvironmentConfig.svr2Mrenclaves()
99 .stream()
100 .map(mr -> (SecureValueRecovery) accountManager.getSecureValueRecoveryV2(mr))
101 .toList();
102 this.pinHelper = new PinHelper(secureValueRecoveryV2);
103 }
104
105 @Override
106 public void register(
107 boolean voiceVerification, String captcha, final boolean forceRegister
108 ) throws IOException, CaptchaRequiredException, NonNormalizedPhoneNumberException, RateLimitException, VerificationMethodNotAvailableException {
109 if (account.isRegistered()
110 && account.getServiceEnvironment() != null
111 && account.getServiceEnvironment() != serviceEnvironmentConfig.type()) {
112 throw new IOException("Account is registered in another environment: " + account.getServiceEnvironment());
113 }
114
115 try {
116 if (!forceRegister) {
117 if (account.isRegistered()) {
118 throw new IOException("Account is already registered");
119 }
120
121 if (account.getAci() != null && attemptReactivateAccount()) {
122 return;
123 }
124 }
125
126 final var recoveryPassword = account.getRecoveryPassword();
127 if (recoveryPassword != null && account.isPrimaryDevice() && attemptReregisterAccount(recoveryPassword)) {
128 return;
129 }
130
131 String sessionId = NumberVerificationUtils.handleVerificationSession(accountManager,
132 account.getSessionId(account.getNumber()),
133 id -> account.setSessionId(account.getNumber(), id),
134 voiceVerification,
135 captcha);
136 NumberVerificationUtils.requestVerificationCode(accountManager, sessionId, voiceVerification);
137 account.setRegistered(false);
138 } catch (DeprecatedVersionException e) {
139 logger.debug("Signal-Server returned deprecated version exception", e);
140 throw e;
141 }
142 }
143
144 @Override
145 public void verifyAccount(
146 String verificationCode, String pin
147 ) throws IOException, PinLockedException, IncorrectPinException {
148 if (account.isRegistered()) {
149 throw new IOException("Account is already registered");
150 }
151
152 if (account.getPniIdentityKeyPair() == null) {
153 account.setPniIdentityKeyPair(KeyUtils.generateIdentityKeyPair());
154 }
155
156 final var aciPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.ACI));
157 final var pniPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.PNI));
158 final var result = NumberVerificationUtils.verifyNumber(account.getSessionId(account.getNumber()),
159 verificationCode,
160 pin,
161 pinHelper,
162 (sessionId1, verificationCode1, registrationLock) -> verifyAccountWithCode(sessionId1,
163 verificationCode1,
164 registrationLock,
165 aciPreKeys,
166 pniPreKeys));
167 final var response = result.first();
168 final var masterKey = result.second();
169 if (masterKey == null) {
170 pin = null;
171 }
172
173 finishAccountRegistration(response, pin, masterKey, aciPreKeys, pniPreKeys);
174 }
175
176 @Override
177 public void deleteLocalAccountData() throws IOException {
178 account.deleteAccountData();
179 accountFileUpdater.removeAccount();
180 account = null;
181 }
182
183 @Override
184 public boolean isRegistered() {
185 return account.isRegistered();
186 }
187
188 private boolean attemptReregisterAccount(final String recoveryPassword) {
189 try {
190 if (account.getPniIdentityKeyPair() == null) {
191 account.setPniIdentityKeyPair(KeyUtils.generateIdentityKeyPair());
192 }
193
194 final var aciPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.ACI));
195 final var pniPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.PNI));
196 final var response = Utils.handleResponseException(accountManager.registerAccount(null,
197 recoveryPassword,
198 account.getAccountAttributes(null),
199 aciPreKeys,
200 pniPreKeys,
201 null,
202 true));
203 finishAccountRegistration(response,
204 account.getRegistrationLockPin(),
205 account.getPinBackedMasterKey(),
206 aciPreKeys,
207 pniPreKeys);
208 logger.info("Reregistered existing account, verify is not necessary.");
209 return true;
210 } catch (IOException e) {
211 logger.debug("Failed to reregister account with recovery password", e);
212 }
213 return false;
214 }
215
216 private boolean attemptReactivateAccount() {
217 try {
218 final var accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.signalServiceConfiguration(),
219 account.getCredentialsProvider(),
220 userAgent,
221 groupsV2Operations,
222 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
223 accountManager.setAccountAttributes(account.getAccountAttributes(null));
224 account.setRegistered(true);
225 logger.info("Reactivated existing account, verify is not necessary.");
226 if (newManagerListener != null) {
227 final var m = new ManagerImpl(account,
228 pathConfig,
229 accountFileUpdater,
230 serviceEnvironmentConfig,
231 userAgent);
232 account = null;
233 newManagerListener.accept(m);
234 }
235 return true;
236 } catch (IOException e) {
237 logger.debug("Failed to reactivate account");
238 }
239 return false;
240 }
241
242 private VerifyAccountResponse verifyAccountWithCode(
243 final String sessionId,
244 final String verificationCode,
245 final String registrationLock,
246 final PreKeyCollection aciPreKeys,
247 final PreKeyCollection pniPreKeys
248 ) throws IOException {
249 try {
250 Utils.handleResponseException(accountManager.verifyAccount(verificationCode, sessionId));
251 } catch (AlreadyVerifiedException e) {
252 // Already verified so can continue registering
253 }
254 return Utils.handleResponseException(accountManager.registerAccount(sessionId,
255 null,
256 account.getAccountAttributes(registrationLock),
257 aciPreKeys,
258 pniPreKeys,
259 null,
260 true));
261 }
262
263 private void finishAccountRegistration(
264 final VerifyAccountResponse response,
265 final String pin,
266 final MasterKey masterKey,
267 final PreKeyCollection aciPreKeys,
268 final PreKeyCollection pniPreKeys
269 ) throws IOException {
270 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
271 final var aci = ACI.parseOrThrow(response.getUuid());
272 final var pni = PNI.parseOrThrow(response.getPni());
273 account.finishRegistration(aci, pni, masterKey, pin, aciPreKeys, pniPreKeys);
274 accountFileUpdater.updateAccountIdentifiers(account.getNumber(), aci);
275
276 ManagerImpl m = null;
277 try {
278 m = new ManagerImpl(account, pathConfig, accountFileUpdater, serviceEnvironmentConfig, userAgent);
279 account = null;
280
281 m.refreshPreKeys();
282 if (response.isStorageCapable()) {
283 m.syncRemoteStorage();
284 }
285 // Set an initial empty profile so user can be added to groups
286 try {
287 m.updateProfile(UpdateProfile.newBuilder().build());
288 } catch (NoClassDefFoundError e) {
289 logger.warn("Failed to set default profile: {}", e.getMessage());
290 }
291
292 try {
293 m.refreshCurrentUsername();
294 } catch (IOException | BaseUsernameException e) {
295 logger.warn("Failed to refresh current username", e);
296 }
297
298 if (newManagerListener != null) {
299 newManagerListener.accept(m);
300 m = null;
301 }
302 } finally {
303 if (m != null) {
304 m.close();
305 }
306 }
307 }
308
309 @Override
310 public void close() {
311 if (account != null) {
312 account.close();
313 account = null;
314 }
315 }
316 }