blob: 92f30b1d9f0734cbb55e56d4f19158b632a84232 [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)
Amna4a70f5c2023-09-14 17:32:05 -040095 : logger(dht::log::getStdLogger())
96 // , std::shared_ptr<tls::CertificateStore>(path / "certstore", logger)
97{
98 auto certStore = std::make_shared<tls::CertificateStore>(path / "certstore", logger);
99
100 ioContext = std::make_shared<asio::io_context>();
101 ioContextRunner = std::thread([context = ioContext, logger = logger] {
102 try {
103 auto work = asio::make_work_guard(*context);
104 context->run();
105 } catch (const std::exception& ex) {
106 if (logger)
107 logger->error("Error in ioContextRunner: {}", ex.what());
108 }
109 });
110 // Build a server
111 auto config = connectionManagerConfig(path,
112 identity,
113 bootstrap,
114 logger,
115 certStore,
116 ioContext,
117 factory);
118 // create a connection manager
119 connectionManager = std::make_unique<ConnectionManager>(std::move(config));
120
121 connectionManager->onDhtConnected(identity.first->getPublicKey());
122 connectionManager->onICERequest([this](const dht::Hash<32>&) { // handle ICE request
123 if (logger)
124 logger->debug("ICE request received");
125 return true;
126 });
127
128 std::mutex mtx;
129 std::unique_lock<std::mutex> lk {mtx};
130
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
221dhtnet::Dsh::Dsh(const std::filesystem::path& path,
222 dht::crypto::Identity identity,
223 const std::string& bootstrap,
224 dht::InfoHash peer_id,
Amna2b5b07f2024-01-22 17:04:36 -0500225 const std::string& binary,
226 const std::string& turn_host,
227 const std::string& turn_user,
228 const std::string& turn_pass,
229 const std::string& turn_realm)
230 : Dsh(path, identity, bootstrap, turn_host, turn_user, turn_pass, turn_realm)
Amna4a70f5c2023-09-14 17:32:05 -0400231{
232 // Build a client
233 std::condition_variable cv;
234 connectionManager->connectDevice(
235 peer_id, binary, [&](std::shared_ptr<ChannelSocket> socket, const dht::InfoHash&) {
236 if (socket) {
237 socket->setOnRecv([this, socket](const uint8_t* data, size_t size) {
238 std::cout.write((const char*) data, size);
239 std::cout.flush();
240 return size;
241 });
242 // Create a buffer to read data into
243 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
244
245 // Create a shared_ptr to the stream_descriptor
246 auto stdinPipe = std::make_shared<asio::posix::stream_descriptor>(*ioContext,
247 ::dup(
248 STDIN_FILENO));
249 readFromPipe(socket, stdinPipe, buffer);
250
251 socket->onShutdown([this]() {
252 if (logger)
253 logger->debug("Exit program");
254 ioContext->stop();
255 });
256 }
257 });
258
259 connectionManager->onConnectionReady([&](const DeviceId&,
260 const std::string& name,
261 std::shared_ptr<ChannelSocket> socket_received) {
262 if (logger)
263 logger->debug("Connected!");
264 });
265}
266
267void
268dhtnet::Dsh::run()
269{
270 ioContext->run();
271}
272
273dhtnet::Dsh::~Dsh()
274{
275 ioContext->stop();
276 ioContextRunner.join();
277}
278
279} // namespace dhtnet