]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/internal/ProvisioningManagerImpl.java
Convert classes to records
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / internal / ProvisioningManagerImpl.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.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.signal.libsignal.protocol.util.KeyHelper;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.whispersystems.signalservice.api.SignalServiceAccountManager;
34 import org.whispersystems.signalservice.api.groupsv2.ClientZkOperations;
35 import org.whispersystems.signalservice.api.groupsv2.GroupsV2Operations;
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.push.ConfirmCodeMessage;
40 import org.whispersystems.signalservice.internal.util.DynamicCredentialsProvider;
41
42 import java.io.IOException;
43 import java.net.URI;
44 import java.nio.channels.OverlappingFileLockException;
45 import java.util.concurrent.TimeoutException;
46 import java.util.function.Consumer;
47
48 import static org.asamk.signal.manager.config.ServiceConfig.getCapabilities;
49
50 public class ProvisioningManagerImpl implements ProvisioningManager {
51
52 private final static Logger logger = LoggerFactory.getLogger(ProvisioningManagerImpl.class);
53
54 private final PathConfig pathConfig;
55 private final ServiceEnvironmentConfig serviceEnvironmentConfig;
56 private final String userAgent;
57 private final Consumer<Manager> newManagerListener;
58 private final AccountsStore accountsStore;
59
60 private final SignalServiceAccountManager accountManager;
61 private final IdentityKeyPair tempIdentityKey;
62 private final int registrationId;
63 private final int pniRegistrationId;
64 private final String password;
65
66 public ProvisioningManagerImpl(
67 PathConfig pathConfig,
68 ServiceEnvironmentConfig serviceEnvironmentConfig,
69 String userAgent,
70 final Consumer<Manager> newManagerListener,
71 final AccountsStore accountsStore
72 ) {
73 this.pathConfig = pathConfig;
74 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
75 this.userAgent = userAgent;
76 this.newManagerListener = newManagerListener;
77 this.accountsStore = accountsStore;
78
79 tempIdentityKey = KeyUtils.generateIdentityKeyPair();
80 registrationId = KeyHelper.generateRegistrationId(false);
81 pniRegistrationId = KeyHelper.generateRegistrationId(false);
82 password = KeyUtils.createPassword();
83 GroupsV2Operations groupsV2Operations;
84 try {
85 groupsV2Operations = new GroupsV2Operations(ClientZkOperations.create(serviceEnvironmentConfig.signalServiceConfiguration()),
86 ServiceConfig.GROUP_MAX_SIZE);
87 } catch (Throwable ignored) {
88 groupsV2Operations = null;
89 }
90 accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.signalServiceConfiguration(),
91 new DynamicCredentialsProvider(null, null, null, password, SignalServiceAddress.DEFAULT_DEVICE_ID),
92 userAgent,
93 groupsV2Operations,
94 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
95 }
96
97 @Override
98 public URI getDeviceLinkUri() throws TimeoutException, IOException {
99 var deviceUuid = accountManager.getNewDeviceUuid();
100
101 return new DeviceLinkUrl(deviceUuid, tempIdentityKey.getPublicKey().getPublicKey()).createDeviceLinkUri();
102 }
103
104 @Override
105 public String finishDeviceLink(String deviceName) throws IOException, TimeoutException, UserAlreadyExistsException {
106 var ret = accountManager.getNewDeviceRegistration(tempIdentityKey);
107 var number = ret.getNumber();
108 var aci = ret.getAci();
109 var pni = ret.getPni();
110
111 logger.info("Received link information from {}, linking in progress ...", number);
112
113 var accountPath = accountsStore.getPathByAci(aci);
114 if (accountPath == null) {
115 accountPath = accountsStore.getPathByNumber(number);
116 }
117 if (accountPath != null
118 && SignalAccount.accountFileExists(pathConfig.dataPath(), accountPath)
119 && !canRelinkExistingAccount(accountPath)) {
120 throw new UserAlreadyExistsException(number, SignalAccount.getFileName(pathConfig.dataPath(), accountPath));
121 }
122 if (accountPath == null) {
123 accountPath = accountsStore.addAccount(number, aci);
124 } else {
125 accountsStore.updateAccount(accountPath, number, aci);
126 }
127
128 var encryptedDeviceName = deviceName == null
129 ? null
130 : DeviceNameUtil.encryptDeviceName(deviceName, ret.getAciIdentity().getPrivateKey());
131
132 logger.debug("Finishing new device registration");
133 var deviceId = accountManager.finishNewDeviceRegistration(ret.getProvisioningCode(),
134 new ConfirmCodeMessage(false,
135 true,
136 registrationId,
137 pniRegistrationId,
138 encryptedDeviceName,
139 getCapabilities(false)));
140
141 // Create new account with the synced identity
142 var profileKey = ret.getProfileKey() == null ? KeyUtils.createProfileKey() : ret.getProfileKey();
143
144 SignalAccount account = null;
145 try {
146 account = SignalAccount.createOrUpdateLinkedAccount(pathConfig.dataPath(),
147 accountPath,
148 number,
149 serviceEnvironmentConfig.type(),
150 aci,
151 pni,
152 password,
153 encryptedDeviceName,
154 deviceId,
155 ret.getAciIdentity(),
156 ret.getPniIdentity(),
157 registrationId,
158 pniRegistrationId,
159 profileKey,
160 Settings.DEFAULT);
161 account.getConfigurationStore().setReadReceipts(ret.isReadReceipts());
162
163 ManagerImpl m = null;
164 try {
165 m = new ManagerImpl(account,
166 pathConfig,
167 new AccountFileUpdaterImpl(accountsStore, accountPath),
168 serviceEnvironmentConfig,
169 userAgent);
170 account = null;
171
172 logger.debug("Refreshing pre keys");
173 try {
174 m.refreshPreKeys();
175 } catch (Exception e) {
176 logger.error("Failed to refresh pre keys.", e);
177 }
178
179 logger.debug("Requesting sync data");
180 try {
181 m.requestAllSyncData();
182 } catch (Exception e) {
183 logger.error(
184 "Failed to request sync messages from linked device, data can be requested again with `sendSyncRequest`.",
185 e);
186 }
187
188 if (newManagerListener != null) {
189 newManagerListener.accept(m);
190 m = null;
191 }
192 return number;
193 } finally {
194 if (m != null) {
195 m.close();
196 }
197 }
198 } finally {
199 if (account != null) {
200 account.close();
201 }
202 }
203 }
204
205 private boolean canRelinkExistingAccount(final String accountPath) throws IOException {
206 final SignalAccount signalAccount;
207 try {
208 signalAccount = SignalAccount.load(pathConfig.dataPath(), accountPath, false, Settings.DEFAULT);
209 } catch (IOException e) {
210 logger.debug("Account in use or failed to load.", e);
211 return false;
212 } catch (OverlappingFileLockException e) {
213 logger.debug("Account in use.", e);
214 return false;
215 }
216
217 try (signalAccount) {
218 if (signalAccount.isPrimaryDevice()) {
219 logger.debug("Account is a primary device.");
220 return false;
221 }
222 if (signalAccount.isRegistered()
223 && signalAccount.getServiceEnvironment() != null
224 && signalAccount.getServiceEnvironment() != serviceEnvironmentConfig.type()) {
225 logger.debug("Account is registered in another environment: {}.",
226 signalAccount.getServiceEnvironment());
227 return false;
228 }
229
230 final var m = new ManagerImpl(signalAccount,
231 pathConfig,
232 new AccountFileUpdaterImpl(accountsStore, accountPath),
233 serviceEnvironmentConfig,
234 userAgent);
235 try (m) {
236 m.checkAccountState();
237 } catch (AuthorizationFailedException ignored) {
238 return true;
239 }
240
241 logger.debug("Account is still successfully linked.");
242 return false;
243 }
244 }
245 }