httplib.h 50 KB

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