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
.SignalServiceAccountManager
;
33 import org
.whispersystems
.signalservice
.api
.groupsv2
.ClientZkOperations
;
34 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
35 import org
.whispersystems
.signalservice
.api
.push
.ServiceIdType
;
36 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
37 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.AuthorizationFailedException
;
38 import org
.whispersystems
.signalservice
.api
.util
.DeviceNameUtil
;
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 SignalServiceAccountManager accountManager
;
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 GroupsV2Operations groupsV2Operations
= new GroupsV2Operations(ClientZkOperations
.create(
79 serviceEnvironmentConfig
.signalServiceConfiguration()), ServiceConfig
.GROUP_MAX_SIZE
);
80 accountManager
= new SignalServiceAccountManager(serviceEnvironmentConfig
.signalServiceConfiguration(),
81 new DynamicCredentialsProvider(null, null, null, password
, SignalServiceAddress
.DEFAULT_DEVICE_ID
),
84 ServiceConfig
.AUTOMATIC_NETWORK_RETRY
);
88 public URI
getDeviceLinkUri() throws TimeoutException
, IOException
{
89 var deviceUuid
= accountManager
.getNewDeviceUuid();
91 return new DeviceLinkUrl(deviceUuid
, tempIdentityKey
.getPublicKey().getPublicKey()).createDeviceLinkUri();
95 public String
finishDeviceLink(String deviceName
) throws IOException
, TimeoutException
, UserAlreadyExistsException
{
96 var ret
= accountManager
.getNewDeviceRegistration(tempIdentityKey
);
97 var number
= ret
.getNumber();
98 var aci
= ret
.getAci();
99 var pni
= ret
.getPni();
101 logger
.info("Received link information from {}, linking in progress ...", number
);
103 var accountPath
= accountsStore
.getPathByAci(aci
);
104 if (accountPath
== null) {
105 accountPath
= accountsStore
.getPathByNumber(number
);
107 final var accountExists
= accountPath
!= null && SignalAccount
.accountFileExists(pathConfig
.dataPath(),
109 if (accountExists
&& !canRelinkExistingAccount(accountPath
)) {
110 throw new UserAlreadyExistsException(number
, SignalAccount
.getFileName(pathConfig
.dataPath(), accountPath
));
112 if (accountPath
== null) {
113 accountPath
= accountsStore
.addAccount(number
, aci
);
115 accountsStore
.updateAccount(accountPath
, number
, aci
);
118 var encryptedDeviceName
= deviceName
== null
120 : DeviceNameUtil
.encryptDeviceName(deviceName
, ret
.getAciIdentity().getPrivateKey());
121 // Create new account with the synced identity
122 var profileKey
= ret
.getProfileKey() == null ? KeyUtils
.createProfileKey() : ret
.getProfileKey();
124 SignalAccount account
= null;
126 if (!accountExists
) {
127 account
= SignalAccount
.createLinkedAccount(pathConfig
.dataPath(),
129 serviceEnvironmentConfig
.type(),
132 account
= SignalAccount
.load(pathConfig
.dataPath(), accountPath
, true, Settings
.DEFAULT
);
135 account
.setProvisioningData(number
,
140 ret
.getAciIdentity(),
141 ret
.getPniIdentity(),
145 account
.getConfigurationStore().setReadReceipts(ret
.isReadReceipts());
147 final var aciPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.ACI
));
148 final var pniPreKeys
= generatePreKeysForType(account
.getAccountData(ServiceIdType
.PNI
));
150 logger
.debug("Finishing new device registration");
151 var deviceId
= accountManager
.finishNewDeviceRegistration(ret
.getProvisioningCode(),
152 account
.getAccountAttributes(null),
156 account
.finishLinking(deviceId
, aciPreKeys
, pniPreKeys
);
158 ManagerImpl m
= null;
160 m
= new ManagerImpl(account
,
162 new AccountFileUpdaterImpl(accountsStore
, accountPath
),
163 serviceEnvironmentConfig
,
167 logger
.debug("Refreshing pre keys");
170 } catch (Exception e
) {
171 logger
.error("Failed to refresh pre keys.", e
);
174 logger
.debug("Requesting sync data");
176 m
.requestAllSyncData();
177 } catch (Exception e
) {
179 "Failed to request sync messages from linked device, data can be requested again with `sendSyncRequest`.",
183 if (newManagerListener
!= null) {
184 newManagerListener
.accept(m
);
194 if (account
!= null) {
200 private boolean canRelinkExistingAccount(final String accountPath
) throws IOException
{
201 final SignalAccount signalAccount
;
203 signalAccount
= SignalAccount
.load(pathConfig
.dataPath(), accountPath
, false, Settings
.DEFAULT
);
204 } catch (IOException e
) {
205 logger
.debug("Account in use or failed to load.", e
);
207 } catch (OverlappingFileLockException e
) {
208 logger
.debug("Account in use.", e
);
212 try (signalAccount
) {
213 if (signalAccount
.isPrimaryDevice()) {
214 logger
.debug("Account is a primary device.");
217 if (signalAccount
.isRegistered()
218 && signalAccount
.getServiceEnvironment() != null
219 && signalAccount
.getServiceEnvironment() != serviceEnvironmentConfig
.type()) {
220 logger
.debug("Account is registered in another environment: {}.",
221 signalAccount
.getServiceEnvironment());
225 final var m
= new ManagerImpl(signalAccount
,
227 new AccountFileUpdaterImpl(accountsStore
, accountPath
),
228 serviceEnvironmentConfig
,
231 m
.checkAccountState();
232 } catch (AuthorizationFailedException ignored
) {
236 logger
.debug("Account is still successfully linked.");