]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/internal/ProvisioningManagerImpl.java
Check if account is already registered before attempting verification
[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.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.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 String password;
63
64 public ProvisioningManagerImpl(
65 PathConfig pathConfig,
66 ServiceEnvironmentConfig serviceEnvironmentConfig,
67 String userAgent,
68 final Consumer<Manager> newManagerListener,
69 final AccountsStore accountsStore
70 ) {
71 this.pathConfig = pathConfig;
72 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
73 this.userAgent = userAgent;
74 this.newManagerListener = newManagerListener;
75 this.accountsStore = accountsStore;
76
77 tempIdentityKey = KeyUtils.generateIdentityKeyPair();
78 password = KeyUtils.createPassword();
79 GroupsV2Operations groupsV2Operations;
80 try {
81 groupsV2Operations = new GroupsV2Operations(ClientZkOperations.create(serviceEnvironmentConfig.signalServiceConfiguration()),
82 ServiceConfig.GROUP_MAX_SIZE);
83 } catch (Throwable ignored) {
84 groupsV2Operations = null;
85 }
86 accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.signalServiceConfiguration(),
87 new DynamicCredentialsProvider(null, null, null, password, SignalServiceAddress.DEFAULT_DEVICE_ID),
88 userAgent,
89 groupsV2Operations,
90 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
91 }
92
93 @Override
94 public URI getDeviceLinkUri() throws TimeoutException, IOException {
95 var deviceUuid = accountManager.getNewDeviceUuid();
96
97 return new DeviceLinkUrl(deviceUuid, tempIdentityKey.getPublicKey().getPublicKey()).createDeviceLinkUri();
98 }
99
100 @Override
101 public String finishDeviceLink(String deviceName) throws IOException, TimeoutException, UserAlreadyExistsException {
102 var ret = accountManager.getNewDeviceRegistration(tempIdentityKey);
103 var number = ret.getNumber();
104 var aci = ret.getAci();
105 var pni = ret.getPni();
106
107 logger.info("Received link information from {}, linking in progress ...", number);
108
109 var accountPath = accountsStore.getPathByAci(aci);
110 if (accountPath == null) {
111 accountPath = accountsStore.getPathByNumber(number);
112 }
113 final var accountExists = accountPath != null && SignalAccount.accountFileExists(pathConfig.dataPath(),
114 accountPath);
115 if (accountExists && !canRelinkExistingAccount(accountPath)) {
116 throw new UserAlreadyExistsException(number, SignalAccount.getFileName(pathConfig.dataPath(), accountPath));
117 }
118 if (accountPath == null) {
119 accountPath = accountsStore.addAccount(number, aci);
120 } else {
121 accountsStore.updateAccount(accountPath, number, aci);
122 }
123
124 var encryptedDeviceName = deviceName == null
125 ? null
126 : DeviceNameUtil.encryptDeviceName(deviceName, ret.getAciIdentity().getPrivateKey());
127 // Create new account with the synced identity
128 var profileKey = ret.getProfileKey() == null ? KeyUtils.createProfileKey() : ret.getProfileKey();
129
130 SignalAccount account = null;
131 try {
132 if (!accountExists) {
133 account = SignalAccount.createLinkedAccount(pathConfig.dataPath(),
134 accountPath,
135 serviceEnvironmentConfig.type(),
136 Settings.DEFAULT);
137 } else {
138 account = SignalAccount.load(pathConfig.dataPath(), accountPath, true, Settings.DEFAULT);
139 }
140
141 account.setProvisioningData(number,
142 aci,
143 pni,
144 password,
145 encryptedDeviceName,
146 ret.getAciIdentity(),
147 ret.getPniIdentity(),
148 profileKey);
149
150 account.getConfigurationStore().setReadReceipts(ret.isReadReceipts());
151
152 logger.debug("Finishing new device registration");
153 var deviceId = accountManager.finishNewDeviceRegistration(ret.getProvisioningCode(),
154 new ConfirmCodeMessage(false,
155 true,
156 account.getAccountData(ServiceIdType.ACI).getLocalRegistrationId(),
157 account.getAccountData(ServiceIdType.PNI).getLocalRegistrationId(),
158 encryptedDeviceName,
159 getCapabilities(false)));
160
161 account.finishLinking(deviceId);
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 }