blob: 4e7507d7e555b02deca73d7fe9a16be6761be73a [file] [log] [blame]
Amna4a70f5c2023-09-14 17:32:05 -04001/*
2 * Copyright (C) 2023 Savoir-faire Linux Inc.
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 <https://www.gnu.org/licenses/>.
16 */
17#include "dsh.h"
18#include "../common.h"
19#include <opendht/log.h>
20#include <opendht/crypto.h>
21
22#include <asio/io_context.hpp>
23#include <sys/types.h>
24#include <sys/wait.h>
25namespace dhtnet {
26
27const int READ_END = 0;
28const int WRITE_END = 1;
29
30void
Adrien Béraud651a4c62023-09-20 14:17:08 -040031create_pipe(int apipe[2])
Amna4a70f5c2023-09-14 17:32:05 -040032{
Adrien Béraud651a4c62023-09-20 14:17:08 -040033#ifdef __APPLE__
34 if (pipe(apipe) < 0)
35 perror("pipe");
36
37 if (fcntl(apipe[0], F_SETFD, FD_CLOEXEC) < 0)
38 perror("unable to set pipe FD_CLOEXEC");
39
40 if (fcntl(apipe[1], F_SETFD, FD_CLOEXEC) < 0)
41 perror("unable to set pipe FD_CLOEXEC");
42#else
43 if (pipe2(apipe, O_CLOEXEC) == -1) {
Amna4a70f5c2023-09-14 17:32:05 -040044 perror("pipe2");
45 exit(EXIT_FAILURE);
46 }
Adrien Béraud651a4c62023-09-20 14:17:08 -040047#endif
Amna4a70f5c2023-09-14 17:32:05 -040048}
Adrien Béraud651a4c62023-09-20 14:17:08 -040049
Amna4a70f5c2023-09-14 17:32:05 -040050void
51child_proc(const int in_pipe[2],
52 const int out_pipe[2],
53 const int error_pipe[2],
54 const std::string& name)
55{
56 // close unused write end of input pipe and read end of output pipe
57 close(in_pipe[WRITE_END]);
58 close(out_pipe[READ_END]);
59 close(error_pipe[READ_END]);
60
61 // replace stdin with input pipe
62 if (dup2(in_pipe[READ_END], STDIN_FILENO) == -1) {
63 perror("dup2: error replacing stdin");
64 exit(EXIT_FAILURE);
65 }
66
67 // replace stdout with output pipe
68 if (dup2(out_pipe[WRITE_END], STDOUT_FILENO) == -1) {
69 perror("dup2: error replacing stdout");
70 exit(EXIT_FAILURE);
71 }
72 // replace stderr with error pipe
73 if (dup2(error_pipe[WRITE_END], STDERR_FILENO) == -1) {
74 perror("dup2: error replacing stderr");
75 exit(EXIT_FAILURE);
76 }
77
78 // prepare arguments
79 const char* args[] = {name.c_str(), NULL};
80 // execute subprocess
81 execvp(args[0], const_cast<char* const*>(args));
82
83 // if execv returns, an error occurred
84 perror("execvp");
85 exit(EXIT_FAILURE);
86}
87
88dhtnet::Dsh::Dsh(const std::filesystem::path& path,
89 dht::crypto::Identity identity,
Amna2b5b07f2024-01-22 17:04:36 -050090 const std::string& bootstrap,
91 const std::string& turn_host,
92 const std::string& turn_user,
93 const std::string& turn_pass,
Amna4325f0f2024-01-22 16:11:00 -050094 const std::string& turn_realm,
95 bool anonymous)
Amnaa5452cf2024-01-22 16:07:24 -050096 :logger(dht::log::getStdLogger())
97 , ioContext(std::make_shared<asio::io_context>()),
Amna4325f0f2024-01-22 16:11:00 -050098 iceFactory(std::make_shared<IceTransportFactory>(logger)),
99 certStore(std::make_shared<tls::CertificateStore>(path / "certstore", logger)),
100 trustStore(std::make_shared<tls::TrustStore>(*certStore))
Amna4a70f5c2023-09-14 17:32:05 -0400101{
Amna4a70f5c2023-09-14 17:32:05 -0400102 ioContext = std::make_shared<asio::io_context>();
103 ioContextRunner = std::thread([context = ioContext, logger = logger] {
104 try {
105 auto work = asio::make_work_guard(*context);
106 context->run();
107 } catch (const std::exception& ex) {
108 if (logger)
109 logger->error("Error in ioContextRunner: {}", ex.what());
110 }
111 });
Amna4325f0f2024-01-22 16:11:00 -0500112 auto ca = identity.second->issuer;
113 trustStore->setCertificateStatus(ca->getId().toString(), tls::TrustStore::PermissionStatus::ALLOWED);
Amna4a70f5c2023-09-14 17:32:05 -0400114 // Build a server
115 auto config = connectionManagerConfig(path,
116 identity,
117 bootstrap,
118 logger,
119 certStore,
120 ioContext,
Amnaa5452cf2024-01-22 16:07:24 -0500121 iceFactory);
Amna4a70f5c2023-09-14 17:32:05 -0400122 // create a connection manager
123 connectionManager = std::make_unique<ConnectionManager>(std::move(config));
124
125 connectionManager->onDhtConnected(identity.first->getPublicKey());
Amna4325f0f2024-01-22 16:11:00 -0500126 connectionManager->onICERequest([this,identity,anonymous](const DeviceId& deviceId ) { // handle ICE request
127 return trustStore->isAllowed(*certStore->getCertificate(deviceId.toString()), anonymous);
Amna4a70f5c2023-09-14 17:32:05 -0400128 });
129
130 std::mutex mtx;
131 std::unique_lock<std::mutex> lk {mtx};
132
133 connectionManager->onChannelRequest(
134 [&](const std::shared_ptr<dht::crypto::Certificate>&, const std::string& name) {
135 // handle channel request
136 if (logger)
137 logger->debug("Channel request received");
138 return true;
139 });
140
141 connectionManager->onConnectionReady([&](const DeviceId&,
142 const std::string& name,
143 std::shared_ptr<ChannelSocket> socket) {
144 // handle connection ready
145 try {
146 // Create a pipe for communication with the subprocess
147 // create pipes
148 int in_pipe[2], out_pipe[2], error_pipe[2];
149 create_pipe(in_pipe);
150 create_pipe(out_pipe);
151 create_pipe(error_pipe);
152
153 ioContext->notify_fork(asio::io_context::fork_prepare);
154
155 // Fork to create a child process
156 pid_t pid = fork();
157 if (pid == -1) {
158 perror("fork");
159 return EXIT_FAILURE;
160 } else if (pid == 0) { // Child process
161 ioContext->notify_fork(asio::io_context::fork_child);
162 child_proc(in_pipe, out_pipe, error_pipe, name);
163 return EXIT_SUCCESS; // never reached
164 } else {
165 ioContext->notify_fork(asio::io_context::fork_parent);
166
167 // close unused read end of input pipe and write end of output pipe
168 close(in_pipe[READ_END]);
169 close(out_pipe[WRITE_END]);
170 close(error_pipe[WRITE_END]);
171
172 asio::io_context& ioContextRef = *ioContext;
173 // create stream descriptors
174 auto inStream
175 = std::make_shared<asio::posix::stream_descriptor>(ioContextRef.get_executor(),
176 in_pipe[WRITE_END]);
177 auto outStream
178 = std::make_shared<asio::posix::stream_descriptor>(ioContextRef.get_executor(),
179 out_pipe[READ_END]);
180 auto errorStream
181 = std::make_shared<asio::posix::stream_descriptor>(ioContextRef.get_executor(),
182 error_pipe[READ_END]);
183
184 if (socket) {
185 socket->setOnRecv([this, socket, inStream](const uint8_t* data, size_t size) {
186 auto data_copy = std::make_shared<std::vector<uint8_t>>(data, data + size);
187 // write on pipe to sub child
188 std::error_code ec;
189 asio::async_write(*inStream,
190 asio::buffer(*data_copy),
191 [data_copy, this](const std::error_code& error,
192 std::size_t bytesWritten) {
193 if (error) {
194 if (logger)
195 logger->error("Write error: {}",
196 error.message());
197 }
198 });
199 return size;
200 });
201
202 // read from pipe to sub child
203
204 // Create a buffer to read data into
205 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
206
207 // Create a shared_ptr to the stream_descriptor
208 readFromPipe(socket, outStream, buffer);
209 readFromPipe(socket, errorStream, buffer);
210
211 return EXIT_SUCCESS;
212 }
213 }
214
215 } catch (const std::exception& e) {
216 if (logger)
217 logger->error("Error: {}", e.what());
218 }
219 return 0;
220 });
221}
222
223dhtnet::Dsh::Dsh(const std::filesystem::path& path,
224 dht::crypto::Identity identity,
225 const std::string& bootstrap,
226 dht::InfoHash peer_id,
Amna2b5b07f2024-01-22 17:04:36 -0500227 const std::string& binary,
228 const std::string& turn_host,
229 const std::string& turn_user,
230 const std::string& turn_pass,
231 const std::string& turn_realm)
Amna4325f0f2024-01-22 16:11:00 -0500232 : Dsh(path, identity, bootstrap, turn_host, turn_user, turn_pass, turn_realm, false)
Amna4a70f5c2023-09-14 17:32:05 -0400233{
234 // Build a client
235 std::condition_variable cv;
236 connectionManager->connectDevice(
237 peer_id, binary, [&](std::shared_ptr<ChannelSocket> socket, const dht::InfoHash&) {
238 if (socket) {
239 socket->setOnRecv([this, socket](const uint8_t* data, size_t size) {
240 std::cout.write((const char*) data, size);
241 std::cout.flush();
242 return size;
243 });
244 // Create a buffer to read data into
245 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
246
247 // Create a shared_ptr to the stream_descriptor
248 auto stdinPipe = std::make_shared<asio::posix::stream_descriptor>(*ioContext,
249 ::dup(
250 STDIN_FILENO));
251 readFromPipe(socket, stdinPipe, buffer);
252
253 socket->onShutdown([this]() {
254 if (logger)
255 logger->debug("Exit program");
256 ioContext->stop();
257 });
258 }
259 });
260
261 connectionManager->onConnectionReady([&](const DeviceId&,
262 const std::string& name,
263 std::shared_ptr<ChannelSocket> socket_received) {
264 if (logger)
265 logger->debug("Connected!");
266 });
267}
268
269void
270dhtnet::Dsh::run()
271{
272 ioContext->run();
273}
274
275dhtnet::Dsh::~Dsh()
276{
277 ioContext->stop();
278 ioContextRunner.join();
279}
280
281} // namespace dhtnet