blob: ca4e99d2f38ee754114b73ac1d4a3234ae72ed82 [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,
94 const std::string& turn_realm)
Amnaa5452cf2024-01-22 16:07:24 -050095 :logger(dht::log::getStdLogger())
96 , ioContext(std::make_shared<asio::io_context>()),
97 iceFactory(std::make_shared<IceTransportFactory>(logger))
Amna4a70f5c2023-09-14 17:32:05 -040098{
99 auto certStore = std::make_shared<tls::CertificateStore>(path / "certstore", logger);
100
101 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 });
111 // Build a server
112 auto config = connectionManagerConfig(path,
113 identity,
114 bootstrap,
115 logger,
116 certStore,
117 ioContext,
Amnaa5452cf2024-01-22 16:07:24 -0500118 iceFactory);
Amna4a70f5c2023-09-14 17:32:05 -0400119 // create a connection manager
120 connectionManager = std::make_unique<ConnectionManager>(std::move(config));
121
122 connectionManager->onDhtConnected(identity.first->getPublicKey());
123 connectionManager->onICERequest([this](const dht::Hash<32>&) { // handle ICE request
124 if (logger)
125 logger->debug("ICE request received");
126 return true;
127 });
128
129 std::mutex mtx;
130 std::unique_lock<std::mutex> lk {mtx};
131
132 connectionManager->onChannelRequest(
133 [&](const std::shared_ptr<dht::crypto::Certificate>&, const std::string& name) {
134 // handle channel request
135 if (logger)
136 logger->debug("Channel request received");
137 return true;
138 });
139
140 connectionManager->onConnectionReady([&](const DeviceId&,
141 const std::string& name,
142 std::shared_ptr<ChannelSocket> socket) {
143 // handle connection ready
144 try {
145 // Create a pipe for communication with the subprocess
146 // create pipes
147 int in_pipe[2], out_pipe[2], error_pipe[2];
148 create_pipe(in_pipe);
149 create_pipe(out_pipe);
150 create_pipe(error_pipe);
151
152 ioContext->notify_fork(asio::io_context::fork_prepare);
153
154 // Fork to create a child process
155 pid_t pid = fork();
156 if (pid == -1) {
157 perror("fork");
158 return EXIT_FAILURE;
159 } else if (pid == 0) { // Child process
160 ioContext->notify_fork(asio::io_context::fork_child);
161 child_proc(in_pipe, out_pipe, error_pipe, name);
162 return EXIT_SUCCESS; // never reached
163 } else {
164 ioContext->notify_fork(asio::io_context::fork_parent);
165
166 // close unused read end of input pipe and write end of output pipe
167 close(in_pipe[READ_END]);
168 close(out_pipe[WRITE_END]);
169 close(error_pipe[WRITE_END]);
170
171 asio::io_context& ioContextRef = *ioContext;
172 // create stream descriptors
173 auto inStream
174 = std::make_shared<asio::posix::stream_descriptor>(ioContextRef.get_executor(),
175 in_pipe[WRITE_END]);
176 auto outStream
177 = std::make_shared<asio::posix::stream_descriptor>(ioContextRef.get_executor(),
178 out_pipe[READ_END]);
179 auto errorStream
180 = std::make_shared<asio::posix::stream_descriptor>(ioContextRef.get_executor(),
181 error_pipe[READ_END]);
182
183 if (socket) {
184 socket->setOnRecv([this, socket, inStream](const uint8_t* data, size_t size) {
185 auto data_copy = std::make_shared<std::vector<uint8_t>>(data, data + size);
186 // write on pipe to sub child
187 std::error_code ec;
188 asio::async_write(*inStream,
189 asio::buffer(*data_copy),
190 [data_copy, this](const std::error_code& error,
191 std::size_t bytesWritten) {
192 if (error) {
193 if (logger)
194 logger->error("Write error: {}",
195 error.message());
196 }
197 });
198 return size;
199 });
200
201 // read from pipe to sub child
202
203 // Create a buffer to read data into
204 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
205
206 // Create a shared_ptr to the stream_descriptor
207 readFromPipe(socket, outStream, buffer);
208 readFromPipe(socket, errorStream, buffer);
209
210 return EXIT_SUCCESS;
211 }
212 }
213
214 } catch (const std::exception& e) {
215 if (logger)
216 logger->error("Error: {}", e.what());
217 }
218 return 0;
219 });
220}
221
222dhtnet::Dsh::Dsh(const std::filesystem::path& path,
223 dht::crypto::Identity identity,
224 const std::string& bootstrap,
225 dht::InfoHash peer_id,
Amna2b5b07f2024-01-22 17:04:36 -0500226 const std::string& binary,
227 const std::string& turn_host,
228 const std::string& turn_user,
229 const std::string& turn_pass,
230 const std::string& turn_realm)
231 : Dsh(path, identity, bootstrap, turn_host, turn_user, turn_pass, turn_realm)
Amna4a70f5c2023-09-14 17:32:05 -0400232{
233 // Build a client
234 std::condition_variable cv;
235 connectionManager->connectDevice(
236 peer_id, binary, [&](std::shared_ptr<ChannelSocket> socket, const dht::InfoHash&) {
237 if (socket) {
238 socket->setOnRecv([this, socket](const uint8_t* data, size_t size) {
239 std::cout.write((const char*) data, size);
240 std::cout.flush();
241 return size;
242 });
243 // Create a buffer to read data into
244 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
245
246 // Create a shared_ptr to the stream_descriptor
247 auto stdinPipe = std::make_shared<asio::posix::stream_descriptor>(*ioContext,
248 ::dup(
249 STDIN_FILENO));
250 readFromPipe(socket, stdinPipe, buffer);
251
252 socket->onShutdown([this]() {
253 if (logger)
254 logger->debug("Exit program");
255 ioContext->stop();
256 });
257 }
258 });
259
260 connectionManager->onConnectionReady([&](const DeviceId&,
261 const std::string& name,
262 std::shared_ptr<ChannelSocket> socket_received) {
263 if (logger)
264 logger->debug("Connected!");
265 });
266}
267
268void
269dhtnet::Dsh::run()
270{
271 ioContext->run();
272}
273
274dhtnet::Dsh::~Dsh()
275{
276 ioContext->stop();
277 ioContextRunner.join();
278}
279
280} // namespace dhtnet