]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/ProvisioningManagerImpl.java
Handle OverlappingFileLockException when linking
[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.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import org.whispersystems.libsignal.IdentityKeyPair;
29 import org.whispersystems.libsignal.util.KeyHelper;
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 } catch (Throwable ignored) {
79 groupsV2Operations = null;
80 }
81 accountManager = new SignalServiceAccountManager(serviceEnvironmentConfig.getSignalServiceConfiguration(),
82 new DynamicCredentialsProvider(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 DeviceLinkInfo(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
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 if (accountPath != null
108 && SignalAccount.accountFileExists(pathConfig.dataPath(), accountPath)
109 && !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.getIdentity().getPrivateKey());
121
122 logger.debug("Finishing new device registration");
123 var deviceId = accountManager.finishNewDeviceRegistration(ret.getProvisioningCode(),
124 false,
125 true,
126 registrationId,
127 encryptedDeviceName);
128
129 // Create new account with the synced identity
130 var profileKey = ret.getProfileKey() == null ? KeyUtils.createProfileKey() : ret.getProfileKey();
131
132 SignalAccount account = null;
133 try {
134 account = SignalAccount.createOrUpdateLinkedAccount(pathConfig.dataPath(),
135 accountPath,
136 number,
137 aci,
138 password,
139 encryptedDeviceName,
140 deviceId,
141 ret.getIdentity(),
142 registrationId,
143 profileKey,
144 TrustNewIdentity.ON_FIRST_USE);
145
146 ManagerImpl m = null;
147 try {
148 final var accountPathFinal = accountPath;
149 m = new ManagerImpl(account,
150 pathConfig,
151 (newNumber, newAci) -> accountsStore.updateAccount(accountPathFinal, newNumber, newAci),
152 serviceEnvironmentConfig,
153 userAgent);
154 account = null;
155
156 logger.debug("Refreshing pre keys");
157 try {
158 m.refreshPreKeys();
159 } catch (Exception e) {
160 logger.error("Failed to refresh pre keys.");
161 }
162
163 logger.debug("Requesting sync data");
164 try {
165 m.requestAllSyncData();
166 } catch (Exception e) {
167 logger.error(
168 "Failed to request sync messages from linked device, data can be requested again with `sendSyncRequest`.");
169 }
170
171 if (newManagerListener != null) {
172 newManagerListener.accept(m);
173 m = null;
174 }
175 return number;
176 } finally {
177 if (m != null) {
178 m.close();
179 }
180 }
181 } finally {
182 if (account != null) {
183 account.close();
184 }
185 }
186 }
187
188 private boolean canRelinkExistingAccount(final String accountPath) throws IOException {
189 final SignalAccount signalAccount;
190 try {
191 signalAccount = SignalAccount.load(pathConfig.dataPath(),
192 accountPath,
193 false,
194 TrustNewIdentity.ON_FIRST_USE);
195 } catch (IOException e) {
196 logger.debug("Account in use or failed to load.", e);
197 return false;
198 } catch (OverlappingFileLockException e) {
199 logger.debug("Account in use.", e);
200 return false;
201 }
202
203 try (signalAccount) {
204 if (signalAccount.isMasterDevice()) {
205 logger.debug("Account is a master device.");
206 return false;
207 }
208
209 final var m = new ManagerImpl(signalAccount,
210 pathConfig,
211 (newNumber, newAci) -> accountsStore.updateAccount(accountPath, newNumber, newAci),
212 serviceEnvironmentConfig,
213 userAgent);
214 try (m) {
215 m.checkAccountState();
216 } catch (AuthorizationFailedException ignored) {
217 return true;
218 }
219
220 logger.debug("Account is still successfully linked.");
221 return false;
222 }
223 }
224 }