httplib.h 54 KB

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