httplib.h 60 KB

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