main.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. //
  2. // main.cc
  3. //
  4. // Copyright (c) 2026 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #include <atomic>
  8. #include <chrono>
  9. #include <ctime>
  10. #include <format>
  11. #include <iomanip>
  12. #include <iostream>
  13. #include <signal.h>
  14. #include <sstream>
  15. #include <httplib.h>
  16. using namespace httplib;
  17. const auto SERVER_NAME =
  18. std::format("cpp-httplib-server/{}", CPPHTTPLIB_VERSION);
  19. Server svr;
  20. void signal_handler(int signal) {
  21. if (signal == SIGINT || signal == SIGTERM) {
  22. std::cout << "\nReceived signal, shutting down gracefully...\n";
  23. svr.stop();
  24. }
  25. }
  26. std::string get_time_format() {
  27. auto now = std::chrono::system_clock::now();
  28. auto time_t = std::chrono::system_clock::to_time_t(now);
  29. std::stringstream ss;
  30. ss << std::put_time(std::localtime(&time_t), "%d/%b/%Y:%H:%M:%S %z");
  31. return ss.str();
  32. }
  33. std::string get_error_time_format() {
  34. auto now = std::chrono::system_clock::now();
  35. auto time_t = std::chrono::system_clock::to_time_t(now);
  36. std::stringstream ss;
  37. ss << std::put_time(std::localtime(&time_t), "%Y/%m/%d %H:%M:%S");
  38. return ss.str();
  39. }
  40. // Escape a value for a log line the way NGINX does: '"', '\\', control
  41. // bytes and non-ASCII bytes become \xHH. Request fields are attacker-controlled
  42. // (e.g. a raw CR in the request target or a decoded %0D%0A in req.path), so
  43. // writing them verbatim would let a client forge extra log lines.
  44. std::string escape_log(const std::string &s) {
  45. std::string out;
  46. out.reserve(s.size());
  47. for (unsigned char c : s) {
  48. if (c == '"' || c == '\\' || c < 0x20 || c >= 0x7f) {
  49. out += std::format("\\x{:02X}", c);
  50. } else {
  51. out += static_cast<char>(c);
  52. }
  53. }
  54. return out;
  55. }
  56. // NGINX Combined log format:
  57. // $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent
  58. // "$http_referer" "$http_user_agent"
  59. void nginx_access_logger(const Request &req, const Response &res) {
  60. std::string remote_user =
  61. "-"; // cpp-httplib doesn't have built-in auth user tracking
  62. auto time_local = get_time_format();
  63. // $request is the original request line, so log the raw target rather than
  64. // the percent-decoded req.path.
  65. auto request = std::format("{} {} {}", req.method, req.target, req.version);
  66. auto status = res.status;
  67. auto body_bytes_sent = res.body.size();
  68. auto http_referer = req.get_header_value("Referer");
  69. if (http_referer.empty()) http_referer = "-";
  70. auto http_user_agent = req.get_header_value("User-Agent");
  71. if (http_user_agent.empty()) http_user_agent = "-";
  72. std::cout << std::format("{} - {} [{}] \"{}\" {} {} \"{}\" \"{}\"",
  73. req.remote_addr, remote_user, time_local,
  74. escape_log(request), status, body_bytes_sent,
  75. escape_log(http_referer), escape_log(http_user_agent))
  76. << std::endl;
  77. }
  78. // NGINX Error log format:
  79. // YYYY/MM/DD HH:MM:SS [level] message, client: client_ip, request: "request",
  80. // host: "host"
  81. void nginx_error_logger(const Error &err, const Request *req) {
  82. auto time_local = get_error_time_format();
  83. std::string level = "error";
  84. if (req) {
  85. auto request =
  86. std::format("{} {} {}", req->method, req->target, req->version);
  87. auto host = req->get_header_value("Host");
  88. if (host.empty()) host = "-";
  89. std::cerr << std::format("{} [{}] {}, client: {}, request: "
  90. "\"{}\", host: \"{}\"",
  91. time_local, level, to_string(err),
  92. req->remote_addr, escape_log(request),
  93. escape_log(host))
  94. << std::endl;
  95. } else {
  96. // If no request context, just log the error
  97. std::cerr << std::format("{} [{}] {}", time_local, level, to_string(err))
  98. << std::endl;
  99. }
  100. }
  101. void print_usage(const char *program_name) {
  102. std::cout << "Usage: " << program_name << " [OPTIONS]" << std::endl;
  103. std::cout << std::endl;
  104. std::cout << "Options:" << std::endl;
  105. std::cout << " --host <hostname> Server hostname (default: localhost)"
  106. << std::endl;
  107. std::cout << " --port <port> Server port (default: 8080)"
  108. << std::endl;
  109. std::cout << " --mount <mount:path> Mount point and document root"
  110. << std::endl;
  111. std::cout << " Format: mount_point:document_root"
  112. << std::endl;
  113. std::cout << " (default: /:./html)" << std::endl;
  114. std::cout << " --trusted-proxy <ip> Add trusted proxy IP address"
  115. << std::endl;
  116. std::cout << " (can be specified multiple times)"
  117. << std::endl;
  118. std::cout << " --version Show version information"
  119. << std::endl;
  120. std::cout << " --help Show this help message" << std::endl;
  121. std::cout << std::endl;
  122. std::cout << "Examples:" << std::endl;
  123. std::cout << " " << program_name
  124. << " --host localhost --port 8080 --mount /:./html" << std::endl;
  125. std::cout << " " << program_name
  126. << " --host 0.0.0.0 --port 3000 --mount /api:./api" << std::endl;
  127. std::cout << " " << program_name
  128. << " --trusted-proxy 192.168.1.100 --trusted-proxy 10.0.0.1"
  129. << std::endl;
  130. }
  131. struct ServerConfig {
  132. std::string hostname = "localhost";
  133. int port = 8080;
  134. std::string mount_point = "/";
  135. std::string document_root = "./html";
  136. std::vector<std::string> trusted_proxies;
  137. };
  138. enum class ParseResult { SUCCESS, HELP_REQUESTED, VERSION_REQUESTED, ERROR };
  139. ParseResult parse_command_line(int argc, char *argv[], ServerConfig &config) {
  140. for (int i = 1; i < argc; i++) {
  141. if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
  142. print_usage(argv[0]);
  143. return ParseResult::HELP_REQUESTED;
  144. } else if (strcmp(argv[i], "--host") == 0) {
  145. if (i + 1 >= argc) {
  146. std::cerr << "Error: --host requires a hostname argument" << std::endl;
  147. print_usage(argv[0]);
  148. return ParseResult::ERROR;
  149. }
  150. config.hostname = argv[++i];
  151. } else if (strcmp(argv[i], "--port") == 0) {
  152. if (i + 1 >= argc) {
  153. std::cerr << "Error: --port requires a port number argument"
  154. << std::endl;
  155. print_usage(argv[0]);
  156. return ParseResult::ERROR;
  157. }
  158. config.port = std::atoi(argv[++i]);
  159. if (config.port <= 0 || config.port > 65535) {
  160. std::cerr << "Error: Invalid port number. Must be between 1 and 65535"
  161. << std::endl;
  162. return ParseResult::ERROR;
  163. }
  164. } else if (strcmp(argv[i], "--mount") == 0) {
  165. if (i + 1 >= argc) {
  166. std::cerr
  167. << "Error: --mount requires mount_point:document_root argument"
  168. << std::endl;
  169. print_usage(argv[0]);
  170. return ParseResult::ERROR;
  171. }
  172. std::string mount_arg = argv[++i];
  173. auto colon_pos = mount_arg.find(':');
  174. if (colon_pos == std::string::npos) {
  175. std::cerr << "Error: --mount argument must be in format "
  176. "mount_point:document_root"
  177. << std::endl;
  178. print_usage(argv[0]);
  179. return ParseResult::ERROR;
  180. }
  181. config.mount_point = mount_arg.substr(0, colon_pos);
  182. config.document_root = mount_arg.substr(colon_pos + 1);
  183. if (config.mount_point.empty() || config.document_root.empty()) {
  184. std::cerr
  185. << "Error: Both mount_point and document_root must be non-empty"
  186. << std::endl;
  187. return ParseResult::ERROR;
  188. }
  189. } else if (strcmp(argv[i], "--version") == 0) {
  190. std::cout << CPPHTTPLIB_VERSION << std::endl;
  191. return ParseResult::VERSION_REQUESTED;
  192. } else if (strcmp(argv[i], "--trusted-proxy") == 0) {
  193. if (i + 1 >= argc) {
  194. std::cerr << "Error: --trusted-proxy requires an IP address argument"
  195. << std::endl;
  196. print_usage(argv[0]);
  197. return ParseResult::ERROR;
  198. }
  199. config.trusted_proxies.push_back(argv[++i]);
  200. } else {
  201. std::cerr << "Error: Unknown option '" << argv[i] << "'" << std::endl;
  202. print_usage(argv[0]);
  203. return ParseResult::ERROR;
  204. }
  205. }
  206. return ParseResult::SUCCESS;
  207. }
  208. bool setup_server(Server &svr, const ServerConfig &config) {
  209. svr.set_logger(nginx_access_logger);
  210. svr.set_error_logger(nginx_error_logger);
  211. // Set trusted proxies if specified
  212. if (!config.trusted_proxies.empty()) {
  213. svr.set_trusted_proxies(config.trusted_proxies);
  214. }
  215. auto ret = svr.set_mount_point(config.mount_point, config.document_root);
  216. if (!ret) {
  217. std::cerr
  218. << std::format(
  219. "Error: Cannot mount '{}' to '{}'. Directory may not exist.",
  220. config.mount_point, config.document_root)
  221. << std::endl;
  222. return false;
  223. }
  224. svr.set_file_extension_and_mimetype_mapping("html", "text/html");
  225. svr.set_file_extension_and_mimetype_mapping("htm", "text/html");
  226. svr.set_file_extension_and_mimetype_mapping("css", "text/css");
  227. svr.set_file_extension_and_mimetype_mapping("js", "text/javascript");
  228. svr.set_file_extension_and_mimetype_mapping("json", "application/json");
  229. svr.set_file_extension_and_mimetype_mapping("xml", "application/xml");
  230. svr.set_file_extension_and_mimetype_mapping("png", "image/png");
  231. svr.set_file_extension_and_mimetype_mapping("jpg", "image/jpeg");
  232. svr.set_file_extension_and_mimetype_mapping("jpeg", "image/jpeg");
  233. svr.set_file_extension_and_mimetype_mapping("gif", "image/gif");
  234. svr.set_file_extension_and_mimetype_mapping("svg", "image/svg+xml");
  235. svr.set_file_extension_and_mimetype_mapping("ico", "image/x-icon");
  236. svr.set_file_extension_and_mimetype_mapping("pdf", "application/pdf");
  237. svr.set_file_extension_and_mimetype_mapping("zip", "application/zip");
  238. svr.set_file_extension_and_mimetype_mapping("txt", "text/plain");
  239. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  240. if (res.status == 404) {
  241. res.set_content(
  242. std::format(
  243. "<html><head><title>404 Not Found</title></head>"
  244. "<body><h1>404 Not Found</h1>"
  245. "<p>The requested resource was not found on this server.</p>"
  246. "<hr><p>{}</p></body></html>",
  247. SERVER_NAME),
  248. "text/html");
  249. }
  250. });
  251. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  252. res.set_header("Server", SERVER_NAME);
  253. return Server::HandlerResponse::Unhandled;
  254. });
  255. signal(SIGINT, signal_handler);
  256. signal(SIGTERM, signal_handler);
  257. return true;
  258. }
  259. int main(int argc, char *argv[]) {
  260. ServerConfig config;
  261. auto result = parse_command_line(argc, argv, config);
  262. switch (result) {
  263. case ParseResult::HELP_REQUESTED:
  264. case ParseResult::VERSION_REQUESTED: return 0;
  265. case ParseResult::ERROR: return 1;
  266. case ParseResult::SUCCESS: break;
  267. }
  268. if (!setup_server(svr, config)) { return 1; }
  269. std::cout << "Serving HTTP on " << config.hostname << ":" << config.port
  270. << std::endl;
  271. std::cout << "Mount point: " << config.mount_point << " -> "
  272. << config.document_root << std::endl;
  273. if (!config.trusted_proxies.empty()) {
  274. std::cout << "Trusted proxies: ";
  275. for (size_t i = 0; i < config.trusted_proxies.size(); ++i) {
  276. if (i > 0) std::cout << ", ";
  277. std::cout << config.trusted_proxies[i];
  278. }
  279. std::cout << std::endl;
  280. }
  281. std::cout << "Press Ctrl+C to shutdown gracefully..." << std::endl;
  282. auto ret = svr.listen(config.hostname, config.port);
  283. std::cout << "Server has been shut down." << std::endl;
  284. return ret ? 0 : 1;
  285. }