2 Copyright (C) 2015-2022 AsamK and contributors
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.
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.
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/>.
17 package org
.asamk
.signal
.manager
.internal
;
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
.signal
.libsignal
.usernames
.BaseUsernameException
;
36 import org
.slf4j
.Logger
;
37 import org
.slf4j
.LoggerFactory
;
38 import org
.whispersystems
.signalservice
.api
.SignalServiceAccountManager
;
39 import org
.whispersystems
.signalservice
.api
.account
.PreKeyCollection
;
40 import org
.whispersystems
.signalservice
.api
.kbs
.MasterKey
;
41 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.ACI
;
42 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
.PNI
;
43 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
44 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
45 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AlreadyVerifiedException
;
46 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.DeprecatedVersionException
;
47 import org
.whispersystems
.signalservice
.api
.svr
.SecureValueRecovery
;
48 import org
.whispersystems
.signalservice
.internal
.push
.VerifyAccountResponse
;
50 import java
.io
.IOException
;
51 import java
.util
.function
.Consumer
;
53 import static org
.asamk
.signal
.manager
.util
.KeyUtils
.generatePreKeysForType
;
54 import static org
.asamk
.signal
.manager
.util
.Utils
.handleResponseException
;
56 public class RegistrationManagerImpl
implements RegistrationManager
{
58 private static final Logger logger
= LoggerFactory
.getLogger(RegistrationManagerImpl
.class);
60 private SignalAccount account
;
61 private final PathConfig pathConfig
;
62 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
63 private final String userAgent
;
64 private final Consumer
<Manager
> newManagerListener
;
66 private final SignalServiceAccountManager unauthenticatedAccountManager
;
67 private final PinHelper pinHelper
;
68 private final AccountFileUpdater accountFileUpdater
;
70 public RegistrationManagerImpl(
71 SignalAccount account
,
72 PathConfig pathConfig
,
73 ServiceEnvironmentConfig serviceEnvironmentConfig
,
75 Consumer
<Manager
> newManagerListener
,
76 AccountFileUpdater accountFileUpdater
78 this.account
= account
;
79 this.pathConfig
= pathConfig
;
80 this.accountFileUpdater
= accountFileUpdater
;
81 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
82 this.userAgent
= userAgent
;
83 this.newManagerListener
= newManagerListener
;
85 this.unauthenticatedAccountManager
= SignalServiceAccountManager
.createWithStaticCredentials(
86 serviceEnvironmentConfig
.signalServiceConfiguration(),
87 // Using empty UUID, because registering doesn't work otherwise
91 SignalServiceAddress
.DEFAULT_DEVICE_ID
,
92 account
.getPassword(),
94 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
,
95 ServiceConfig
.GROUP_MAX_SIZE
);
96 final var secureValueRecovery
= serviceEnvironmentConfig
.svr2Mrenclaves()
98 .map(mr
-> (SecureValueRecovery
) this.unauthenticatedAccountManager
.getSecureValueRecoveryV2(mr
))
100 this.pinHelper
= new PinHelper(secureValueRecovery
);
104 public void register(
105 boolean voiceVerification
,
107 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());
116 if (!forceRegister
) {
117 if (account
.isRegistered()) {
118 throw new IOException("Account is already registered");
121 if (account
.getAci() != null && attemptReactivateAccount()) {
126 final var recoveryPassword
= account
.getRecoveryPassword();
127 if (recoveryPassword
!= null && account
.isPrimaryDevice() && attemptReregisterAccount(recoveryPassword
)) {
131 final var registrationApi
= unauthenticatedAccountManager
.getRegistrationApi();
132 String sessionId
= NumberVerificationUtils
.handleVerificationSession(registrationApi
,
133 account
.getSessionId(account
.getNumber()),
134 id
-> account
.setSessionId(account
.getNumber(), id
),
137 NumberVerificationUtils
.requestVerificationCode(registrationApi
, sessionId
, voiceVerification
);
138 account
.setRegistered(false);
139 } catch (DeprecatedVersionException e
) {
140 logger
.debug("Signal-Server returned deprecated version exception", e
);
146 public void verifyAccount(
147 String verificationCode
,
149 ) throws IOException
, PinLockedException
, IncorrectPinException
{
150 if (account
.isRegistered()) {
151 throw new IOException("Account is already registered");
154 if (account
.getPniIdentityKeyPair() == null) {
155 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
158 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
159 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
160 final var result
= NumberVerificationUtils
.verifyNumber(account
.getSessionId(account
.getNumber()),
164 (sessionId1
, verificationCode1
, registrationLock
) -> verifyAccountWithCode(sessionId1
,
169 final var response
= result
.first();
170 final var masterKey
= result
.second();
171 if (masterKey
== null) {
175 finishAccountRegistration(response
, pin
, masterKey
, aciPreKeys
, pniPreKeys
);
179 public void deleteLocalAccountData() throws IOException
{
180 account
.deleteAccountData();
181 accountFileUpdater
.removeAccount();
186 public boolean isRegistered() {
187 return account
.isRegistered();
190 private boolean attemptReregisterAccount(final String recoveryPassword
) {
192 if (account
.getPniIdentityKeyPair() == null) {
193 account
.setPniIdentityKeyPair(KeyUtils
.generateIdentityKeyPair());
196 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
197 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
198 final var registrationApi
= unauthenticatedAccountManager
.getRegistrationApi();
199 final var response
= handleResponseException(registrationApi
.registerAccount(null,
201 account
.getAccountAttributes(null),
206 finishAccountRegistration(response
,
207 account
.getRegistrationLockPin(),
208 account
.getPinBackedMasterKey(),
211 logger
.info("Reregistered existing account, verify is not necessary.");
213 } catch (IOException e
) {
214 logger
.debug("Failed to reregister account with recovery password", e
);
219 private boolean attemptReactivateAccount() {
221 final var dependencies
= new SignalDependencies(serviceEnvironmentConfig
,
223 account
.getCredentialsProvider(),
224 account
.getSignalServiceDataStore(),
226 new ReentrantSignalSessionLock());
227 handleResponseException(dependencies
.getAccountApi()
228 .setAccountAttributes(account
.getAccountAttributes(null)));
229 account
.setRegistered(true);
230 logger
.info("Reactivated existing account, verify is not necessary.");
231 if (newManagerListener
!= null) {
232 final var m
= new ManagerImpl(account
,
235 serviceEnvironmentConfig
,
238 newManagerListener
.accept(m
);
241 } catch (IOException e
) {
242 logger
.debug("Failed to reactivate account");
247 private VerifyAccountResponse
verifyAccountWithCode(
248 final String sessionId
,
249 final String verificationCode
,
250 final String registrationLock
,
251 final PreKeyCollection aciPreKeys
,
252 final PreKeyCollection pniPreKeys
253 ) throws IOException
{
254 final var registrationApi
= unauthenticatedAccountManager
.getRegistrationApi();
256 handleResponseException(registrationApi
.verifyAccount(sessionId
, verificationCode
));
257 } catch (AlreadyVerifiedException e
) {
258 // Already verified so can continue registering
260 return handleResponseException(registrationApi
.registerAccount(sessionId
,
262 account
.getAccountAttributes(registrationLock
),
269 private void finishAccountRegistration(
270 final VerifyAccountResponse response
,
272 final MasterKey masterKey
,
273 final PreKeyCollection aciPreKeys
,
274 final PreKeyCollection pniPreKeys
275 ) throws IOException
{
276 //accountManager.setGcmId(Optional.of(GoogleCloudMessaging.getInstance(this).register(REGISTRATION_ID)));
277 final var aci
= ACI
.parseOrThrow(response
.getUuid());
278 final var pni
= PNI
.parseOrThrow(response
.getPni());
279 account
.finishRegistration(aci
, pni
, masterKey
, pin
, aciPreKeys
, pniPreKeys
);
280 accountFileUpdater
.updateAccountIdentifiers(account
.getNumber(), aci
);
282 ManagerImpl m
= null;
284 m
= new ManagerImpl(account
, pathConfig
, accountFileUpdater
, serviceEnvironmentConfig
, userAgent
);
288 if (response
.isStorageCapable()) {
289 m
.syncRemoteStorage();
291 // Set an initial empty profile so user can be added to groups
293 m
.updateProfile(UpdateProfile
.newBuilder().build());
294 } catch (NoClassDefFoundError e
) {
295 logger
.warn("Failed to set default profile: {}", e
.getMessage());
299 m
.refreshCurrentUsername();
300 } catch (IOException
| BaseUsernameException e
) {
301 logger
.warn("Failed to refresh current username", e
);
304 if (newManagerListener
!= null) {
305 newManagerListener
.accept(m
);
316 public void close() {
317 if (account
!= null) {