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