blob: 9da05443d60a100c67b9a9cf426f6e58f363a022 [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
Amnac75ffe92024-02-08 17:23:29 -050088dhtnet::Dsh::Dsh(dht::crypto::Identity identity,
Amna2b5b07f2024-01-22 17:04:36 -050089 const std::string& bootstrap,
90 const std::string& turn_host,
91 const std::string& turn_user,
92 const std::string& turn_pass,
Amna4325f0f2024-01-22 16:11:00 -050093 const std::string& turn_realm,
94 bool anonymous)
Amnaa5452cf2024-01-22 16:07:24 -050095 :logger(dht::log::getStdLogger())
96 , ioContext(std::make_shared<asio::io_context>()),
Amna4325f0f2024-01-22 16:11:00 -050097 iceFactory(std::make_shared<IceTransportFactory>(logger)),
Amnac75ffe92024-02-08 17:23:29 -050098 certStore(std::make_shared<tls::CertificateStore>(PATH/"certstore", logger)),
Amna4325f0f2024-01-22 16:11:00 -050099 trustStore(std::make_shared<tls::TrustStore>(*certStore))
Amna4a70f5c2023-09-14 17:32:05 -0400100{
Amna4a70f5c2023-09-14 17:32:05 -0400101 ioContext = std::make_shared<asio::io_context>();
102 ioContextRunner = std::thread([context = ioContext, logger = logger] {
103 try {
104 auto work = asio::make_work_guard(*context);
105 context->run();
106 } catch (const std::exception& ex) {
107 if (logger)
108 logger->error("Error in ioContextRunner: {}", ex.what());
109 }
110 });
Amna4325f0f2024-01-22 16:11:00 -0500111 auto ca = identity.second->issuer;
112 trustStore->setCertificateStatus(ca->getId().toString(), tls::TrustStore::PermissionStatus::ALLOWED);
Amna4a70f5c2023-09-14 17:32:05 -0400113 // Build a server
Amnac75ffe92024-02-08 17:23:29 -0500114 auto config = connectionManagerConfig(identity,
Amna4a70f5c2023-09-14 17:32:05 -0400115 bootstrap,
116 logger,
117 certStore,
118 ioContext,
Amnaa5452cf2024-01-22 16:07:24 -0500119 iceFactory);
Amna4a70f5c2023-09-14 17:32:05 -0400120 // create a connection manager
121 connectionManager = std::make_unique<ConnectionManager>(std::move(config));
122
123 connectionManager->onDhtConnected(identity.first->getPublicKey());
Amna4325f0f2024-01-22 16:11:00 -0500124 connectionManager->onICERequest([this,identity,anonymous](const DeviceId& deviceId ) { // handle ICE request
125 return trustStore->isAllowed(*certStore->getCertificate(deviceId.toString()), anonymous);
Amna4a70f5c2023-09-14 17:32:05 -0400126 });
127
128 std::mutex mtx;
Adrien Béraud024c46f2024-03-02 23:53:18 -0500129 std::unique_lock lk {mtx};
Amna4a70f5c2023-09-14 17:32:05 -0400130
131 connectionManager->onChannelRequest(
132 [&](const std::shared_ptr<dht::crypto::Certificate>&, const std::string& name) {
133 // handle channel request
134 if (logger)
135 logger->debug("Channel request received");
136 return true;
137 });
138
139 connectionManager->onConnectionReady([&](const DeviceId&,
140 const std::string& name,
141 std::shared_ptr<ChannelSocket> socket) {
142 // handle connection ready
143 try {
144 // Create a pipe for communication with the subprocess
145 // create pipes
146 int in_pipe[2], out_pipe[2], error_pipe[2];
147 create_pipe(in_pipe);
148 create_pipe(out_pipe);
149 create_pipe(error_pipe);
150
151 ioContext->notify_fork(asio::io_context::fork_prepare);
152
153 // Fork to create a child process
154 pid_t pid = fork();
155 if (pid == -1) {
156 perror("fork");
157 return EXIT_FAILURE;
158 } else if (pid == 0) { // Child process
159 ioContext->notify_fork(asio::io_context::fork_child);
160 child_proc(in_pipe, out_pipe, error_pipe, name);
161 return EXIT_SUCCESS; // never reached
162 } else {
163 ioContext->notify_fork(asio::io_context::fork_parent);
164
165 // close unused read end of input pipe and write end of output pipe
166 close(in_pipe[READ_END]);
167 close(out_pipe[WRITE_END]);
168 close(error_pipe[WRITE_END]);
169
170 asio::io_context& ioContextRef = *ioContext;
171 // create stream descriptors
172 auto inStream
173 = std::make_shared<asio::posix::stream_descriptor>(ioContextRef.get_executor(),
174 in_pipe[WRITE_END]);
175 auto outStream
176 = std::make_shared<asio::posix::stream_descriptor>(ioContextRef.get_executor(),
177 out_pipe[READ_END]);
178 auto errorStream
179 = std::make_shared<asio::posix::stream_descriptor>(ioContextRef.get_executor(),
180 error_pipe[READ_END]);
181
182 if (socket) {
183 socket->setOnRecv([this, socket, inStream](const uint8_t* data, size_t size) {
184 auto data_copy = std::make_shared<std::vector<uint8_t>>(data, data + size);
185 // write on pipe to sub child
186 std::error_code ec;
187 asio::async_write(*inStream,
188 asio::buffer(*data_copy),
189 [data_copy, this](const std::error_code& error,
190 std::size_t bytesWritten) {
191 if (error) {
192 if (logger)
193 logger->error("Write error: {}",
194 error.message());
195 }
196 });
197 return size;
198 });
199
200 // read from pipe to sub child
201
202 // Create a buffer to read data into
203 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
204
205 // Create a shared_ptr to the stream_descriptor
206 readFromPipe(socket, outStream, buffer);
207 readFromPipe(socket, errorStream, buffer);
208
209 return EXIT_SUCCESS;
210 }
211 }
212
213 } catch (const std::exception& e) {
214 if (logger)
215 logger->error("Error: {}", e.what());
216 }
217 return 0;
218 });
219}
220
Amnac75ffe92024-02-08 17:23:29 -0500221dhtnet::Dsh::Dsh(dht::crypto::Identity identity,
Amna4a70f5c2023-09-14 17:32:05 -0400222 const std::string& bootstrap,
223 dht::InfoHash peer_id,
Amna2b5b07f2024-01-22 17:04:36 -0500224 const std::string& binary,
225 const std::string& turn_host,
226 const std::string& turn_user,
227 const std::string& turn_pass,
228 const std::string& turn_realm)
Amnac75ffe92024-02-08 17:23:29 -0500229 : Dsh(identity, bootstrap, turn_host, turn_user, turn_pass, turn_realm, false)
Amna4a70f5c2023-09-14 17:32:05 -0400230{
231 // Build a client
232 std::condition_variable cv;
233 connectionManager->connectDevice(
234 peer_id, binary, [&](std::shared_ptr<ChannelSocket> socket, const dht::InfoHash&) {
235 if (socket) {
236 socket->setOnRecv([this, socket](const uint8_t* data, size_t size) {
237 std::cout.write((const char*) data, size);
238 std::cout.flush();
239 return size;
240 });
241 // Create a buffer to read data into
242 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
243
244 // Create a shared_ptr to the stream_descriptor
245 auto stdinPipe = std::make_shared<asio::posix::stream_descriptor>(*ioContext,
246 ::dup(
247 STDIN_FILENO));
248 readFromPipe(socket, stdinPipe, buffer);
249
250 socket->onShutdown([this]() {
251 if (logger)
252 logger->debug("Exit program");
253 ioContext->stop();
254 });
255 }
256 });
257
258 connectionManager->onConnectionReady([&](const DeviceId&,
259 const std::string& name,
260 std::shared_ptr<ChannelSocket> socket_received) {
261 if (logger)
262 logger->debug("Connected!");
263 });
264}
265
266void
267dhtnet::Dsh::run()
268{
269 ioContext->run();
270}
271
272dhtnet::Dsh::~Dsh()
273{
274 ioContext->stop();
275 ioContextRunner.join();
276}
277
278} // namespace dhtnet