blob: 8fce1de3632a59c4c5b53dda09a78c78d1b6aca9 [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,
Amna69996232024-07-23 14:04:44 -040062 const bool anonymous,
Amna2ee14f02024-07-24 15:15:55 -040063 const bool verbose,
Amna45db7762024-07-24 18:33:48 -040064 const std::map<std::string, std::vector<int>> authorized_services,
65 const bool enable_upnp)
Amna69996232024-07-23 14:04:44 -040066 :logger(verbose ? dht::log::getStdLogger() : nullptr),
67 ioContext(std::make_shared<asio::io_context>()),
Amna0e5f0762024-05-06 15:40:14 -040068 iceFactory(std::make_shared<IceTransportFactory>(logger))
Amna38768302023-08-21 11:51:56 -040069{
Amna38768302023-08-21 11:51:56 -040070 ioContextRunner = std::thread([context = ioContext, logger = logger] {
71 try {
72 auto work = asio::make_work_guard(*context);
73 context->run();
74 } catch (const std::exception& ex) {
75 if (logger)
76 logger->error("Error in ioContextRunner: {}", ex.what());
77 }
78 });
79
Amna0e5f0762024-05-06 15:40:14 -040080 certStore = std::make_shared<tls::CertificateStore>(cachePath()/"certStore", logger);
81 trustStore = std::make_shared<tls::TrustStore>(*certStore);
82
Amna4325f0f2024-01-22 16:11:00 -050083 auto ca = identity.second->issuer;
84 trustStore->setCertificateStatus(ca->getId().toString(), tls::TrustStore::PermissionStatus::ALLOWED);
85
Amnac75ffe92024-02-08 17:23:29 -050086 auto config = connectionManagerConfig(identity,
Amna2f3539b2023-09-18 13:59:22 -040087 bootstrap,
88 logger,
89 certStore,
90 ioContext,
91 iceFactory,
92 turn_host,
93 turn_user,
94 turn_pass,
Amna45db7762024-07-24 18:33:48 -040095 turn_realm,
96 enable_upnp);
Amna38768302023-08-21 11:51:56 -040097 // create a connection manager
Adrien Béraudc1cac452023-08-22 20:32:36 -040098 connectionManager = std::make_unique<ConnectionManager>(std::move(config));
Amna38768302023-08-21 11:51:56 -040099
100 connectionManager->onDhtConnected(identity.first->getPublicKey());
Amna4325f0f2024-01-22 16:11:00 -0500101 connectionManager->onICERequest([this, identity, anonymous](const DeviceId& deviceId) {
102 auto cert = certStore->getCertificate(deviceId.toString());
103 return trustStore->isAllowed(*cert, anonymous);
Amna38768302023-08-21 11:51:56 -0400104 });
105
106 std::mutex mtx;
Adrien Béraud024c46f2024-03-02 23:53:18 -0500107 std::unique_lock lk {mtx};
Amna38768302023-08-21 11:51:56 -0400108
109 connectionManager->onChannelRequest(
Amna2ee14f02024-07-24 15:15:55 -0400110 [authorized_services, this](const std::shared_ptr<dht::crypto::Certificate>&, const std::string& name) {
Amna38768302023-08-21 11:51:56 -0400111 // handle channel request
Amna2ee14f02024-07-24 15:15:55 -0400112 if (authorized_services.empty()) {
113 // Accept all connections if no authorized services are provided
114 return true;
115 }
116 // parse channel name to get the ip address and port: nc://<ip>:<port>
117 auto parsedName = parseName(name);
118 const std::string &ip = parsedName.first;
119 int port = 0;
120 try {
121 port = std::stoi(parsedName.second);
122 }
123 catch (std::exception const &err) {
124 fmt::print(stderr, "Rejecting connection: port '{}' is not a valid number", parsedName.second);
125 return false;
126 }
127
128 // Check if the IP is authorized
129 auto it = authorized_services.find(ip);
130 if (it == authorized_services.end()) {
131 // Reject the connection if the ip is not authorized
Amnac03c4b52024-07-24 17:57:25 -0400132 Log("Rejecting connection to {}:{}", ip, port);
Amna2ee14f02024-07-24 15:15:55 -0400133 return false;
134 }
135
136 // Check if the port is authorized
137 const auto &ports = it->second;
138 if (std::find(ports.begin(), ports.end(), port) == ports.end()) {
139 // Reject the connection if the port is not authorized
Amnac03c4b52024-07-24 17:57:25 -0400140 Log("Rejecting connection to {}:{}", ip, port);
Amna2ee14f02024-07-24 15:15:55 -0400141 return false;
142 }
Amnac03c4b52024-07-24 17:57:25 -0400143 Log("Accepting connection to {}:{}", ip, port);
Amna38768302023-08-21 11:51:56 -0400144 return true;
145 });
146
147 connectionManager->onConnectionReady([&](const DeviceId&,
148 const std::string& name,
149 std::shared_ptr<ChannelSocket> mtlxSocket) {
150 if (name.empty()) {
151 // Handle the empty input case here
152 return;
153 }
154 try {
155 auto parsedName = parseName(name);
Amnac03c4b52024-07-24 17:57:25 -0400156 Log("Connecting to {}:{}", parsedName.first, parsedName.second);
Adrien Béraudecde63f2023-08-26 18:11:21 -0400157
Amna38768302023-08-21 11:51:56 -0400158 asio::ip::tcp::resolver resolver(*ioContext);
159 asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(parsedName.first,
160 parsedName.second);
161
162 // Create a TCP socket
163 auto socket = std::make_shared<asio::ip::tcp::socket>(*ioContext);
Amna2f3539b2023-09-18 13:59:22 -0400164 socket->open(asio::ip::tcp::v4());
165 socket->set_option(asio::socket_base::keep_alive(true));
Amna38768302023-08-21 11:51:56 -0400166 asio::async_connect(
167 *socket,
168 endpoints,
169 [this, socket, mtlxSocket](const std::error_code& error,
Amna2f3539b2023-09-18 13:59:22 -0400170 const asio::ip::tcp::endpoint& ep) {
Amna38768302023-08-21 11:51:56 -0400171 if (!error) {
Amnac03c4b52024-07-24 17:57:25 -0400172 Log("Connected!\n");
Amna38768302023-08-21 11:51:56 -0400173 mtlxSocket->setOnRecv([socket, this](const uint8_t* data, size_t size) {
174 auto data_copy = std::make_shared<std::vector<uint8_t>>(data,
175 data + size);
176 asio::async_write(*socket,
177 asio::buffer(*data_copy),
178 [data_copy, this](const std::error_code& error,
179 std::size_t bytesWritten) {
180 if (error) {
Amnac03c4b52024-07-24 17:57:25 -0400181 Log("Write error: {}\n", error.message());
Amna38768302023-08-21 11:51:56 -0400182 }
Amna69996232024-07-23 14:04:44 -0400183
Amna38768302023-08-21 11:51:56 -0400184 });
185 return size;
186 });
187 // Create a buffer to read data into
Amna2f3539b2023-09-18 13:59:22 -0400188 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
Amna38768302023-08-21 11:51:56 -0400189 readFromPipe(mtlxSocket, socket, buffer);
190 } else {
Amnac03c4b52024-07-24 17:57:25 -0400191 Log("Connection error: {}\n", error.message());
Adrien Béraudecde63f2023-08-26 18:11:21 -0400192 mtlxSocket->shutdown();
Amna38768302023-08-21 11:51:56 -0400193 }
194 });
195
196 } catch (std::exception& e) {
Amnac03c4b52024-07-24 17:57:25 -0400197 Log("Exception: {}\n", e.what());
Amna38768302023-08-21 11:51:56 -0400198 }
199 });
200}
201// Build a client
Amnac75ffe92024-02-08 17:23:29 -0500202Dnc::Dnc(dht::crypto::Identity identity,
Adrien Béraudecde63f2023-08-26 18:11:21 -0400203 const std::string& bootstrap,
Amna38768302023-08-21 11:51:56 -0400204 dht::InfoHash peer_id,
Amna2f3539b2023-09-18 13:59:22 -0400205 const std::string& remote_host,
206 int remote_port,
207 const std::string& turn_host,
208 const std::string& turn_user,
209 const std::string& turn_pass,
Amna69996232024-07-23 14:04:44 -0400210 const std::string& turn_realm,
Amna45db7762024-07-24 18:33:48 -0400211 const bool verbose,
212 const bool enable_upnp)
213 : Dnc(identity, bootstrap,turn_host,turn_user,turn_pass, turn_realm, true, verbose, {}, enable_upnp)
Amna38768302023-08-21 11:51:56 -0400214{
215 std::condition_variable cv;
Adrien Béraudecde63f2023-08-26 18:11:21 -0400216 auto name = fmt::format("nc://{:s}:{:d}", remote_host, remote_port);
Amnac5ce2692024-08-05 12:18:40 -0400217 Log("Requesting socket: {}\n", name.c_str());
Amna2f3539b2023-09-18 13:59:22 -0400218 connectionManager->connectDevice(
219 peer_id, name, [&](std::shared_ptr<ChannelSocket> socket, const dht::InfoHash&) {
220 if (socket) {
221 socket->setOnRecv([this, socket](const uint8_t* data, size_t size) {
222 std::cout.write((const char*) data, size);
223 std::cout.flush();
224 return size;
225 });
226 // Create a buffer to read data into
227 auto buffer = std::make_shared<std::vector<uint8_t>>(BUFFER_SIZE);
Amna38768302023-08-21 11:51:56 -0400228
Amna2f3539b2023-09-18 13:59:22 -0400229 // Create a shared_ptr to the stream_descriptor
230 auto stdinPipe = std::make_shared<asio::posix::stream_descriptor>(*ioContext,
231 ::dup(
232 STDIN_FILENO));
233 readFromPipe(socket, stdinPipe, buffer);
Amna38768302023-08-21 11:51:56 -0400234
Amna2f3539b2023-09-18 13:59:22 -0400235 socket->onShutdown([this]() {
Amnac03c4b52024-07-24 17:57:25 -0400236 Log("Exit program\n");
Amna2f3539b2023-09-18 13:59:22 -0400237 ioContext->stop();
238 });
239 }
240 });
Amna38768302023-08-21 11:51:56 -0400241
Amna2f3539b2023-09-18 13:59:22 -0400242 connectionManager->onConnectionReady(
243 [&](const DeviceId&, const std::string& name, std::shared_ptr<ChannelSocket> mtlxSocket) {
Amnac03c4b52024-07-24 17:57:25 -0400244 Log("Connected!\n");
Amna2f3539b2023-09-18 13:59:22 -0400245 });
Amna38768302023-08-21 11:51:56 -0400246}
247
248void
249Dnc::run()
250{
251 ioContext->run();
252}
253
Amna38768302023-08-21 11:51:56 -0400254Dnc::~Dnc()
255{
256 ioContext->stop();
257 ioContextRunner.join();
258}
259} // namespace dhtnet