httplib.h 62 KB

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