httplib.h 53 KB

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