httplib.h 52 KB

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