]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/internal/ProvisioningManagerImpl.java
2a7ef9e4828bf68742e47c7edcfe84c602fb3933
[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 static final 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 = new GroupsV2Operations(ClientZkOperations.create(
80 serviceEnvironmentConfig.signalServiceConfiguration()), ServiceConfig.GROUP_MAX_SIZE);
81 accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.signalServiceConfiguration(),
82 new DynamicCredentialsProvider(null, null, null, password, SignalServiceAddress.DEFAULT_DEVICE_ID),
83 userAgent,
84 groupsV2Operations,
85 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
86 }
87
88 @Override
89 public URI getDeviceLinkUri() throws TimeoutException, IOException {
90 var deviceUuid = accountManager.getNewDeviceUuid();
91
92 return new DeviceLinkUrl(deviceUuid, tempIdentityKey.getPublicKey().getPublicKey()).createDeviceLinkUri();
93 }
94
95 @Override
96 public String finishDeviceLink(String deviceName) throws IOException, TimeoutException, UserAlreadyExistsException {
97 var ret = accountManager.getNewDeviceRegistration(tempIdentityKey);
98 var number = ret.getNumber();
99 var aci = ret.getAci();
100 var pni = ret.getPni();
101
102 logger.info("Received link information from {}, linking in progress ...", number);
103
104 var accountPath = accountsStore.getPathByAci(aci);
105 if (accountPath == null) {
106 accountPath = accountsStore.getPathByNumber(number);
107 }
108 final var accountExists = accountPath != null && SignalAccount.accountFileExists(pathConfig.dataPath(),
109 accountPath);
110 if (accountExists && !canRelinkExistingAccount(accountPath)) {
111 throw new UserAlreadyExistsException(number, SignalAccount.getFileName(pathConfig.dataPath(), accountPath));
112 }
113 if (accountPath == null) {
114 accountPath = accountsStore.addAccount(number, aci);
115 } else {
116 accountsStore.updateAccount(accountPath, number, aci);
117 }
118
119 var encryptedDeviceName = deviceName == null
120 ? null
121 : DeviceNameUtil.encryptDeviceName(deviceName, ret.getAciIdentity().getPrivateKey());
122 // Create new account with the synced identity
123 var profileKey = ret.getProfileKey() == null ? KeyUtils.createProfileKey() : ret.getProfileKey();
124
125 SignalAccount account = null;
126 try {
127 if (!accountExists) {
128 account = SignalAccount.createLinkedAccount(pathConfig.dataPath(),
129 accountPath,
130 serviceEnvironmentConfig.type(),
131 Settings.DEFAULT);
132 } else {
133 account = SignalAccount.load(pathConfig.dataPath(), accountPath, true, Settings.DEFAULT);
134 }
135
136 account.setProvisioningData(number,
137 aci,
138 pni,
139 password,
140 encryptedDeviceName,
141 ret.getAciIdentity(),
142 ret.getPniIdentity(),
143 profileKey);
144
145 account.getConfigurationStore().setReadReceipts(ret.isReadReceipts());
146
147 logger.debug("Finishing new device registration");
148 var deviceId = accountManager.finishNewDeviceRegistration(ret.getProvisioningCode(),
149 new ConfirmCodeMessage(false,
150 true,
151 account.getAccountData(ServiceIdType.ACI).getLocalRegistrationId(),
152 account.getAccountData(ServiceIdType.PNI).getLocalRegistrationId(),
153 encryptedDeviceName,
154 getCapabilities(false)));
155
156 account.finishLinking(deviceId);
157
158 ManagerImpl m = null;
159 try {
160 m = new ManagerImpl(account,
161 pathConfig,
162 new AccountFileUpdaterImpl(accountsStore, accountPath),
163 serviceEnvironmentConfig,
164 userAgent);
165 account = null;
166
167 logger.debug("Refreshing pre keys");
168 try {
169 m.refreshPreKeys();
170 } catch (Exception e) {
171 logger.error("Failed to refresh pre keys.", e);
172 }
173
174 logger.debug("Requesting sync data");
175 try {
176 m.requestAllSyncData();
177 } catch (Exception e) {
178 logger.error(
179 "Failed to request sync messages from linked device, data can be requested again with `sendSyncRequest`.",
180 e);
181 }
182
183 if (newManagerListener != null) {
184 newManagerListener.accept(m);
185 m = null;
186 }
187 return number;
188 } finally {
189 if (m != null) {
190 m.close();
191 }
192 }
193 } finally {
194 if (account != null) {
195 account.close();
196 }
197 }
198 }
199
200 private boolean canRelinkExistingAccount(final String accountPath) throws IOException {
201 final SignalAccount signalAccount;
202 try {
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);
206 return false;
207 } catch (OverlappingFileLockException e) {
208 logger.debug("Account in use.", e);
209 return false;
210 }
211
212 try (signalAccount) {
213 if (signalAccount.isPrimaryDevice()) {
214 logger.debug("Account is a primary device.");
215 return false;
216 }
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());
222 return false;
223 }
224
225 final var m = new ManagerImpl(signalAccount,
226 pathConfig,
227 new AccountFileUpdaterImpl(accountsStore, accountPath),
228 serviceEnvironmentConfig,
229 userAgent);
230 try (m) {
231 m.checkAccountState();
232 } catch (AuthorizationFailedException ignored) {
233 return true;
234 }
235
236 logger.debug("Account is still successfully linked.");
237 return false;
238 }
239 }
240 }