httplib.h 57 KB

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