Line data Source code
1 : /*
2 : * Copyright (C) 2004-2026 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 :
18 : #ifdef HAVE_CONFIG_H
19 : #include "config.h"
20 : #endif
21 : #include "namedirectory.h"
22 :
23 : #include "logger.h"
24 : #include "string_utils.h"
25 : #include "fileutils.h"
26 : #include "base64.h"
27 :
28 : #include <asio.hpp>
29 :
30 : #include "manager.h"
31 : #include <opendht/crypto.h>
32 : #include <opendht/utils.h>
33 : #include <opendht/http.h>
34 : #include <opendht/logger.h>
35 : #include <opendht/thread_pool.h>
36 :
37 : #include <cstddef>
38 : #include <msgpack.hpp>
39 : #include "json_utils.h"
40 :
41 : /* for Visual Studio */
42 :
43 : #include <sstream>
44 : #include <regex>
45 : #include <fstream>
46 :
47 : namespace jami {
48 :
49 : constexpr const char* const QUERY_NAME {"/name/"};
50 : constexpr const char* const QUERY_ADDR {"/addr/"};
51 : constexpr auto CACHE_DIRECTORY {"namecache"sv};
52 : constexpr const char DEFAULT_SERVER_HOST[] = "https://ns.jami.net";
53 :
54 : constexpr std::string_view HEX_PREFIX = "0x"sv;
55 : constexpr std::chrono::seconds SAVE_INTERVAL {5};
56 :
57 : /*
58 : * Parser for URIs. ( protocol ) ( username ) ( hostname )
59 : * - Requires "@" if a username is present (e.g., "user@domain.com").
60 : * - Allows common URL-safe special characters in usernames and domains.
61 : *
62 : * Regex breakdown:
63 : * 1. `([a-zA-Z]+:(?://)?)?` → Optional scheme ("http://", "ftp://").
64 : * 2. `(?:([^\s@]{1,64})@)?` → Optional username (max 64 chars, Unicode allowed).
65 : * 3. `([^\s@]+)` → Domain or standalone name (Unicode allowed, no spaces or "@").
66 : */
67 : const std::regex URI_VALIDATOR {R"(^([a-zA-Z]+:(?://)?)?(?:([\w\-.~%!$&'()*+,;=]{1,64}|[^\s@]{1,64})@)?([^\s@]+)$)"};
68 :
69 : constexpr size_t MAX_RESPONSE_SIZE {1024ul * 1024};
70 :
71 : using Request = dht::http::Request;
72 :
73 : void
74 1 : toLower(std::string& string)
75 : {
76 1 : std::transform(string.begin(), string.end(), string.begin(), ::tolower);
77 1 : }
78 :
79 : NameDirectory&
80 0 : NameDirectory::instance()
81 : {
82 0 : return instance(DEFAULT_SERVER_HOST);
83 : }
84 :
85 : void
86 3 : NameDirectory::lookupUri(std::string_view uri, const std::string& default_server, LookupCallback cb)
87 : {
88 3 : const std::string& default_ns = default_server.empty() ? DEFAULT_SERVER_HOST : default_server;
89 3 : std::svmatch pieces_match;
90 3 : if (std::regex_match(uri, pieces_match, URI_VALIDATOR)) {
91 3 : if (pieces_match.size() == 4) {
92 3 : if (pieces_match[2].length() == 0)
93 3 : instance(default_ns).lookupName(pieces_match[3], std::move(cb));
94 : else
95 0 : instance(pieces_match[3].str()).lookupName(pieces_match[2], std::move(cb));
96 3 : return;
97 : }
98 : }
99 0 : JAMI_ERROR("Unable to parse URI: {}", uri);
100 0 : cb("", "", Response::invalidResponse);
101 6 : }
102 :
103 30 : NameDirectory::NameDirectory(const std::string& serverUrl, std::shared_ptr<dht::Logger> l)
104 30 : : serverUrl_(serverUrl)
105 30 : , logger_(std::move(l))
106 30 : , httpContext_(Manager::instance().ioContext())
107 60 : , saveTask_(*httpContext_)
108 : {
109 30 : if (!serverUrl_.empty() && serverUrl_.back() == '/')
110 0 : serverUrl_.pop_back();
111 30 : resolver_ = std::make_shared<dht::http::Resolver>(*httpContext_, serverUrl, logger_);
112 30 : cachePath_ = fileutils::get_cache_dir() / CACHE_DIRECTORY / resolver_->get_url().host;
113 30 : }
114 :
115 30 : NameDirectory::~NameDirectory()
116 : {
117 30 : decltype(requests_) requests;
118 : {
119 30 : std::lock_guard lk(requestsMtx_);
120 30 : requests = std::move(requests_);
121 30 : }
122 30 : for (auto& req : requests)
123 0 : req->cancel();
124 30 : }
125 :
126 : void
127 30 : NameDirectory::load()
128 : {
129 30 : loadCache();
130 30 : }
131 :
132 : std::string
133 10 : canonicalName(const std::string& url)
134 : {
135 10 : std::string name = url;
136 10 : std::transform(name.begin(), name.end(), name.begin(), ::tolower);
137 10 : if (name.find("://") == std::string::npos)
138 0 : name = "https://" + name;
139 10 : return name;
140 0 : }
141 :
142 : NameDirectory&
143 843 : NameDirectory::instance(const std::string& serverUrl, std::shared_ptr<dht::Logger> l)
144 : {
145 1676 : const std::string& s = serverUrl.empty() ? DEFAULT_SERVER_HOST : canonicalName(serverUrl);
146 : static std::mutex instanceMtx {};
147 :
148 843 : std::lock_guard lock(instanceMtx);
149 843 : static std::map<std::string, NameDirectory> instances {};
150 843 : auto it = instances.find(s);
151 843 : if (it != instances.end())
152 813 : return it->second;
153 30 : auto r = instances.emplace(std::piecewise_construct, std::forward_as_tuple(s), std::forward_as_tuple(s, l));
154 30 : if (r.second)
155 30 : r.first->second.load();
156 30 : return r.first->second;
157 843 : }
158 :
159 : void
160 841 : NameDirectory::setHeaderFields(Request& request)
161 : {
162 841 : request.set_header_field(restinio::http_field_t::user_agent,
163 1682 : fmt::format("Jami ({}/{})", jami::platform(), jami::arch()));
164 1682 : request.set_header_field(restinio::http_field_t::accept, "*/*");
165 841 : request.set_header_field(restinio::http_field_t::content_type, "application/json");
166 841 : }
167 :
168 : void
169 838 : NameDirectory::lookupAddress(const std::string& addr, LookupCallback cb)
170 : {
171 838 : auto cacheResult = nameCache(addr);
172 838 : if (not cacheResult.first.empty()) {
173 1 : cb(cacheResult.first, cacheResult.second, Response::found);
174 1 : return;
175 : }
176 837 : auto request = std::make_shared<Request>(*httpContext_, resolver_, serverUrl_ + QUERY_ADDR + addr);
177 : try {
178 837 : request->set_method(restinio::http_method_get());
179 837 : setHeaderFields(*request);
180 837 : request->add_on_done_callback([this, cb, addr](const dht::http::Response& response) {
181 837 : if (response.status_code > 400 && response.status_code < 500) {
182 835 : auto cacheResult = nameCache(addr);
183 835 : if (not cacheResult.first.empty())
184 0 : cb(cacheResult.first, cacheResult.second, Response::found);
185 : else
186 4175 : cb("", "", Response::notFound);
187 837 : } else if (response.status_code == 400)
188 5 : cb("", "", Response::invalidResponse);
189 1 : else if (response.status_code != 200) {
190 0 : JAMI_ERROR("Address lookup for {} on {} failed with code={}", addr, serverUrl_, response.status_code);
191 0 : cb("", "", Response::error);
192 : } else {
193 : try {
194 1 : Json::Value json;
195 1 : if (!json::parse(response.body, json)) {
196 0 : cb("", "", Response::error);
197 0 : return;
198 : }
199 1 : auto name = json["name"].asString();
200 1 : if (name.empty()) {
201 0 : cb(name, addr, Response::notFound);
202 0 : return;
203 : }
204 1 : JAMI_DEBUG("Found name for {}: {}", addr, name);
205 : {
206 1 : std::lock_guard l(cacheLock_);
207 1 : addrCache_.emplace(name, std::pair(name, addr));
208 1 : nameCache_.emplace(addr, std::pair(name, addr));
209 1 : scheduleCacheSave();
210 1 : }
211 1 : cb(name, addr, Response::found);
212 1 : } catch (const std::exception& e) {
213 0 : JAMI_ERROR("Error when performing address lookup: {}", e.what());
214 0 : cb("", "", Response::error);
215 0 : }
216 : }
217 837 : std::lock_guard lk(requestsMtx_);
218 837 : if (auto req = response.request.lock())
219 837 : requests_.erase(req);
220 837 : });
221 : {
222 837 : std::lock_guard lk(requestsMtx_);
223 837 : requests_.emplace(request);
224 837 : }
225 837 : request->send();
226 0 : } catch (const std::exception& e) {
227 0 : JAMI_ERROR("Error when performing address lookup: {}", e.what());
228 : {
229 0 : std::lock_guard lk(requestsMtx_);
230 0 : requests_.erase(request);
231 0 : }
232 : // The request will never complete, so answer here: callers must always get a reply.
233 0 : cb("", "", Response::error);
234 0 : }
235 838 : }
236 :
237 : bool
238 0 : NameDirectory::verify(const std::string& name, const dht::crypto::PublicKey& pk, const std::string& signature)
239 : {
240 0 : return pk.checkSignature(std::vector<uint8_t>(name.begin(), name.end()), base64::decode(signature));
241 : }
242 :
243 : void
244 3 : NameDirectory::lookupName(const std::string& name, LookupCallback cb)
245 : {
246 3 : auto cacheResult = addrCache(name);
247 3 : if (not cacheResult.first.empty()) {
248 0 : cb(cacheResult.first, cacheResult.second, Response::found);
249 0 : return;
250 : }
251 3 : auto encodedName = urlEncode(name);
252 3 : auto request = std::make_shared<Request>(*httpContext_, resolver_, serverUrl_ + QUERY_NAME + encodedName);
253 : try {
254 3 : request->set_method(restinio::http_method_get());
255 3 : setHeaderFields(*request);
256 3 : request->add_on_done_callback([this, name, cb](const dht::http::Response& response) {
257 3 : if (response.status_code > 400 && response.status_code < 500)
258 5 : cb("", "", Response::notFound);
259 2 : else if (response.status_code == 400)
260 5 : cb("", "", Response::invalidResponse);
261 1 : else if (response.status_code < 200 || response.status_code > 299) {
262 0 : JAMI_ERROR("Name lookup for {} on {} failed with code={}", name, serverUrl_, response.status_code);
263 0 : cb("", "", Response::error);
264 : } else {
265 : try {
266 1 : Json::Value json;
267 1 : if (!json::parse(response.body, json)) {
268 0 : cb("", "", Response::error);
269 0 : return;
270 : }
271 1 : auto nameResult = json["name"].asString();
272 1 : auto addr = json["addr"].asString();
273 1 : auto publickey = json["publickey"].asString();
274 1 : auto signature = json["signature"].asString();
275 :
276 1 : if (starts_with(addr, HEX_PREFIX))
277 0 : addr = addr.substr(HEX_PREFIX.size());
278 1 : if (addr.empty()) {
279 0 : cb("", "", Response::notFound);
280 0 : return;
281 : }
282 1 : if (not publickey.empty() and not signature.empty()) {
283 : try {
284 0 : auto pk = dht::crypto::PublicKey(base64::decode(publickey));
285 0 : if (pk.getId().toString() != addr or not verify(nameResult, pk, signature)) {
286 0 : cb("", "", Response::invalidResponse);
287 0 : return;
288 : }
289 0 : } catch (const std::exception& e) {
290 0 : cb("", "", Response::invalidResponse);
291 0 : return;
292 0 : }
293 : }
294 1 : JAMI_DEBUG("Found address for {}: {}", name, addr);
295 : {
296 1 : std::lock_guard l(cacheLock_);
297 1 : addrCache_.emplace(name, std::pair(nameResult, addr));
298 1 : addrCache_.emplace(nameResult, std::pair(nameResult, addr));
299 1 : nameCache_.emplace(addr, std::pair(nameResult, addr));
300 1 : scheduleCacheSave();
301 1 : }
302 1 : cb(nameResult, addr, Response::found);
303 1 : } catch (const std::exception& e) {
304 0 : JAMI_ERROR("Error when performing name lookup: {}", e.what());
305 0 : cb("", "", Response::error);
306 0 : }
307 : }
308 3 : std::lock_guard lk(requestsMtx_);
309 3 : if (auto req = response.request.lock())
310 3 : requests_.erase(req);
311 3 : });
312 : {
313 3 : std::lock_guard lk(requestsMtx_);
314 3 : requests_.emplace(request);
315 3 : }
316 3 : request->send();
317 0 : } catch (const std::exception& e) {
318 0 : JAMI_ERROR("Name lookup for {} failed: {}", name, e.what());
319 : {
320 0 : std::lock_guard lk(requestsMtx_);
321 0 : requests_.erase(request);
322 0 : }
323 : // The request will never complete, so answer here: callers must always get a reply.
324 0 : cb("", "", Response::error);
325 0 : }
326 3 : }
327 :
328 : using Blob = std::vector<uint8_t>;
329 : void
330 1 : NameDirectory::registerName(const std::string& addr,
331 : const std::string& n,
332 : const std::string& owner,
333 : RegistrationCallback cb,
334 : const std::string& signedname,
335 : const std::string& publickey)
336 : {
337 1 : std::string name {n};
338 1 : toLower(name);
339 1 : auto cacheResult = addrCache(name);
340 1 : if (not cacheResult.first.empty()) {
341 0 : if (cacheResult.second == addr)
342 0 : cb(RegistrationResponse::success, name);
343 : else
344 0 : cb(RegistrationResponse::alreadyTaken, name);
345 0 : return;
346 : }
347 : {
348 1 : std::lock_guard l(cacheLock_);
349 1 : if (not pendingRegistrations_.emplace(addr, name).second) {
350 0 : JAMI_WARNING("RegisterName: already registering name {} {}", addr, name);
351 0 : cb(RegistrationResponse::error, name);
352 0 : return;
353 : }
354 1 : }
355 : std::string body = fmt::format("{{\"addr\":\"{}\",\"owner\":\"{}\",\"signature\":\"{}\",\"publickey\":\"{}\"}}",
356 : addr,
357 : owner,
358 : signedname,
359 2 : base64::encode(publickey));
360 :
361 1 : auto encodedName = urlEncode(name);
362 1 : auto request = std::make_shared<Request>(*httpContext_, resolver_, serverUrl_ + QUERY_NAME + encodedName);
363 : try {
364 1 : request->set_method(restinio::http_method_post());
365 1 : setHeaderFields(*request);
366 1 : request->set_body(body);
367 :
368 1 : JAMI_WARNING("RegisterName: sending request {} {}", addr, name);
369 :
370 1 : request->add_on_done_callback([this, name, addr, cb = std::move(cb)](const dht::http::Response& response) {
371 : {
372 1 : std::lock_guard l(cacheLock_);
373 1 : pendingRegistrations_.erase(name);
374 1 : }
375 1 : if (response.status_code == 400) {
376 0 : cb(RegistrationResponse::incompleteRequest, name);
377 0 : JAMI_ERROR("RegistrationResponse::incompleteRequest");
378 1 : } else if (response.status_code == 401) {
379 0 : cb(RegistrationResponse::signatureVerificationFailed, name);
380 0 : JAMI_ERROR("RegistrationResponse::signatureVerificationFailed");
381 1 : } else if (response.status_code == 403) {
382 0 : cb(RegistrationResponse::alreadyTaken, name);
383 0 : JAMI_ERROR("RegistrationResponse::alreadyTaken");
384 1 : } else if (response.status_code == 409) {
385 0 : cb(RegistrationResponse::alreadyTaken, name);
386 0 : JAMI_ERROR("RegistrationResponse::alreadyTaken");
387 1 : } else if (response.status_code > 400 && response.status_code < 500) {
388 0 : cb(RegistrationResponse::alreadyTaken, name);
389 0 : JAMI_ERROR("RegistrationResponse::alreadyTaken");
390 1 : } else if (response.status_code < 200 || response.status_code > 299) {
391 0 : cb(RegistrationResponse::error, name);
392 0 : JAMI_ERROR("RegistrationResponse::error");
393 : } else {
394 1 : Json::Value json;
395 1 : std::string err;
396 1 : Json::CharReaderBuilder rbuilder;
397 :
398 1 : auto reader = std::unique_ptr<Json::CharReader>(rbuilder.newCharReader());
399 1 : if (!reader->parse(response.body.data(), response.body.data() + response.body.size(), &json, &err)) {
400 0 : cb(RegistrationResponse::error, name);
401 0 : return;
402 : }
403 1 : auto success = json["success"].asBool();
404 1 : JAMI_DEBUG("Got reply for registration of {} {}: {}", name, addr, success ? "success" : "failure");
405 1 : if (success) {
406 1 : std::lock_guard l(cacheLock_);
407 1 : addrCache_.emplace(name, std::pair(name, addr));
408 1 : nameCache_.emplace(addr, std::pair(name, addr));
409 1 : }
410 1 : cb(success ? RegistrationResponse::success : RegistrationResponse::error, name);
411 1 : }
412 1 : std::lock_guard lk(requestsMtx_);
413 1 : if (auto req = response.request.lock())
414 1 : requests_.erase(req);
415 1 : });
416 : {
417 1 : std::lock_guard lk(requestsMtx_);
418 1 : requests_.emplace(request);
419 1 : }
420 1 : request->send();
421 0 : } catch (const std::exception& e) {
422 0 : JAMI_ERROR("Error when performing name registration: {}", e.what());
423 0 : cb(RegistrationResponse::error, name);
424 : {
425 0 : std::lock_guard l(cacheLock_);
426 0 : pendingRegistrations_.erase(name);
427 0 : }
428 0 : std::lock_guard lk(requestsMtx_);
429 0 : if (request)
430 0 : requests_.erase(request);
431 0 : }
432 1 : }
433 :
434 : void
435 2 : NameDirectory::scheduleCacheSave()
436 : {
437 2 : saveTask_.expires_after(SAVE_INTERVAL);
438 2 : saveTask_.async_wait([this](const asio::error_code& ec) {
439 2 : if (ec)
440 0 : return;
441 2 : saveCache();
442 : });
443 2 : }
444 :
445 : void
446 2 : NameDirectory::saveCache()
447 : {
448 2 : dhtnet::fileutils::recursive_mkdir(fileutils::get_cache_dir() / CACHE_DIRECTORY);
449 2 : std::lock_guard lock(dhtnet::fileutils::getFileLock(cachePath_));
450 2 : std::ofstream file(cachePath_, std::ios::trunc | std::ios::binary);
451 2 : if (!file.is_open()) {
452 0 : JAMI_ERROR("Unable to save cache to {}", cachePath_);
453 0 : return;
454 : }
455 : {
456 2 : std::lock_guard l(cacheLock_);
457 2 : msgpack::pack(file, nameCache_);
458 2 : }
459 2 : JAMI_DEBUG("Saved {:d} name-address mapping(s) to {}", nameCache_.size(), cachePath_);
460 2 : }
461 :
462 : void
463 30 : NameDirectory::loadCache()
464 : {
465 30 : msgpack::unpacker pac;
466 :
467 : // read file
468 : {
469 30 : std::lock_guard lock(dhtnet::fileutils::getFileLock(cachePath_));
470 30 : std::ifstream file(cachePath_);
471 30 : if (!file.is_open()) {
472 30 : JAMI_DEBUG("Unable to load {}", cachePath_);
473 30 : return;
474 : }
475 0 : std::string line;
476 0 : while (std::getline(file, line)) {
477 0 : pac.reserve_buffer(line.size());
478 0 : memcpy(pac.buffer(), line.data(), line.size());
479 0 : pac.buffer_consumed(line.size());
480 : }
481 60 : }
482 :
483 : try {
484 : // load values
485 0 : std::lock_guard l(cacheLock_);
486 0 : msgpack::object_handle oh;
487 0 : if (pac.next(oh))
488 0 : oh.get().convert(nameCache_);
489 0 : for (const auto& m : nameCache_)
490 0 : addrCache_.emplace(m.second.second, m.second);
491 0 : } catch (const msgpack::parse_error& e) {
492 0 : JAMI_ERROR("Error when parsing msgpack object: {}", e.what());
493 0 : } catch (const std::bad_cast& e) {
494 0 : JAMI_ERROR("Error when loading cache: {}", e.what());
495 0 : }
496 :
497 0 : JAMI_DEBUG("Loaded {:d} name-address mapping(s) from cache", nameCache_.size());
498 30 : }
499 :
500 : } // namespace jami
|