httplib.h 51 KB

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