blob: 3923716c6a561c0b583ad6c3c11d08591b934cc4 [file] [log] [blame]
Amna38768302023-08-21 11:51:56 -04001/*
Amna2f3539b2023-09-18 13:59:22 -04002 * Copyright (C) 2023 Savoir-faire Linux Inc.
Amna38768302023-08-21 11:51:56 -04003 *
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 "dnc.h"
18#include "certstore.h"
19#include "connectionmanager.h"
20#include "fileutils.h"
21#include "../common.h"
22
23#include <opendht/log.h>
24#include <opendht/crypto.h>
25#include <asio.hpp>
26
27#include <fcntl.h>
28#include <unistd.h>
29
Amna38768302023-08-21 11:51:56 -040030#include <chrono>
31#include <string>
32#include <string_view>
33#include <filesystem>
34#include <memory>
35
36namespace dhtnet {
37std::pair<std::string, std::string>
38Dnc::parseName(const std::string_view name)
39{
40 // Find the position of the first ':' character after "nc//"
41 size_t ip_add_start = name.find("nc//") + 6; // Adding 5 to skip "nc//"
42 size_t colonPos = name.find(':', ip_add_start);
43
44 if (colonPos == std::string::npos) {
45 // Return an empty pair if ':' is not found
46 return std::make_pair("", "");
47 }
48
49 std::string ip_add(name.substr(ip_add_start, colonPos - ip_add_start));
50 std::string port(name.substr(colonPos + 1));
51
52 return std::make_pair(ip_add, port);
53}
54
Amna38768302023-08-21 11:51:56 -040055// Build a server
Amnac75ffe92024-02-08 17:23:29 -050056Dnc::Dnc(dht::crypto::Identity identity,
Amna2f3539b2023-09-18 13:59:22 -040057 const std::string& bootstrap,
58 const std::string& turn_host,
59 const std::string& turn_user,
60 const std::string& turn_pass,
Amna4325f0f2024-01-22 16:11:00 -050061 const std::string& turn_realm,
62 const bool anonymous)
Amna38768302023-08-21 11:51:56 -040063 : logger(dht::log::getStdLogger())
Amnaa5452cf2024-01-22 16:07:24 -050064 , ioContext(std::make_shared<asio::io_context>()),
Amna4325f0f2024-01-22 16:11:00 -050065 iceFactory(std::make_shared<IceTransportFactory>(logger)),
Amnac75ffe92024-02-08 17:23:29 -050066 certStore(std::make_shared<tls::CertificateStore>(PATH/"certstore", logger)),
Amna4325f0f2024-01-22 16:11:00 -050067 trustStore(std::make_shared<tls::TrustStore>(*certStore))
Amna38768302023-08-21 11:51:56 -040068{
Amna38768302023-08-21 11:51:56 -040069 ioContextRunner = std::thread([context = ioContext, logger = logger] {
70 try {
71 auto work = asio::make_work_guard(*context);
72 context->run();
73 } catch (const std::exception& ex) {
74 if (logger)
75 logger->error("Error in ioContextRunner: {}", ex.what());
76 }
77 });
78
Amna4325f0f2024-01-22 16:11:00 -050079 auto ca = identity.second->issuer;
80 trustStore->setCertificateStatus(ca->getId().toString(), tls::TrustStore::PermissionStatus::ALLOWED);
81
Amnac75ffe92024-02-08 17:23:29 -050082 auto config = connectionManagerConfig(identity,
Amna2f3539b2023-09-18 13:59:22 -040083 bootstrap,
84 logger,
85 certStore,
86 ioContext,
87 iceFactory,
88 turn_host,
89 turn_user,
90 turn_pass,
91 turn_realm);
Amna38768302023-08-21 11:51:56 -040092 // create a connection manager
Adrien Béraudc1cac452023-08-22 20:32:36 -040093 connectionManager = std::make_unique<ConnectionManager>(std::move(config));
Amna38768302023-08-21 11:51:56 -040094
95 connectionManager->onDhtConnected(identity.first->getPublicKey());
Amna4325f0f2024-01-22 16:11:00 -050096 connectionManager->onICERequest([this, identity, anonymous](const DeviceId& deviceId) {
97 auto cert = certStore->getCertificate(deviceId.toString());
98 return trustStore->isAllowed(*cert, anonymous);
Amna38768302023-08-21 11:51:56 -040099 });
100
101 std::mutex mtx;
Adrien Béraud024c46f2024-03-02 23:53:18 -0500102 std::unique_lock lk {mtx};
Amna38768302023-08-21 11:51:56 -0400103
104 connectionManager->onChannelRequest(
105 [&](const std::shared_ptr<dht::crypto::Certificate>&, const std::string& name) {
106 // handle channel request
107 if (logger)
Adrien Béraudecde63f2023-08-26 18:11:21 -0400108 logger->debug("Channel request received: {}", name);
Amna38768302023-08-21 11:51:56 -0400109 return true;
110 });
111
112 connectionManager->onConnectionReady([&](const DeviceId&,
113 const std::string& name,
114 std::shared_ptr<ChannelSocket> mtlxSocket) {
115 if (name.empty()) {
116 // Handle the empty input case here
117 return;
118 }
119 try {
120 auto parsedName = parseName(name);
Adrien Béraudecde63f2023-08-26 18:11:21 -0400121 if (logger)
122 logger->debug("Connecting to {}:{}", parsedName.first, parsedName.second);
123
Amna38768302023-08-21 11:51:56 -0400124 asio::ip::tcp::resolver resolver(*ioContext);
125 asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(parsedName.first,
126 parsedName.second);
127
128 // Create a TCP socket
129 auto socket = std::make_shared<asio::ip::tcp::socket>(*ioContext);
Amna2f3539b2023-09-18 13:59:22 -0400130 socket->open(asio::ip::tcp::v4());
131 socket->set_option(asio::socket_base::keep_alive(true));
Amna38768302023-08-21 11:51:56 -0400132 asio::async_connect(
133 *socket,
134 endpoints,
135 [this, socket, mtlxSocket](const std::error_code& error,
Amna2f3539b2023-09-18 13:59:22 -0400136 const asio::ip::tcp::endpoint& ep) {
Amna38768302023-08-21 11:51:56 -0400137 if (!error) {
138 if (logger)
139 logger->debug("Connected!");
140 mtlxSocket->setOnRecv([socket, this](const uint8_t* data, size_t size) {
141 auto data_copy = std::make_shared<std::vector<uint8_t>>(data,
142 data + size);
143 asio::async_write(*socket,
144 asio::buffer(*data_copy),
145 [data_copy, this](const std::error_code& error,
146 std::size_t bytesWritten) {
147 if (error) {
148 if (logger)
149 logger->error("Write error: {}",
150 error.message());
151 }
152 });
153 return size;
154 });
155 // Create a buffer to read data into
Amna2f3539b2023-09-18 13:59:22 -0400156 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
Amna38768302023-08-21 11:51:56 -0400157 readFromPipe(mtlxSocket, socket, buffer);
158 } else {
159 if (logger)
160 logger->error("Connection error: {}", error.message());
Adrien Béraudecde63f2023-08-26 18:11:21 -0400161 mtlxSocket->shutdown();
Amna38768302023-08-21 11:51:56 -0400162 }
163 });
164
165 } catch (std::exception& e) {
166 if (logger)
167 logger->error("Exception: {}", e.what());
168 }
169 });
170}
171// Build a client
Amnac75ffe92024-02-08 17:23:29 -0500172Dnc::Dnc(dht::crypto::Identity identity,
Adrien Béraudecde63f2023-08-26 18:11:21 -0400173 const std::string& bootstrap,
Amna38768302023-08-21 11:51:56 -0400174 dht::InfoHash peer_id,
Amna2f3539b2023-09-18 13:59:22 -0400175 const std::string& remote_host,
176 int remote_port,
177 const std::string& turn_host,
178 const std::string& turn_user,
179 const std::string& turn_pass,
180 const std::string& turn_realm)
Amnac75ffe92024-02-08 17:23:29 -0500181 : Dnc(identity, bootstrap,turn_host,turn_user,turn_pass, turn_realm, true)
Amna38768302023-08-21 11:51:56 -0400182{
183 std::condition_variable cv;
Adrien Béraudecde63f2023-08-26 18:11:21 -0400184 auto name = fmt::format("nc://{:s}:{:d}", remote_host, remote_port);
Amna2f3539b2023-09-18 13:59:22 -0400185 connectionManager->connectDevice(
186 peer_id, name, [&](std::shared_ptr<ChannelSocket> socket, const dht::InfoHash&) {
187 if (socket) {
188 socket->setOnRecv([this, socket](const uint8_t* data, size_t size) {
189 std::cout.write((const char*) data, size);
190 std::cout.flush();
191 return size;
192 });
193 // Create a buffer to read data into
194 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
Amna38768302023-08-21 11:51:56 -0400195
Amna2f3539b2023-09-18 13:59:22 -0400196 // Create a shared_ptr to the stream_descriptor
197 auto stdinPipe = std::make_shared<asio::posix::stream_descriptor>(*ioContext,
198 ::dup(
199 STDIN_FILENO));
200 readFromPipe(socket, stdinPipe, buffer);
Amna38768302023-08-21 11:51:56 -0400201
Amna2f3539b2023-09-18 13:59:22 -0400202 socket->onShutdown([this]() {
203 if (logger)
204 logger->debug("Exit program");
205 ioContext->stop();
206 });
207 }
208 });
Amna38768302023-08-21 11:51:56 -0400209
Amna2f3539b2023-09-18 13:59:22 -0400210 connectionManager->onConnectionReady(
211 [&](const DeviceId&, const std::string& name, std::shared_ptr<ChannelSocket> mtlxSocket) {
212 if (logger)
213 logger->debug("Connected!");
214 });
Amna38768302023-08-21 11:51:56 -0400215}
216
217void
218Dnc::run()
219{
220 ioContext->run();
221}
222
Amna38768302023-08-21 11:51:56 -0400223Dnc::~Dnc()
224{
225 ioContext->stop();
226 ioContextRunner.join();
227}
228} // namespace dhtnet