httplib.h 63 KB

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