httplib.h 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2017 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef _CPPHTTPLIB_HTTPLIB_H_
  8. #define _CPPHTTPLIB_HTTPLIB_H_
  9. #ifdef _WIN32
  10. #ifndef _CRT_SECURE_NO_WARNINGS
  11. #define _CRT_SECURE_NO_WARNINGS
  12. #endif
  13. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  14. #define _CRT_NONSTDC_NO_DEPRECATE
  15. #endif
  16. #if defined(_MSC_VER) && _MSC_VER < 1900
  17. #define snprintf _snprintf_s
  18. #endif
  19. #ifndef S_ISREG
  20. #define S_ISREG(m) (((m)&S_IFREG)==S_IFREG)
  21. #endif
  22. #ifndef S_ISDIR
  23. #define S_ISDIR(m) (((m)&S_IFDIR)==S_IFDIR)
  24. #endif
  25. #include <io.h>
  26. #include <winsock2.h>
  27. #include <ws2tcpip.h>
  28. #undef min
  29. #undef max
  30. typedef SOCKET socket_t;
  31. #else
  32. #include <pthread.h>
  33. #include <unistd.h>
  34. #include <netdb.h>
  35. #include <cstring>
  36. #include <netinet/in.h>
  37. #include <arpa/inet.h>
  38. #include <signal.h>
  39. #include <sys/socket.h>
  40. typedef int socket_t;
  41. #endif
  42. #include <fstream>
  43. #include <functional>
  44. #include <map>
  45. #include <memory>
  46. #include <mutex>
  47. #include <regex>
  48. #include <string>
  49. #include <thread>
  50. #include <sys/stat.h>
  51. #include <fcntl.h>
  52. #include <assert.h>
  53. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  54. #include <openssl/ssl.h>
  55. #endif
  56. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  57. #include <zlib.h>
  58. #endif
  59. /*
  60. * Configuration
  61. */
  62. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  63. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  64. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  65. namespace httplib
  66. {
  67. namespace detail {
  68. struct ci {
  69. bool operator() (const std::string & s1, const std::string & s2) const {
  70. return std::lexicographical_compare(
  71. s1.begin(), s1.end(),
  72. s2.begin(), s2.end(),
  73. [](char c1, char c2) {
  74. return ::tolower(c1) < ::tolower(c2);
  75. });
  76. }
  77. };
  78. } // namespace detail
  79. enum class HttpVersion { v1_0 = 0, v1_1 };
  80. typedef std::multimap<std::string, std::string, detail::ci> Headers;
  81. template<typename uint64_t, typename... Args>
  82. std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args);
  83. typedef std::multimap<std::string, std::string> Params;
  84. typedef std::smatch Match;
  85. typedef std::function<void (uint64_t current, uint64_t total)> Progress;
  86. struct MultipartFile {
  87. std::string filename;
  88. std::string content_type;
  89. size_t offset = 0;
  90. size_t length = 0;
  91. };
  92. typedef std::multimap<std::string, MultipartFile> MultipartFiles;
  93. struct Request {
  94. std::string version;
  95. std::string method;
  96. std::string path;
  97. Headers headers;
  98. std::string body;
  99. Params params;
  100. MultipartFiles files;
  101. Match matches;
  102. Progress progress;
  103. bool has_header(const char* key) const;
  104. std::string get_header_value(const char* key) const;
  105. void set_header(const char* key, const char* val);
  106. bool has_param(const char* key) const;
  107. std::string get_param_value(const char* key) const;
  108. bool has_file(const char* key) const;
  109. MultipartFile get_file_value(const char* key) const;
  110. };
  111. struct Response {
  112. std::string version;
  113. int status;
  114. Headers headers;
  115. std::string body;
  116. bool has_header(const char* key) const;
  117. std::string get_header_value(const char* key) const;
  118. void set_header(const char* key, const char* val);
  119. void set_redirect(const char* url);
  120. void set_content(const char* s, size_t n, const char* content_type);
  121. void set_content(const std::string& s, const char* content_type);
  122. Response() : status(-1) {}
  123. };
  124. class Stream {
  125. public:
  126. virtual ~Stream() {}
  127. virtual int read(char* ptr, size_t size) = 0;
  128. virtual int write(const char* ptr, size_t size1) = 0;
  129. virtual int write(const char* ptr) = 0;
  130. virtual std::string get_remote_addr() = 0;
  131. template <typename ...Args>
  132. void write_format(const char* fmt, const Args& ...args);
  133. };
  134. class SocketStream : public Stream {
  135. public:
  136. SocketStream(socket_t sock);
  137. virtual ~SocketStream();
  138. virtual int read(char* ptr, size_t size);
  139. virtual int write(const char* ptr, size_t size);
  140. virtual int write(const char* ptr);
  141. virtual std::string get_remote_addr();
  142. private:
  143. socket_t sock_;
  144. };
  145. class Server {
  146. public:
  147. typedef std::function<void (const Request&, Response&)> Handler;
  148. typedef std::function<void (const Request&, const Response&)> Logger;
  149. Server(HttpVersion http_version = HttpVersion::v1_0);
  150. virtual ~Server();
  151. virtual bool is_valid() const;
  152. Server& get(const char* pattern, Handler handler);
  153. Server& post(const char* pattern, Handler handler);
  154. bool set_base_dir(const char* path);
  155. void set_error_handler(Handler handler);
  156. void set_logger(Logger logger);
  157. int bind_to_any_port(const char* host, int socket_flags = 0);
  158. bool listen_after_bind();
  159. bool listen(const char* host, int port, int socket_flags = 0);
  160. bool is_running() const;
  161. void stop();
  162. bool is_handling_requests() const;
  163. protected:
  164. bool process_request(Stream& strm, bool last_connection);
  165. const HttpVersion http_version_;
  166. private:
  167. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  168. socket_t create_server_socket(const char* host, int port, int socket_flags) const;
  169. int bind_internal(const char* host, int port, int socket_flags);
  170. bool listen_internal();
  171. bool routing(Request& req, Response& res);
  172. bool handle_file_request(Request& req, Response& res);
  173. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  174. bool parse_request_line(const char* s, Request& req);
  175. void write_response(Stream& strm, bool last_connection, const Request& req, Response& res);
  176. virtual bool read_and_close_socket(socket_t sock);
  177. socket_t svr_sock_;
  178. std::string base_dir_;
  179. Handlers get_handlers_;
  180. Handlers post_handlers_;
  181. Handler error_handler_;
  182. Logger logger_;
  183. // TODO: Use thread pool...
  184. std::mutex running_threads_mutex_;
  185. int running_threads_;
  186. };
  187. class Client {
  188. public:
  189. Client(
  190. const char* host,
  191. int port = 80,
  192. size_t timeout_sec = 300,
  193. HttpVersion http_version = HttpVersion::v1_0);
  194. virtual ~Client();
  195. virtual bool is_valid() const;
  196. std::shared_ptr<Response> get(const char* path, Progress progress = nullptr);
  197. std::shared_ptr<Response> get(const char* path, const Headers& headers, Progress progress = nullptr);
  198. std::shared_ptr<Response> head(const char* path);
  199. std::shared_ptr<Response> head(const char* path, const Headers& headers);
  200. std::shared_ptr<Response> post(const char* path, const std::string& body, const char* content_type);
  201. std::shared_ptr<Response> post(const char* path, const Headers& headers, const std::string& body, const char* content_type);
  202. std::shared_ptr<Response> post(const char* path, const Params& params);
  203. std::shared_ptr<Response> post(const char* path, const Headers& headers, const Params& params);
  204. bool send(Request& req, Response& res);
  205. protected:
  206. bool process_request(Stream& strm, Request& req, Response& res);
  207. const std::string host_;
  208. const int port_;
  209. size_t timeout_sec_;
  210. const HttpVersion http_version_;
  211. const std::string host_and_port_;
  212. private:
  213. socket_t create_client_socket() const;
  214. bool read_response_line(Stream& strm, Response& res);
  215. void write_request(Stream& strm, Request& req);
  216. virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
  217. };
  218. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  219. class SSLSocketStream : public Stream {
  220. public:
  221. SSLSocketStream(socket_t sock, SSL* ssl);
  222. virtual ~SSLSocketStream();
  223. virtual int read(char* ptr, size_t size);
  224. virtual int write(const char* ptr, size_t size);
  225. virtual int write(const char* ptr);
  226. virtual std::string get_remote_addr();
  227. private:
  228. socket_t sock_;
  229. SSL* ssl_;
  230. };
  231. class SSLServer : public Server {
  232. public:
  233. SSLServer(
  234. const char* cert_path, const char* private_key_path,
  235. HttpVersion http_version = HttpVersion::v1_0);
  236. virtual ~SSLServer();
  237. virtual bool is_valid() const;
  238. private:
  239. virtual bool read_and_close_socket(socket_t sock);
  240. SSL_CTX* ctx_;
  241. };
  242. class SSLClient : public Client {
  243. public:
  244. SSLClient(
  245. const char* host,
  246. int port = 80,
  247. size_t timeout_sec = 300,
  248. HttpVersion http_version = HttpVersion::v1_0);
  249. virtual ~SSLClient();
  250. virtual bool is_valid() const;
  251. private:
  252. virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
  253. SSL_CTX* ctx_;
  254. };
  255. #endif
  256. /*
  257. * Implementation
  258. */
  259. namespace detail {
  260. static std::vector<const char*> http_version_strings = { "HTTP/1.0", "HTTP/1.1" };
  261. template <class Fn>
  262. void split(const char* b, const char* e, char d, Fn fn)
  263. {
  264. int i = 0;
  265. int beg = 0;
  266. while (e ? (b + i != e) : (b[i] != '\0')) {
  267. if (b[i] == d) {
  268. fn(&b[beg], &b[i]);
  269. beg = i + 1;
  270. }
  271. i++;
  272. }
  273. if (i) {
  274. fn(&b[beg], &b[i]);
  275. }
  276. }
  277. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  278. // to store data. The call can set memory on stack for performance.
  279. class stream_line_reader {
  280. public:
  281. stream_line_reader(Stream& strm, char* fixed_buffer, size_t fixed_buffer_size)
  282. : strm_(strm)
  283. , fixed_buffer_(fixed_buffer)
  284. , fixed_buffer_size_(fixed_buffer_size) {
  285. }
  286. const char* ptr() const {
  287. if (glowable_buffer_.empty()) {
  288. return fixed_buffer_;
  289. } else {
  290. return glowable_buffer_.data();
  291. }
  292. }
  293. bool getline() {
  294. fixed_buffer_used_size_ = 0;
  295. glowable_buffer_.clear();
  296. for (size_t i = 0; ; i++) {
  297. char byte;
  298. auto n = strm_.read(&byte, 1);
  299. if (n < 0) {
  300. return false;
  301. } else if (n == 0) {
  302. if (i == 0) {
  303. return false;
  304. } else {
  305. break;
  306. }
  307. }
  308. append(byte);
  309. if (byte == '\n') {
  310. break;
  311. }
  312. }
  313. return true;
  314. }
  315. private:
  316. void append(char c) {
  317. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  318. fixed_buffer_[fixed_buffer_used_size_++] = c;
  319. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  320. } else {
  321. if (glowable_buffer_.empty()) {
  322. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  323. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  324. }
  325. glowable_buffer_ += c;
  326. }
  327. }
  328. Stream& strm_;
  329. char* fixed_buffer_;
  330. const size_t fixed_buffer_size_;
  331. size_t fixed_buffer_used_size_;
  332. std::string glowable_buffer_;
  333. };
  334. inline int close_socket(socket_t sock)
  335. {
  336. #ifdef _WIN32
  337. return closesocket(sock);
  338. #else
  339. return close(sock);
  340. #endif
  341. }
  342. inline int select_read(socket_t sock, size_t sec, size_t usec)
  343. {
  344. fd_set fds;
  345. FD_ZERO(&fds);
  346. FD_SET(sock, &fds);
  347. timeval tv;
  348. tv.tv_sec = sec;
  349. tv.tv_usec = usec;
  350. return select(sock + 1, &fds, NULL, NULL, &tv);
  351. }
  352. inline bool wait_until_socket_is_ready(socket_t sock, size_t sec, size_t usec)
  353. {
  354. fd_set fdsr;
  355. FD_ZERO(&fdsr);
  356. FD_SET(sock, &fdsr);
  357. auto fdsw = fdsr;
  358. auto fdse = fdsr;
  359. timeval tv;
  360. tv.tv_sec = sec;
  361. tv.tv_usec = usec;
  362. if (select(sock + 1, &fdsr, &fdsw, &fdse, &tv) < 0) {
  363. return false;
  364. } else if (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw)) {
  365. int error = 0;
  366. socklen_t len = sizeof(error);
  367. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)&error, &len) < 0 || error) {
  368. return false;
  369. }
  370. } else {
  371. return false;
  372. }
  373. return true;
  374. }
  375. template <typename T>
  376. inline bool read_and_close_socket(socket_t sock, bool keep_alive, T callback)
  377. {
  378. bool ret = false;
  379. if (keep_alive) {
  380. auto count = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  381. while (count > 0 &&
  382. detail::select_read(sock,
  383. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  384. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  385. auto last_connection = count == 1;
  386. SocketStream strm(sock);
  387. ret = callback(strm, last_connection);
  388. if (!ret) {
  389. break;
  390. }
  391. count--;
  392. }
  393. } else {
  394. SocketStream strm(sock);
  395. ret = callback(strm, true);
  396. }
  397. close_socket(sock);
  398. return ret;
  399. }
  400. inline int shutdown_socket(socket_t sock)
  401. {
  402. #ifdef _WIN32
  403. return shutdown(sock, SD_BOTH);
  404. #else
  405. return shutdown(sock, SHUT_RDWR);
  406. #endif
  407. }
  408. template <typename Fn>
  409. socket_t create_socket(const char* host, int port, Fn fn, int socket_flags = 0)
  410. {
  411. #ifdef _WIN32
  412. #define SO_SYNCHRONOUS_NONALERT 0x20
  413. #define SO_OPENTYPE 0x7008
  414. int opt = SO_SYNCHRONOUS_NONALERT;
  415. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  416. #endif
  417. // Get address info
  418. struct addrinfo hints;
  419. struct addrinfo *result;
  420. memset(&hints, 0, sizeof(struct addrinfo));
  421. hints.ai_family = AF_UNSPEC;
  422. hints.ai_socktype = SOCK_STREAM;
  423. hints.ai_flags = socket_flags;
  424. hints.ai_protocol = 0;
  425. auto service = std::to_string(port);
  426. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  427. return -1;
  428. }
  429. for (auto rp = result; rp; rp = rp->ai_next) {
  430. // Create a socket
  431. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  432. if (sock == -1) {
  433. continue;
  434. }
  435. // Make 'reuse address' option available
  436. int yes = 1;
  437. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  438. // bind or connect
  439. if (fn(sock, *rp)) {
  440. freeaddrinfo(result);
  441. return sock;
  442. }
  443. close_socket(sock);
  444. }
  445. freeaddrinfo(result);
  446. return -1;
  447. }
  448. inline void set_nonblocking(socket_t sock, bool nonblocking)
  449. {
  450. #ifdef _WIN32
  451. auto flags = nonblocking ? 1UL : 0UL;
  452. ioctlsocket(sock, FIONBIO, &flags);
  453. #else
  454. auto flags = fcntl(sock, F_GETFL, 0);
  455. fcntl(sock, F_SETFL, nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  456. #endif
  457. }
  458. inline bool is_connection_error()
  459. {
  460. #ifdef _WIN32
  461. return WSAGetLastError() != WSAEWOULDBLOCK;
  462. #else
  463. return errno != EINPROGRESS;
  464. #endif
  465. }
  466. inline std::string get_remote_addr(socket_t sock) {
  467. struct sockaddr_storage addr;
  468. char ipstr[INET6_ADDRSTRLEN];
  469. socklen_t len = sizeof(addr);
  470. getpeername(sock, (struct sockaddr*)&addr, &len);
  471. // deal with both IPv4 and IPv6:
  472. if (addr.ss_family == AF_INET) {
  473. auto s = (struct sockaddr_in *)&addr;
  474. inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr));
  475. } else { // AF_INET6
  476. auto s = (struct sockaddr_in6 *)&addr;
  477. inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof(ipstr));
  478. }
  479. return ipstr;
  480. }
  481. inline bool is_file(const std::string& path)
  482. {
  483. struct stat st;
  484. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  485. }
  486. inline bool is_dir(const std::string& path)
  487. {
  488. struct stat st;
  489. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  490. }
  491. inline bool is_valid_path(const std::string& path) {
  492. size_t level = 0;
  493. size_t i = 0;
  494. // Skip slash
  495. while (i < path.size() && path[i] == '/') {
  496. i++;
  497. }
  498. while (i < path.size()) {
  499. // Read component
  500. auto beg = i;
  501. while (i < path.size() && path[i] != '/') {
  502. i++;
  503. }
  504. auto len = i - beg;
  505. assert(len > 0);
  506. if (!path.compare(beg, len, ".")) {
  507. ;
  508. } else if (!path.compare(beg, len, "..")) {
  509. if (level == 0) {
  510. return false;
  511. }
  512. level--;
  513. } else {
  514. level++;
  515. }
  516. // Skip slash
  517. while (i < path.size() && path[i] == '/') {
  518. i++;
  519. }
  520. }
  521. return true;
  522. }
  523. inline void read_file(const std::string& path, std::string& out)
  524. {
  525. std::ifstream fs(path, std::ios_base::binary);
  526. fs.seekg(0, std::ios_base::end);
  527. auto size = fs.tellg();
  528. fs.seekg(0);
  529. out.resize(static_cast<size_t>(size));
  530. fs.read(&out[0], size);
  531. }
  532. inline std::string file_extension(const std::string& path)
  533. {
  534. std::smatch m;
  535. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  536. if (std::regex_search(path, m, pat)) {
  537. return m[1].str();
  538. }
  539. return std::string();
  540. }
  541. inline const char* find_content_type(const std::string& path)
  542. {
  543. auto ext = file_extension(path);
  544. if (ext == "txt") {
  545. return "text/plain";
  546. } else if (ext == "html") {
  547. return "text/html";
  548. } else if (ext == "css") {
  549. return "text/css";
  550. } else if (ext == "jpeg" || ext == "jpg") {
  551. return "image/jpg";
  552. } else if (ext == "png") {
  553. return "image/png";
  554. } else if (ext == "gif") {
  555. return "image/gif";
  556. } else if (ext == "svg") {
  557. return "image/svg+xml";
  558. } else if (ext == "ico") {
  559. return "image/x-icon";
  560. } else if (ext == "json") {
  561. return "application/json";
  562. } else if (ext == "pdf") {
  563. return "application/pdf";
  564. } else if (ext == "js") {
  565. return "application/javascript";
  566. } else if (ext == "xml") {
  567. return "application/xml";
  568. } else if (ext == "xhtml") {
  569. return "application/xhtml+xml";
  570. }
  571. return nullptr;
  572. }
  573. inline const char* status_message(int status)
  574. {
  575. switch (status) {
  576. case 200: return "OK";
  577. case 400: return "Bad Request";
  578. case 404: return "Not Found";
  579. case 415: return "Unsupported Media Type";
  580. default:
  581. case 500: return "Internal Server Error";
  582. }
  583. }
  584. inline const char* get_header_value(const Headers& headers, const char* key, const char* def)
  585. {
  586. auto it = headers.find(key);
  587. if (it != headers.end()) {
  588. return it->second.c_str();
  589. }
  590. return def;
  591. }
  592. inline int get_header_value_int(const Headers& headers, const char* key, int def)
  593. {
  594. auto it = headers.find(key);
  595. if (it != headers.end()) {
  596. return std::stoi(it->second);
  597. }
  598. return def;
  599. }
  600. inline bool read_headers(Stream& strm, Headers& headers)
  601. {
  602. static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
  603. const auto bufsiz = 2048;
  604. char buf[bufsiz];
  605. stream_line_reader reader(strm, buf, bufsiz);
  606. for (;;) {
  607. if (!reader.getline()) {
  608. return false;
  609. }
  610. if (!strcmp(reader.ptr(), "\r\n")) {
  611. break;
  612. }
  613. std::cmatch m;
  614. if (std::regex_match(reader.ptr(), m, re)) {
  615. auto key = std::string(m[1]);
  616. auto val = std::string(m[2]);
  617. headers.emplace(key, val);
  618. }
  619. }
  620. return true;
  621. }
  622. template <typename T>
  623. bool read_content_with_length(Stream& strm, T& x, size_t len, Progress progress)
  624. {
  625. x.body.assign(len, 0);
  626. size_t r = 0;
  627. while (r < len){
  628. auto n = strm.read(&x.body[r], len - r);
  629. if (n <= 0) {
  630. return false;
  631. }
  632. r += n;
  633. if (progress) {
  634. progress(r, len);
  635. }
  636. }
  637. return true;
  638. }
  639. template <typename T>
  640. bool read_content_without_length(Stream& strm, T& x)
  641. {
  642. for (;;) {
  643. char byte;
  644. auto n = strm.read(&byte, 1);
  645. if (n < 0) {
  646. return false;
  647. } else if (n == 0) {
  648. return true;
  649. }
  650. x.body += byte;
  651. }
  652. return true;
  653. }
  654. template <typename T>
  655. bool read_content_chunked(Stream& strm, T& x)
  656. {
  657. const auto bufsiz = 16;
  658. char buf[bufsiz];
  659. stream_line_reader reader(strm, buf, bufsiz);
  660. if (!reader.getline()) {
  661. return false;
  662. }
  663. auto chunk_len = std::stoi(reader.ptr(), 0, 16);
  664. while (chunk_len > 0){
  665. std::string chunk(chunk_len, 0);
  666. auto n = strm.read(&chunk[0], chunk_len);
  667. if (n <= 0) {
  668. return false;
  669. }
  670. if (!reader.getline()) {
  671. return false;
  672. }
  673. if (strcmp(reader.ptr(), "\r\n")) {
  674. break;
  675. }
  676. x.body += chunk;
  677. if (!reader.getline()) {
  678. return false;
  679. }
  680. chunk_len = std::stoi(reader.ptr(), 0, 16);
  681. }
  682. if (chunk_len == 0) {
  683. // Reader terminator after chunks
  684. if (!reader.getline() || strcmp(reader.ptr(), "\r\n"))
  685. return false;
  686. }
  687. return true;
  688. }
  689. template <typename T>
  690. bool read_content(Stream& strm, T& x, Progress progress = Progress())
  691. {
  692. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  693. if (len) {
  694. return read_content_with_length(strm, x, len, progress);
  695. } else {
  696. const auto& encoding = get_header_value(x.headers, "Transfer-Encoding", "");
  697. if (!strcmp(encoding, "chunked")) {
  698. return read_content_chunked(strm, x);
  699. } else {
  700. return read_content_without_length(strm, x);
  701. }
  702. }
  703. return true;
  704. }
  705. template <typename T>
  706. inline void write_headers(Stream& strm, const T& info)
  707. {
  708. for (const auto& x: info.headers) {
  709. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  710. }
  711. strm.write("\r\n");
  712. }
  713. inline std::string encode_url(const std::string& s)
  714. {
  715. std::string result;
  716. for (auto i = 0; s[i]; i++) {
  717. switch (s[i]) {
  718. case ' ': result += "+"; break;
  719. case '\'': result += "%27"; break;
  720. case ',': result += "%2C"; break;
  721. case ':': result += "%3A"; break;
  722. case ';': result += "%3B"; break;
  723. default:
  724. if (s[i] < 0) {
  725. result += '%';
  726. char hex[4];
  727. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", (unsigned char)s[i]);
  728. assert(len == 2);
  729. result.append(hex, len);
  730. } else {
  731. result += s[i];
  732. }
  733. break;
  734. }
  735. }
  736. return result;
  737. }
  738. inline bool is_hex(char c, int& v)
  739. {
  740. if (0x20 <= c && isdigit(c)) {
  741. v = c - '0';
  742. return true;
  743. } else if ('A' <= c && c <= 'F') {
  744. v = c - 'A' + 10;
  745. return true;
  746. } else if ('a' <= c && c <= 'f') {
  747. v = c - 'a' + 10;
  748. return true;
  749. }
  750. return false;
  751. }
  752. inline bool from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  753. {
  754. val = 0;
  755. for (; cnt; i++, cnt--) {
  756. if (!s[i]) {
  757. return false;
  758. }
  759. int v = 0;
  760. if (is_hex(s[i], v)) {
  761. val = val * 16 + v;
  762. } else {
  763. return false;
  764. }
  765. }
  766. return true;
  767. }
  768. inline size_t to_utf8(int code, char* buff)
  769. {
  770. if (code < 0x0080) {
  771. buff[0] = (code & 0x7F);
  772. return 1;
  773. } else if (code < 0x0800) {
  774. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  775. buff[1] = (0x80 | (code & 0x3F));
  776. return 2;
  777. } else if (code < 0xD800) {
  778. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  779. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  780. buff[2] = (0x80 | (code & 0x3F));
  781. return 3;
  782. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  783. return 0;
  784. } else if (code < 0x10000) {
  785. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  786. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  787. buff[2] = (0x80 | (code & 0x3F));
  788. return 3;
  789. } else if (code < 0x110000) {
  790. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  791. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  792. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  793. buff[3] = (0x80 | (code & 0x3F));
  794. return 4;
  795. }
  796. // NOTREACHED
  797. return 0;
  798. }
  799. inline std::string decode_url(const std::string& s)
  800. {
  801. std::string result;
  802. for (int i = 0; s[i]; i++) {
  803. if (s[i] == '%') {
  804. if (s[i + 1] && s[i + 1] == 'u') {
  805. int val = 0;
  806. if (from_hex_to_i(s, i + 2, 4, val)) {
  807. // 4 digits Unicode codes
  808. char buff[4];
  809. size_t len = to_utf8(val, buff);
  810. if (len > 0) {
  811. result.append(buff, len);
  812. }
  813. i += 5; // 'u0000'
  814. } else {
  815. result += s[i];
  816. }
  817. } else {
  818. int val = 0;
  819. if (from_hex_to_i(s, i + 1, 2, val)) {
  820. // 2 digits hex codes
  821. result += val;
  822. i += 2; // '00'
  823. } else {
  824. result += s[i];
  825. }
  826. }
  827. } else if (s[i] == '+') {
  828. result += ' ';
  829. } else {
  830. result += s[i];
  831. }
  832. }
  833. return result;
  834. }
  835. inline void parse_query_text(const std::string& s, Params& params)
  836. {
  837. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  838. std::string key;
  839. std::string val;
  840. split(b, e, '=', [&](const char* b, const char* e) {
  841. if (key.empty()) {
  842. key.assign(b, e);
  843. } else {
  844. val.assign(b, e);
  845. }
  846. });
  847. params.emplace(key, decode_url(val));
  848. });
  849. }
  850. inline bool parse_multipart_boundary(const std::string& content_type, std::string& boundary)
  851. {
  852. auto pos = content_type.find("boundary=");
  853. if (pos == std::string::npos) {
  854. return false;
  855. }
  856. boundary = content_type.substr(pos + 9);
  857. return true;
  858. }
  859. inline bool parse_multipart_formdata(
  860. const std::string& boundary, const std::string& body, MultipartFiles& files)
  861. {
  862. static std::string dash = "--";
  863. static std::string crlf = "\r\n";
  864. static std::regex re_content_type(
  865. "Content-Type: (.*?)", std::regex_constants::icase);
  866. static std::regex re_content_disposition(
  867. "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?",
  868. std::regex_constants::icase);
  869. auto dash_boundary = dash + boundary;
  870. auto pos = body.find(dash_boundary);
  871. if (pos != 0) {
  872. return false;
  873. }
  874. pos += dash_boundary.size();
  875. auto next_pos = body.find(crlf, pos);
  876. if (next_pos == std::string::npos) {
  877. return false;
  878. }
  879. pos = next_pos + crlf.size();
  880. while (pos < body.size()) {
  881. next_pos = body.find(crlf, pos);
  882. if (next_pos == std::string::npos) {
  883. return false;
  884. }
  885. std::string name;
  886. MultipartFile file;
  887. auto header = body.substr(pos, (next_pos - pos));
  888. while (pos != next_pos) {
  889. std::smatch m;
  890. if (std::regex_match(header, m, re_content_type)) {
  891. file.content_type = m[1];
  892. } else if (std::regex_match(header, m, re_content_disposition)) {
  893. name = m[1];
  894. file.filename = m[2];
  895. }
  896. pos = next_pos + crlf.size();
  897. next_pos = body.find(crlf, pos);
  898. if (next_pos == std::string::npos) {
  899. return false;
  900. }
  901. header = body.substr(pos, (next_pos - pos));
  902. }
  903. pos = next_pos + crlf.size();
  904. next_pos = body.find(crlf + dash_boundary, pos);
  905. if (next_pos == std::string::npos) {
  906. return false;
  907. }
  908. file.offset = pos;
  909. file.length = next_pos - pos;
  910. pos = next_pos + crlf.size() + dash_boundary.size();
  911. next_pos = body.find(crlf, pos);
  912. if (next_pos == std::string::npos) {
  913. return false;
  914. }
  915. files.emplace(name, file);
  916. pos = next_pos + crlf.size();
  917. }
  918. return true;
  919. }
  920. inline std::string to_lower(const char* beg, const char* end)
  921. {
  922. std::string out;
  923. auto it = beg;
  924. while (it != end) {
  925. out += ::tolower(*it);
  926. it++;
  927. }
  928. return out;
  929. }
  930. inline void make_range_header_core(std::string&) {}
  931. template<typename uint64_t>
  932. inline void make_range_header_core(std::string& field, uint64_t value)
  933. {
  934. if (!field.empty()) {
  935. field += ", ";
  936. }
  937. field += std::to_string(value) + "-";
  938. }
  939. template<typename uint64_t, typename... Args>
  940. inline void make_range_header_core(std::string& field, uint64_t value1, uint64_t value2, Args... args)
  941. {
  942. if (!field.empty()) {
  943. field += ", ";
  944. }
  945. field += std::to_string(value1) + "-" + std::to_string(value2);
  946. make_range_header_core(field, args...);
  947. }
  948. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  949. inline bool can_compress(const std::string& content_type) {
  950. return !content_type.find("text/") ||
  951. content_type == "image/svg+xml" ||
  952. content_type == "application/javascript" ||
  953. content_type == "application/json" ||
  954. content_type == "application/xml" ||
  955. content_type == "application/xhtml+xml";
  956. }
  957. inline void compress(const Request& req, Response& res)
  958. {
  959. // TODO: Server version is HTTP/1.1 and 'Accpet-Encoding' has gzip, not gzip;q=0
  960. const auto& encodings = req.get_header_value("Accept-Encoding");
  961. if (encodings.find("gzip") == std::string::npos) {
  962. return;
  963. }
  964. if (!can_compress(res.get_header_value("Content-Type"))) {
  965. return;
  966. }
  967. z_stream strm;
  968. strm.zalloc = Z_NULL;
  969. strm.zfree = Z_NULL;
  970. strm.opaque = Z_NULL;
  971. auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY);
  972. if (ret != Z_OK) {
  973. return;
  974. }
  975. strm.avail_in = res.body.size();
  976. strm.next_in = (Bytef *)res.body.data();
  977. std::string compressed;
  978. const auto bufsiz = 16384;
  979. char buff[bufsiz];
  980. do {
  981. strm.avail_out = bufsiz;
  982. strm.next_out = (Bytef *)buff;
  983. deflate(&strm, Z_FINISH);
  984. compressed.append(buff, bufsiz - strm.avail_out);
  985. } while (strm.avail_out == 0);
  986. res.set_header("Content-Encoding", "gzip");
  987. res.body.swap(compressed);
  988. deflateEnd(&strm);
  989. }
  990. inline void decompress_request_body(Request& req)
  991. {
  992. if (req.get_header_value("Content-Encoding") != "gzip")
  993. return;
  994. z_stream strm;
  995. strm.zalloc = Z_NULL;
  996. strm.zfree = Z_NULL;
  997. strm.opaque = Z_NULL;
  998. // 15 is the value of wbits, which should be at the maximum possible value to ensure
  999. // that any gzip stream can be decoded. The offset of 16 specifies that the stream
  1000. // to decompress will be formatted with a gzip wrapper.
  1001. auto ret = inflateInit2(&strm, 16 + 15);
  1002. if (ret != Z_OK) {
  1003. return;
  1004. }
  1005. strm.avail_in = req.body.size();
  1006. strm.next_in = (Bytef *)req.body.data();
  1007. std::string decompressed;
  1008. const auto bufsiz = 16384;
  1009. char buff[bufsiz];
  1010. do {
  1011. strm.avail_out = bufsiz;
  1012. strm.next_out = (Bytef *)buff;
  1013. inflate(&strm, Z_NO_FLUSH);
  1014. decompressed.append(buff, bufsiz - strm.avail_out);
  1015. } while (strm.avail_out == 0);
  1016. req.body.swap(decompressed);
  1017. inflateEnd(&strm);
  1018. }
  1019. #endif
  1020. #ifdef _WIN32
  1021. class WSInit {
  1022. public:
  1023. WSInit() {
  1024. WSADATA wsaData;
  1025. WSAStartup(0x0002, &wsaData);
  1026. }
  1027. ~WSInit() {
  1028. WSACleanup();
  1029. }
  1030. };
  1031. static WSInit wsinit_;
  1032. #endif
  1033. } // namespace detail
  1034. // Header utilities
  1035. template<typename uint64_t, typename... Args>
  1036. inline std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args)
  1037. {
  1038. std::string field;
  1039. detail::make_range_header_core(field, value, args...);
  1040. field.insert(0, "bytes=");
  1041. return std::make_pair("Range", field);
  1042. }
  1043. // Request implementation
  1044. inline bool Request::has_header(const char* key) const
  1045. {
  1046. return headers.find(key) != headers.end();
  1047. }
  1048. inline std::string Request::get_header_value(const char* key) const
  1049. {
  1050. return detail::get_header_value(headers, key, "");
  1051. }
  1052. inline void Request::set_header(const char* key, const char* val)
  1053. {
  1054. headers.emplace(key, val);
  1055. }
  1056. inline bool Request::has_param(const char* key) const
  1057. {
  1058. return params.find(key) != params.end();
  1059. }
  1060. inline std::string Request::get_param_value(const char* key) const
  1061. {
  1062. auto it = params.find(key);
  1063. if (it != params.end()) {
  1064. return it->second;
  1065. }
  1066. return std::string();
  1067. }
  1068. inline bool Request::has_file(const char* key) const
  1069. {
  1070. return files.find(key) != files.end();
  1071. }
  1072. inline MultipartFile Request::get_file_value(const char* key) const
  1073. {
  1074. auto it = files.find(key);
  1075. if (it != files.end()) {
  1076. return it->second;
  1077. }
  1078. return MultipartFile();
  1079. }
  1080. // Response implementation
  1081. inline bool Response::has_header(const char* key) const
  1082. {
  1083. return headers.find(key) != headers.end();
  1084. }
  1085. inline std::string Response::get_header_value(const char* key) const
  1086. {
  1087. return detail::get_header_value(headers, key, "");
  1088. }
  1089. inline void Response::set_header(const char* key, const char* val)
  1090. {
  1091. headers.emplace(key, val);
  1092. }
  1093. inline void Response::set_redirect(const char* url)
  1094. {
  1095. set_header("Location", url);
  1096. status = 302;
  1097. }
  1098. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  1099. {
  1100. body.assign(s, n);
  1101. set_header("Content-Type", content_type);
  1102. }
  1103. inline void Response::set_content(const std::string& s, const char* content_type)
  1104. {
  1105. body = s;
  1106. set_header("Content-Type", content_type);
  1107. }
  1108. // Rstream implementation
  1109. template <typename ...Args>
  1110. inline void Stream::write_format(const char* fmt, const Args& ...args)
  1111. {
  1112. const auto bufsiz = 2048;
  1113. char buf[bufsiz];
  1114. #if defined(_MSC_VER) && _MSC_VER < 1900
  1115. auto n = _snprintf_s(buf, bufsiz, bufsiz - 1, fmt, args...);
  1116. #else
  1117. auto n = snprintf(buf, bufsiz - 1, fmt, args...);
  1118. #endif
  1119. if (n > 0) {
  1120. if (n >= bufsiz - 1) {
  1121. std::vector<char> glowable_buf(bufsiz);
  1122. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  1123. glowable_buf.resize(glowable_buf.size() * 2);
  1124. #if defined(_MSC_VER) && _MSC_VER < 1900
  1125. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(), glowable_buf.size() - 1, fmt, args...);
  1126. #else
  1127. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  1128. #endif
  1129. }
  1130. write(&glowable_buf[0], n);
  1131. } else {
  1132. write(buf, n);
  1133. }
  1134. }
  1135. }
  1136. // Socket stream implementation
  1137. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  1138. {
  1139. }
  1140. inline SocketStream::~SocketStream()
  1141. {
  1142. }
  1143. inline int SocketStream::read(char* ptr, size_t size)
  1144. {
  1145. return recv(sock_, ptr, size, 0);
  1146. }
  1147. inline int SocketStream::write(const char* ptr, size_t size)
  1148. {
  1149. return send(sock_, ptr, size, 0);
  1150. }
  1151. inline int SocketStream::write(const char* ptr)
  1152. {
  1153. return write(ptr, strlen(ptr));
  1154. }
  1155. inline std::string SocketStream::get_remote_addr() {
  1156. return detail::get_remote_addr(sock_);
  1157. }
  1158. // HTTP server implementation
  1159. inline Server::Server(HttpVersion http_version)
  1160. : http_version_(http_version)
  1161. , svr_sock_(-1)
  1162. , running_threads_(0)
  1163. {
  1164. #ifndef _WIN32
  1165. signal(SIGPIPE, SIG_IGN);
  1166. #endif
  1167. }
  1168. inline Server::~Server()
  1169. {
  1170. }
  1171. inline Server& Server::get(const char* pattern, Handler handler)
  1172. {
  1173. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1174. return *this;
  1175. }
  1176. inline Server& Server::post(const char* pattern, Handler handler)
  1177. {
  1178. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1179. return *this;
  1180. }
  1181. inline bool Server::set_base_dir(const char* path)
  1182. {
  1183. if (detail::is_dir(path)) {
  1184. base_dir_ = path;
  1185. return true;
  1186. }
  1187. return false;
  1188. }
  1189. inline void Server::set_error_handler(Handler handler)
  1190. {
  1191. error_handler_ = handler;
  1192. }
  1193. inline void Server::set_logger(Logger logger)
  1194. {
  1195. logger_ = logger;
  1196. }
  1197. inline int Server::bind_to_any_port(const char* host, int socket_flags)
  1198. {
  1199. return bind_internal(host, 0, socket_flags);
  1200. }
  1201. inline bool Server::listen_after_bind() {
  1202. return listen_internal();
  1203. }
  1204. inline bool Server::listen(const char* host, int port, int socket_flags)
  1205. {
  1206. if (bind_internal(host, port, socket_flags) < 0)
  1207. return false;
  1208. return listen_internal();
  1209. }
  1210. inline bool Server::is_running() const
  1211. {
  1212. return svr_sock_ != -1;
  1213. }
  1214. inline void Server::stop()
  1215. {
  1216. detail::shutdown_socket(svr_sock_);
  1217. detail::close_socket(svr_sock_);
  1218. svr_sock_ = -1;
  1219. }
  1220. inline bool Server::is_handling_requests() const
  1221. {
  1222. return running_threads_ > 0;
  1223. }
  1224. inline bool Server::parse_request_line(const char* s, Request& req)
  1225. {
  1226. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? (HTTP/1\\.[01])\r\n");
  1227. std::cmatch m;
  1228. if (std::regex_match(s, m, re)) {
  1229. req.version = std::string(m[4]);
  1230. req.method = std::string(m[1]);
  1231. req.path = detail::decode_url(m[2]);
  1232. // Parse query text
  1233. auto len = std::distance(m[3].first, m[3].second);
  1234. if (len > 0) {
  1235. detail::parse_query_text(m[3], req.params);
  1236. }
  1237. return true;
  1238. }
  1239. return false;
  1240. }
  1241. inline void Server::write_response(Stream& strm, bool last_connection, const Request& req, Response& res)
  1242. {
  1243. assert(res.status != -1);
  1244. if (400 <= res.status && error_handler_) {
  1245. error_handler_(req, res);
  1246. }
  1247. // Response line
  1248. strm.write_format("%s %d %s\r\n",
  1249. detail::http_version_strings[static_cast<size_t>(http_version_)],
  1250. res.status,
  1251. detail::status_message(res.status));
  1252. // Headers
  1253. if (!res.has_header("Connection") && (last_connection || req.version == "HTTP/1.0")) {
  1254. res.set_header("Connection", "close");
  1255. }
  1256. if (!res.body.empty()) {
  1257. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1258. detail::compress(req, res);
  1259. #endif
  1260. if (!res.has_header("Content-Type")) {
  1261. res.set_header("Content-Type", "text/plain");
  1262. }
  1263. auto length = std::to_string(res.body.size());
  1264. res.set_header("Content-Length", length.c_str());
  1265. }
  1266. detail::write_headers(strm, res);
  1267. // Body
  1268. if (!res.body.empty() && req.method != "HEAD") {
  1269. strm.write(res.body.c_str(), res.body.size());
  1270. }
  1271. // Log
  1272. if (logger_) {
  1273. logger_(req, res);
  1274. }
  1275. }
  1276. inline bool Server::handle_file_request(Request& req, Response& res)
  1277. {
  1278. if (!base_dir_.empty() && detail::is_valid_path(req.path)) {
  1279. std::string path = base_dir_ + req.path;
  1280. if (!path.empty() && path.back() == '/') {
  1281. path += "index.html";
  1282. }
  1283. if (detail::is_file(path)) {
  1284. detail::read_file(path, res.body);
  1285. auto type = detail::find_content_type(path);
  1286. if (type) {
  1287. res.set_header("Content-Type", type);
  1288. }
  1289. res.status = 200;
  1290. return true;
  1291. }
  1292. }
  1293. return false;
  1294. }
  1295. inline socket_t Server::create_server_socket(const char* host, int port, int socket_flags) const
  1296. {
  1297. return detail::create_socket(host, port,
  1298. [](socket_t sock, struct addrinfo& ai) -> bool {
  1299. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  1300. return false;
  1301. }
  1302. if (::listen(sock, 5)) { // Listen through 5 channels
  1303. return false;
  1304. }
  1305. return true;
  1306. }, socket_flags);
  1307. }
  1308. inline int Server::bind_internal(const char* host, int port, int socket_flags)
  1309. {
  1310. if (!is_valid()) {
  1311. return -1;
  1312. }
  1313. svr_sock_ = create_server_socket(host, port, socket_flags);
  1314. if (svr_sock_ == -1) {
  1315. return -1;
  1316. }
  1317. if (port == 0) {
  1318. struct sockaddr_in sin;
  1319. socklen_t len = sizeof(sin);
  1320. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&sin), &len) == -1) {
  1321. return -1;
  1322. }
  1323. return ntohs(sin.sin_port);
  1324. } else {
  1325. return port;
  1326. }
  1327. }
  1328. inline bool Server::listen_internal()
  1329. {
  1330. auto ret = true;
  1331. for (;;) {
  1332. auto val = detail::select_read(svr_sock_, 0, 100000);
  1333. if (val == 0) { // Timeout
  1334. if (svr_sock_ == -1) {
  1335. // The server socket was closed by 'stop' method.
  1336. break;
  1337. }
  1338. continue;
  1339. }
  1340. socket_t sock = accept(svr_sock_, NULL, NULL);
  1341. if (sock == -1) {
  1342. if (svr_sock_ != -1) {
  1343. detail::close_socket(svr_sock_);
  1344. ret = false;
  1345. } else {
  1346. ; // The server socket was closed by user.
  1347. }
  1348. break;
  1349. }
  1350. // TODO: Use thread pool...
  1351. std::thread([=]() {
  1352. {
  1353. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1354. running_threads_++;
  1355. }
  1356. read_and_close_socket(sock);
  1357. {
  1358. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1359. running_threads_--;
  1360. }
  1361. }).detach();
  1362. }
  1363. // TODO: Use thread pool...
  1364. for (;;) {
  1365. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1366. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1367. if (!running_threads_) {
  1368. break;
  1369. }
  1370. }
  1371. return ret;
  1372. }
  1373. inline bool Server::routing(Request& req, Response& res)
  1374. {
  1375. if (req.method == "GET" && handle_file_request(req, res)) {
  1376. return true;
  1377. }
  1378. if (req.method == "GET" || req.method == "HEAD") {
  1379. return dispatch_request(req, res, get_handlers_);
  1380. } else if (req.method == "POST") {
  1381. return dispatch_request(req, res, post_handlers_);
  1382. }
  1383. return false;
  1384. }
  1385. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  1386. {
  1387. for (const auto& x: handlers) {
  1388. const auto& pattern = x.first;
  1389. const auto& handler = x.second;
  1390. if (std::regex_match(req.path, req.matches, pattern)) {
  1391. handler(req, res);
  1392. return true;
  1393. }
  1394. }
  1395. return false;
  1396. }
  1397. inline bool Server::process_request(Stream& strm, bool last_connection)
  1398. {
  1399. const auto bufsiz = 2048;
  1400. char buf[bufsiz];
  1401. detail::stream_line_reader reader(strm, buf, bufsiz);
  1402. // Connection has been closed on client
  1403. if (!reader.getline()) {
  1404. return false;
  1405. }
  1406. Request req;
  1407. Response res;
  1408. res.version = detail::http_version_strings[static_cast<size_t>(http_version_)];
  1409. // Request line and headers
  1410. if (!parse_request_line(reader.ptr(), req) || !detail::read_headers(strm, req.headers)) {
  1411. res.status = 400;
  1412. write_response(strm, last_connection, req, res);
  1413. return true;
  1414. }
  1415. auto ret = true;
  1416. if (req.get_header_value("Connection") == "close") {
  1417. ret = false;
  1418. }
  1419. req.set_header("REMOTE_ADDR", strm.get_remote_addr().c_str());
  1420. // Body
  1421. if (req.method == "POST") {
  1422. if (!detail::read_content(strm, req)) {
  1423. res.status = 400;
  1424. write_response(strm, last_connection, req, res);
  1425. return ret;
  1426. }
  1427. const auto& content_type = req.get_header_value("Content-Type");
  1428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1429. detail::decompress_request_body(req);
  1430. #else
  1431. if (req.get_header_value("Content-Encoding") == "gzip") {
  1432. res.status = 415;
  1433. write_response(strm, last_connection, req, res);
  1434. return ret;
  1435. }
  1436. #endif
  1437. if (!content_type.find("application/x-www-form-urlencoded")) {
  1438. detail::parse_query_text(req.body, req.params);
  1439. } else if(!content_type.find("multipart/form-data")) {
  1440. std::string boundary;
  1441. if (!detail::parse_multipart_boundary(content_type, boundary) ||
  1442. !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
  1443. res.status = 400;
  1444. write_response(strm, last_connection, req, res);
  1445. return ret;
  1446. }
  1447. }
  1448. }
  1449. if (routing(req, res)) {
  1450. if (res.status == -1) {
  1451. res.status = 200;
  1452. }
  1453. } else {
  1454. res.status = 404;
  1455. }
  1456. write_response(strm, last_connection, req, res);
  1457. return ret;
  1458. }
  1459. inline bool Server::is_valid() const
  1460. {
  1461. return true;
  1462. }
  1463. inline bool Server::read_and_close_socket(socket_t sock)
  1464. {
  1465. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1466. return detail::read_and_close_socket(
  1467. sock,
  1468. keep_alive,
  1469. [this](Stream& strm, bool last_connection) {
  1470. return process_request(strm, last_connection);
  1471. });
  1472. }
  1473. // HTTP client implementation
  1474. inline Client::Client(
  1475. const char* host, int port, size_t timeout_sec, HttpVersion http_version)
  1476. : host_(host)
  1477. , port_(port)
  1478. , timeout_sec_(timeout_sec)
  1479. , http_version_(http_version)
  1480. , host_and_port_(host_ + ":" + std::to_string(port_))
  1481. {
  1482. }
  1483. inline Client::~Client()
  1484. {
  1485. }
  1486. inline bool Client::is_valid() const
  1487. {
  1488. return true;
  1489. }
  1490. inline socket_t Client::create_client_socket() const
  1491. {
  1492. return detail::create_socket(host_.c_str(), port_,
  1493. [=](socket_t sock, struct addrinfo& ai) -> bool {
  1494. detail::set_nonblocking(sock, true);
  1495. auto ret = connect(sock, ai.ai_addr, ai.ai_addrlen);
  1496. if (ret < 0) {
  1497. if (detail::is_connection_error() ||
  1498. !detail::wait_until_socket_is_ready(sock, timeout_sec_, 0)) {
  1499. detail::close_socket(sock);
  1500. return false;
  1501. }
  1502. }
  1503. detail::set_nonblocking(sock, false);
  1504. return true;
  1505. });
  1506. }
  1507. inline bool Client::read_response_line(Stream& strm, Response& res)
  1508. {
  1509. const auto bufsiz = 2048;
  1510. char buf[bufsiz];
  1511. detail::stream_line_reader reader(strm, buf, bufsiz);
  1512. if (!reader.getline()) {
  1513. return false;
  1514. }
  1515. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  1516. std::cmatch m;
  1517. if (std::regex_match(reader.ptr(), m, re)) {
  1518. res.status = std::stoi(std::string(m[1]));
  1519. }
  1520. return true;
  1521. }
  1522. inline bool Client::send(Request& req, Response& res)
  1523. {
  1524. if (req.path.empty()) {
  1525. return false;
  1526. }
  1527. auto sock = create_client_socket();
  1528. if (sock == -1) {
  1529. return false;
  1530. }
  1531. return read_and_close_socket(sock, req, res);
  1532. }
  1533. inline void Client::write_request(Stream& strm, Request& req)
  1534. {
  1535. auto path = detail::encode_url(req.path);
  1536. // Request line
  1537. strm.write_format("%s %s %s\r\n",
  1538. req.method.c_str(),
  1539. path.c_str(),
  1540. detail::http_version_strings[static_cast<size_t>(http_version_)]);
  1541. // Headers
  1542. req.set_header("Host", host_and_port_.c_str());
  1543. if (!req.has_header("Accept")) {
  1544. req.set_header("Accept", "*/*");
  1545. }
  1546. if (!req.has_header("User-Agent")) {
  1547. req.set_header("User-Agent", "cpp-httplib/0.2");
  1548. }
  1549. // TODO: if (!req.has_header("Connection") &&
  1550. // (last_connection || http_version_ == detail::HttpVersion::v1_0)) {
  1551. if (!req.has_header("Connection")) {
  1552. req.set_header("Connection", "close");
  1553. }
  1554. if (!req.body.empty()) {
  1555. if (!req.has_header("Content-Type")) {
  1556. req.set_header("Content-Type", "text/plain");
  1557. }
  1558. auto length = std::to_string(req.body.size());
  1559. req.set_header("Content-Length", length.c_str());
  1560. }
  1561. detail::write_headers(strm, req);
  1562. // Body
  1563. if (!req.body.empty()) {
  1564. if (req.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
  1565. auto str = detail::encode_url(req.body);
  1566. strm.write(str.c_str(), str.size());
  1567. } else {
  1568. strm.write(req.body.c_str(), req.body.size());
  1569. }
  1570. }
  1571. }
  1572. inline bool Client::process_request(Stream& strm, Request& req, Response& res)
  1573. {
  1574. // Send request
  1575. write_request(strm, req);
  1576. // Receive response and headers
  1577. if (!read_response_line(strm, res) || !detail::read_headers(strm, res.headers)) {
  1578. return false;
  1579. }
  1580. // TODO: Check if 'Connection' header is 'close' or HTTP version is 1.0, then close socket...
  1581. // Body
  1582. if (req.method != "HEAD") {
  1583. if (!detail::read_content(strm, res, req.progress)) {
  1584. return false;
  1585. }
  1586. }
  1587. return true;
  1588. }
  1589. inline bool Client::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1590. {
  1591. return detail::read_and_close_socket(sock, false, [&](Stream& strm, bool /*last_connection*/) {
  1592. return process_request(strm, req, res);
  1593. });
  1594. }
  1595. inline std::shared_ptr<Response> Client::get(const char* path, Progress progress)
  1596. {
  1597. return get(path, Headers(), progress);
  1598. }
  1599. inline std::shared_ptr<Response> Client::get(const char* path, const Headers& headers, Progress progress)
  1600. {
  1601. Request req;
  1602. req.method = "GET";
  1603. req.path = path;
  1604. req.headers = headers;
  1605. req.progress = progress;
  1606. auto res = std::make_shared<Response>();
  1607. return send(req, *res) ? res : nullptr;
  1608. }
  1609. inline std::shared_ptr<Response> Client::head(const char* path)
  1610. {
  1611. return head(path, Headers());
  1612. }
  1613. inline std::shared_ptr<Response> Client::head(const char* path, const Headers& headers)
  1614. {
  1615. Request req;
  1616. req.method = "HEAD";
  1617. req.headers = headers;
  1618. req.path = path;
  1619. auto res = std::make_shared<Response>();
  1620. return send(req, *res) ? res : nullptr;
  1621. }
  1622. inline std::shared_ptr<Response> Client::post(
  1623. const char* path, const std::string& body, const char* content_type)
  1624. {
  1625. return post(path, Headers(), body, content_type);
  1626. }
  1627. inline std::shared_ptr<Response> Client::post(
  1628. const char* path, const Headers& headers, const std::string& body, const char* content_type)
  1629. {
  1630. Request req;
  1631. req.method = "POST";
  1632. req.headers = headers;
  1633. req.path = path;
  1634. req.headers.emplace("Content-Type", content_type);
  1635. req.body = body;
  1636. auto res = std::make_shared<Response>();
  1637. return send(req, *res) ? res : nullptr;
  1638. }
  1639. inline std::shared_ptr<Response> Client::post(const char* path, const Params& params)
  1640. {
  1641. return post(path, Headers(), params);
  1642. }
  1643. inline std::shared_ptr<Response> Client::post(const char* path, const Headers& headers, const Params& params)
  1644. {
  1645. std::string query;
  1646. for (auto it = params.begin(); it != params.end(); ++it) {
  1647. if (it != params.begin()) {
  1648. query += "&";
  1649. }
  1650. query += it->first;
  1651. query += "=";
  1652. query += it->second;
  1653. }
  1654. return post(path, headers, query, "application/x-www-form-urlencoded");
  1655. }
  1656. /*
  1657. * SSL Implementation
  1658. */
  1659. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1660. namespace detail {
  1661. template <typename U, typename V, typename T>
  1662. inline bool read_and_close_socket_ssl(
  1663. socket_t sock, bool keep_alive,
  1664. SSL_CTX* ctx, U SSL_connect_or_accept, V setup,
  1665. T callback)
  1666. {
  1667. auto ssl = SSL_new(ctx);
  1668. if (!ssl) {
  1669. return false;
  1670. }
  1671. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1672. SSL_set_bio(ssl, bio, bio);
  1673. setup(ssl);
  1674. SSL_connect_or_accept(ssl);
  1675. bool ret = false;
  1676. if (keep_alive) {
  1677. auto count = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1678. while (count > 0 &&
  1679. detail::select_read(sock,
  1680. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1681. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  1682. auto last_connection = count == 1;
  1683. SSLSocketStream strm(sock, ssl);
  1684. ret = callback(strm, last_connection);
  1685. if (!ret) {
  1686. break;
  1687. }
  1688. count--;
  1689. }
  1690. } else {
  1691. SSLSocketStream strm(sock, ssl);
  1692. ret = callback(strm, true);
  1693. }
  1694. SSL_shutdown(ssl);
  1695. SSL_free(ssl);
  1696. close_socket(sock);
  1697. return ret;
  1698. }
  1699. class SSLInit {
  1700. public:
  1701. SSLInit() {
  1702. SSL_load_error_strings();
  1703. SSL_library_init();
  1704. }
  1705. };
  1706. static SSLInit sslinit_;
  1707. } // namespace detail
  1708. // SSL socket stream implementation
  1709. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL* ssl)
  1710. : sock_(sock), ssl_(ssl)
  1711. {
  1712. }
  1713. inline SSLSocketStream::~SSLSocketStream()
  1714. {
  1715. }
  1716. inline int SSLSocketStream::read(char* ptr, size_t size)
  1717. {
  1718. return SSL_read(ssl_, ptr, size);
  1719. }
  1720. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1721. {
  1722. return SSL_write(ssl_, ptr, size);
  1723. }
  1724. inline int SSLSocketStream::write(const char* ptr)
  1725. {
  1726. return write(ptr, strlen(ptr));
  1727. }
  1728. inline std::string SSLSocketStream::get_remote_addr() {
  1729. return detail::get_remote_addr(sock_);
  1730. }
  1731. // SSL HTTP server implementation
  1732. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path, HttpVersion http_version)
  1733. : Server(http_version)
  1734. {
  1735. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1736. if (ctx_) {
  1737. SSL_CTX_set_options(ctx_,
  1738. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1739. SSL_OP_NO_COMPRESSION |
  1740. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1741. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1742. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1743. // EC_KEY_free(ecdh);
  1744. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1745. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1746. SSL_CTX_free(ctx_);
  1747. ctx_ = nullptr;
  1748. }
  1749. }
  1750. }
  1751. inline SSLServer::~SSLServer()
  1752. {
  1753. if (ctx_) {
  1754. SSL_CTX_free(ctx_);
  1755. }
  1756. }
  1757. inline bool SSLServer::is_valid() const
  1758. {
  1759. return ctx_;
  1760. }
  1761. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1762. {
  1763. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1764. return detail::read_and_close_socket_ssl(
  1765. sock,
  1766. keep_alive,
  1767. ctx_,
  1768. SSL_accept,
  1769. [](SSL* /*ssl*/) {},
  1770. [this](Stream& strm, bool last_connection) {
  1771. return process_request(strm, last_connection);
  1772. });
  1773. }
  1774. // SSL HTTP client implementation
  1775. inline SSLClient::SSLClient(
  1776. const char* host, int port, size_t timeout_sec, HttpVersion http_version)
  1777. : Client(host, port, timeout_sec, http_version)
  1778. {
  1779. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1780. }
  1781. inline SSLClient::~SSLClient()
  1782. {
  1783. if (ctx_) {
  1784. SSL_CTX_free(ctx_);
  1785. }
  1786. }
  1787. inline bool SSLClient::is_valid() const
  1788. {
  1789. return ctx_;
  1790. }
  1791. inline bool SSLClient::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1792. {
  1793. return is_valid() && detail::read_and_close_socket_ssl(
  1794. sock, false,
  1795. ctx_, SSL_connect,
  1796. [&](SSL* ssl) {
  1797. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1798. },
  1799. [&](Stream& strm, bool /*last_connection*/) {
  1800. return process_request(strm, req, res);
  1801. });
  1802. }
  1803. #endif
  1804. } // namespace httplib
  1805. #endif
  1806. // vim: et ts=4 sw=4 cin cino={1s ff=unix