blob: 101fbb9d4c752c06bff21882f73be205407e5bb6 [file] [log] [blame]
Amna38768302023-08-21 11:51:56 -04001/*
2 * Copyright (C) 2004-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 "certstore.h"
18#include <opendht/crypto.h>
19#include "connectionmanager.h"
20#include "common.h"
21#include "fileutils.h"
22#include "ice_transport.h"
23
24#include <iostream>
25#include <string>
26#include <filesystem>
27#include <unistd.h>
28#include <fcntl.h>
29#include <asio.hpp>
30
31namespace dhtnet {
32
33std::shared_ptr<asio::posix::stream_descriptor> stdinDescriptor;
34
35dht::crypto::Identity
36loadIdentity(bool isServer)
37{
38 std::string idDir = std::string(getenv("HOME")) + "/.dhtnetTools";
39 if (isServer){
40
41 if (!std::filesystem::exists(idDir)) {
42 std::filesystem::create_directory(idDir);
43 }
44
45 try {
46 std::filesystem::directory_iterator endIter;
47 for (std::filesystem::directory_iterator iter(idDir); iter != endIter; ++iter) {
48 if (iter->path().extension() == ".pem") {
49 auto privateKey = std::make_unique<dht::crypto::PrivateKey>(
50 fileutils::loadFile(std::filesystem::path(iter->path())));
51 // Generate certificate
52 auto certificate = std::make_unique<dht::crypto::Certificate>(
53 dht::crypto::Certificate::generate(*privateKey, "dhtnc"));
54 // return
55 return dht::crypto::Identity(std::move(privateKey), std::move(certificate));
56 }
57 }
58 } catch (const std::exception& e) {
59 fmt::print(stderr, "Error loadind key from .dhtnetTools: {}\n", e.what());
60 }
61 }
62 auto ca = dht::crypto::generateIdentity("ca");
63 auto id = dht::crypto::generateIdentity("dhtnc", ca);
64 idDir += "/id";
65 if (isServer)
66 dht::crypto::saveIdentity(id, idDir);
67 return id;
68}
69
70std::unique_ptr<ConnectionManager::Config>
71connectionManagerConfig(dht::crypto::Identity identity,
72 const std::string& bootstrap_ip_add,
73 const std::string& bootstrap_port,
74 std::shared_ptr<Logger> logger,
75 tls::CertificateStore& certStore,
76 std::shared_ptr<asio::io_context> ioContext,
77 IceTransportFactory& iceFactory)
78{
79 std::filesystem::create_directories(std::string(getenv("HOME")) + "/.dhtnetTools/certstore");
80
81 // DHT node creation: To make a connection manager at first a DHT node should be created
82
83 dht::DhtRunner::Config dhtConfig;
84 dhtConfig.dht_config.id = identity;
85 dhtConfig.threaded = true;
86 dhtConfig.peer_discovery = false;
87 dhtConfig.peer_publish = false;
88 dht::DhtRunner::Context dhtContext;
89 dhtContext.identityAnnouncedCb = [logger](bool ok) {
90 if (logger)
91 logger->debug("Identity announced {}\n", ok);
92 };
93 dhtContext.certificateStore = [&](const dht::InfoHash& pk_id) {
94 std::vector<std::shared_ptr<dht::crypto::Certificate>> ret;
95 if (auto cert = certStore.getCertificate(pk_id.toString()))
96 ret.emplace_back(std::move(cert));
97 return ret;
98 };
99 auto runner = std::make_shared<dht::DhtRunner>();
100 runner->run(dhtConfig, std::move(dhtContext));
101 runner->bootstrap(bootstrap_ip_add, bootstrap_port);
102
103 // DHT node creation end:
104 // ConnectionManager creation:
105 auto config = std::make_unique<ConnectionManager::Config>();
106 config->dht = runner;
107 config->id = identity;
108 config->ioContext = ioContext;
109 config->certStore = &certStore;
110 config->factory = &iceFactory;
111 config->cachePath = std::string(getenv("HOME")) + "/.dhtnetTools";
112
113 return std::move(config);
114}
115template <typename T>
116void readFromPipe(std::shared_ptr<ChannelSocket> socket, T input, Buffer buffer)
117{
118 asio::async_read(*input,
119 asio::buffer(*buffer),
120 asio::transfer_at_least(1),
121 [socket, input, buffer](const asio::error_code& error, size_t bytesRead) {
122 if (!error) {
123 // Process the data received in the buffer
124 std::error_code ec;
125 // print the data to stdout
126 socket->write(buffer->data(), bytesRead, ec);
127 if (!ec) {
128 // Continue reading more data
129 readFromPipe(socket, input, buffer);
130 } else {
131 fmt::print(stderr, "Error writing to socket: {}\n", ec.message());
132 // logger->error("Error writing to socket: {}", ec.message());
133 }
134 } else if(error != asio::error::eof) {
135 fmt::print(stderr, "Error reading from stdin: {}\n", error.message());
136 // logger->error("Error reading from stdin: {}", error.message());
137 }
138 });
139}
140
141template void readFromPipe(std::shared_ptr<ChannelSocket> socket, std::shared_ptr<asio::posix::stream_descriptor> input, Buffer buffer);
142template void readFromPipe(std::shared_ptr<ChannelSocket> socket, std::shared_ptr<asio::ip::tcp::socket> input, Buffer buffer);
143
144
145
146
147} // namespace dhtnet