]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/internal/ProvisioningManagerImpl.java
Allow setting a username with explicit descriminator
[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.util.DynamicCredentialsProvider;
40
41 import java.io.IOException;
42 import java.net.URI;
43 import java.nio.channels.OverlappingFileLockException;
44 import java.util.concurrent.TimeoutException;
45 import java.util.function.Consumer;
46
47 import static org.asamk.signal.manager.util.KeyUtils.generatePreKeysForType;
48
49 public class ProvisioningManagerImpl implements ProvisioningManager {
50
51 private static final Logger logger = LoggerFactory.getLogger(ProvisioningManagerImpl.class);
52
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;
58
59 private final SignalServiceAccountManager accountManager;
60 private final IdentityKeyPair tempIdentityKey;
61 private final String password;
62
63 public ProvisioningManagerImpl(
64 PathConfig pathConfig,
65 ServiceEnvironmentConfig serviceEnvironmentConfig,
66 String userAgent,
67 final Consumer<Manager> newManagerListener,
68 final AccountsStore accountsStore
69 ) {
70 this.pathConfig = pathConfig;
71 this.serviceEnvironmentConfig = serviceEnvironmentConfig;
72 this.userAgent = userAgent;
73 this.newManagerListener = newManagerListener;
74 this.accountsStore = accountsStore;
75
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),
82 userAgent,
83 groupsV2Operations,
84 ServiceConfig.AUTOMATIC_NETWORK_RETRY);
85 }
86
87 @Override
88 public URI getDeviceLinkUri() throws TimeoutException, IOException {
89 var deviceUuid = accountManager.getNewDeviceUuid();
90
91 return new DeviceLinkUrl(deviceUuid, tempIdentityKey.getPublicKey().getPublicKey()).createDeviceLinkUri();
92 }
93
94 @Override
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();
100
101 logger.info("Received link information from {}, linking in progress ...", number);
102
103 var accountPath = accountsStore.getPathByAci(aci);
104 if (accountPath == null) {
105 accountPath = accountsStore.getPathByNumber(number);
106 }
107 final var accountExists = accountPath != null && SignalAccount.accountFileExists(pathConfig.dataPath(),
108 accountPath);
109 if (accountExists && !canRelinkExistingAccount(accountPath)) {
110 throw new UserAlreadyExistsException(number, SignalAccount.getFileName(pathConfig.dataPath(), accountPath));
111 }
112 if (accountPath == null) {
113 accountPath = accountsStore.addAccount(number, aci);
114 } else {
115 accountsStore.updateAccount(accountPath, number, aci);
116 }
117
118 var encryptedDeviceName = deviceName == null
119 ? 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();
123
124 SignalAccount account = null;
125 try {
126 if (!accountExists) {
127 account = SignalAccount.createLinkedAccount(pathConfig.dataPath(),
128 accountPath,
129 serviceEnvironmentConfig.type(),
130 Settings.DEFAULT);
131 } else {
132 account = SignalAccount.load(pathConfig.dataPath(), accountPath, true, Settings.DEFAULT);
133 }
134
135 account.setProvisioningData(number,
136 aci,
137 pni,
138 password,
139 encryptedDeviceName,
140 ret.getAciIdentity(),
141 ret.getPniIdentity(),
142 profileKey,
143 ret.getMasterKey());
144
145 account.getConfigurationStore().setReadReceipts(ret.isReadReceipts());
146
147 final var aciPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.ACI));
148 final var pniPreKeys = generatePreKeysForType(account.getAccountData(ServiceIdType.PNI));
149
150 logger.debug("Finishing new device registration");
151 var deviceId = accountManager.finishNewDeviceRegistration(ret.getProvisioningCode(),
152 account.getAccountAttributes(null),
153 aciPreKeys,
154 pniPreKeys);
155
156 account.finishLinking(deviceId, aciPreKeys, pniPreKeys);
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 }