httplib.h 57 KB

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