httplib.h 53 KB

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