httplib.h 56 KB

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