Daemon.cpp
1 /* 2 * Copyright (c) 2013-2026, The PurpleI2P Project 3 * 4 * This file is part of Purple i2pd project and licensed under BSD3 5 * 6 * See full license text in LICENSE file at top of project tree 7 */ 8 9 #include <thread> 10 #include <memory> 11 #include <regex> 12 13 #include "Daemon.h" 14 15 #include "Config.h" 16 #include "Log.h" 17 #include "FS.h" 18 #include "Base.h" 19 #include "version.h" 20 #include "Transports.h" 21 #include "RouterInfo.h" 22 #include "RouterContext.h" 23 #include "Tunnel.h" 24 #include "HTTP.h" 25 #include "NetDb.hpp" 26 #include "Garlic.h" 27 #include "Streaming.h" 28 #include "Destination.h" 29 #include "HTTPServer.h" 30 #include "I2PControl.h" 31 #include "ClientContext.h" 32 #include "Crypto.h" 33 #include "UPnP.h" 34 #include "Timestamp.h" 35 #include "I18N.h" 36 37 namespace i2p 38 { 39 namespace util 40 { 41 class Daemon_Singleton::Daemon_Singleton_Private 42 { 43 public: 44 Daemon_Singleton_Private() {}; 45 ~Daemon_Singleton_Private() {}; 46 47 std::unique_ptr<i2p::http::HTTPServer> httpServer; 48 std::unique_ptr<i2p::client::I2PControlService> m_I2PControlService; 49 std::unique_ptr<i2p::transport::UPnP> UPnP; 50 std::unique_ptr<i2p::util::NTPTimeSync> m_NTPSync; 51 }; 52 53 Daemon_Singleton::Daemon_Singleton() : isDaemon(false), running(true), d(*new Daemon_Singleton_Private()) {} 54 Daemon_Singleton::~Daemon_Singleton() { 55 delete &d; 56 } 57 58 bool Daemon_Singleton::IsService () const 59 { 60 bool service = false; 61 i2p::config::GetOption("service", service); 62 return service; 63 } 64 65 void Daemon_Singleton::setDataDir(std::string_view path) 66 { 67 if (!path.empty ()) 68 DaemonDataDir = path; 69 } 70 71 bool Daemon_Singleton::init(int argc, char* argv[]) { 72 return init(argc, argv, nullptr); 73 } 74 75 bool Daemon_Singleton::init(int argc, char* argv[], std::shared_ptr<std::ostream> logstream) 76 { 77 i2p::config::Init(); 78 i2p::config::ParseCmdline(argc, argv); 79 80 std::string config; i2p::config::GetOption("conf", config); 81 std::string datadir; 82 if(DaemonDataDir != "") { 83 datadir = DaemonDataDir; 84 } else { 85 i2p::config::GetOption("datadir", datadir); 86 } 87 88 i2p::fs::DetectDataDir(datadir, IsService()); 89 i2p::fs::Init(); 90 91 datadir = i2p::fs::GetDataDir(); 92 93 if (config == "") 94 { 95 config = i2p::fs::DataDirPath("i2pd.conf"); 96 if (!i2p::fs::Exists (config)) { 97 // use i2pd.conf only if exists 98 config = ""; /* reset */ 99 } 100 } 101 102 i2p::config::ParseConfig(config); 103 i2p::config::Finalize(); 104 105 i2p::config::GetOption("daemon", isDaemon); 106 107 std::string certsdir; i2p::config::GetOption("certsdir", certsdir); 108 i2p::fs::SetCertsDir(certsdir); 109 110 certsdir = i2p::fs::GetCertsDir(); 111 112 std::string logs = ""; i2p::config::GetOption("log", logs); 113 std::string logfile = ""; i2p::config::GetOption("logfile", logfile); 114 std::string loglevel = ""; i2p::config::GetOption("loglevel", loglevel); 115 bool logclftime; i2p::config::GetOption("logclftime", logclftime); 116 117 /* setup logging */ 118 if (logclftime) 119 i2p::log::Logger().SetTimeFormat ("[%d/%b/%Y:%H:%M:%S %z]"); 120 121 #if defined(WIN32_APP) || defined(__HAIKU__) 122 // Win32 app with GUI or Haiku supports only logging to file 123 logs = "file"; 124 #else 125 if (isDaemon && (logs == "" || logs == "stdout")) 126 logs = "file"; 127 #endif 128 129 i2p::log::Logger().SetLogLevel(loglevel); 130 if (logstream) { 131 LogPrint(eLogInfo, "Log: Sending messages to std::ostream"); 132 i2p::log::Logger().SendTo (logstream); 133 } else if (logs == "file") { 134 if (logfile == "") 135 logfile = i2p::fs::DataDirPath("i2pd.log"); 136 LogPrint(eLogInfo, "Log: Sending messages to ", logfile); 137 i2p::log::Logger().SendTo (logfile); 138 #ifndef _WIN32 139 } else if (logs == "syslog") { 140 LogPrint(eLogInfo, "Log: Sending messages to syslog"); 141 i2p::log::Logger().SendTo("i2pd", LOG_DAEMON); 142 #endif 143 } else { 144 // use stdout -- default 145 } 146 147 LogPrint(eLogNone, "i2pd v", VERSION, " (", I2P_VERSION, ") starting..."); 148 LogPrint(eLogDebug, "FS: Main config file: ", config); 149 LogPrint(eLogDebug, "FS: Data directory: ", datadir); 150 LogPrint(eLogDebug, "FS: Certificates directory: ", certsdir); 151 152 bool precomputation; i2p::config::GetOption("precomputation.elgamal", precomputation); 153 bool ssu; i2p::config::GetOption("ssu", ssu); 154 if (!ssu && i2p::config::IsDefault ("precomputation.elgamal")) 155 precomputation = false; // we don't elgamal table if no ssu, unless it's specified explicitly 156 i2p::crypto::InitCrypto (precomputation); 157 158 i2p::transport::InitAddressFromIface (); // get address4/6 from interfaces 159 160 int netID; i2p::config::GetOption("netid", netID); 161 i2p::context.SetNetID (netID); 162 163 bool checkReserved; i2p::config::GetOption("reservedrange", checkReserved); 164 i2p::transport::transports.SetCheckReserved(checkReserved); 165 166 i2p::context.Init (); 167 168 i2p::transport::InitTransports (); 169 170 bool isFloodfill; i2p::config::GetOption("floodfill", isFloodfill); 171 if (isFloodfill) 172 { 173 LogPrint(eLogInfo, "Daemon: Router configured as floodfill"); 174 i2p::context.SetFloodfill (true); 175 } 176 else 177 i2p::context.SetFloodfill (false); 178 179 bool transit; i2p::config::GetOption("notransit", transit); 180 i2p::context.SetAcceptsTunnels (!transit); 181 uint32_t transitTunnels; i2p::config::GetOption("limits.transittunnels", transitTunnels); 182 if (transitTunnels < 2) 183 transitTunnels = 2; 184 if (isFloodfill && i2p::config::IsDefault ("limits.transittunnels")) 185 transitTunnels *= 2; // double default number of transit tunnels for floodfill 186 i2p::tunnel::tunnels.SetMaxNumTransitTunnels (transitTunnels); 187 188 /* this section also honors 'floodfill' flag, if set above */ 189 std::string bandwidth; i2p::config::GetOption("bandwidth", bandwidth); 190 if (bandwidth.length () > 0) 191 { 192 const auto NumBandwithRegex = std::regex(R"(^\d+$)"); 193 const auto BandwithRegex = std::regex(R"((\d+)(b|kb|mb|gb))"); 194 std::smatch bandWithMatch; 195 196 if (bandwidth.length () == 1 && ((bandwidth[0] >= 'K' && bandwidth[0] <= 'P') || bandwidth[0] == 'X' )) 197 { 198 i2p::context.SetBandwidth (bandwidth[0]); 199 LogPrint(eLogInfo, "Daemon: Bandwidth set to ", i2p::context.GetBandwidthLimit (), "KBps"); 200 } 201 else if (std::regex_match(bandwidth, bandWithMatch, BandwithRegex)) { 202 const auto number = bandWithMatch[1].str(); 203 const auto unit = bandWithMatch[2].str(); 204 int limit = std::atoi(number.c_str()); 205 std::cout << unit; 206 if (unit == "b") 207 { 208 limit /= 1000; 209 } 210 else if(unit == "mb") 211 { 212 limit *= 1000; 213 } else if(unit == "gb") 214 { 215 limit *= 1000000; 216 } 217 // if limit more than 32 bits then its will be negative 218 if (limit < 0) 219 { 220 LogPrint(eLogInfo, "Daemon: Unexpected bandwidth ", bandwidth, ". Set to 'low'"); 221 i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_LOW_BANDWIDTH2); 222 } else { 223 i2p::context.SetBandwidth(limit); 224 } 225 } 226 else if(std::regex_search(bandwidth, NumBandwithRegex)) 227 { 228 auto value = std::atoi(bandwidth.c_str()); 229 if (value > 0) 230 { 231 i2p::context.SetBandwidth (value); 232 LogPrint(eLogInfo, "Daemon: Bandwidth set to ", i2p::context.GetBandwidthLimit (), " KBps"); 233 } 234 else 235 { 236 LogPrint(eLogInfo, "Daemon: Unexpected bandwidth ", bandwidth, ". Set to 'low'"); 237 i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_LOW_BANDWIDTH2); 238 } 239 } 240 } 241 else if (isFloodfill) 242 { 243 LogPrint(eLogInfo, "Daemon: Floodfill bandwidth set to 'extra'"); 244 i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_EXTRA_BANDWIDTH2); 245 } 246 else 247 { 248 LogPrint(eLogInfo, "Daemon: bandwidth set to 'low'"); 249 i2p::context.SetBandwidth (i2p::data::CAPS_FLAG_LOW_BANDWIDTH2); 250 } 251 252 int shareRatio; i2p::config::GetOption("share", shareRatio); 253 i2p::context.SetShareRatio (shareRatio); 254 255 std::string family; i2p::config::GetOption("family", family); 256 i2p::context.SetFamily (family); 257 if (family.length () > 0) 258 LogPrint(eLogInfo, "Daemon: Router family set to ", family); 259 260 bool trust; i2p::config::GetOption("trust.enabled", trust); 261 if (trust) 262 { 263 LogPrint(eLogInfo, "Daemon: Explicit trust enabled"); 264 std::string f; i2p::config::GetOption("trust.family", f); std::string_view fam(f); 265 std::string routers; i2p::config::GetOption("trust.routers", routers); 266 bool restricted = false; 267 if (fam.length() > 0) 268 { 269 std::vector<std::string_view> fams; 270 size_t pos = 0, comma; 271 do 272 { 273 comma = fam.find (',', pos); 274 fams.push_back (fam.substr (pos, comma != std::string::npos ? comma - pos : std::string::npos)); 275 pos = comma + 1; 276 } 277 while (comma != std::string::npos); 278 i2p::transport::transports.RestrictRoutesToFamilies(fams); 279 restricted = fams.size() > 0; 280 } 281 if (!routers.empty ()) 282 { 283 auto idents = i2p::data::ExtractIdentHashes (routers); 284 LogPrint(eLogInfo, "Daemon: Setting restricted routes to use ", idents.size(), " trusted routers"); 285 i2p::transport::transports.RestrictRoutesToRouters(idents); 286 restricted = idents.size() > 0; 287 } 288 if(!restricted) 289 LogPrint(eLogError, "Daemon: No trusted routers of families specified"); 290 } 291 292 bool hidden; i2p::config::GetOption("trust.hidden", hidden); 293 if (hidden) 294 { 295 LogPrint(eLogInfo, "Daemon: Hidden mode enabled"); 296 i2p::context.SetHidden(true); 297 } 298 299 std::string httpLang; i2p::config::GetOption("http.lang", httpLang); 300 i2p::i18n::SetLanguage(httpLang); 301 302 return true; 303 } 304 305 bool Daemon_Singleton::start() 306 { 307 i2p::log::Logger().Start(); 308 LogPrint(eLogInfo, "Daemon: Starting NetDB"); 309 i2p::data::netdb.Start(); 310 311 bool upnp; i2p::config::GetOption("upnp.enabled", upnp); 312 if (upnp) { 313 d.UPnP = std::unique_ptr<i2p::transport::UPnP>(new i2p::transport::UPnP); 314 d.UPnP->Start (); 315 } 316 317 bool nettime; i2p::config::GetOption("nettime.enabled", nettime); 318 if (nettime) 319 { 320 d.m_NTPSync = std::unique_ptr<i2p::util::NTPTimeSync>(new i2p::util::NTPTimeSync); 321 d.m_NTPSync->Start (); 322 } 323 324 bool ntcp2; i2p::config::GetOption("ntcp2.enabled", ntcp2); 325 bool ssu2; i2p::config::GetOption("ssu2.enabled", ssu2); 326 LogPrint(eLogInfo, "Daemon: Starting Transports"); 327 if(!ssu2) LogPrint(eLogInfo, "Daemon: SSU2 disabled"); 328 if(!ntcp2) LogPrint(eLogInfo, "Daemon: NTCP2 disabled"); 329 330 i2p::transport::transports.Start(ntcp2, ssu2); 331 if (i2p::transport::transports.IsBoundSSU2() || i2p::transport::transports.IsBoundNTCP2()) 332 LogPrint(eLogInfo, "Daemon: Transports started"); 333 else 334 { 335 LogPrint(eLogCritical, "Daemon: Failed to start Transports"); 336 /** shut down netdb right away */ 337 i2p::transport::transports.Stop(); 338 i2p::data::netdb.Stop(); 339 return false; 340 } 341 342 bool http; i2p::config::GetOption("http.enabled", http); 343 if (http) { 344 std::string httpAddr; i2p::config::GetOption("http.address", httpAddr); 345 uint16_t httpPort; i2p::config::GetOption("http.port", httpPort); 346 LogPrint(eLogInfo, "Daemon: Starting Webconsole at ", httpAddr, ":", httpPort); 347 try 348 { 349 d.httpServer = std::unique_ptr<i2p::http::HTTPServer>(new i2p::http::HTTPServer(httpAddr, httpPort)); 350 d.httpServer->Start(); 351 } 352 catch (std::exception& ex) 353 { 354 LogPrint (eLogCritical, "Daemon: Failed to start Webconsole: ", ex.what ()); 355 ThrowFatal ("Unable to start webconsole at ", httpAddr, ":", httpPort, ": ", ex.what ()); 356 } 357 } 358 359 LogPrint(eLogInfo, "Daemon: Starting Tunnels"); 360 i2p::tunnel::tunnels.Start(); 361 362 LogPrint(eLogInfo, "Daemon: Starting Router context"); 363 i2p::context.Start(); 364 365 LogPrint(eLogInfo, "Daemon: Starting Client"); 366 i2p::client::context.Start (); 367 368 // I2P Control Protocol 369 bool i2pcontrol; i2p::config::GetOption("i2pcontrol.enabled", i2pcontrol); 370 if (i2pcontrol) { 371 std::string i2pcpAddr; i2p::config::GetOption("i2pcontrol.address", i2pcpAddr); 372 uint16_t i2pcpPort; i2p::config::GetOption("i2pcontrol.port", i2pcpPort); 373 LogPrint(eLogInfo, "Daemon: Starting I2PControl at ", i2pcpAddr, ":", i2pcpPort); 374 try 375 { 376 d.m_I2PControlService = std::unique_ptr<i2p::client::I2PControlService>(new i2p::client::I2PControlService (i2pcpAddr, i2pcpPort)); 377 d.m_I2PControlService->Start (); 378 } 379 catch (std::exception& ex) 380 { 381 LogPrint (eLogCritical, "Daemon: Failed to start I2PControl: ", ex.what ()); 382 ThrowFatal ("Unable to start I2PControl service at ", i2pcpAddr, ":", i2pcpPort, ": ", ex.what ()); 383 } 384 } 385 return true; 386 } 387 388 bool Daemon_Singleton::stop() 389 { 390 LogPrint(eLogInfo, "Daemon: Shutting down"); 391 LogPrint(eLogInfo, "Daemon: Stopping Client"); 392 i2p::client::context.Stop(); 393 LogPrint(eLogInfo, "Daemon: Stopping Router context"); 394 i2p::context.Stop(); 395 LogPrint(eLogInfo, "Daemon: Stopping Tunnels"); 396 i2p::tunnel::tunnels.Stop(); 397 398 if (d.UPnP) 399 { 400 d.UPnP->Stop (); 401 d.UPnP = nullptr; 402 } 403 404 if (d.m_NTPSync) 405 { 406 d.m_NTPSync->Stop (); 407 d.m_NTPSync = nullptr; 408 } 409 410 LogPrint(eLogInfo, "Daemon: Stopping Transports"); 411 i2p::transport::transports.Stop(); 412 LogPrint(eLogInfo, "Daemon: Stopping NetDB"); 413 i2p::data::netdb.Stop(); 414 if (d.httpServer) { 415 LogPrint(eLogInfo, "Daemon: Stopping HTTP Server"); 416 d.httpServer->Stop(); 417 d.httpServer = nullptr; 418 } 419 if (d.m_I2PControlService) 420 { 421 LogPrint(eLogInfo, "Daemon: Stopping I2PControl"); 422 d.m_I2PControlService->Stop (); 423 d.m_I2PControlService = nullptr; 424 } 425 i2p::crypto::TerminateCrypto (); 426 i2p::log::Logger().Stop(); 427 428 return true; 429 } 430 431 static void ShowUptime (std::stringstream& s, int seconds) 432 { 433 int num; 434 435 if ((num = seconds / 86400) > 0) { 436 s << num << " days, "; 437 seconds -= num * 86400; 438 } 439 if ((num = seconds / 3600) > 0) { 440 s << num << " hours, "; 441 seconds -= num * 3600; 442 } 443 if ((num = seconds / 60) > 0) { 444 s << num << " min, "; 445 seconds -= num * 60; 446 } 447 s << seconds << " seconds\n"; 448 } 449 450 static void ShowTransfered (std::stringstream& s, size_t transfer) 451 { 452 auto bytes = transfer & 0x03ff; 453 transfer >>= 10; 454 auto kbytes = transfer & 0x03ff; 455 transfer >>= 10; 456 auto mbytes = transfer & 0x03ff; 457 transfer >>= 10; 458 auto gbytes = transfer; 459 460 if (gbytes) 461 s << gbytes << " GB, "; 462 if (mbytes) 463 s << mbytes << " MB, "; 464 if (kbytes) 465 s << kbytes << " KB, "; 466 s << bytes << " Bytes\n"; 467 } 468 469 static void ShowNetworkStatus (std::stringstream& s, RouterStatus status, bool testing, RouterError error) 470 { 471 switch (status) 472 { 473 case eRouterStatusOK: s << "OK"; break; 474 case eRouterStatusFirewalled: s << "FW"; break; 475 case eRouterStatusUnknown: s << "Unk"; break; 476 case eRouterStatusProxy: s << "Proxy"; break; 477 case eRouterStatusMesh: s << "Mesh"; break; 478 case eRouterStatusStan: s << "Stan"; break; 479 default: s << "Unk"; 480 }; 481 if (testing) 482 s << " (Test)"; 483 if (error != eRouterErrorNone) 484 { 485 switch (error) 486 { 487 case eRouterErrorClockSkew: 488 s << " - " << tr("Clock skew"); 489 break; 490 case eRouterErrorOffline: 491 s << " - " << tr("Offline"); 492 break; 493 case eRouterErrorSymmetricNAT: 494 s << " - " << tr("Symmetric NAT"); 495 break; 496 case eRouterErrorFullConeNAT: 497 s << " - " << tr("Full cone NAT"); 498 break; 499 case eRouterErrorNoDescriptors: 500 s << " - " << tr("No Descriptors"); 501 break; 502 default: ; 503 } 504 } 505 } 506 507 void PrintMainWindowText (std::stringstream& s) 508 { 509 s << "\n"; 510 s << "Status: "; 511 ShowNetworkStatus (s, i2p::context.GetStatus (), i2p::context.GetTesting(), i2p::context.GetError ()); 512 if (i2p::context.SupportsV6 ()) 513 { 514 s << " / "; 515 ShowNetworkStatus (s, i2p::context.GetStatusV6 (), i2p::context.GetTestingV6(), i2p::context.GetErrorV6 ()); 516 } 517 s << "; "; 518 s << "Success Rate: " << i2p::tunnel::tunnels.GetTunnelCreationSuccessRate() << "%\n"; 519 s << "Uptime: "; ShowUptime(s, i2p::context.GetUptime ()); 520 auto gracefulTimeLeft = Daemon.GetGracefulShutdownInterval (); 521 if (gracefulTimeLeft > 0) 522 { 523 s << "Graceful shutdown, time left: "; ShowUptime(s, gracefulTimeLeft); 524 } 525 else 526 s << "\n"; 527 s << "Inbound: " << i2p::transport::transports.GetInBandwidth() / 1024 << " KiB/s; "; 528 s << "Outbound: " << i2p::transport::transports.GetOutBandwidth() / 1024 << " KiB/s\n"; 529 s << "Received: "; ShowTransfered (s, i2p::transport::transports.GetTotalReceivedBytes()); 530 s << "Sent: "; ShowTransfered (s, i2p::transport::transports.GetTotalSentBytes()); 531 s << "\n"; 532 s << "Routers: " << i2p::data::netdb.GetNumRouters () << "; "; 533 s << "Floodfills: " << i2p::data::netdb.GetNumFloodfills () << "; "; 534 s << "LeaseSets: " << i2p::data::netdb.GetNumLeaseSets () << "\n"; 535 s << "Tunnels: "; 536 s << "In: " << i2p::tunnel::tunnels.CountInboundTunnels() << "; "; 537 s << "Out: " << i2p::tunnel::tunnels.CountOutboundTunnels() << "; "; 538 s << "Transit: " << i2p::tunnel::tunnels.CountTransitTunnels() << "\n"; 539 s << "\n"; 540 } 541 } 542 }