httplib.h 69 KB

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