blob: bce0388098323ed7c3840d0db8afd4e961299c97 [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>()),
Amna0e5f0762024-05-06 15:40:14 -040065 iceFactory(std::make_shared<IceTransportFactory>(logger))
Amna38768302023-08-21 11:51:56 -040066{
Amna38768302023-08-21 11:51:56 -040067 ioContextRunner = std::thread([context = ioContext, logger = logger] {
68 try {
69 auto work = asio::make_work_guard(*context);
70 context->run();
71 } catch (const std::exception& ex) {
72 if (logger)
73 logger->error("Error in ioContextRunner: {}", ex.what());
74 }
75 });
76
Amna0e5f0762024-05-06 15:40:14 -040077 certStore = std::make_shared<tls::CertificateStore>(cachePath()/"certStore", logger);
78 trustStore = std::make_shared<tls::TrustStore>(*certStore);
79
Amna4325f0f2024-01-22 16:11:00 -050080 auto ca = identity.second->issuer;
81 trustStore->setCertificateStatus(ca->getId().toString(), tls::TrustStore::PermissionStatus::ALLOWED);
82
Amnac75ffe92024-02-08 17:23:29 -050083 auto config = connectionManagerConfig(identity,
Amna2f3539b2023-09-18 13:59:22 -040084 bootstrap,
85 logger,
86 certStore,
87 ioContext,
88 iceFactory,
89 turn_host,
90 turn_user,
91 turn_pass,
92 turn_realm);
Amna38768302023-08-21 11:51:56 -040093 // create a connection manager
Adrien Béraudc1cac452023-08-22 20:32:36 -040094 connectionManager = std::make_unique<ConnectionManager>(std::move(config));
Amna38768302023-08-21 11:51:56 -040095
96 connectionManager->onDhtConnected(identity.first->getPublicKey());
Amna4325f0f2024-01-22 16:11:00 -050097 connectionManager->onICERequest([this, identity, anonymous](const DeviceId& deviceId) {
98 auto cert = certStore->getCertificate(deviceId.toString());
99 return trustStore->isAllowed(*cert, anonymous);
Amna38768302023-08-21 11:51:56 -0400100 });
101
102 std::mutex mtx;
Adrien Béraud024c46f2024-03-02 23:53:18 -0500103 std::unique_lock lk {mtx};
Amna38768302023-08-21 11:51:56 -0400104
105 connectionManager->onChannelRequest(
106 [&](const std::shared_ptr<dht::crypto::Certificate>&, const std::string& name) {
107 // handle channel request
108 if (logger)
Adrien Béraudecde63f2023-08-26 18:11:21 -0400109 logger->debug("Channel request received: {}", name);
Amna38768302023-08-21 11:51:56 -0400110 return true;
111 });
112
113 connectionManager->onConnectionReady([&](const DeviceId&,
114 const std::string& name,
115 std::shared_ptr<ChannelSocket> mtlxSocket) {
116 if (name.empty()) {
117 // Handle the empty input case here
118 return;
119 }
120 try {
121 auto parsedName = parseName(name);
Adrien Béraudecde63f2023-08-26 18:11:21 -0400122 if (logger)
123 logger->debug("Connecting to {}:{}", parsedName.first, parsedName.second);
124
Amna38768302023-08-21 11:51:56 -0400125 asio::ip::tcp::resolver resolver(*ioContext);
126 asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(parsedName.first,
127 parsedName.second);
128
129 // Create a TCP socket
130 auto socket = std::make_shared<asio::ip::tcp::socket>(*ioContext);
Amna2f3539b2023-09-18 13:59:22 -0400131 socket->open(asio::ip::tcp::v4());
132 socket->set_option(asio::socket_base::keep_alive(true));
Amna38768302023-08-21 11:51:56 -0400133 asio::async_connect(
134 *socket,
135 endpoints,
136 [this, socket, mtlxSocket](const std::error_code& error,
Amna2f3539b2023-09-18 13:59:22 -0400137 const asio::ip::tcp::endpoint& ep) {
Amna38768302023-08-21 11:51:56 -0400138 if (!error) {
139 if (logger)
140 logger->debug("Connected!");
141 mtlxSocket->setOnRecv([socket, this](const uint8_t* data, size_t size) {
142 auto data_copy = std::make_shared<std::vector<uint8_t>>(data,
143 data + size);
144 asio::async_write(*socket,
145 asio::buffer(*data_copy),
146 [data_copy, this](const std::error_code& error,
147 std::size_t bytesWritten) {
148 if (error) {
149 if (logger)
150 logger->error("Write error: {}",
151 error.message());
152 }
153 });
154 return size;
155 });
156 // Create a buffer to read data into
Amna2f3539b2023-09-18 13:59:22 -0400157 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
Amna38768302023-08-21 11:51:56 -0400158 readFromPipe(mtlxSocket, socket, buffer);
159 } else {
160 if (logger)
161 logger->error("Connection error: {}", error.message());
Adrien Béraudecde63f2023-08-26 18:11:21 -0400162 mtlxSocket->shutdown();
Amna38768302023-08-21 11:51:56 -0400163 }
164 });
165
166 } catch (std::exception& e) {
167 if (logger)
168 logger->error("Exception: {}", e.what());
169 }
170 });
171}
172// Build a client
Amnac75ffe92024-02-08 17:23:29 -0500173Dnc::Dnc(dht::crypto::Identity identity,
Adrien Béraudecde63f2023-08-26 18:11:21 -0400174 const std::string& bootstrap,
Amna38768302023-08-21 11:51:56 -0400175 dht::InfoHash peer_id,
Amna2f3539b2023-09-18 13:59:22 -0400176 const std::string& remote_host,
177 int remote_port,
178 const std::string& turn_host,
179 const std::string& turn_user,
180 const std::string& turn_pass,
181 const std::string& turn_realm)
Amnac75ffe92024-02-08 17:23:29 -0500182 : Dnc(identity, bootstrap,turn_host,turn_user,turn_pass, turn_realm, true)
Amna38768302023-08-21 11:51:56 -0400183{
184 std::condition_variable cv;
Adrien Béraudecde63f2023-08-26 18:11:21 -0400185 auto name = fmt::format("nc://{:s}:{:d}", remote_host, remote_port);
Amna2f3539b2023-09-18 13:59:22 -0400186 connectionManager->connectDevice(
187 peer_id, name, [&](std::shared_ptr<ChannelSocket> socket, const dht::InfoHash&) {
188 if (socket) {
189 socket->setOnRecv([this, socket](const uint8_t* data, size_t size) {
190 std::cout.write((const char*) data, size);
191 std::cout.flush();
192 return size;
193 });
194 // Create a buffer to read data into
195 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
Amna38768302023-08-21 11:51:56 -0400196
Amna2f3539b2023-09-18 13:59:22 -0400197 // Create a shared_ptr to the stream_descriptor
198 auto stdinPipe = std::make_shared<asio::posix::stream_descriptor>(*ioContext,
199 ::dup(
200 STDIN_FILENO));
201 readFromPipe(socket, stdinPipe, buffer);
Amna38768302023-08-21 11:51:56 -0400202
Amna2f3539b2023-09-18 13:59:22 -0400203 socket->onShutdown([this]() {
204 if (logger)
205 logger->debug("Exit program");
206 ioContext->stop();
207 });
208 }
209 });
Amna38768302023-08-21 11:51:56 -0400210
Amna2f3539b2023-09-18 13:59:22 -0400211 connectionManager->onConnectionReady(
212 [&](const DeviceId&, const std::string& name, std::shared_ptr<ChannelSocket> mtlxSocket) {
213 if (logger)
214 logger->debug("Connected!");
215 });
Amna38768302023-08-21 11:51:56 -0400216}
217
218void
219Dnc::run()
220{
221 ioContext->run();
222}
223
Amna38768302023-08-21 11:51:56 -0400224Dnc::~Dnc()
225{
226 ioContext->stop();
227 ioContextRunner.join();
228}
229} // namespace dhtnet