httplib.h 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209
  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. #ifndef strcasecmp
  31. #define strcasecmp _stricmp
  32. #endif
  33. typedef SOCKET socket_t;
  34. #else
  35. #include <pthread.h>
  36. #include <unistd.h>
  37. #include <netdb.h>
  38. #include <cstring>
  39. #include <netinet/in.h>
  40. #include <arpa/inet.h>
  41. #include <signal.h>
  42. #include <sys/socket.h>
  43. typedef int socket_t;
  44. #endif
  45. #include <fstream>
  46. #include <functional>
  47. #include <map>
  48. #include <memory>
  49. #include <mutex>
  50. #include <regex>
  51. #include <string>
  52. #include <thread>
  53. #include <sys/stat.h>
  54. #include <fcntl.h>
  55. #include <assert.h>
  56. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  57. #include <openssl/ssl.h>
  58. #endif
  59. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  60. #include <zlib.h>
  61. #endif
  62. /*
  63. * Configuration
  64. */
  65. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  66. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  67. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  68. namespace httplib
  69. {
  70. namespace detail {
  71. struct ci {
  72. bool operator() (const std::string & s1, const std::string & s2) const {
  73. return std::lexicographical_compare(
  74. s1.begin(), s1.end(),
  75. s2.begin(), s2.end(),
  76. [](char c1, char c2) {
  77. return ::tolower(c1) < ::tolower(c2);
  78. });
  79. }
  80. };
  81. } // namespace detail
  82. enum class HttpVersion { v1_0 = 0, v1_1 };
  83. typedef std::multimap<std::string, std::string, detail::ci> Headers;
  84. template<typename uint64_t, typename... Args>
  85. std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args);
  86. typedef std::multimap<std::string, std::string> Params;
  87. typedef std::smatch Match;
  88. typedef std::function<void (uint64_t current, uint64_t total)> Progress;
  89. struct MultipartFile {
  90. std::string filename;
  91. std::string content_type;
  92. size_t offset = 0;
  93. size_t length = 0;
  94. };
  95. typedef std::multimap<std::string, MultipartFile> MultipartFiles;
  96. struct Request {
  97. std::string version;
  98. std::string method;
  99. std::string path;
  100. Headers headers;
  101. std::string body;
  102. Params params;
  103. MultipartFiles files;
  104. Match matches;
  105. Progress progress;
  106. bool has_header(const char* key) const;
  107. std::string get_header_value(const char* key) const;
  108. void set_header(const char* key, const char* val);
  109. bool has_param(const char* key) const;
  110. std::string get_param_value(const char* key) const;
  111. bool has_file(const char* key) const;
  112. MultipartFile get_file_value(const char* key) const;
  113. };
  114. struct Response {
  115. std::string version;
  116. int status;
  117. Headers headers;
  118. std::string body;
  119. bool has_header(const char* key) const;
  120. std::string get_header_value(const char* key) const;
  121. void set_header(const char* key, const char* val);
  122. void set_redirect(const char* url);
  123. void set_content(const char* s, size_t n, const char* content_type);
  124. void set_content(const std::string& s, const char* content_type);
  125. Response() : status(-1) {}
  126. };
  127. class Stream {
  128. public:
  129. virtual ~Stream() {}
  130. virtual int read(char* ptr, size_t size) = 0;
  131. virtual int write(const char* ptr, size_t size1) = 0;
  132. virtual int write(const char* ptr) = 0;
  133. virtual std::string get_remote_addr() = 0;
  134. template <typename ...Args>
  135. void write_format(const char* fmt, const Args& ...args);
  136. };
  137. class SocketStream : public Stream {
  138. public:
  139. SocketStream(socket_t sock);
  140. virtual ~SocketStream();
  141. virtual int read(char* ptr, size_t size);
  142. virtual int write(const char* ptr, size_t size);
  143. virtual int write(const char* ptr);
  144. virtual std::string get_remote_addr();
  145. private:
  146. socket_t sock_;
  147. };
  148. class Server {
  149. public:
  150. typedef std::function<void (const Request&, Response&)> Handler;
  151. typedef std::function<void (const Request&, const Response&)> Logger;
  152. Server(HttpVersion http_version = HttpVersion::v1_0);
  153. virtual ~Server();
  154. virtual bool is_valid() const;
  155. Server& get(const char* pattern, Handler handler);
  156. Server& post(const char* pattern, Handler handler);
  157. bool set_base_dir(const char* path);
  158. void set_error_handler(Handler handler);
  159. void set_logger(Logger logger);
  160. int bind_to_any_port(const char* host, int socket_flags = 0);
  161. bool listen_after_bind();
  162. bool listen(const char* host, int port, int socket_flags = 0);
  163. bool is_running() const;
  164. void stop();
  165. protected:
  166. bool process_request(Stream& strm, bool last_connection);
  167. const HttpVersion http_version_;
  168. private:
  169. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  170. socket_t create_server_socket(const char* host, int port, int socket_flags) const;
  171. int bind_internal(const char* host, int port, int socket_flags);
  172. bool listen_internal();
  173. bool routing(Request& req, Response& res);
  174. bool handle_file_request(Request& req, Response& res);
  175. bool dispatch_request(Request& req, Response& res, Handlers& handlers);
  176. bool parse_request_line(const char* s, Request& req);
  177. void write_response(Stream& strm, bool last_connection, const Request& req, Response& res);
  178. virtual bool read_and_close_socket(socket_t sock);
  179. bool is_running_;
  180. socket_t svr_sock_;
  181. std::string base_dir_;
  182. Handlers get_handlers_;
  183. Handlers post_handlers_;
  184. Handler error_handler_;
  185. Logger logger_;
  186. // TODO: Use thread pool...
  187. std::mutex running_threads_mutex_;
  188. int running_threads_;
  189. };
  190. class Client {
  191. public:
  192. Client(
  193. const char* host,
  194. int port = 80,
  195. size_t timeout_sec = 300,
  196. HttpVersion http_version = HttpVersion::v1_0);
  197. virtual ~Client();
  198. virtual bool is_valid() const;
  199. std::shared_ptr<Response> get(const char* path, Progress progress = nullptr);
  200. std::shared_ptr<Response> get(const char* path, const Headers& headers, Progress progress = nullptr);
  201. std::shared_ptr<Response> head(const char* path);
  202. std::shared_ptr<Response> head(const char* path, const Headers& headers);
  203. std::shared_ptr<Response> post(const char* path, const std::string& body, const char* content_type);
  204. std::shared_ptr<Response> post(const char* path, const Headers& headers, const std::string& body, const char* content_type);
  205. std::shared_ptr<Response> post(const char* path, const Params& params);
  206. std::shared_ptr<Response> post(const char* path, const Headers& headers, const Params& params);
  207. bool send(Request& req, Response& res);
  208. protected:
  209. bool process_request(Stream& strm, Request& req, Response& res);
  210. const std::string host_;
  211. const int port_;
  212. size_t timeout_sec_;
  213. const HttpVersion http_version_;
  214. const std::string host_and_port_;
  215. private:
  216. socket_t create_client_socket() const;
  217. bool read_response_line(Stream& strm, Response& res);
  218. void write_request(Stream& strm, Request& req);
  219. virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
  220. };
  221. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  222. class SSLSocketStream : public Stream {
  223. public:
  224. SSLSocketStream(socket_t sock, SSL* ssl);
  225. virtual ~SSLSocketStream();
  226. virtual int read(char* ptr, size_t size);
  227. virtual int write(const char* ptr, size_t size);
  228. virtual int write(const char* ptr);
  229. virtual std::string get_remote_addr();
  230. private:
  231. socket_t sock_;
  232. SSL* ssl_;
  233. };
  234. class SSLServer : public Server {
  235. public:
  236. SSLServer(
  237. const char* cert_path, const char* private_key_path,
  238. HttpVersion http_version = HttpVersion::v1_0);
  239. virtual ~SSLServer();
  240. virtual bool is_valid() const;
  241. private:
  242. virtual bool read_and_close_socket(socket_t sock);
  243. SSL_CTX* ctx_;
  244. };
  245. class SSLClient : public Client {
  246. public:
  247. SSLClient(
  248. const char* host,
  249. int port = 80,
  250. size_t timeout_sec = 300,
  251. HttpVersion http_version = HttpVersion::v1_0);
  252. virtual ~SSLClient();
  253. virtual bool is_valid() const;
  254. private:
  255. virtual bool read_and_close_socket(socket_t sock, Request& req, Response& res);
  256. SSL_CTX* ctx_;
  257. };
  258. #endif
  259. /*
  260. * Implementation
  261. */
  262. namespace detail {
  263. static std::vector<const char*> http_version_strings = { "HTTP/1.0", "HTTP/1.1" };
  264. template <class Fn>
  265. void split(const char* b, const char* e, char d, Fn fn)
  266. {
  267. int i = 0;
  268. int beg = 0;
  269. while (e ? (b + i != e) : (b[i] != '\0')) {
  270. if (b[i] == d) {
  271. fn(&b[beg], &b[i]);
  272. beg = i + 1;
  273. }
  274. i++;
  275. }
  276. if (i) {
  277. fn(&b[beg], &b[i]);
  278. }
  279. }
  280. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  281. // to store data. The call can set memory on stack for performance.
  282. class stream_line_reader {
  283. public:
  284. stream_line_reader(Stream& strm, char* fixed_buffer, size_t fixed_buffer_size)
  285. : strm_(strm)
  286. , fixed_buffer_(fixed_buffer)
  287. , fixed_buffer_size_(fixed_buffer_size) {
  288. }
  289. const char* ptr() const {
  290. if (glowable_buffer_.empty()) {
  291. return fixed_buffer_;
  292. } else {
  293. return glowable_buffer_.data();
  294. }
  295. }
  296. bool getline() {
  297. fixed_buffer_used_size_ = 0;
  298. glowable_buffer_.clear();
  299. for (size_t i = 0; ; i++) {
  300. char byte;
  301. auto n = strm_.read(&byte, 1);
  302. if (n < 0) {
  303. return false;
  304. } else if (n == 0) {
  305. if (i == 0) {
  306. return false;
  307. } else {
  308. break;
  309. }
  310. }
  311. append(byte);
  312. if (byte == '\n') {
  313. break;
  314. }
  315. }
  316. return true;
  317. }
  318. private:
  319. void append(char c) {
  320. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  321. fixed_buffer_[fixed_buffer_used_size_++] = c;
  322. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  323. } else {
  324. if (glowable_buffer_.empty()) {
  325. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  326. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  327. }
  328. glowable_buffer_ += c;
  329. }
  330. }
  331. Stream& strm_;
  332. char* fixed_buffer_;
  333. const size_t fixed_buffer_size_;
  334. size_t fixed_buffer_used_size_;
  335. std::string glowable_buffer_;
  336. };
  337. inline int close_socket(socket_t sock)
  338. {
  339. #ifdef _WIN32
  340. return closesocket(sock);
  341. #else
  342. return close(sock);
  343. #endif
  344. }
  345. inline int select_read(socket_t sock, size_t sec, size_t usec)
  346. {
  347. fd_set fds;
  348. FD_ZERO(&fds);
  349. FD_SET(sock, &fds);
  350. timeval tv;
  351. tv.tv_sec = sec;
  352. tv.tv_usec = usec;
  353. return select(sock + 1, &fds, NULL, NULL, &tv);
  354. }
  355. inline bool wait_until_socket_is_ready(socket_t sock, size_t sec, size_t usec)
  356. {
  357. fd_set fdsr;
  358. FD_ZERO(&fdsr);
  359. FD_SET(sock, &fdsr);
  360. auto fdsw = fdsr;
  361. auto fdse = fdsr;
  362. timeval tv;
  363. tv.tv_sec = sec;
  364. tv.tv_usec = usec;
  365. if (select(sock + 1, &fdsr, &fdsw, &fdse, &tv) < 0) {
  366. return false;
  367. } else if (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw)) {
  368. int error = 0;
  369. socklen_t len = sizeof(error);
  370. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)&error, &len) < 0 || error) {
  371. return false;
  372. }
  373. } else {
  374. return false;
  375. }
  376. return true;
  377. }
  378. template <typename T>
  379. inline bool read_and_close_socket(socket_t sock, bool keep_alive, T callback)
  380. {
  381. bool ret = false;
  382. if (keep_alive) {
  383. auto count = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  384. while (count > 0 &&
  385. detail::select_read(sock,
  386. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  387. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  388. auto last_connection = count == 1;
  389. SocketStream strm(sock);
  390. ret = callback(strm, last_connection);
  391. if (!ret) {
  392. break;
  393. }
  394. count--;
  395. }
  396. } else {
  397. SocketStream strm(sock);
  398. ret = callback(strm, true);
  399. }
  400. close_socket(sock);
  401. return ret;
  402. }
  403. inline int shutdown_socket(socket_t sock)
  404. {
  405. #ifdef _WIN32
  406. return shutdown(sock, SD_BOTH);
  407. #else
  408. return shutdown(sock, SHUT_RDWR);
  409. #endif
  410. }
  411. template <typename Fn>
  412. socket_t create_socket(const char* host, int port, Fn fn, int socket_flags = 0)
  413. {
  414. #ifdef _WIN32
  415. #define SO_SYNCHRONOUS_NONALERT 0x20
  416. #define SO_OPENTYPE 0x7008
  417. int opt = SO_SYNCHRONOUS_NONALERT;
  418. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char*)&opt, sizeof(opt));
  419. #endif
  420. // Get address info
  421. struct addrinfo hints;
  422. struct addrinfo *result;
  423. memset(&hints, 0, sizeof(struct addrinfo));
  424. hints.ai_family = AF_UNSPEC;
  425. hints.ai_socktype = SOCK_STREAM;
  426. hints.ai_flags = socket_flags;
  427. hints.ai_protocol = 0;
  428. auto service = std::to_string(port);
  429. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  430. return -1;
  431. }
  432. for (auto rp = result; rp; rp = rp->ai_next) {
  433. // Create a socket
  434. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  435. if (sock == -1) {
  436. continue;
  437. }
  438. // Make 'reuse address' option available
  439. int yes = 1;
  440. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&yes, sizeof(yes));
  441. // bind or connect
  442. if (fn(sock, *rp)) {
  443. freeaddrinfo(result);
  444. return sock;
  445. }
  446. close_socket(sock);
  447. }
  448. freeaddrinfo(result);
  449. return -1;
  450. }
  451. inline void set_nonblocking(socket_t sock, bool nonblocking)
  452. {
  453. #ifdef _WIN32
  454. auto flags = nonblocking ? 1UL : 0UL;
  455. ioctlsocket(sock, FIONBIO, &flags);
  456. #else
  457. auto flags = fcntl(sock, F_GETFL, 0);
  458. fcntl(sock, F_SETFL, nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  459. #endif
  460. }
  461. inline bool is_connection_error()
  462. {
  463. #ifdef _WIN32
  464. return WSAGetLastError() != WSAEWOULDBLOCK;
  465. #else
  466. return errno != EINPROGRESS;
  467. #endif
  468. }
  469. inline std::string get_remote_addr(socket_t sock) {
  470. struct sockaddr_storage addr;
  471. char ipstr[INET6_ADDRSTRLEN];
  472. socklen_t len = sizeof(addr);
  473. getpeername(sock, (struct sockaddr*)&addr, &len);
  474. // deal with both IPv4 and IPv6:
  475. if (addr.ss_family == AF_INET) {
  476. auto s = (struct sockaddr_in *)&addr;
  477. inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof(ipstr));
  478. } else { // AF_INET6
  479. auto s = (struct sockaddr_in6 *)&addr;
  480. inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof(ipstr));
  481. }
  482. return ipstr;
  483. }
  484. inline bool is_file(const std::string& path)
  485. {
  486. struct stat st;
  487. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  488. }
  489. inline bool is_dir(const std::string& path)
  490. {
  491. struct stat st;
  492. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  493. }
  494. inline bool is_valid_path(const std::string& path) {
  495. size_t level = 0;
  496. size_t i = 0;
  497. // Skip slash
  498. while (i < path.size() && path[i] == '/') {
  499. i++;
  500. }
  501. while (i < path.size()) {
  502. // Read component
  503. auto beg = i;
  504. while (i < path.size() && path[i] != '/') {
  505. i++;
  506. }
  507. auto len = i - beg;
  508. assert(len > 0);
  509. if (!path.compare(beg, len, ".")) {
  510. ;
  511. } else if (!path.compare(beg, len, "..")) {
  512. if (level == 0) {
  513. return false;
  514. }
  515. level--;
  516. } else {
  517. level++;
  518. }
  519. // Skip slash
  520. while (i < path.size() && path[i] == '/') {
  521. i++;
  522. }
  523. }
  524. return true;
  525. }
  526. inline void read_file(const std::string& path, std::string& out)
  527. {
  528. std::ifstream fs(path, std::ios_base::binary);
  529. fs.seekg(0, std::ios_base::end);
  530. auto size = fs.tellg();
  531. fs.seekg(0);
  532. out.resize(static_cast<size_t>(size));
  533. fs.read(&out[0], size);
  534. }
  535. inline std::string file_extension(const std::string& path)
  536. {
  537. std::smatch m;
  538. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  539. if (std::regex_search(path, m, pat)) {
  540. return m[1].str();
  541. }
  542. return std::string();
  543. }
  544. inline const char* find_content_type(const std::string& path)
  545. {
  546. auto ext = file_extension(path);
  547. if (ext == "txt") {
  548. return "text/plain";
  549. } else if (ext == "html") {
  550. return "text/html";
  551. } else if (ext == "css") {
  552. return "text/css";
  553. } else if (ext == "jpeg" || ext == "jpg") {
  554. return "image/jpg";
  555. } else if (ext == "png") {
  556. return "image/png";
  557. } else if (ext == "gif") {
  558. return "image/gif";
  559. } else if (ext == "svg") {
  560. return "image/svg+xml";
  561. } else if (ext == "ico") {
  562. return "image/x-icon";
  563. } else if (ext == "json") {
  564. return "application/json";
  565. } else if (ext == "pdf") {
  566. return "application/pdf";
  567. } else if (ext == "js") {
  568. return "application/javascript";
  569. } else if (ext == "xml") {
  570. return "application/xml";
  571. } else if (ext == "xhtml") {
  572. return "application/xhtml+xml";
  573. }
  574. return nullptr;
  575. }
  576. inline const char* status_message(int status)
  577. {
  578. switch (status) {
  579. case 200: return "OK";
  580. case 400: return "Bad Request";
  581. case 404: return "Not Found";
  582. case 415: return "Unsupported Media Type";
  583. default:
  584. case 500: return "Internal Server Error";
  585. }
  586. }
  587. inline const char* get_header_value(const Headers& headers, const char* key, const char* def)
  588. {
  589. auto it = headers.find(key);
  590. if (it != headers.end()) {
  591. return it->second.c_str();
  592. }
  593. return def;
  594. }
  595. inline int get_header_value_int(const Headers& headers, const char* key, int def)
  596. {
  597. auto it = headers.find(key);
  598. if (it != headers.end()) {
  599. return std::stoi(it->second);
  600. }
  601. return def;
  602. }
  603. inline bool read_headers(Stream& strm, Headers& headers)
  604. {
  605. static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
  606. const auto bufsiz = 2048;
  607. char buf[bufsiz];
  608. stream_line_reader reader(strm, buf, bufsiz);
  609. for (;;) {
  610. if (!reader.getline()) {
  611. return false;
  612. }
  613. if (!strcmp(reader.ptr(), "\r\n")) {
  614. break;
  615. }
  616. std::cmatch m;
  617. if (std::regex_match(reader.ptr(), m, re)) {
  618. auto key = std::string(m[1]);
  619. auto val = std::string(m[2]);
  620. headers.emplace(key, val);
  621. }
  622. }
  623. return true;
  624. }
  625. bool read_content_with_length(Stream& strm, std::string& out, size_t len, Progress progress)
  626. {
  627. out.assign(len, 0);
  628. size_t r = 0;
  629. while (r < len){
  630. auto n = strm.read(&out[r], len - r);
  631. if (n <= 0) {
  632. return false;
  633. }
  634. r += n;
  635. if (progress) {
  636. progress(r, len);
  637. }
  638. }
  639. return true;
  640. }
  641. bool read_content_without_length(Stream& strm, std::string& out)
  642. {
  643. for (;;) {
  644. char byte;
  645. auto n = strm.read(&byte, 1);
  646. if (n < 0) {
  647. return false;
  648. } else if (n == 0) {
  649. return true;
  650. }
  651. out += byte;
  652. }
  653. return true;
  654. }
  655. bool read_content_chunked(Stream& strm, std::string& out)
  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. out += 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.body, len, progress);
  695. } else {
  696. const auto& encoding = get_header_value(x.headers, "Transfer-Encoding", "");
  697. if (!strcasecmp(encoding, "chunked")) {
  698. return read_content_chunked(strm, x.body);
  699. } else {
  700. return read_content_without_length(strm, x.body);
  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. , is_running_(false)
  1162. , svr_sock_(-1)
  1163. , running_threads_(0)
  1164. {
  1165. #ifndef _WIN32
  1166. signal(SIGPIPE, SIG_IGN);
  1167. #endif
  1168. }
  1169. inline Server::~Server()
  1170. {
  1171. }
  1172. inline Server& Server::get(const char* pattern, Handler handler)
  1173. {
  1174. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1175. return *this;
  1176. }
  1177. inline Server& Server::post(const char* pattern, Handler handler)
  1178. {
  1179. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1180. return *this;
  1181. }
  1182. inline bool Server::set_base_dir(const char* path)
  1183. {
  1184. if (detail::is_dir(path)) {
  1185. base_dir_ = path;
  1186. return true;
  1187. }
  1188. return false;
  1189. }
  1190. inline void Server::set_error_handler(Handler handler)
  1191. {
  1192. error_handler_ = handler;
  1193. }
  1194. inline void Server::set_logger(Logger logger)
  1195. {
  1196. logger_ = logger;
  1197. }
  1198. inline int Server::bind_to_any_port(const char* host, int socket_flags)
  1199. {
  1200. return bind_internal(host, 0, socket_flags);
  1201. }
  1202. inline bool Server::listen_after_bind() {
  1203. return listen_internal();
  1204. }
  1205. inline bool Server::listen(const char* host, int port, int socket_flags)
  1206. {
  1207. if (bind_internal(host, port, socket_flags) < 0)
  1208. return false;
  1209. return listen_internal();
  1210. }
  1211. inline bool Server::is_running() const
  1212. {
  1213. return is_running_;
  1214. }
  1215. inline void Server::stop()
  1216. {
  1217. if (is_running_) {
  1218. assert(svr_sock_ != -1);
  1219. detail::shutdown_socket(svr_sock_);
  1220. detail::close_socket(svr_sock_);
  1221. svr_sock_ = -1;
  1222. }
  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. is_running_ = true;
  1332. for (;;) {
  1333. auto val = detail::select_read(svr_sock_, 0, 100000);
  1334. if (val == 0) { // Timeout
  1335. if (svr_sock_ == -1) {
  1336. // The server socket was closed by 'stop' method.
  1337. break;
  1338. }
  1339. continue;
  1340. }
  1341. socket_t sock = accept(svr_sock_, NULL, NULL);
  1342. if (sock == -1) {
  1343. if (svr_sock_ != -1) {
  1344. detail::close_socket(svr_sock_);
  1345. ret = false;
  1346. } else {
  1347. ; // The server socket was closed by user.
  1348. }
  1349. break;
  1350. }
  1351. // TODO: Use thread pool...
  1352. std::thread([=]() {
  1353. {
  1354. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1355. running_threads_++;
  1356. }
  1357. read_and_close_socket(sock);
  1358. {
  1359. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1360. running_threads_--;
  1361. }
  1362. }).detach();
  1363. }
  1364. // TODO: Use thread pool...
  1365. for (;;) {
  1366. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1367. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1368. if (!running_threads_) {
  1369. break;
  1370. }
  1371. }
  1372. is_running_ = false;
  1373. return ret;
  1374. }
  1375. inline bool Server::routing(Request& req, Response& res)
  1376. {
  1377. if (req.method == "GET" && handle_file_request(req, res)) {
  1378. return true;
  1379. }
  1380. if (req.method == "GET" || req.method == "HEAD") {
  1381. return dispatch_request(req, res, get_handlers_);
  1382. } else if (req.method == "POST") {
  1383. return dispatch_request(req, res, post_handlers_);
  1384. }
  1385. return false;
  1386. }
  1387. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  1388. {
  1389. for (const auto& x: handlers) {
  1390. const auto& pattern = x.first;
  1391. const auto& handler = x.second;
  1392. if (std::regex_match(req.path, req.matches, pattern)) {
  1393. handler(req, res);
  1394. return true;
  1395. }
  1396. }
  1397. return false;
  1398. }
  1399. inline bool Server::process_request(Stream& strm, bool last_connection)
  1400. {
  1401. const auto bufsiz = 2048;
  1402. char buf[bufsiz];
  1403. detail::stream_line_reader reader(strm, buf, bufsiz);
  1404. // Connection has been closed on client
  1405. if (!reader.getline()) {
  1406. return false;
  1407. }
  1408. Request req;
  1409. Response res;
  1410. res.version = detail::http_version_strings[static_cast<size_t>(http_version_)];
  1411. // Request line and headers
  1412. if (!parse_request_line(reader.ptr(), req) || !detail::read_headers(strm, req.headers)) {
  1413. res.status = 400;
  1414. write_response(strm, last_connection, req, res);
  1415. return true;
  1416. }
  1417. auto ret = true;
  1418. if (req.get_header_value("Connection") == "close") {
  1419. ret = false;
  1420. }
  1421. req.set_header("REMOTE_ADDR", strm.get_remote_addr().c_str());
  1422. // Body
  1423. if (req.method == "POST") {
  1424. if (!detail::read_content(strm, req)) {
  1425. res.status = 400;
  1426. write_response(strm, last_connection, req, res);
  1427. return ret;
  1428. }
  1429. const auto& content_type = req.get_header_value("Content-Type");
  1430. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1431. detail::decompress_request_body(req);
  1432. #else
  1433. if (req.get_header_value("Content-Encoding") == "gzip") {
  1434. res.status = 415;
  1435. write_response(strm, last_connection, req, res);
  1436. return ret;
  1437. }
  1438. #endif
  1439. if (!content_type.find("application/x-www-form-urlencoded")) {
  1440. detail::parse_query_text(req.body, req.params);
  1441. } else if(!content_type.find("multipart/form-data")) {
  1442. std::string boundary;
  1443. if (!detail::parse_multipart_boundary(content_type, boundary) ||
  1444. !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
  1445. res.status = 400;
  1446. write_response(strm, last_connection, req, res);
  1447. return ret;
  1448. }
  1449. }
  1450. }
  1451. if (routing(req, res)) {
  1452. if (res.status == -1) {
  1453. res.status = 200;
  1454. }
  1455. } else {
  1456. res.status = 404;
  1457. }
  1458. write_response(strm, last_connection, req, res);
  1459. return ret;
  1460. }
  1461. inline bool Server::is_valid() const
  1462. {
  1463. return true;
  1464. }
  1465. inline bool Server::read_and_close_socket(socket_t sock)
  1466. {
  1467. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1468. return detail::read_and_close_socket(
  1469. sock,
  1470. keep_alive,
  1471. [this](Stream& strm, bool last_connection) {
  1472. return process_request(strm, last_connection);
  1473. });
  1474. }
  1475. // HTTP client implementation
  1476. inline Client::Client(
  1477. const char* host, int port, size_t timeout_sec, HttpVersion http_version)
  1478. : host_(host)
  1479. , port_(port)
  1480. , timeout_sec_(timeout_sec)
  1481. , http_version_(http_version)
  1482. , host_and_port_(host_ + ":" + std::to_string(port_))
  1483. {
  1484. }
  1485. inline Client::~Client()
  1486. {
  1487. }
  1488. inline bool Client::is_valid() const
  1489. {
  1490. return true;
  1491. }
  1492. inline socket_t Client::create_client_socket() const
  1493. {
  1494. return detail::create_socket(host_.c_str(), port_,
  1495. [=](socket_t sock, struct addrinfo& ai) -> bool {
  1496. detail::set_nonblocking(sock, true);
  1497. auto ret = connect(sock, ai.ai_addr, ai.ai_addrlen);
  1498. if (ret < 0) {
  1499. if (detail::is_connection_error() ||
  1500. !detail::wait_until_socket_is_ready(sock, timeout_sec_, 0)) {
  1501. detail::close_socket(sock);
  1502. return false;
  1503. }
  1504. }
  1505. detail::set_nonblocking(sock, false);
  1506. return true;
  1507. });
  1508. }
  1509. inline bool Client::read_response_line(Stream& strm, Response& res)
  1510. {
  1511. const auto bufsiz = 2048;
  1512. char buf[bufsiz];
  1513. detail::stream_line_reader reader(strm, buf, bufsiz);
  1514. if (!reader.getline()) {
  1515. return false;
  1516. }
  1517. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  1518. std::cmatch m;
  1519. if (std::regex_match(reader.ptr(), m, re)) {
  1520. res.status = std::stoi(std::string(m[1]));
  1521. }
  1522. return true;
  1523. }
  1524. inline bool Client::send(Request& req, Response& res)
  1525. {
  1526. if (req.path.empty()) {
  1527. return false;
  1528. }
  1529. auto sock = create_client_socket();
  1530. if (sock == -1) {
  1531. return false;
  1532. }
  1533. return read_and_close_socket(sock, req, res);
  1534. }
  1535. inline void Client::write_request(Stream& strm, Request& req)
  1536. {
  1537. auto path = detail::encode_url(req.path);
  1538. // Request line
  1539. strm.write_format("%s %s %s\r\n",
  1540. req.method.c_str(),
  1541. path.c_str(),
  1542. detail::http_version_strings[static_cast<size_t>(http_version_)]);
  1543. // Headers
  1544. req.set_header("Host", host_and_port_.c_str());
  1545. if (!req.has_header("Accept")) {
  1546. req.set_header("Accept", "*/*");
  1547. }
  1548. if (!req.has_header("User-Agent")) {
  1549. req.set_header("User-Agent", "cpp-httplib/0.2");
  1550. }
  1551. // TODO: if (!req.has_header("Connection") &&
  1552. // (last_connection || http_version_ == detail::HttpVersion::v1_0)) {
  1553. if (!req.has_header("Connection")) {
  1554. req.set_header("Connection", "close");
  1555. }
  1556. if (!req.body.empty()) {
  1557. if (!req.has_header("Content-Type")) {
  1558. req.set_header("Content-Type", "text/plain");
  1559. }
  1560. auto length = std::to_string(req.body.size());
  1561. req.set_header("Content-Length", length.c_str());
  1562. }
  1563. detail::write_headers(strm, req);
  1564. // Body
  1565. if (!req.body.empty()) {
  1566. if (req.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
  1567. auto str = detail::encode_url(req.body);
  1568. strm.write(str.c_str(), str.size());
  1569. } else {
  1570. strm.write(req.body.c_str(), req.body.size());
  1571. }
  1572. }
  1573. }
  1574. inline bool Client::process_request(Stream& strm, Request& req, Response& res)
  1575. {
  1576. // Send request
  1577. write_request(strm, req);
  1578. // Receive response and headers
  1579. if (!read_response_line(strm, res) || !detail::read_headers(strm, res.headers)) {
  1580. return false;
  1581. }
  1582. // TODO: Check if 'Connection' header is 'close' or HTTP version is 1.0, then close socket...
  1583. // Body
  1584. if (req.method != "HEAD") {
  1585. if (!detail::read_content(strm, res, req.progress)) {
  1586. return false;
  1587. }
  1588. }
  1589. return true;
  1590. }
  1591. inline bool Client::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1592. {
  1593. return detail::read_and_close_socket(sock, false, [&](Stream& strm, bool /*last_connection*/) {
  1594. return process_request(strm, req, res);
  1595. });
  1596. }
  1597. inline std::shared_ptr<Response> Client::get(const char* path, Progress progress)
  1598. {
  1599. return get(path, Headers(), progress);
  1600. }
  1601. inline std::shared_ptr<Response> Client::get(const char* path, const Headers& headers, Progress progress)
  1602. {
  1603. Request req;
  1604. req.method = "GET";
  1605. req.path = path;
  1606. req.headers = headers;
  1607. req.progress = progress;
  1608. auto res = std::make_shared<Response>();
  1609. return send(req, *res) ? res : nullptr;
  1610. }
  1611. inline std::shared_ptr<Response> Client::head(const char* path)
  1612. {
  1613. return head(path, Headers());
  1614. }
  1615. inline std::shared_ptr<Response> Client::head(const char* path, const Headers& headers)
  1616. {
  1617. Request req;
  1618. req.method = "HEAD";
  1619. req.headers = headers;
  1620. req.path = path;
  1621. auto res = std::make_shared<Response>();
  1622. return send(req, *res) ? res : nullptr;
  1623. }
  1624. inline std::shared_ptr<Response> Client::post(
  1625. const char* path, const std::string& body, const char* content_type)
  1626. {
  1627. return post(path, Headers(), body, content_type);
  1628. }
  1629. inline std::shared_ptr<Response> Client::post(
  1630. const char* path, const Headers& headers, const std::string& body, const char* content_type)
  1631. {
  1632. Request req;
  1633. req.method = "POST";
  1634. req.headers = headers;
  1635. req.path = path;
  1636. req.headers.emplace("Content-Type", content_type);
  1637. req.body = body;
  1638. auto res = std::make_shared<Response>();
  1639. return send(req, *res) ? res : nullptr;
  1640. }
  1641. inline std::shared_ptr<Response> Client::post(const char* path, const Params& params)
  1642. {
  1643. return post(path, Headers(), params);
  1644. }
  1645. inline std::shared_ptr<Response> Client::post(const char* path, const Headers& headers, const Params& params)
  1646. {
  1647. std::string query;
  1648. for (auto it = params.begin(); it != params.end(); ++it) {
  1649. if (it != params.begin()) {
  1650. query += "&";
  1651. }
  1652. query += it->first;
  1653. query += "=";
  1654. query += it->second;
  1655. }
  1656. return post(path, headers, query, "application/x-www-form-urlencoded");
  1657. }
  1658. /*
  1659. * SSL Implementation
  1660. */
  1661. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1662. namespace detail {
  1663. template <typename U, typename V, typename T>
  1664. inline bool read_and_close_socket_ssl(
  1665. socket_t sock, bool keep_alive,
  1666. SSL_CTX* ctx, U SSL_connect_or_accept, V setup,
  1667. T callback)
  1668. {
  1669. auto ssl = SSL_new(ctx);
  1670. if (!ssl) {
  1671. return false;
  1672. }
  1673. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1674. SSL_set_bio(ssl, bio, bio);
  1675. setup(ssl);
  1676. SSL_connect_or_accept(ssl);
  1677. bool ret = false;
  1678. if (keep_alive) {
  1679. auto count = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1680. while (count > 0 &&
  1681. detail::select_read(sock,
  1682. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1683. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  1684. auto last_connection = count == 1;
  1685. SSLSocketStream strm(sock, ssl);
  1686. ret = callback(strm, last_connection);
  1687. if (!ret) {
  1688. break;
  1689. }
  1690. count--;
  1691. }
  1692. } else {
  1693. SSLSocketStream strm(sock, ssl);
  1694. ret = callback(strm, true);
  1695. }
  1696. SSL_shutdown(ssl);
  1697. SSL_free(ssl);
  1698. close_socket(sock);
  1699. return ret;
  1700. }
  1701. class SSLInit {
  1702. public:
  1703. SSLInit() {
  1704. SSL_load_error_strings();
  1705. SSL_library_init();
  1706. }
  1707. };
  1708. static SSLInit sslinit_;
  1709. } // namespace detail
  1710. // SSL socket stream implementation
  1711. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL* ssl)
  1712. : sock_(sock), ssl_(ssl)
  1713. {
  1714. }
  1715. inline SSLSocketStream::~SSLSocketStream()
  1716. {
  1717. }
  1718. inline int SSLSocketStream::read(char* ptr, size_t size)
  1719. {
  1720. return SSL_read(ssl_, ptr, size);
  1721. }
  1722. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1723. {
  1724. return SSL_write(ssl_, ptr, size);
  1725. }
  1726. inline int SSLSocketStream::write(const char* ptr)
  1727. {
  1728. return write(ptr, strlen(ptr));
  1729. }
  1730. inline std::string SSLSocketStream::get_remote_addr() {
  1731. return detail::get_remote_addr(sock_);
  1732. }
  1733. // SSL HTTP server implementation
  1734. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path, HttpVersion http_version)
  1735. : Server(http_version)
  1736. {
  1737. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1738. if (ctx_) {
  1739. SSL_CTX_set_options(ctx_,
  1740. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1741. SSL_OP_NO_COMPRESSION |
  1742. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1743. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1744. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1745. // EC_KEY_free(ecdh);
  1746. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1747. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1748. SSL_CTX_free(ctx_);
  1749. ctx_ = nullptr;
  1750. }
  1751. }
  1752. }
  1753. inline SSLServer::~SSLServer()
  1754. {
  1755. if (ctx_) {
  1756. SSL_CTX_free(ctx_);
  1757. }
  1758. }
  1759. inline bool SSLServer::is_valid() const
  1760. {
  1761. return ctx_;
  1762. }
  1763. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1764. {
  1765. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1766. return detail::read_and_close_socket_ssl(
  1767. sock,
  1768. keep_alive,
  1769. ctx_,
  1770. SSL_accept,
  1771. [](SSL* /*ssl*/) {},
  1772. [this](Stream& strm, bool last_connection) {
  1773. return process_request(strm, last_connection);
  1774. });
  1775. }
  1776. // SSL HTTP client implementation
  1777. inline SSLClient::SSLClient(
  1778. const char* host, int port, size_t timeout_sec, HttpVersion http_version)
  1779. : Client(host, port, timeout_sec, http_version)
  1780. {
  1781. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1782. }
  1783. inline SSLClient::~SSLClient()
  1784. {
  1785. if (ctx_) {
  1786. SSL_CTX_free(ctx_);
  1787. }
  1788. }
  1789. inline bool SSLClient::is_valid() const
  1790. {
  1791. return ctx_;
  1792. }
  1793. inline bool SSLClient::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1794. {
  1795. return is_valid() && detail::read_and_close_socket_ssl(
  1796. sock, false,
  1797. ctx_, SSL_connect,
  1798. [&](SSL* ssl) {
  1799. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1800. },
  1801. [&](Stream& strm, bool /*last_connection*/) {
  1802. return process_request(strm, req, res);
  1803. });
  1804. }
  1805. #endif
  1806. } // namespace httplib
  1807. #endif
  1808. // vim: et ts=4 sw=4 cin cino={1s ff=unix