httplib.h 51 KB

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