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
.ProvisioningManager
;
21 import org
.asamk
.signal
.manager
.Settings
;
22 import org
.asamk
.signal
.manager
.api
.DeviceLinkUrl
;
23 import org
.asamk
.signal
.manager
.api
.UserAlreadyExistsException
;
24 import org
.asamk
.signal
.manager
.config
.ServiceConfig
;
25 import org
.asamk
.signal
.manager
.config
.ServiceEnvironmentConfig
;
26 import org
.asamk
.signal
.manager
.storage
.SignalAccount
;
27 import org
.asamk
.signal
.manager
.storage
.accounts
.AccountsStore
;
28 import org
.asamk
.signal
.manager
.util
.KeyUtils
;
29 import org
.signal
.libsignal
.protocol
.IdentityKeyPair
;
30 import org
.slf4j
.Logger
;
31 import org
.slf4j
.LoggerFactory
;
32 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
33 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
34 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
35 import org
.whispersystems
.signalservice
.api
.registration
.ProvisioningApi
;
36 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
37 import org
.whispersystems
.signalservice
.internal
.push
.ProvisioningSocket
;
38 import org
.whispersystems
.signalservice
.internal
.push
.PushServiceSocket
;
39 import org
.whispersystems
.signalservice
.internal
.util
.DynamicCredentialsProvider
;
41 import java
.io
.IOException
;
43 import java
.nio
.channels
.OverlappingFileLockException
;
44 import java
.util
.concurrent
.TimeoutException
;
45 import java
.util
.function
.Consumer
;
47 import static org
.asamk
.signal
.manager
.util
.KeyUtils
.generatePreKeysForType
;
49 public class ProvisioningManagerImpl
implements ProvisioningManager
{
51 private static final Logger logger
= LoggerFactory
.getLogger(ProvisioningManagerImpl
.class);
53 private final PathConfig pathConfig
;
54 private final ServiceEnvironmentConfig serviceEnvironmentConfig
;
55 private final String userAgent
;
56 private final Consumer
<Manager
> newManagerListener
;
57 private final AccountsStore accountsStore
;
59 private final ProvisioningApi provisioningApi
;
60 private final IdentityKeyPair tempIdentityKey
;
61 private final String password
;
63 public ProvisioningManagerImpl(
64 PathConfig pathConfig
,
65 ServiceEnvironmentConfig serviceEnvironmentConfig
,
67 final Consumer
<Manager
> newManagerListener
,
68 final AccountsStore accountsStore
70 this.pathConfig
= pathConfig
;
71 this.serviceEnvironmentConfig
= serviceEnvironmentConfig
;
72 this.userAgent
= userAgent
;
73 this.newManagerListener
= newManagerListener
;
74 this.accountsStore
= accountsStore
;
76 tempIdentityKey
= KeyUtils
.generateIdentityKeyPair();
77 password
= KeyUtils
.createPassword();
78 final var credentialsProvider
= new DynamicCredentialsProvider(null,
82 SignalServiceAddress
.DEFAULT_DEVICE_ID
);
83 final var pushServiceSocket
= new PushServiceSocket(serviceEnvironmentConfig
.signalServiceConfiguration(),
86 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
87 final var provisioningSocket
= new ProvisioningSocket(serviceEnvironmentConfig
.signalServiceConfiguration(),
89 this.provisioningApi
= new ProvisioningApi(pushServiceSocket
, provisioningSocket
, credentialsProvider
);
93 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
94 var deviceUuid
= provisioningApi
.getNewDeviceUuid();
96 return new DeviceLinkUrl(deviceUuid
, tempIdentityKey
.getPublicKey().getPublicKey()).createDeviceLinkUri();
100 public String
finishDeviceLink(String deviceName
) throws IOException
, TimeoutException
, UserAlreadyExistsException
{
101 var ret
= provisioningApi
.getNewDeviceRegistration(tempIdentityKey
);
102 var number
= ret
.getNumber();
103 var aci
= ret
.getAci();
104 var pni
= ret
.getPni();
106 logger
.info("Received link information from {}, linking in progress ...", number
);
108 var accountPath
= accountsStore
.getPathByAci(aci
);
109 if (accountPath
== null) {
110 accountPath
= accountsStore
.getPathByNumber(number
);
112 final var accountExists
= accountPath
!= null && SignalAccount
.accountFileExists(pathConfig
.dataPath(),
114 if (accountExists
&& !canRelinkExistingAccount(accountPath
)) {
115 throw new UserAlreadyExistsException(number
, SignalAccount
.getFileName(pathConfig
.dataPath(), accountPath
));
117 if (accountPath
== null) {
118 accountPath
= accountsStore
.addAccount(number
, aci
);
120 accountsStore
.updateAccount(accountPath
, number
, aci
);
123 var encryptedDeviceName
= deviceName
== null
125 : DeviceNameUtil
.encryptDeviceName(deviceName
, ret
.getAciIdentity().getPrivateKey());
126 // Create new account with the synced identity
127 var profileKey
= ret
.getProfileKey() == null ? KeyUtils
.createProfileKey() : ret
.getProfileKey();
129 SignalAccount account
= null;
131 if (!accountExists
) {
132 account
= SignalAccount
.createLinkedAccount(pathConfig
.dataPath(),
134 serviceEnvironmentConfig
.type(),
137 account
= SignalAccount
.load(pathConfig
.dataPath(), accountPath
, true, Settings
.DEFAULT
);
140 account
.setProvisioningData(number
,
145 ret
.getAciIdentity(),
146 ret
.getPniIdentity(),
149 ret
.getAccountEntropyPool(),
150 ret
.getMediaRootBackupKey());
152 account
.getConfigurationStore().setReadReceipts(ret
.isReadReceipts());
154 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
155 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
157 logger
.debug("Finishing new device registration");
158 var deviceId
= provisioningApi
.finishNewDeviceRegistration(ret
.getProvisioningCode(),
159 account
.getAccountAttributes(null),
163 account
.finishLinking(deviceId
, aciPreKeys
, pniPreKeys
);
165 ManagerImpl m
= null;
167 m
= new ManagerImpl(account
,
169 new AccountFileUpdaterImpl(accountsStore
, accountPath
),
170 serviceEnvironmentConfig
,
174 logger
.debug("Refreshing pre keys");
177 } catch (Exception e
) {
178 logger
.error("Failed to refresh pre keys.", e
);
181 logger
.debug("Requesting sync data");
183 m
.requestAllSyncData();
184 } catch (Exception e
) {
186 "Failed to request sync messages from linked device, data can be requested again with `sendSyncRequest`.",
190 if (newManagerListener
!= null) {
191 newManagerListener
.accept(m
);
201 if (account
!= null) {
207 private boolean canRelinkExistingAccount(final String accountPath
) throws IOException
{
208 final SignalAccount signalAccount
;
210 signalAccount
= SignalAccount
.load(pathConfig
.dataPath(), accountPath
, false, Settings
.DEFAULT
);
211 } catch (IOException e
) {
212 logger
.debug("Account in use or failed to load.", e
);
214 } catch (OverlappingFileLockException e
) {
215 logger
.debug("Account in use.", e
);
219 try (signalAccount
) {
220 if (signalAccount
.isPrimaryDevice()) {
221 logger
.debug("Account is a primary device.");
224 if (signalAccount
.isRegistered()
225 && signalAccount
.getServiceEnvironment() != null
226 && signalAccount
.getServiceEnvironment() != serviceEnvironmentConfig
.type()) {
227 logger
.debug("Account is registered in another environment: {}.",
228 signalAccount
.getServiceEnvironment());
232 final var m
= new ManagerImpl(signalAccount
,
234 new AccountFileUpdaterImpl(accountsStore
, accountPath
),
235 serviceEnvironmentConfig
,
238 m
.checkAccountState();
239 } catch (AuthorizationFailedException ignored
) {
243 logger
.debug("Account is still successfully linked.");