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. };
  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;
  666. if (!read_content_with_length(strm, chunk, chunk_len, nullptr)) {
  667. return false;
  668. }
  669. if (!reader.getline()) {
  670. return false;
  671. }
  672. if (strcmp(reader.ptr(), "\r\n")) {
  673. break;
  674. }
  675. out += chunk;
  676. if (!reader.getline()) {
  677. return false;
  678. }
  679. chunk_len = std::stoi(reader.ptr(), 0, 16);
  680. }
  681. if (chunk_len == 0) {
  682. // Reader terminator after chunks
  683. if (!reader.getline() || strcmp(reader.ptr(), "\r\n"))
  684. return false;
  685. }
  686. return true;
  687. }
  688. template <typename T>
  689. bool read_content(Stream& strm, T& x, Progress progress = Progress())
  690. {
  691. auto len = get_header_value_int(x.headers, "Content-Length", 0);
  692. if (len) {
  693. return read_content_with_length(strm, x.body, len, progress);
  694. } else {
  695. const auto& encoding = get_header_value(x.headers, "Transfer-Encoding", "");
  696. if (!strcasecmp(encoding, "chunked")) {
  697. return read_content_chunked(strm, x.body);
  698. } else {
  699. return read_content_without_length(strm, x.body);
  700. }
  701. }
  702. return true;
  703. }
  704. template <typename T>
  705. inline void write_headers(Stream& strm, const T& info)
  706. {
  707. for (const auto& x: info.headers) {
  708. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  709. }
  710. strm.write("\r\n");
  711. }
  712. inline std::string encode_url(const std::string& s)
  713. {
  714. std::string result;
  715. for (auto i = 0; s[i]; i++) {
  716. switch (s[i]) {
  717. case ' ': result += "+"; break;
  718. case '\'': result += "%27"; break;
  719. case ',': result += "%2C"; break;
  720. case ':': result += "%3A"; break;
  721. case ';': result += "%3B"; break;
  722. default:
  723. if (s[i] < 0) {
  724. result += '%';
  725. char hex[4];
  726. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", (unsigned char)s[i]);
  727. assert(len == 2);
  728. result.append(hex, len);
  729. } else {
  730. result += s[i];
  731. }
  732. break;
  733. }
  734. }
  735. return result;
  736. }
  737. inline bool is_hex(char c, int& v)
  738. {
  739. if (0x20 <= c && isdigit(c)) {
  740. v = c - '0';
  741. return true;
  742. } else if ('A' <= c && c <= 'F') {
  743. v = c - 'A' + 10;
  744. return true;
  745. } else if ('a' <= c && c <= 'f') {
  746. v = c - 'a' + 10;
  747. return true;
  748. }
  749. return false;
  750. }
  751. inline bool from_hex_to_i(const std::string& s, int i, int cnt, int& val)
  752. {
  753. val = 0;
  754. for (; cnt; i++, cnt--) {
  755. if (!s[i]) {
  756. return false;
  757. }
  758. int v = 0;
  759. if (is_hex(s[i], v)) {
  760. val = val * 16 + v;
  761. } else {
  762. return false;
  763. }
  764. }
  765. return true;
  766. }
  767. inline size_t to_utf8(int code, char* buff)
  768. {
  769. if (code < 0x0080) {
  770. buff[0] = (code & 0x7F);
  771. return 1;
  772. } else if (code < 0x0800) {
  773. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  774. buff[1] = (0x80 | (code & 0x3F));
  775. return 2;
  776. } else if (code < 0xD800) {
  777. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  778. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  779. buff[2] = (0x80 | (code & 0x3F));
  780. return 3;
  781. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  782. return 0;
  783. } else if (code < 0x10000) {
  784. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  785. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  786. buff[2] = (0x80 | (code & 0x3F));
  787. return 3;
  788. } else if (code < 0x110000) {
  789. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  790. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  791. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  792. buff[3] = (0x80 | (code & 0x3F));
  793. return 4;
  794. }
  795. // NOTREACHED
  796. return 0;
  797. }
  798. inline std::string decode_url(const std::string& s)
  799. {
  800. std::string result;
  801. for (int i = 0; s[i]; i++) {
  802. if (s[i] == '%') {
  803. if (s[i + 1] && s[i + 1] == 'u') {
  804. int val = 0;
  805. if (from_hex_to_i(s, i + 2, 4, val)) {
  806. // 4 digits Unicode codes
  807. char buff[4];
  808. size_t len = to_utf8(val, buff);
  809. if (len > 0) {
  810. result.append(buff, len);
  811. }
  812. i += 5; // 'u0000'
  813. } else {
  814. result += s[i];
  815. }
  816. } else {
  817. int val = 0;
  818. if (from_hex_to_i(s, i + 1, 2, val)) {
  819. // 2 digits hex codes
  820. result += val;
  821. i += 2; // '00'
  822. } else {
  823. result += s[i];
  824. }
  825. }
  826. } else if (s[i] == '+') {
  827. result += ' ';
  828. } else {
  829. result += s[i];
  830. }
  831. }
  832. return result;
  833. }
  834. inline void parse_query_text(const std::string& s, Params& params)
  835. {
  836. split(&s[0], &s[s.size()], '&', [&](const char* b, const char* e) {
  837. std::string key;
  838. std::string val;
  839. split(b, e, '=', [&](const char* b, const char* e) {
  840. if (key.empty()) {
  841. key.assign(b, e);
  842. } else {
  843. val.assign(b, e);
  844. }
  845. });
  846. params.emplace(key, decode_url(val));
  847. });
  848. }
  849. inline bool parse_multipart_boundary(const std::string& content_type, std::string& boundary)
  850. {
  851. auto pos = content_type.find("boundary=");
  852. if (pos == std::string::npos) {
  853. return false;
  854. }
  855. boundary = content_type.substr(pos + 9);
  856. return true;
  857. }
  858. inline bool parse_multipart_formdata(
  859. const std::string& boundary, const std::string& body, MultipartFiles& files)
  860. {
  861. static std::string dash = "--";
  862. static std::string crlf = "\r\n";
  863. static std::regex re_content_type(
  864. "Content-Type: (.*?)", std::regex_constants::icase);
  865. static std::regex re_content_disposition(
  866. "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?",
  867. std::regex_constants::icase);
  868. auto dash_boundary = dash + boundary;
  869. auto pos = body.find(dash_boundary);
  870. if (pos != 0) {
  871. return false;
  872. }
  873. pos += dash_boundary.size();
  874. auto next_pos = body.find(crlf, pos);
  875. if (next_pos == std::string::npos) {
  876. return false;
  877. }
  878. pos = next_pos + crlf.size();
  879. while (pos < body.size()) {
  880. next_pos = body.find(crlf, pos);
  881. if (next_pos == std::string::npos) {
  882. return false;
  883. }
  884. std::string name;
  885. MultipartFile file;
  886. auto header = body.substr(pos, (next_pos - pos));
  887. while (pos != next_pos) {
  888. std::smatch m;
  889. if (std::regex_match(header, m, re_content_type)) {
  890. file.content_type = m[1];
  891. } else if (std::regex_match(header, m, re_content_disposition)) {
  892. name = m[1];
  893. file.filename = m[2];
  894. }
  895. pos = next_pos + crlf.size();
  896. next_pos = body.find(crlf, pos);
  897. if (next_pos == std::string::npos) {
  898. return false;
  899. }
  900. header = body.substr(pos, (next_pos - pos));
  901. }
  902. pos = next_pos + crlf.size();
  903. next_pos = body.find(crlf + dash_boundary, pos);
  904. if (next_pos == std::string::npos) {
  905. return false;
  906. }
  907. file.offset = pos;
  908. file.length = next_pos - pos;
  909. pos = next_pos + crlf.size() + dash_boundary.size();
  910. next_pos = body.find(crlf, pos);
  911. if (next_pos == std::string::npos) {
  912. return false;
  913. }
  914. files.emplace(name, file);
  915. pos = next_pos + crlf.size();
  916. }
  917. return true;
  918. }
  919. inline std::string to_lower(const char* beg, const char* end)
  920. {
  921. std::string out;
  922. auto it = beg;
  923. while (it != end) {
  924. out += ::tolower(*it);
  925. it++;
  926. }
  927. return out;
  928. }
  929. inline void make_range_header_core(std::string&) {}
  930. template<typename uint64_t>
  931. inline void make_range_header_core(std::string& field, uint64_t value)
  932. {
  933. if (!field.empty()) {
  934. field += ", ";
  935. }
  936. field += std::to_string(value) + "-";
  937. }
  938. template<typename uint64_t, typename... Args>
  939. inline void make_range_header_core(std::string& field, uint64_t value1, uint64_t value2, Args... args)
  940. {
  941. if (!field.empty()) {
  942. field += ", ";
  943. }
  944. field += std::to_string(value1) + "-" + std::to_string(value2);
  945. make_range_header_core(field, args...);
  946. }
  947. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  948. inline bool can_compress(const std::string& content_type) {
  949. return !content_type.find("text/") ||
  950. content_type == "image/svg+xml" ||
  951. content_type == "application/javascript" ||
  952. content_type == "application/json" ||
  953. content_type == "application/xml" ||
  954. content_type == "application/xhtml+xml";
  955. }
  956. inline void compress(const Request& req, Response& res)
  957. {
  958. // TODO: Server version is HTTP/1.1 and 'Accpet-Encoding' has gzip, not gzip;q=0
  959. const auto& encodings = req.get_header_value("Accept-Encoding");
  960. if (encodings.find("gzip") == std::string::npos) {
  961. return;
  962. }
  963. if (!can_compress(res.get_header_value("Content-Type"))) {
  964. return;
  965. }
  966. z_stream strm;
  967. strm.zalloc = Z_NULL;
  968. strm.zfree = Z_NULL;
  969. strm.opaque = Z_NULL;
  970. auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY);
  971. if (ret != Z_OK) {
  972. return;
  973. }
  974. strm.avail_in = res.body.size();
  975. strm.next_in = (Bytef *)res.body.data();
  976. std::string compressed;
  977. const auto bufsiz = 16384;
  978. char buff[bufsiz];
  979. do {
  980. strm.avail_out = bufsiz;
  981. strm.next_out = (Bytef *)buff;
  982. deflate(&strm, Z_FINISH);
  983. compressed.append(buff, bufsiz - strm.avail_out);
  984. } while (strm.avail_out == 0);
  985. res.set_header("Content-Encoding", "gzip");
  986. res.body.swap(compressed);
  987. deflateEnd(&strm);
  988. }
  989. inline void decompress_request_body(Request& req)
  990. {
  991. if (req.get_header_value("Content-Encoding") != "gzip")
  992. return;
  993. z_stream strm;
  994. strm.zalloc = Z_NULL;
  995. strm.zfree = Z_NULL;
  996. strm.opaque = Z_NULL;
  997. // 15 is the value of wbits, which should be at the maximum possible value to ensure
  998. // that any gzip stream can be decoded. The offset of 16 specifies that the stream
  999. // to decompress will be formatted with a gzip wrapper.
  1000. auto ret = inflateInit2(&strm, 16 + 15);
  1001. if (ret != Z_OK) {
  1002. return;
  1003. }
  1004. strm.avail_in = req.body.size();
  1005. strm.next_in = (Bytef *)req.body.data();
  1006. std::string decompressed;
  1007. const auto bufsiz = 16384;
  1008. char buff[bufsiz];
  1009. do {
  1010. strm.avail_out = bufsiz;
  1011. strm.next_out = (Bytef *)buff;
  1012. inflate(&strm, Z_NO_FLUSH);
  1013. decompressed.append(buff, bufsiz - strm.avail_out);
  1014. } while (strm.avail_out == 0);
  1015. req.body.swap(decompressed);
  1016. inflateEnd(&strm);
  1017. }
  1018. #endif
  1019. #ifdef _WIN32
  1020. class WSInit {
  1021. public:
  1022. WSInit() {
  1023. WSADATA wsaData;
  1024. WSAStartup(0x0002, &wsaData);
  1025. }
  1026. ~WSInit() {
  1027. WSACleanup();
  1028. }
  1029. };
  1030. static WSInit wsinit_;
  1031. #endif
  1032. } // namespace detail
  1033. // Header utilities
  1034. template<typename uint64_t, typename... Args>
  1035. inline std::pair<std::string, std::string> make_range_header(uint64_t value, Args... args)
  1036. {
  1037. std::string field;
  1038. detail::make_range_header_core(field, value, args...);
  1039. field.insert(0, "bytes=");
  1040. return std::make_pair("Range", field);
  1041. }
  1042. // Request implementation
  1043. inline bool Request::has_header(const char* key) const
  1044. {
  1045. return headers.find(key) != headers.end();
  1046. }
  1047. inline std::string Request::get_header_value(const char* key) const
  1048. {
  1049. return detail::get_header_value(headers, key, "");
  1050. }
  1051. inline void Request::set_header(const char* key, const char* val)
  1052. {
  1053. headers.emplace(key, val);
  1054. }
  1055. inline bool Request::has_param(const char* key) const
  1056. {
  1057. return params.find(key) != params.end();
  1058. }
  1059. inline std::string Request::get_param_value(const char* key) const
  1060. {
  1061. auto it = params.find(key);
  1062. if (it != params.end()) {
  1063. return it->second;
  1064. }
  1065. return std::string();
  1066. }
  1067. inline bool Request::has_file(const char* key) const
  1068. {
  1069. return files.find(key) != files.end();
  1070. }
  1071. inline MultipartFile Request::get_file_value(const char* key) const
  1072. {
  1073. auto it = files.find(key);
  1074. if (it != files.end()) {
  1075. return it->second;
  1076. }
  1077. return MultipartFile();
  1078. }
  1079. // Response implementation
  1080. inline bool Response::has_header(const char* key) const
  1081. {
  1082. return headers.find(key) != headers.end();
  1083. }
  1084. inline std::string Response::get_header_value(const char* key) const
  1085. {
  1086. return detail::get_header_value(headers, key, "");
  1087. }
  1088. inline void Response::set_header(const char* key, const char* val)
  1089. {
  1090. headers.emplace(key, val);
  1091. }
  1092. inline void Response::set_redirect(const char* url)
  1093. {
  1094. set_header("Location", url);
  1095. status = 302;
  1096. }
  1097. inline void Response::set_content(const char* s, size_t n, const char* content_type)
  1098. {
  1099. body.assign(s, n);
  1100. set_header("Content-Type", content_type);
  1101. }
  1102. inline void Response::set_content(const std::string& s, const char* content_type)
  1103. {
  1104. body = s;
  1105. set_header("Content-Type", content_type);
  1106. }
  1107. // Rstream implementation
  1108. template <typename ...Args>
  1109. inline void Stream::write_format(const char* fmt, const Args& ...args)
  1110. {
  1111. const auto bufsiz = 2048;
  1112. char buf[bufsiz];
  1113. #if defined(_MSC_VER) && _MSC_VER < 1900
  1114. auto n = _snprintf_s(buf, bufsiz, bufsiz - 1, fmt, args...);
  1115. #else
  1116. auto n = snprintf(buf, bufsiz - 1, fmt, args...);
  1117. #endif
  1118. if (n > 0) {
  1119. if (n >= bufsiz - 1) {
  1120. std::vector<char> glowable_buf(bufsiz);
  1121. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  1122. glowable_buf.resize(glowable_buf.size() * 2);
  1123. #if defined(_MSC_VER) && _MSC_VER < 1900
  1124. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(), glowable_buf.size() - 1, fmt, args...);
  1125. #else
  1126. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  1127. #endif
  1128. }
  1129. write(&glowable_buf[0], n);
  1130. } else {
  1131. write(buf, n);
  1132. }
  1133. }
  1134. }
  1135. // Socket stream implementation
  1136. inline SocketStream::SocketStream(socket_t sock): sock_(sock)
  1137. {
  1138. }
  1139. inline SocketStream::~SocketStream()
  1140. {
  1141. }
  1142. inline int SocketStream::read(char* ptr, size_t size)
  1143. {
  1144. return recv(sock_, ptr, size, 0);
  1145. }
  1146. inline int SocketStream::write(const char* ptr, size_t size)
  1147. {
  1148. return send(sock_, ptr, size, 0);
  1149. }
  1150. inline int SocketStream::write(const char* ptr)
  1151. {
  1152. return write(ptr, strlen(ptr));
  1153. }
  1154. inline std::string SocketStream::get_remote_addr() {
  1155. return detail::get_remote_addr(sock_);
  1156. }
  1157. // HTTP server implementation
  1158. inline Server::Server(HttpVersion http_version)
  1159. : http_version_(http_version)
  1160. , is_running_(false)
  1161. , svr_sock_(-1)
  1162. , running_threads_(0)
  1163. {
  1164. #ifndef _WIN32
  1165. signal(SIGPIPE, SIG_IGN);
  1166. #endif
  1167. }
  1168. inline Server::~Server()
  1169. {
  1170. }
  1171. inline Server& Server::get(const char* pattern, Handler handler)
  1172. {
  1173. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1174. return *this;
  1175. }
  1176. inline Server& Server::post(const char* pattern, Handler handler)
  1177. {
  1178. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1179. return *this;
  1180. }
  1181. inline bool Server::set_base_dir(const char* path)
  1182. {
  1183. if (detail::is_dir(path)) {
  1184. base_dir_ = path;
  1185. return true;
  1186. }
  1187. return false;
  1188. }
  1189. inline void Server::set_error_handler(Handler handler)
  1190. {
  1191. error_handler_ = handler;
  1192. }
  1193. inline void Server::set_logger(Logger logger)
  1194. {
  1195. logger_ = logger;
  1196. }
  1197. inline int Server::bind_to_any_port(const char* host, int socket_flags)
  1198. {
  1199. return bind_internal(host, 0, socket_flags);
  1200. }
  1201. inline bool Server::listen_after_bind() {
  1202. return listen_internal();
  1203. }
  1204. inline bool Server::listen(const char* host, int port, int socket_flags)
  1205. {
  1206. if (bind_internal(host, port, socket_flags) < 0)
  1207. return false;
  1208. return listen_internal();
  1209. }
  1210. inline bool Server::is_running() const
  1211. {
  1212. return is_running_;
  1213. }
  1214. inline void Server::stop()
  1215. {
  1216. if (is_running_) {
  1217. assert(svr_sock_ != -1);
  1218. detail::shutdown_socket(svr_sock_);
  1219. detail::close_socket(svr_sock_);
  1220. svr_sock_ = -1;
  1221. }
  1222. }
  1223. inline bool Server::parse_request_line(const char* s, Request& req)
  1224. {
  1225. static std::regex re("(GET|HEAD|POST) ([^?]+)(?:\\?(.+?))? (HTTP/1\\.[01])\r\n");
  1226. std::cmatch m;
  1227. if (std::regex_match(s, m, re)) {
  1228. req.version = std::string(m[4]);
  1229. req.method = std::string(m[1]);
  1230. req.path = detail::decode_url(m[2]);
  1231. // Parse query text
  1232. auto len = std::distance(m[3].first, m[3].second);
  1233. if (len > 0) {
  1234. detail::parse_query_text(m[3], req.params);
  1235. }
  1236. return true;
  1237. }
  1238. return false;
  1239. }
  1240. inline void Server::write_response(Stream& strm, bool last_connection, const Request& req, Response& res)
  1241. {
  1242. assert(res.status != -1);
  1243. if (400 <= res.status && error_handler_) {
  1244. error_handler_(req, res);
  1245. }
  1246. // Response line
  1247. strm.write_format("%s %d %s\r\n",
  1248. detail::http_version_strings[static_cast<size_t>(http_version_)],
  1249. res.status,
  1250. detail::status_message(res.status));
  1251. // Headers
  1252. if (!res.has_header("Connection") && (last_connection || req.version == "HTTP/1.0")) {
  1253. res.set_header("Connection", "close");
  1254. }
  1255. if (!res.body.empty()) {
  1256. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1257. detail::compress(req, res);
  1258. #endif
  1259. if (!res.has_header("Content-Type")) {
  1260. res.set_header("Content-Type", "text/plain");
  1261. }
  1262. auto length = std::to_string(res.body.size());
  1263. res.set_header("Content-Length", length.c_str());
  1264. }
  1265. detail::write_headers(strm, res);
  1266. // Body
  1267. if (!res.body.empty() && req.method != "HEAD") {
  1268. strm.write(res.body.c_str(), res.body.size());
  1269. }
  1270. // Log
  1271. if (logger_) {
  1272. logger_(req, res);
  1273. }
  1274. }
  1275. inline bool Server::handle_file_request(Request& req, Response& res)
  1276. {
  1277. if (!base_dir_.empty() && detail::is_valid_path(req.path)) {
  1278. std::string path = base_dir_ + req.path;
  1279. if (!path.empty() && path.back() == '/') {
  1280. path += "index.html";
  1281. }
  1282. if (detail::is_file(path)) {
  1283. detail::read_file(path, res.body);
  1284. auto type = detail::find_content_type(path);
  1285. if (type) {
  1286. res.set_header("Content-Type", type);
  1287. }
  1288. res.status = 200;
  1289. return true;
  1290. }
  1291. }
  1292. return false;
  1293. }
  1294. inline socket_t Server::create_server_socket(const char* host, int port, int socket_flags) const
  1295. {
  1296. return detail::create_socket(host, port,
  1297. [](socket_t sock, struct addrinfo& ai) -> bool {
  1298. if (::bind(sock, ai.ai_addr, ai.ai_addrlen)) {
  1299. return false;
  1300. }
  1301. if (::listen(sock, 5)) { // Listen through 5 channels
  1302. return false;
  1303. }
  1304. return true;
  1305. }, socket_flags);
  1306. }
  1307. inline int Server::bind_internal(const char* host, int port, int socket_flags)
  1308. {
  1309. if (!is_valid()) {
  1310. return -1;
  1311. }
  1312. svr_sock_ = create_server_socket(host, port, socket_flags);
  1313. if (svr_sock_ == -1) {
  1314. return -1;
  1315. }
  1316. if (port == 0) {
  1317. struct sockaddr_in sin;
  1318. socklen_t len = sizeof(sin);
  1319. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&sin), &len) == -1) {
  1320. return -1;
  1321. }
  1322. return ntohs(sin.sin_port);
  1323. } else {
  1324. return port;
  1325. }
  1326. }
  1327. inline bool Server::listen_internal()
  1328. {
  1329. auto ret = true;
  1330. is_running_ = true;
  1331. for (;;) {
  1332. auto val = detail::select_read(svr_sock_, 0, 100000);
  1333. if (val == 0) { // Timeout
  1334. if (svr_sock_ == -1) {
  1335. // The server socket was closed by 'stop' method.
  1336. break;
  1337. }
  1338. continue;
  1339. }
  1340. socket_t sock = accept(svr_sock_, NULL, NULL);
  1341. if (sock == -1) {
  1342. if (svr_sock_ != -1) {
  1343. detail::close_socket(svr_sock_);
  1344. ret = false;
  1345. } else {
  1346. ; // The server socket was closed by user.
  1347. }
  1348. break;
  1349. }
  1350. // TODO: Use thread pool...
  1351. std::thread([=]() {
  1352. {
  1353. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1354. running_threads_++;
  1355. }
  1356. read_and_close_socket(sock);
  1357. {
  1358. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1359. running_threads_--;
  1360. }
  1361. }).detach();
  1362. }
  1363. // TODO: Use thread pool...
  1364. for (;;) {
  1365. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1366. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  1367. if (!running_threads_) {
  1368. break;
  1369. }
  1370. }
  1371. is_running_ = false;
  1372. return ret;
  1373. }
  1374. inline bool Server::routing(Request& req, Response& res)
  1375. {
  1376. if (req.method == "GET" && handle_file_request(req, res)) {
  1377. return true;
  1378. }
  1379. if (req.method == "GET" || req.method == "HEAD") {
  1380. return dispatch_request(req, res, get_handlers_);
  1381. } else if (req.method == "POST") {
  1382. return dispatch_request(req, res, post_handlers_);
  1383. }
  1384. return false;
  1385. }
  1386. inline bool Server::dispatch_request(Request& req, Response& res, Handlers& handlers)
  1387. {
  1388. for (const auto& x: handlers) {
  1389. const auto& pattern = x.first;
  1390. const auto& handler = x.second;
  1391. if (std::regex_match(req.path, req.matches, pattern)) {
  1392. handler(req, res);
  1393. return true;
  1394. }
  1395. }
  1396. return false;
  1397. }
  1398. inline bool Server::process_request(Stream& strm, bool last_connection)
  1399. {
  1400. const auto bufsiz = 2048;
  1401. char buf[bufsiz];
  1402. detail::stream_line_reader reader(strm, buf, bufsiz);
  1403. // Connection has been closed on client
  1404. if (!reader.getline()) {
  1405. return false;
  1406. }
  1407. Request req;
  1408. Response res;
  1409. res.version = detail::http_version_strings[static_cast<size_t>(http_version_)];
  1410. // Request line and headers
  1411. if (!parse_request_line(reader.ptr(), req) || !detail::read_headers(strm, req.headers)) {
  1412. res.status = 400;
  1413. write_response(strm, last_connection, req, res);
  1414. return true;
  1415. }
  1416. auto ret = true;
  1417. if (req.get_header_value("Connection") == "close") {
  1418. ret = false;
  1419. }
  1420. req.set_header("REMOTE_ADDR", strm.get_remote_addr().c_str());
  1421. // Body
  1422. if (req.method == "POST") {
  1423. if (!detail::read_content(strm, req)) {
  1424. res.status = 400;
  1425. write_response(strm, last_connection, req, res);
  1426. return ret;
  1427. }
  1428. const auto& content_type = req.get_header_value("Content-Type");
  1429. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1430. detail::decompress_request_body(req);
  1431. #else
  1432. if (req.get_header_value("Content-Encoding") == "gzip") {
  1433. res.status = 415;
  1434. write_response(strm, last_connection, req, res);
  1435. return ret;
  1436. }
  1437. #endif
  1438. if (!content_type.find("application/x-www-form-urlencoded")) {
  1439. detail::parse_query_text(req.body, req.params);
  1440. } else if(!content_type.find("multipart/form-data")) {
  1441. std::string boundary;
  1442. if (!detail::parse_multipart_boundary(content_type, boundary) ||
  1443. !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
  1444. res.status = 400;
  1445. write_response(strm, last_connection, req, res);
  1446. return ret;
  1447. }
  1448. }
  1449. }
  1450. if (routing(req, res)) {
  1451. if (res.status == -1) {
  1452. res.status = 200;
  1453. }
  1454. } else {
  1455. res.status = 404;
  1456. }
  1457. write_response(strm, last_connection, req, res);
  1458. return ret;
  1459. }
  1460. inline bool Server::is_valid() const
  1461. {
  1462. return true;
  1463. }
  1464. inline bool Server::read_and_close_socket(socket_t sock)
  1465. {
  1466. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1467. return detail::read_and_close_socket(
  1468. sock,
  1469. keep_alive,
  1470. [this](Stream& strm, bool last_connection) {
  1471. return process_request(strm, last_connection);
  1472. });
  1473. }
  1474. // HTTP client implementation
  1475. inline Client::Client(
  1476. const char* host, int port, size_t timeout_sec, HttpVersion http_version)
  1477. : host_(host)
  1478. , port_(port)
  1479. , timeout_sec_(timeout_sec)
  1480. , http_version_(http_version)
  1481. , host_and_port_(host_ + ":" + std::to_string(port_))
  1482. {
  1483. }
  1484. inline Client::~Client()
  1485. {
  1486. }
  1487. inline bool Client::is_valid() const
  1488. {
  1489. return true;
  1490. }
  1491. inline socket_t Client::create_client_socket() const
  1492. {
  1493. return detail::create_socket(host_.c_str(), port_,
  1494. [=](socket_t sock, struct addrinfo& ai) -> bool {
  1495. detail::set_nonblocking(sock, true);
  1496. auto ret = connect(sock, ai.ai_addr, ai.ai_addrlen);
  1497. if (ret < 0) {
  1498. if (detail::is_connection_error() ||
  1499. !detail::wait_until_socket_is_ready(sock, timeout_sec_, 0)) {
  1500. detail::close_socket(sock);
  1501. return false;
  1502. }
  1503. }
  1504. detail::set_nonblocking(sock, false);
  1505. return true;
  1506. });
  1507. }
  1508. inline bool Client::read_response_line(Stream& strm, Response& res)
  1509. {
  1510. const auto bufsiz = 2048;
  1511. char buf[bufsiz];
  1512. detail::stream_line_reader reader(strm, buf, bufsiz);
  1513. if (!reader.getline()) {
  1514. return false;
  1515. }
  1516. const static std::regex re("HTTP/1\\.[01] (\\d+?) .+\r\n");
  1517. std::cmatch m;
  1518. if (std::regex_match(reader.ptr(), m, re)) {
  1519. res.status = std::stoi(std::string(m[1]));
  1520. }
  1521. return true;
  1522. }
  1523. inline bool Client::send(Request& req, Response& res)
  1524. {
  1525. if (req.path.empty()) {
  1526. return false;
  1527. }
  1528. auto sock = create_client_socket();
  1529. if (sock == -1) {
  1530. return false;
  1531. }
  1532. return read_and_close_socket(sock, req, res);
  1533. }
  1534. inline void Client::write_request(Stream& strm, Request& req)
  1535. {
  1536. auto path = detail::encode_url(req.path);
  1537. // Request line
  1538. strm.write_format("%s %s %s\r\n",
  1539. req.method.c_str(),
  1540. path.c_str(),
  1541. detail::http_version_strings[static_cast<size_t>(http_version_)]);
  1542. // Headers
  1543. req.set_header("Host", host_and_port_.c_str());
  1544. if (!req.has_header("Accept")) {
  1545. req.set_header("Accept", "*/*");
  1546. }
  1547. if (!req.has_header("User-Agent")) {
  1548. req.set_header("User-Agent", "cpp-httplib/0.2");
  1549. }
  1550. // TODO: if (!req.has_header("Connection") &&
  1551. // (last_connection || http_version_ == detail::HttpVersion::v1_0)) {
  1552. if (!req.has_header("Connection")) {
  1553. req.set_header("Connection", "close");
  1554. }
  1555. if (!req.body.empty()) {
  1556. if (!req.has_header("Content-Type")) {
  1557. req.set_header("Content-Type", "text/plain");
  1558. }
  1559. auto length = std::to_string(req.body.size());
  1560. req.set_header("Content-Length", length.c_str());
  1561. }
  1562. detail::write_headers(strm, req);
  1563. // Body
  1564. if (!req.body.empty()) {
  1565. if (req.get_header_value("Content-Type") == "application/x-www-form-urlencoded") {
  1566. auto str = detail::encode_url(req.body);
  1567. strm.write(str.c_str(), str.size());
  1568. } else {
  1569. strm.write(req.body.c_str(), req.body.size());
  1570. }
  1571. }
  1572. }
  1573. inline bool Client::process_request(Stream& strm, Request& req, Response& res)
  1574. {
  1575. // Send request
  1576. write_request(strm, req);
  1577. // Receive response and headers
  1578. if (!read_response_line(strm, res) || !detail::read_headers(strm, res.headers)) {
  1579. return false;
  1580. }
  1581. // TODO: Check if 'Connection' header is 'close' or HTTP version is 1.0, then close socket...
  1582. // Body
  1583. if (req.method != "HEAD") {
  1584. if (!detail::read_content(strm, res, req.progress)) {
  1585. return false;
  1586. }
  1587. }
  1588. return true;
  1589. }
  1590. inline bool Client::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1591. {
  1592. return detail::read_and_close_socket(sock, false, [&](Stream& strm, bool /*last_connection*/) {
  1593. return process_request(strm, req, res);
  1594. });
  1595. }
  1596. inline std::shared_ptr<Response> Client::get(const char* path, Progress progress)
  1597. {
  1598. return get(path, Headers(), progress);
  1599. }
  1600. inline std::shared_ptr<Response> Client::get(const char* path, const Headers& headers, Progress progress)
  1601. {
  1602. Request req;
  1603. req.method = "GET";
  1604. req.path = path;
  1605. req.headers = headers;
  1606. req.progress = progress;
  1607. auto res = std::make_shared<Response>();
  1608. return send(req, *res) ? res : nullptr;
  1609. }
  1610. inline std::shared_ptr<Response> Client::head(const char* path)
  1611. {
  1612. return head(path, Headers());
  1613. }
  1614. inline std::shared_ptr<Response> Client::head(const char* path, const Headers& headers)
  1615. {
  1616. Request req;
  1617. req.method = "HEAD";
  1618. req.headers = headers;
  1619. req.path = path;
  1620. auto res = std::make_shared<Response>();
  1621. return send(req, *res) ? res : nullptr;
  1622. }
  1623. inline std::shared_ptr<Response> Client::post(
  1624. const char* path, const std::string& body, const char* content_type)
  1625. {
  1626. return post(path, Headers(), body, content_type);
  1627. }
  1628. inline std::shared_ptr<Response> Client::post(
  1629. const char* path, const Headers& headers, const std::string& body, const char* content_type)
  1630. {
  1631. Request req;
  1632. req.method = "POST";
  1633. req.headers = headers;
  1634. req.path = path;
  1635. req.headers.emplace("Content-Type", content_type);
  1636. req.body = body;
  1637. auto res = std::make_shared<Response>();
  1638. return send(req, *res) ? res : nullptr;
  1639. }
  1640. inline std::shared_ptr<Response> Client::post(const char* path, const Params& params)
  1641. {
  1642. return post(path, Headers(), params);
  1643. }
  1644. inline std::shared_ptr<Response> Client::post(const char* path, const Headers& headers, const Params& params)
  1645. {
  1646. std::string query;
  1647. for (auto it = params.begin(); it != params.end(); ++it) {
  1648. if (it != params.begin()) {
  1649. query += "&";
  1650. }
  1651. query += it->first;
  1652. query += "=";
  1653. query += it->second;
  1654. }
  1655. return post(path, headers, query, "application/x-www-form-urlencoded");
  1656. }
  1657. /*
  1658. * SSL Implementation
  1659. */
  1660. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1661. namespace detail {
  1662. // TODO: OpenSSL 1.0.2 occasionally crashes... The upcoming 1.1.0 is going to be thread safe.
  1663. static std::mutex ssl_ctx_mutex_;
  1664. template <typename U, typename V, typename T>
  1665. inline bool read_and_close_socket_ssl(
  1666. socket_t sock, bool keep_alive,
  1667. SSL_CTX* ctx, U SSL_connect_or_accept, V setup,
  1668. T callback)
  1669. {
  1670. SSL* ssl = nullptr;
  1671. {
  1672. std::lock_guard<std::mutex> guard(ssl_ctx_mutex_);
  1673. ssl = SSL_new(ctx);
  1674. if (!ssl) {
  1675. return false;
  1676. }
  1677. }
  1678. auto bio = BIO_new_socket(sock, BIO_NOCLOSE);
  1679. SSL_set_bio(ssl, bio, bio);
  1680. setup(ssl);
  1681. SSL_connect_or_accept(ssl);
  1682. bool ret = false;
  1683. if (keep_alive) {
  1684. auto count = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1685. while (count > 0 &&
  1686. detail::select_read(sock,
  1687. CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1688. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0) {
  1689. auto last_connection = count == 1;
  1690. SSLSocketStream strm(sock, ssl);
  1691. ret = callback(strm, last_connection);
  1692. if (!ret) {
  1693. break;
  1694. }
  1695. count--;
  1696. }
  1697. } else {
  1698. SSLSocketStream strm(sock, ssl);
  1699. ret = callback(strm, true);
  1700. }
  1701. SSL_shutdown(ssl);
  1702. {
  1703. std::lock_guard<std::mutex> guard(ssl_ctx_mutex_);
  1704. SSL_free(ssl);
  1705. }
  1706. close_socket(sock);
  1707. return ret;
  1708. }
  1709. class SSLInit {
  1710. public:
  1711. SSLInit() {
  1712. SSL_load_error_strings();
  1713. SSL_library_init();
  1714. }
  1715. };
  1716. static SSLInit sslinit_;
  1717. } // namespace detail
  1718. // SSL socket stream implementation
  1719. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL* ssl)
  1720. : sock_(sock), ssl_(ssl)
  1721. {
  1722. }
  1723. inline SSLSocketStream::~SSLSocketStream()
  1724. {
  1725. }
  1726. inline int SSLSocketStream::read(char* ptr, size_t size)
  1727. {
  1728. return SSL_read(ssl_, ptr, size);
  1729. }
  1730. inline int SSLSocketStream::write(const char* ptr, size_t size)
  1731. {
  1732. return SSL_write(ssl_, ptr, size);
  1733. }
  1734. inline int SSLSocketStream::write(const char* ptr)
  1735. {
  1736. return write(ptr, strlen(ptr));
  1737. }
  1738. inline std::string SSLSocketStream::get_remote_addr() {
  1739. return detail::get_remote_addr(sock_);
  1740. }
  1741. // SSL HTTP server implementation
  1742. inline SSLServer::SSLServer(const char* cert_path, const char* private_key_path, HttpVersion http_version)
  1743. : Server(http_version)
  1744. {
  1745. ctx_ = SSL_CTX_new(SSLv23_server_method());
  1746. if (ctx_) {
  1747. SSL_CTX_set_options(ctx_,
  1748. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  1749. SSL_OP_NO_COMPRESSION |
  1750. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  1751. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  1752. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  1753. // EC_KEY_free(ecdh);
  1754. if (SSL_CTX_use_certificate_file(ctx_, cert_path, SSL_FILETYPE_PEM) != 1 ||
  1755. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != 1) {
  1756. SSL_CTX_free(ctx_);
  1757. ctx_ = nullptr;
  1758. }
  1759. }
  1760. }
  1761. inline SSLServer::~SSLServer()
  1762. {
  1763. if (ctx_) {
  1764. SSL_CTX_free(ctx_);
  1765. }
  1766. }
  1767. inline bool SSLServer::is_valid() const
  1768. {
  1769. return ctx_;
  1770. }
  1771. inline bool SSLServer::read_and_close_socket(socket_t sock)
  1772. {
  1773. auto keep_alive = http_version_ == HttpVersion::v1_1;
  1774. return detail::read_and_close_socket_ssl(
  1775. sock,
  1776. keep_alive,
  1777. ctx_,
  1778. SSL_accept,
  1779. [](SSL* /*ssl*/) {},
  1780. [this](Stream& strm, bool last_connection) {
  1781. return process_request(strm, last_connection);
  1782. });
  1783. }
  1784. // SSL HTTP client implementation
  1785. inline SSLClient::SSLClient(
  1786. const char* host, int port, size_t timeout_sec, HttpVersion http_version)
  1787. : Client(host, port, timeout_sec, http_version)
  1788. {
  1789. ctx_ = SSL_CTX_new(SSLv23_client_method());
  1790. }
  1791. inline SSLClient::~SSLClient()
  1792. {
  1793. if (ctx_) {
  1794. SSL_CTX_free(ctx_);
  1795. }
  1796. }
  1797. inline bool SSLClient::is_valid() const
  1798. {
  1799. return ctx_;
  1800. }
  1801. inline bool SSLClient::read_and_close_socket(socket_t sock, Request& req, Response& res)
  1802. {
  1803. return is_valid() && detail::read_and_close_socket_ssl(
  1804. sock, false,
  1805. ctx_, SSL_connect,
  1806. [&](SSL* ssl) {
  1807. SSL_set_tlsext_host_name(ssl, host_.c_str());
  1808. },
  1809. [&](Stream& strm, bool /*last_connection*/) {
  1810. return process_request(strm, req, res);
  1811. });
  1812. }
  1813. #endif
  1814. } // namespace httplib
  1815. #endif
  1816. // vim: et ts=4 sw=4 cin cino={1s ff=unix