httplib.h 103 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674
  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. /*
  10. * Configuration
  11. */
  12. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  13. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  14. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  15. #define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
  16. #define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
  17. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  18. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  19. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (std::numeric_limits<size_t>::max)()
  20. #define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
  21. #define CPPHTTPLIB_THREAD_POOL_COUNT 8
  22. #define CPPHTTPLIB_USE_POLL
  23. #ifdef _WIN32
  24. #ifndef _CRT_SECURE_NO_WARNINGS
  25. #define _CRT_SECURE_NO_WARNINGS
  26. #endif //_CRT_SECURE_NO_WARNINGS
  27. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  28. #define _CRT_NONSTDC_NO_DEPRECATE
  29. #endif //_CRT_NONSTDC_NO_DEPRECATE
  30. #if defined(_MSC_VER)
  31. #ifdef _WIN64
  32. typedef __int64 ssize_t;
  33. #else
  34. typedef int ssize_t;
  35. #endif
  36. #if _MSC_VER < 1900
  37. #define snprintf _snprintf_s
  38. #endif
  39. #endif // _MSC_VER
  40. #ifndef S_ISREG
  41. #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
  42. #endif // S_ISREG
  43. #ifndef S_ISDIR
  44. #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
  45. #endif // S_ISDIR
  46. #ifndef NOMINMAX
  47. #define NOMINMAX
  48. #endif // NOMINMAX
  49. #include <io.h>
  50. #include <winsock2.h>
  51. #include <ws2tcpip.h>
  52. #pragma comment(lib, "ws2_32.lib")
  53. #ifndef strcasecmp
  54. #define strcasecmp _stricmp
  55. #endif // strcasecmp
  56. typedef SOCKET socket_t;
  57. #ifdef CPPHTTPLIB_USE_POLL
  58. #define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
  59. #endif
  60. #else // not _WIN32
  61. #include <arpa/inet.h>
  62. #include <cstring>
  63. #include <netdb.h>
  64. #include <netinet/in.h>
  65. #ifdef CPPHTTPLIB_USE_POLL
  66. #include <poll.h>
  67. #endif
  68. #include <pthread.h>
  69. #include <signal.h>
  70. #include <sys/select.h>
  71. #include <sys/socket.h>
  72. #include <unistd.h>
  73. typedef int socket_t;
  74. #define INVALID_SOCKET (-1)
  75. #endif //_WIN32
  76. #include <assert.h>
  77. #include <atomic>
  78. #include <condition_variable>
  79. #include <fcntl.h>
  80. #include <fstream>
  81. #include <functional>
  82. #include <list>
  83. #include <map>
  84. #include <memory>
  85. #include <mutex>
  86. #include <random>
  87. #include <regex>
  88. #include <string>
  89. #include <sys/stat.h>
  90. #include <thread>
  91. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  92. #include <openssl/err.h>
  93. #include <openssl/ssl.h>
  94. #include <openssl/x509v3.h>
  95. // #if OPENSSL_VERSION_NUMBER < 0x1010100fL
  96. // #error Sorry, OpenSSL versions prior to 1.1.1 are not supported
  97. // #endif
  98. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  99. #include <openssl/crypto.h>
  100. inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
  101. return M_ASN1_STRING_data(asn1);
  102. }
  103. #endif
  104. #endif
  105. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  106. #include <zlib.h>
  107. #endif
  108. namespace httplib {
  109. namespace detail {
  110. struct ci {
  111. bool operator()(const std::string &s1, const std::string &s2) const {
  112. return std::lexicographical_compare(
  113. s1.begin(), s1.end(), s2.begin(), s2.end(),
  114. [](char c1, char c2) { return ::tolower(c1) < ::tolower(c2); });
  115. }
  116. };
  117. } // namespace detail
  118. enum class HttpVersion { v1_0 = 0, v1_1 };
  119. typedef std::multimap<std::string, std::string, detail::ci> Headers;
  120. typedef std::multimap<std::string, std::string> Params;
  121. typedef std::smatch Match;
  122. typedef std::function<void(const char *data, size_t data_len)> DataSink;
  123. typedef std::function<void()> Done;
  124. typedef std::function<void(size_t offset, size_t length, DataSink sink,
  125. Done done)>
  126. ContentProvider;
  127. typedef std::function<bool(const char *data, size_t data_length, size_t offset,
  128. uint64_t content_length)>
  129. ContentReceiver;
  130. typedef std::function<bool(uint64_t current, uint64_t total)> Progress;
  131. struct Response;
  132. typedef std::function<bool(const Response &response)> ResponseHandler;
  133. struct MultipartFile {
  134. std::string filename;
  135. std::string content_type;
  136. size_t offset = 0;
  137. size_t length = 0;
  138. };
  139. typedef std::multimap<std::string, MultipartFile> MultipartFiles;
  140. struct MultipartFormData {
  141. std::string name;
  142. std::string content;
  143. std::string filename;
  144. std::string content_type;
  145. };
  146. typedef std::vector<MultipartFormData> MultipartFormDataItems;
  147. typedef std::pair<ssize_t, ssize_t> Range;
  148. typedef std::vector<Range> Ranges;
  149. struct Request {
  150. std::string method;
  151. std::string path;
  152. Headers headers;
  153. std::string body;
  154. // for server
  155. std::string version;
  156. std::string target;
  157. Params params;
  158. MultipartFiles files;
  159. Ranges ranges;
  160. Match matches;
  161. // for client
  162. size_t redirect_count = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  163. ResponseHandler response_handler;
  164. ContentReceiver content_receiver;
  165. Progress progress;
  166. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  167. const SSL *ssl;
  168. #endif
  169. bool has_header(const char *key) const;
  170. std::string get_header_value(const char *key, size_t id = 0) const;
  171. size_t get_header_value_count(const char *key) const;
  172. void set_header(const char *key, const char *val);
  173. void set_header(const char *key, const std::string &val);
  174. bool has_param(const char *key) const;
  175. std::string get_param_value(const char *key, size_t id = 0) const;
  176. size_t get_param_value_count(const char *key) const;
  177. bool has_file(const char *key) const;
  178. MultipartFile get_file_value(const char *key) const;
  179. };
  180. struct Response {
  181. std::string version;
  182. int status;
  183. Headers headers;
  184. std::string body;
  185. bool has_header(const char *key) const;
  186. std::string get_header_value(const char *key, size_t id = 0) const;
  187. size_t get_header_value_count(const char *key) const;
  188. void set_header(const char *key, const char *val);
  189. void set_header(const char *key, const std::string &val);
  190. void set_redirect(const char *uri);
  191. void set_content(const char *s, size_t n, const char *content_type);
  192. void set_content(const std::string &s, const char *content_type);
  193. void set_content_provider(
  194. size_t length,
  195. std::function<void(size_t offset, size_t length, DataSink sink)> provider,
  196. std::function<void()> resource_releaser = [] {});
  197. void set_chunked_content_provider(
  198. std::function<void(size_t offset, DataSink sink, Done done)> provider,
  199. std::function<void()> resource_releaser = [] {});
  200. Response() : status(-1), content_provider_resource_length(0) {}
  201. ~Response() {
  202. if (content_provider_resource_releaser) {
  203. content_provider_resource_releaser();
  204. }
  205. }
  206. size_t content_provider_resource_length;
  207. ContentProvider content_provider;
  208. std::function<void()> content_provider_resource_releaser;
  209. };
  210. class Stream {
  211. public:
  212. virtual ~Stream() {}
  213. virtual int read(char *ptr, size_t size) = 0;
  214. virtual int write(const char *ptr, size_t size1) = 0;
  215. virtual int write(const char *ptr) = 0;
  216. virtual int write(const std::string &s) = 0;
  217. virtual std::string get_remote_addr() const = 0;
  218. template <typename... Args>
  219. int write_format(const char *fmt, const Args &... args);
  220. };
  221. class SocketStream : public Stream {
  222. public:
  223. SocketStream(socket_t sock);
  224. virtual ~SocketStream();
  225. virtual int read(char *ptr, size_t size);
  226. virtual int write(const char *ptr, size_t size);
  227. virtual int write(const char *ptr);
  228. virtual int write(const std::string &s);
  229. virtual std::string get_remote_addr() const;
  230. private:
  231. socket_t sock_;
  232. };
  233. class BufferStream : public Stream {
  234. public:
  235. BufferStream() {}
  236. virtual ~BufferStream() {}
  237. virtual int read(char *ptr, size_t size);
  238. virtual int write(const char *ptr, size_t size);
  239. virtual int write(const char *ptr);
  240. virtual int write(const std::string &s);
  241. virtual std::string get_remote_addr() const;
  242. const std::string &get_buffer() const;
  243. private:
  244. std::string buffer;
  245. };
  246. class TaskQueue {
  247. public:
  248. TaskQueue() {}
  249. virtual ~TaskQueue() {}
  250. virtual void enqueue(std::function<void()> fn) = 0;
  251. virtual void shutdown() = 0;
  252. };
  253. #if CPPHTTPLIB_THREAD_POOL_COUNT > 0
  254. class ThreadPool : public TaskQueue {
  255. public:
  256. ThreadPool(size_t n) : shutdown_(false) {
  257. while (n) {
  258. auto t = std::make_shared<std::thread>(worker(*this));
  259. threads_.push_back(t);
  260. n--;
  261. }
  262. }
  263. ThreadPool(const ThreadPool &) = delete;
  264. virtual ~ThreadPool() {}
  265. virtual void enqueue(std::function<void()> fn) override {
  266. std::unique_lock<std::mutex> lock(mutex_);
  267. jobs_.push_back(fn);
  268. cond_.notify_one();
  269. }
  270. virtual void shutdown() override {
  271. // Stop all worker threads...
  272. {
  273. std::unique_lock<std::mutex> lock(mutex_);
  274. shutdown_ = true;
  275. }
  276. cond_.notify_all();
  277. // Join...
  278. for (auto t : threads_) {
  279. t->join();
  280. }
  281. }
  282. private:
  283. struct worker {
  284. worker(ThreadPool &pool) : pool_(pool) {}
  285. void operator()() {
  286. for (;;) {
  287. std::function<void()> fn;
  288. {
  289. std::unique_lock<std::mutex> lock(pool_.mutex_);
  290. pool_.cond_.wait(
  291. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  292. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  293. fn = pool_.jobs_.front();
  294. pool_.jobs_.pop_front();
  295. }
  296. assert(true == static_cast<bool>(fn));
  297. fn();
  298. }
  299. }
  300. ThreadPool &pool_;
  301. };
  302. friend struct worker;
  303. std::vector<std::shared_ptr<std::thread>> threads_;
  304. std::list<std::function<void()>> jobs_;
  305. bool shutdown_;
  306. std::condition_variable cond_;
  307. std::mutex mutex_;
  308. };
  309. #else
  310. class Threads : public TaskQueue {
  311. public:
  312. Threads() : running_threads_(0) {}
  313. virtual ~Threads() {}
  314. virtual void enqueue(std::function<void()> fn) override {
  315. std::thread([=]() {
  316. {
  317. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  318. running_threads_++;
  319. }
  320. fn();
  321. {
  322. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  323. running_threads_--;
  324. }
  325. }).detach();
  326. }
  327. virtual void shutdown() override {
  328. for (;;) {
  329. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  330. std::lock_guard<std::mutex> guard(running_threads_mutex_);
  331. if (!running_threads_) { break; }
  332. }
  333. }
  334. private:
  335. std::mutex running_threads_mutex_;
  336. int running_threads_;
  337. };
  338. #endif
  339. class Server {
  340. public:
  341. typedef std::function<void(const Request &, Response &)> Handler;
  342. typedef std::function<void(const Request &, const Response &)> Logger;
  343. Server();
  344. virtual ~Server();
  345. virtual bool is_valid() const;
  346. Server &Get(const char *pattern, Handler handler);
  347. Server &Post(const char *pattern, Handler handler);
  348. Server &Put(const char *pattern, Handler handler);
  349. Server &Patch(const char *pattern, Handler handler);
  350. Server &Delete(const char *pattern, Handler handler);
  351. Server &Options(const char *pattern, Handler handler);
  352. bool set_base_dir(const char *path);
  353. void set_file_request_handler(Handler handler);
  354. void set_error_handler(Handler handler);
  355. void set_logger(Logger logger);
  356. void set_keep_alive_max_count(size_t count);
  357. void set_payload_max_length(size_t length);
  358. int bind_to_any_port(const char *host, int socket_flags = 0);
  359. bool listen_after_bind();
  360. bool listen(const char *host, int port, int socket_flags = 0);
  361. bool is_running() const;
  362. void stop();
  363. std::function<TaskQueue *(void)> new_task_queue;
  364. protected:
  365. bool process_request(Stream &strm, bool last_connection,
  366. bool &connection_close,
  367. std::function<void(Request &)> setup_request);
  368. size_t keep_alive_max_count_;
  369. size_t payload_max_length_;
  370. private:
  371. typedef std::vector<std::pair<std::regex, Handler>> Handlers;
  372. socket_t create_server_socket(const char *host, int port,
  373. int socket_flags) const;
  374. int bind_internal(const char *host, int port, int socket_flags);
  375. bool listen_internal();
  376. bool routing(Request &req, Response &res);
  377. bool handle_file_request(Request &req, Response &res);
  378. bool dispatch_request(Request &req, Response &res, Handlers &handlers);
  379. bool parse_request_line(const char *s, Request &req);
  380. bool write_response(Stream &strm, bool last_connection, const Request &req,
  381. Response &res);
  382. bool write_content_with_provider(Stream &strm, const Request &req,
  383. Response &res, const std::string &boundary,
  384. const std::string &content_type);
  385. virtual bool process_and_close_socket(socket_t sock);
  386. std::atomic<bool> is_running_;
  387. std::atomic<socket_t> svr_sock_;
  388. std::string base_dir_;
  389. Handler file_request_handler_;
  390. Handlers get_handlers_;
  391. Handlers post_handlers_;
  392. Handlers put_handlers_;
  393. Handlers patch_handlers_;
  394. Handlers delete_handlers_;
  395. Handlers options_handlers_;
  396. Handler error_handler_;
  397. Logger logger_;
  398. };
  399. class Client {
  400. public:
  401. Client(const char *host, int port = 80, time_t timeout_sec = 300);
  402. virtual ~Client();
  403. virtual bool is_valid() const;
  404. std::shared_ptr<Response> Get(const char *path);
  405. std::shared_ptr<Response> Get(const char *path, const Headers &headers);
  406. std::shared_ptr<Response> Get(const char *path, Progress progress);
  407. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  408. Progress progress);
  409. std::shared_ptr<Response> Get(const char *path,
  410. ContentReceiver content_receiver);
  411. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  412. ContentReceiver content_receiver);
  413. std::shared_ptr<Response>
  414. Get(const char *path, ContentReceiver content_receiver, Progress progress);
  415. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  416. ContentReceiver content_receiver,
  417. Progress progress);
  418. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  419. ResponseHandler response_handler,
  420. ContentReceiver content_receiver);
  421. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  422. ResponseHandler response_handler,
  423. ContentReceiver content_receiver,
  424. Progress progress);
  425. std::shared_ptr<Response> Head(const char *path);
  426. std::shared_ptr<Response> Head(const char *path, const Headers &headers);
  427. std::shared_ptr<Response> Post(const char *path, const std::string &body,
  428. const char *content_type);
  429. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  430. const std::string &body,
  431. const char *content_type);
  432. std::shared_ptr<Response> Post(const char *path, const Params &params);
  433. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  434. const Params &params);
  435. std::shared_ptr<Response> Post(const char *path,
  436. const MultipartFormDataItems &items);
  437. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  438. const MultipartFormDataItems &items);
  439. std::shared_ptr<Response> Put(const char *path, const std::string &body,
  440. const char *content_type);
  441. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  442. const std::string &body,
  443. const char *content_type);
  444. std::shared_ptr<Response> Patch(const char *path, const std::string &body,
  445. const char *content_type);
  446. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  447. const std::string &body,
  448. const char *content_type);
  449. std::shared_ptr<Response> Delete(const char *path);
  450. std::shared_ptr<Response> Delete(const char *path, const std::string &body,
  451. const char *content_type);
  452. std::shared_ptr<Response> Delete(const char *path, const Headers &headers);
  453. std::shared_ptr<Response> Delete(const char *path, const Headers &headers,
  454. const std::string &body,
  455. const char *content_type);
  456. std::shared_ptr<Response> Options(const char *path);
  457. std::shared_ptr<Response> Options(const char *path, const Headers &headers);
  458. bool send(const Request &req, Response &res);
  459. bool send(const std::vector<Request> &requests,
  460. std::vector<Response> &responses);
  461. void set_keep_alive_max_count(size_t count);
  462. void follow_location(bool on);
  463. protected:
  464. bool process_request(Stream &strm, const Request &req, Response &res,
  465. bool last_connection, bool &connection_close);
  466. const std::string host_;
  467. const int port_;
  468. time_t timeout_sec_;
  469. const std::string host_and_port_;
  470. size_t keep_alive_max_count_;
  471. size_t follow_location_;
  472. private:
  473. socket_t create_client_socket() const;
  474. bool read_response_line(Stream &strm, Response &res);
  475. void write_request(Stream &strm, const Request &req, bool last_connection);
  476. bool redirect(const Request &req, Response &res);
  477. virtual bool process_and_close_socket(
  478. socket_t sock, size_t request_count,
  479. std::function<bool(Stream &strm, bool last_connection,
  480. bool &connection_close)>
  481. callback);
  482. virtual bool is_ssl() const;
  483. };
  484. inline void Get(std::vector<Request> &requests, const char *path,
  485. const Headers &headers) {
  486. Request req;
  487. req.method = "GET";
  488. req.path = path;
  489. req.headers = headers;
  490. requests.emplace_back(std::move(req));
  491. }
  492. inline void Get(std::vector<Request> &requests, const char *path) {
  493. Get(requests, path, Headers());
  494. }
  495. inline void Post(std::vector<Request> &requests, const char *path,
  496. const Headers &headers, const std::string &body,
  497. const char *content_type) {
  498. Request req;
  499. req.method = "POST";
  500. req.path = path;
  501. req.headers = headers;
  502. req.headers.emplace("Content-Type", content_type);
  503. req.body = body;
  504. requests.emplace_back(std::move(req));
  505. }
  506. inline void Post(std::vector<Request> &requests, const char *path,
  507. const std::string &body, const char *content_type) {
  508. Post(requests, path, Headers(), body, content_type);
  509. }
  510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  511. class SSLSocketStream : public Stream {
  512. public:
  513. SSLSocketStream(socket_t sock, SSL *ssl);
  514. virtual ~SSLSocketStream();
  515. virtual int read(char *ptr, size_t size);
  516. virtual int write(const char *ptr, size_t size);
  517. virtual int write(const char *ptr);
  518. virtual int write(const std::string &s);
  519. virtual std::string get_remote_addr() const;
  520. private:
  521. socket_t sock_;
  522. SSL *ssl_;
  523. };
  524. class SSLServer : public Server {
  525. public:
  526. SSLServer(const char *cert_path, const char *private_key_path,
  527. const char *client_ca_cert_file_path = nullptr,
  528. const char *client_ca_cert_dir_path = nullptr);
  529. virtual ~SSLServer();
  530. virtual bool is_valid() const;
  531. private:
  532. virtual bool process_and_close_socket(socket_t sock);
  533. SSL_CTX *ctx_;
  534. std::mutex ctx_mutex_;
  535. };
  536. class SSLClient : public Client {
  537. public:
  538. SSLClient(const char *host, int port = 443, time_t timeout_sec = 300,
  539. const char *client_cert_path = nullptr,
  540. const char *client_key_path = nullptr);
  541. virtual ~SSLClient();
  542. virtual bool is_valid() const;
  543. void set_ca_cert_path(const char *ca_ceert_file_path,
  544. const char *ca_cert_dir_path = nullptr);
  545. void enable_server_certificate_verification(bool enabled);
  546. long get_openssl_verify_result() const;
  547. SSL_CTX* ssl_context() const noexcept;
  548. private:
  549. virtual bool process_and_close_socket(
  550. socket_t sock, size_t request_count,
  551. std::function<bool(Stream &strm, bool last_connection,
  552. bool &connection_close)>
  553. callback);
  554. virtual bool is_ssl() const;
  555. bool verify_host(X509 *server_cert) const;
  556. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  557. bool verify_host_with_common_name(X509 *server_cert) const;
  558. bool check_host_name(const char *pattern, size_t pattern_len) const;
  559. SSL_CTX *ctx_;
  560. std::mutex ctx_mutex_;
  561. std::vector<std::string> host_components_;
  562. std::string ca_cert_file_path_;
  563. std::string ca_cert_dir_path_;
  564. bool server_certificate_verification_ = false;
  565. long verify_result_ = 0;
  566. };
  567. #endif
  568. /*
  569. * Implementation
  570. */
  571. namespace detail {
  572. inline bool is_hex(char c, int &v) {
  573. if (0x20 <= c && isdigit(c)) {
  574. v = c - '0';
  575. return true;
  576. } else if ('A' <= c && c <= 'F') {
  577. v = c - 'A' + 10;
  578. return true;
  579. } else if ('a' <= c && c <= 'f') {
  580. v = c - 'a' + 10;
  581. return true;
  582. }
  583. return false;
  584. }
  585. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  586. int &val) {
  587. if (i >= s.size()) { return false; }
  588. val = 0;
  589. for (; cnt; i++, cnt--) {
  590. if (!s[i]) { return false; }
  591. int v = 0;
  592. if (is_hex(s[i], v)) {
  593. val = val * 16 + v;
  594. } else {
  595. return false;
  596. }
  597. }
  598. return true;
  599. }
  600. inline std::string from_i_to_hex(size_t n) {
  601. const char *charset = "0123456789abcdef";
  602. std::string ret;
  603. do {
  604. ret = charset[n & 15] + ret;
  605. n >>= 4;
  606. } while (n > 0);
  607. return ret;
  608. }
  609. inline size_t to_utf8(int code, char *buff) {
  610. if (code < 0x0080) {
  611. buff[0] = (code & 0x7F);
  612. return 1;
  613. } else if (code < 0x0800) {
  614. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  615. buff[1] = (0x80 | (code & 0x3F));
  616. return 2;
  617. } else if (code < 0xD800) {
  618. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  619. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  620. buff[2] = (0x80 | (code & 0x3F));
  621. return 3;
  622. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  623. return 0;
  624. } else if (code < 0x10000) {
  625. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  626. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  627. buff[2] = (0x80 | (code & 0x3F));
  628. return 3;
  629. } else if (code < 0x110000) {
  630. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  631. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  632. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  633. buff[3] = (0x80 | (code & 0x3F));
  634. return 4;
  635. }
  636. // NOTREACHED
  637. return 0;
  638. }
  639. // NOTE: This code came up with the following stackoverflow post:
  640. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  641. inline std::string base64_encode(const std::string &in) {
  642. static const auto lookup =
  643. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  644. std::string out;
  645. out.reserve(in.size());
  646. int val = 0;
  647. int valb = -6;
  648. for (uint8_t c : in) {
  649. val = (val << 8) + c;
  650. valb += 8;
  651. while (valb >= 0) {
  652. out.push_back(lookup[(val >> valb) & 0x3F]);
  653. valb -= 6;
  654. }
  655. }
  656. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  657. while (out.size() % 4) {
  658. out.push_back('=');
  659. }
  660. return out;
  661. }
  662. inline bool is_file(const std::string &path) {
  663. struct stat st;
  664. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  665. }
  666. inline bool is_dir(const std::string &path) {
  667. struct stat st;
  668. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  669. }
  670. inline bool is_valid_path(const std::string &path) {
  671. size_t level = 0;
  672. size_t i = 0;
  673. // Skip slash
  674. while (i < path.size() && path[i] == '/') {
  675. i++;
  676. }
  677. while (i < path.size()) {
  678. // Read component
  679. auto beg = i;
  680. while (i < path.size() && path[i] != '/') {
  681. i++;
  682. }
  683. auto len = i - beg;
  684. assert(len > 0);
  685. if (!path.compare(beg, len, ".")) {
  686. ;
  687. } else if (!path.compare(beg, len, "..")) {
  688. if (level == 0) { return false; }
  689. level--;
  690. } else {
  691. level++;
  692. }
  693. // Skip slash
  694. while (i < path.size() && path[i] == '/') {
  695. i++;
  696. }
  697. }
  698. return true;
  699. }
  700. inline void read_file(const std::string &path, std::string &out) {
  701. std::ifstream fs(path, std::ios_base::binary);
  702. fs.seekg(0, std::ios_base::end);
  703. auto size = fs.tellg();
  704. fs.seekg(0);
  705. out.resize(static_cast<size_t>(size));
  706. fs.read(&out[0], size);
  707. }
  708. inline std::string file_extension(const std::string &path) {
  709. std::smatch m;
  710. auto pat = std::regex("\\.([a-zA-Z0-9]+)$");
  711. if (std::regex_search(path, m, pat)) { return m[1].str(); }
  712. return std::string();
  713. }
  714. template <class Fn> void split(const char *b, const char *e, char d, Fn fn) {
  715. int i = 0;
  716. int beg = 0;
  717. while (e ? (b + i != e) : (b[i] != '\0')) {
  718. if (b[i] == d) {
  719. fn(&b[beg], &b[i]);
  720. beg = i + 1;
  721. }
  722. i++;
  723. }
  724. if (i) { fn(&b[beg], &b[i]); }
  725. }
  726. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  727. // to store data. The call can set memory on stack for performance.
  728. class stream_line_reader {
  729. public:
  730. stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size)
  731. : strm_(strm), fixed_buffer_(fixed_buffer),
  732. fixed_buffer_size_(fixed_buffer_size) {}
  733. const char *ptr() const {
  734. if (glowable_buffer_.empty()) {
  735. return fixed_buffer_;
  736. } else {
  737. return glowable_buffer_.data();
  738. }
  739. }
  740. size_t size() const {
  741. if (glowable_buffer_.empty()) {
  742. return fixed_buffer_used_size_;
  743. } else {
  744. return glowable_buffer_.size();
  745. }
  746. }
  747. bool getline() {
  748. fixed_buffer_used_size_ = 0;
  749. glowable_buffer_.clear();
  750. for (size_t i = 0;; i++) {
  751. char byte;
  752. auto n = strm_.read(&byte, 1);
  753. if (n < 0) {
  754. return false;
  755. } else if (n == 0) {
  756. if (i == 0) {
  757. return false;
  758. } else {
  759. break;
  760. }
  761. }
  762. append(byte);
  763. if (byte == '\n') { break; }
  764. }
  765. return true;
  766. }
  767. private:
  768. void append(char c) {
  769. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  770. fixed_buffer_[fixed_buffer_used_size_++] = c;
  771. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  772. } else {
  773. if (glowable_buffer_.empty()) {
  774. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  775. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  776. }
  777. glowable_buffer_ += c;
  778. }
  779. }
  780. Stream &strm_;
  781. char *fixed_buffer_;
  782. const size_t fixed_buffer_size_;
  783. size_t fixed_buffer_used_size_;
  784. std::string glowable_buffer_;
  785. };
  786. inline int close_socket(socket_t sock) {
  787. #ifdef _WIN32
  788. return closesocket(sock);
  789. #else
  790. return close(sock);
  791. #endif
  792. }
  793. inline int select_read(socket_t sock, time_t sec, time_t usec) {
  794. #ifdef CPPHTTPLIB_USE_POLL
  795. struct pollfd pfd_read;
  796. pfd_read.fd = sock;
  797. pfd_read.events = POLLIN;
  798. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  799. return poll(&pfd_read, 1, timeout);
  800. #else
  801. fd_set fds;
  802. FD_ZERO(&fds);
  803. FD_SET(sock, &fds);
  804. timeval tv;
  805. tv.tv_sec = static_cast<long>(sec);
  806. tv.tv_usec = static_cast<long>(usec);
  807. return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
  808. #endif
  809. }
  810. inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
  811. #ifdef CPPHTTPLIB_USE_POLL
  812. struct pollfd pfd_read;
  813. pfd_read.fd = sock;
  814. pfd_read.events = POLLIN | POLLOUT;
  815. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  816. if (poll(&pfd_read, 1, timeout) > 0 &&
  817. pfd_read.revents & (POLLIN | POLLOUT)) {
  818. int error = 0;
  819. socklen_t len = sizeof(error);
  820. return getsockopt(sock, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&error), &len) >= 0 &&
  821. !error;
  822. }
  823. return false;
  824. #else
  825. fd_set fdsr;
  826. FD_ZERO(&fdsr);
  827. FD_SET(sock, &fdsr);
  828. auto fdsw = fdsr;
  829. auto fdse = fdsr;
  830. timeval tv;
  831. tv.tv_sec = static_cast<long>(sec);
  832. tv.tv_usec = static_cast<long>(usec);
  833. if (select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv) > 0 &&
  834. (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  835. int error = 0;
  836. socklen_t len = sizeof(error);
  837. return getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&error, &len) >= 0 &&
  838. !error;
  839. }
  840. return false;
  841. #endif
  842. }
  843. template <typename T>
  844. inline bool process_and_close_socket(bool is_client_request, socket_t sock,
  845. size_t keep_alive_max_count, T callback) {
  846. assert(keep_alive_max_count > 0);
  847. bool ret = false;
  848. if (keep_alive_max_count > 1) {
  849. auto count = keep_alive_max_count;
  850. while (count > 0 &&
  851. (is_client_request ||
  852. detail::select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  853. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
  854. SocketStream strm(sock);
  855. auto last_connection = count == 1;
  856. auto connection_close = false;
  857. ret = callback(strm, last_connection, connection_close);
  858. if (!ret || connection_close) { break; }
  859. count--;
  860. }
  861. } else {
  862. SocketStream strm(sock);
  863. auto dummy_connection_close = false;
  864. ret = callback(strm, true, dummy_connection_close);
  865. }
  866. close_socket(sock);
  867. return ret;
  868. }
  869. inline int shutdown_socket(socket_t sock) {
  870. #ifdef _WIN32
  871. return shutdown(sock, SD_BOTH);
  872. #else
  873. return shutdown(sock, SHUT_RDWR);
  874. #endif
  875. }
  876. template <typename Fn>
  877. socket_t create_socket(const char *host, int port, Fn fn,
  878. int socket_flags = 0) {
  879. #ifdef _WIN32
  880. #define SO_SYNCHRONOUS_NONALERT 0x20
  881. #define SO_OPENTYPE 0x7008
  882. int opt = SO_SYNCHRONOUS_NONALERT;
  883. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&opt,
  884. sizeof(opt));
  885. #endif
  886. // Get address info
  887. struct addrinfo hints;
  888. struct addrinfo *result;
  889. memset(&hints, 0, sizeof(struct addrinfo));
  890. hints.ai_family = AF_UNSPEC;
  891. hints.ai_socktype = SOCK_STREAM;
  892. hints.ai_flags = socket_flags;
  893. hints.ai_protocol = 0;
  894. auto service = std::to_string(port);
  895. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  896. return INVALID_SOCKET;
  897. }
  898. for (auto rp = result; rp; rp = rp->ai_next) {
  899. // Create a socket
  900. #ifdef _WIN32
  901. auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
  902. nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT);
  903. #else
  904. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  905. #endif
  906. if (sock == INVALID_SOCKET) { continue; }
  907. #ifndef _WIN32
  908. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; }
  909. #endif
  910. // Make 'reuse address' option available
  911. int yes = 1;
  912. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&yes), sizeof(yes));
  913. #ifdef SO_REUSEPORT
  914. setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<char*>(&yes), sizeof(yes));
  915. #endif
  916. // bind or connect
  917. if (fn(sock, *rp)) {
  918. freeaddrinfo(result);
  919. return sock;
  920. }
  921. close_socket(sock);
  922. }
  923. freeaddrinfo(result);
  924. return INVALID_SOCKET;
  925. }
  926. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  927. #ifdef _WIN32
  928. auto flags = nonblocking ? 1UL : 0UL;
  929. ioctlsocket(sock, FIONBIO, &flags);
  930. #else
  931. auto flags = fcntl(sock, F_GETFL, 0);
  932. fcntl(sock, F_SETFL,
  933. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  934. #endif
  935. }
  936. inline bool is_connection_error() {
  937. #ifdef _WIN32
  938. return WSAGetLastError() != WSAEWOULDBLOCK;
  939. #else
  940. return errno != EINPROGRESS;
  941. #endif
  942. }
  943. inline std::string get_remote_addr(socket_t sock) {
  944. struct sockaddr_storage addr;
  945. socklen_t len = sizeof(addr);
  946. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr), &len)) {
  947. char ipstr[NI_MAXHOST];
  948. if (!getnameinfo(reinterpret_cast<struct sockaddr *>(&addr), len, ipstr, sizeof(ipstr),
  949. nullptr, 0, NI_NUMERICHOST)) {
  950. return ipstr;
  951. }
  952. }
  953. return std::string();
  954. }
  955. inline const char *find_content_type(const std::string &path) {
  956. auto ext = file_extension(path);
  957. if (ext == "txt") {
  958. return "text/plain";
  959. } else if (ext == "html") {
  960. return "text/html";
  961. } else if (ext == "css") {
  962. return "text/css";
  963. } else if (ext == "jpeg" || ext == "jpg") {
  964. return "image/jpg";
  965. } else if (ext == "png") {
  966. return "image/png";
  967. } else if (ext == "gif") {
  968. return "image/gif";
  969. } else if (ext == "svg") {
  970. return "image/svg+xml";
  971. } else if (ext == "ico") {
  972. return "image/x-icon";
  973. } else if (ext == "json") {
  974. return "application/json";
  975. } else if (ext == "pdf") {
  976. return "application/pdf";
  977. } else if (ext == "js") {
  978. return "application/javascript";
  979. } else if (ext == "xml") {
  980. return "application/xml";
  981. } else if (ext == "xhtml") {
  982. return "application/xhtml+xml";
  983. }
  984. return nullptr;
  985. }
  986. inline const char *status_message(int status) {
  987. switch (status) {
  988. case 200: return "OK";
  989. case 206: return "Partial Content";
  990. case 301: return "Moved Permanently";
  991. case 302: return "Found";
  992. case 303: return "See Other";
  993. case 304: return "Not Modified";
  994. case 400: return "Bad Request";
  995. case 403: return "Forbidden";
  996. case 404: return "Not Found";
  997. case 413: return "Payload Too Large";
  998. case 414: return "Request-URI Too Long";
  999. case 415: return "Unsupported Media Type";
  1000. case 416: return "Range Not Satisfiable";
  1001. default:
  1002. case 500: return "Internal Server Error";
  1003. }
  1004. }
  1005. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1006. inline bool can_compress(const std::string &content_type) {
  1007. return !content_type.find("text/") || content_type == "image/svg+xml" ||
  1008. content_type == "application/javascript" ||
  1009. content_type == "application/json" ||
  1010. content_type == "application/xml" ||
  1011. content_type == "application/xhtml+xml";
  1012. }
  1013. inline bool compress(std::string &content) {
  1014. z_stream strm;
  1015. strm.zalloc = Z_NULL;
  1016. strm.zfree = Z_NULL;
  1017. strm.opaque = Z_NULL;
  1018. auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  1019. Z_DEFAULT_STRATEGY);
  1020. if (ret != Z_OK) { return false; }
  1021. strm.avail_in = content.size();
  1022. strm.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef*>(content.data()));
  1023. std::string compressed;
  1024. const auto bufsiz = 16384;
  1025. char buff[bufsiz];
  1026. do {
  1027. strm.avail_out = bufsiz;
  1028. strm.next_out = reinterpret_cast<Bytef*>(buff);
  1029. ret = deflate(&strm, Z_FINISH);
  1030. assert(ret != Z_STREAM_ERROR);
  1031. compressed.append(buff, bufsiz - strm.avail_out);
  1032. } while (strm.avail_out == 0);
  1033. assert(ret == Z_STREAM_END);
  1034. assert(strm.avail_in == 0);
  1035. content.swap(compressed);
  1036. deflateEnd(&strm);
  1037. return true;
  1038. }
  1039. class decompressor {
  1040. public:
  1041. decompressor() {
  1042. strm.zalloc = Z_NULL;
  1043. strm.zfree = Z_NULL;
  1044. strm.opaque = Z_NULL;
  1045. // 15 is the value of wbits, which should be at the maximum possible value
  1046. // to ensure that any gzip stream can be decoded. The offset of 16 specifies
  1047. // that the stream to decompress will be formatted with a gzip wrapper.
  1048. is_valid_ = inflateInit2(&strm, 16 + 15) == Z_OK;
  1049. }
  1050. ~decompressor() { inflateEnd(&strm); }
  1051. bool is_valid() const { return is_valid_; }
  1052. template <typename T>
  1053. bool decompress(const char *data, size_t data_length, T callback) {
  1054. int ret = Z_OK;
  1055. strm.avail_in = data_length;
  1056. strm.next_in = const_cast<Bytef*>(reinterpret_cast<const Bytef *>(data));
  1057. const auto bufsiz = 16384;
  1058. char buff[bufsiz];
  1059. do {
  1060. strm.avail_out = bufsiz;
  1061. strm.next_out = reinterpret_cast<Bytef*>(buff);
  1062. ret = inflate(&strm, Z_NO_FLUSH);
  1063. assert(ret != Z_STREAM_ERROR);
  1064. switch (ret) {
  1065. case Z_NEED_DICT:
  1066. case Z_DATA_ERROR:
  1067. case Z_MEM_ERROR: inflateEnd(&strm); return false;
  1068. }
  1069. if (!callback(buff, bufsiz - strm.avail_out)) { return false; }
  1070. } while (strm.avail_out == 0);
  1071. return ret == Z_STREAM_END;
  1072. }
  1073. private:
  1074. bool is_valid_;
  1075. z_stream strm;
  1076. };
  1077. #endif
  1078. inline bool has_header(const Headers &headers, const char *key) {
  1079. return headers.find(key) != headers.end();
  1080. }
  1081. inline const char *get_header_value(const Headers &headers, const char *key,
  1082. size_t id = 0, const char *def = nullptr) {
  1083. auto it = headers.find(key);
  1084. std::advance(it, id);
  1085. if (it != headers.end()) { return it->second.c_str(); }
  1086. return def;
  1087. }
  1088. inline uint64_t get_header_value_uint64(const Headers &headers, const char *key,
  1089. int def = 0) {
  1090. auto it = headers.find(key);
  1091. if (it != headers.end()) {
  1092. return std::strtoull(it->second.data(), nullptr, 10);
  1093. }
  1094. return def;
  1095. }
  1096. inline bool read_headers(Stream &strm, Headers &headers) {
  1097. static std::regex re(R"((.+?):\s*(.+?)\s*\r\n)");
  1098. const auto bufsiz = 2048;
  1099. char buf[bufsiz];
  1100. stream_line_reader reader(strm, buf, bufsiz);
  1101. for (;;) {
  1102. if (!reader.getline()) { return false; }
  1103. if (!strcmp(reader.ptr(), "\r\n")) { break; }
  1104. std::cmatch m;
  1105. if (std::regex_match(reader.ptr(), m, re)) {
  1106. auto key = std::string(m[1]);
  1107. auto val = std::string(m[2]);
  1108. headers.emplace(key, val);
  1109. }
  1110. }
  1111. return true;
  1112. }
  1113. typedef std::function<bool(const char *data, size_t data_length)>
  1114. ContentReceiverCore;
  1115. inline bool read_content_with_length(Stream &strm, uint64_t len,
  1116. Progress progress,
  1117. ContentReceiverCore out) {
  1118. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1119. uint64_t r = 0;
  1120. while (r < len) {
  1121. auto read_len = static_cast<size_t>(len - r);
  1122. auto n = strm.read(buf, std::min(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1123. if (n <= 0) { return false; }
  1124. if (!out(buf, n)) { return false; }
  1125. r += n;
  1126. if (progress) {
  1127. if (!progress(r, len)) { return false; }
  1128. }
  1129. }
  1130. return true;
  1131. }
  1132. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  1133. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1134. uint64_t r = 0;
  1135. while (r < len) {
  1136. auto read_len = static_cast<size_t>(len - r);
  1137. auto n = strm.read(buf, std::min(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1138. if (n <= 0) { return; }
  1139. r += n;
  1140. }
  1141. }
  1142. inline bool read_content_without_length(Stream &strm, ContentReceiverCore out) {
  1143. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1144. for (;;) {
  1145. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  1146. if (n < 0) {
  1147. return false;
  1148. } else if (n == 0) {
  1149. return true;
  1150. }
  1151. if (!out(buf, n)) { return false; }
  1152. }
  1153. return true;
  1154. }
  1155. inline bool read_content_chunked(Stream &strm, ContentReceiverCore out) {
  1156. const auto bufsiz = 16;
  1157. char buf[bufsiz];
  1158. stream_line_reader reader(strm, buf, bufsiz);
  1159. if (!reader.getline()) { return false; }
  1160. auto chunk_len = std::stoi(reader.ptr(), 0, 16);
  1161. while (chunk_len > 0) {
  1162. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  1163. return false;
  1164. }
  1165. if (!reader.getline()) { return false; }
  1166. if (strcmp(reader.ptr(), "\r\n")) { break; }
  1167. if (!reader.getline()) { return false; }
  1168. chunk_len = std::stoi(reader.ptr(), 0, 16);
  1169. }
  1170. if (chunk_len == 0) {
  1171. // Reader terminator after chunks
  1172. if (!reader.getline() || strcmp(reader.ptr(), "\r\n")) return false;
  1173. }
  1174. return true;
  1175. }
  1176. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  1177. return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""),
  1178. "chunked");
  1179. }
  1180. template <typename T>
  1181. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  1182. Progress progress, ContentReceiverCore receiver) {
  1183. ContentReceiverCore out = [&](const char *buf, size_t n) {
  1184. return receiver(buf, n);
  1185. };
  1186. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1187. detail::decompressor decompressor;
  1188. if (!decompressor.is_valid()) {
  1189. status = 500;
  1190. return false;
  1191. }
  1192. if (x.get_header_value("Content-Encoding") == "gzip") {
  1193. out = [&](const char *buf, size_t n) {
  1194. return decompressor.decompress(
  1195. buf, n, [&](const char *buf, size_t n) { return receiver(buf, n); });
  1196. };
  1197. }
  1198. #else
  1199. if (x.get_header_value("Content-Encoding") == "gzip") {
  1200. status = 415;
  1201. return false;
  1202. }
  1203. #endif
  1204. auto ret = true;
  1205. auto exceed_payload_max_length = false;
  1206. if (is_chunked_transfer_encoding(x.headers)) {
  1207. ret = read_content_chunked(strm, out);
  1208. } else if (!has_header(x.headers, "Content-Length")) {
  1209. ret = read_content_without_length(strm, out);
  1210. } else {
  1211. auto len = get_header_value_uint64(x.headers, "Content-Length", 0);
  1212. if (len > payload_max_length) {
  1213. exceed_payload_max_length = true;
  1214. skip_content_with_length(strm, len);
  1215. ret = false;
  1216. } else if (len > 0) {
  1217. ret = read_content_with_length(strm, len, progress, out);
  1218. }
  1219. }
  1220. if (!ret) { status = exceed_payload_max_length ? 413 : 400; }
  1221. return ret;
  1222. }
  1223. template <typename T>
  1224. inline int write_headers(Stream &strm, const T &info, const Headers &headers) {
  1225. auto write_len = 0;
  1226. for (const auto &x : info.headers) {
  1227. auto len =
  1228. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  1229. if (len < 0) { return len; }
  1230. write_len += len;
  1231. }
  1232. for (const auto &x : headers) {
  1233. auto len =
  1234. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  1235. if (len < 0) { return len; }
  1236. write_len += len;
  1237. }
  1238. auto len = strm.write("\r\n");
  1239. if (len < 0) { return len; }
  1240. write_len += len;
  1241. return write_len;
  1242. }
  1243. inline ssize_t write_content(Stream &strm, ContentProvider content_provider,
  1244. size_t offset, size_t length) {
  1245. size_t begin_offset = offset;
  1246. size_t end_offset = offset + length;
  1247. while (offset < end_offset) {
  1248. ssize_t written_length = 0;
  1249. content_provider(
  1250. offset, end_offset - offset,
  1251. [&](const char *d, size_t l) {
  1252. offset += l;
  1253. written_length = strm.write(d, l);
  1254. },
  1255. [&](void) { written_length = -1; });
  1256. if (written_length < 0) { return written_length; }
  1257. }
  1258. return static_cast<ssize_t>(offset - begin_offset);
  1259. }
  1260. inline ssize_t write_content_chunked(Stream &strm,
  1261. ContentProvider content_provider) {
  1262. size_t offset = 0;
  1263. auto data_available = true;
  1264. ssize_t total_written_length = 0;
  1265. while (data_available) {
  1266. ssize_t written_length = 0;
  1267. content_provider(
  1268. offset, 0,
  1269. [&](const char *d, size_t l) {
  1270. data_available = l > 0;
  1271. offset += l;
  1272. // Emit chunked response header and footer for each chunk
  1273. auto chunk = from_i_to_hex(l) + "\r\n" + std::string(d, l) + "\r\n";
  1274. written_length = strm.write(chunk);
  1275. },
  1276. [&](void) {
  1277. data_available = false;
  1278. written_length = strm.write("0\r\n\r\n");
  1279. });
  1280. if (written_length < 0) { return written_length; }
  1281. total_written_length += written_length;
  1282. }
  1283. return total_written_length;
  1284. }
  1285. template <typename T>
  1286. inline bool redirect(T &cli, const Request &req, Response &res,
  1287. const std::string &path) {
  1288. Request new_req;
  1289. new_req.method = req.method;
  1290. new_req.path = path;
  1291. new_req.headers = req.headers;
  1292. new_req.body = req.body;
  1293. new_req.redirect_count = req.redirect_count - 1;
  1294. new_req.response_handler = req.response_handler;
  1295. new_req.content_receiver = req.content_receiver;
  1296. new_req.progress = req.progress;
  1297. Response new_res;
  1298. auto ret = cli.send(new_req, new_res);
  1299. if (ret) { res = new_res; }
  1300. return ret;
  1301. }
  1302. inline std::string encode_url(const std::string &s) {
  1303. std::string result;
  1304. for (auto i = 0; s[i]; i++) {
  1305. switch (s[i]) {
  1306. case ' ': result += "%20"; break;
  1307. case '+': result += "%2B"; break;
  1308. case '\r': result += "%0D"; break;
  1309. case '\n': result += "%0A"; break;
  1310. case '\'': result += "%27"; break;
  1311. case ',': result += "%2C"; break;
  1312. case ':': result += "%3A"; break;
  1313. case ';': result += "%3B"; break;
  1314. default:
  1315. auto c = static_cast<uint8_t>(s[i]);
  1316. if (c >= 0x80) {
  1317. result += '%';
  1318. char hex[4];
  1319. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  1320. assert(len == 2);
  1321. result.append(hex, len);
  1322. } else {
  1323. result += s[i];
  1324. }
  1325. break;
  1326. }
  1327. }
  1328. return result;
  1329. }
  1330. inline std::string decode_url(const std::string &s) {
  1331. std::string result;
  1332. for (size_t i = 0; i < s.size(); i++) {
  1333. if (s[i] == '%' && i + 1 < s.size()) {
  1334. if (s[i + 1] == 'u') {
  1335. int val = 0;
  1336. if (from_hex_to_i(s, i + 2, 4, val)) {
  1337. // 4 digits Unicode codes
  1338. char buff[4];
  1339. size_t len = to_utf8(val, buff);
  1340. if (len > 0) { result.append(buff, len); }
  1341. i += 5; // 'u0000'
  1342. } else {
  1343. result += s[i];
  1344. }
  1345. } else {
  1346. int val = 0;
  1347. if (from_hex_to_i(s, i + 1, 2, val)) {
  1348. // 2 digits hex codes
  1349. result += val;
  1350. i += 2; // '00'
  1351. } else {
  1352. result += s[i];
  1353. }
  1354. }
  1355. } else if (s[i] == '+') {
  1356. result += ' ';
  1357. } else {
  1358. result += s[i];
  1359. }
  1360. }
  1361. return result;
  1362. }
  1363. inline void parse_query_text(const std::string &s, Params &params) {
  1364. split(&s[0], &s[s.size()], '&', [&](const char *b, const char *e) {
  1365. std::string key;
  1366. std::string val;
  1367. split(b, e, '=', [&](const char *b, const char *e) {
  1368. if (key.empty()) {
  1369. key.assign(b, e);
  1370. } else {
  1371. val.assign(b, e);
  1372. }
  1373. });
  1374. params.emplace(key, decode_url(val));
  1375. });
  1376. }
  1377. inline bool parse_multipart_boundary(const std::string &content_type,
  1378. std::string &boundary) {
  1379. auto pos = content_type.find("boundary=");
  1380. if (pos == std::string::npos) { return false; }
  1381. boundary = content_type.substr(pos + 9);
  1382. return true;
  1383. }
  1384. inline bool parse_multipart_formdata(const std::string &boundary,
  1385. const std::string &body,
  1386. MultipartFiles &files) {
  1387. static std::string dash = "--";
  1388. static std::string crlf = "\r\n";
  1389. static std::regex re_content_type("Content-Type: (.*?)",
  1390. std::regex_constants::icase);
  1391. static std::regex re_content_disposition(
  1392. "Content-Disposition: form-data; name=\"(.*?)\"(?:; filename=\"(.*?)\")?",
  1393. std::regex_constants::icase);
  1394. auto dash_boundary = dash + boundary;
  1395. auto pos = body.find(dash_boundary);
  1396. if (pos != 0) { return false; }
  1397. pos += dash_boundary.size();
  1398. auto next_pos = body.find(crlf, pos);
  1399. if (next_pos == std::string::npos) { return false; }
  1400. pos = next_pos + crlf.size();
  1401. while (pos < body.size()) {
  1402. next_pos = body.find(crlf, pos);
  1403. if (next_pos == std::string::npos) { return false; }
  1404. std::string name;
  1405. MultipartFile file;
  1406. auto header = body.substr(pos, (next_pos - pos));
  1407. while (pos != next_pos) {
  1408. std::smatch m;
  1409. if (std::regex_match(header, m, re_content_type)) {
  1410. file.content_type = m[1];
  1411. } else if (std::regex_match(header, m, re_content_disposition)) {
  1412. name = m[1];
  1413. file.filename = m[2];
  1414. }
  1415. pos = next_pos + crlf.size();
  1416. next_pos = body.find(crlf, pos);
  1417. if (next_pos == std::string::npos) { return false; }
  1418. header = body.substr(pos, (next_pos - pos));
  1419. }
  1420. pos = next_pos + crlf.size();
  1421. next_pos = body.find(crlf + dash_boundary, pos);
  1422. if (next_pos == std::string::npos) { return false; }
  1423. file.offset = pos;
  1424. file.length = next_pos - pos;
  1425. pos = next_pos + crlf.size() + dash_boundary.size();
  1426. next_pos = body.find(crlf, pos);
  1427. if (next_pos == std::string::npos) { return false; }
  1428. files.emplace(name, file);
  1429. pos = next_pos + crlf.size();
  1430. }
  1431. return true;
  1432. }
  1433. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  1434. try {
  1435. static auto re = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
  1436. std::smatch m;
  1437. if (std::regex_match(s, m, re)) {
  1438. auto pos = m.position(1);
  1439. auto len = m.length(1);
  1440. detail::split(&s[pos], &s[pos + len], ',',
  1441. [&](const char *b, const char *e) {
  1442. static auto re = std::regex(R"(\s*(\d*)-(\d*))");
  1443. std::cmatch m;
  1444. if (std::regex_match(b, e, m, re)) {
  1445. ssize_t first = -1;
  1446. if (!m.str(1).empty()) {
  1447. first = static_cast<ssize_t>(std::stoll(m.str(1)));
  1448. }
  1449. ssize_t last = -1;
  1450. if (!m.str(2).empty()) {
  1451. last = static_cast<ssize_t>(std::stoll(m.str(2)));
  1452. }
  1453. if (first != -1 && last != -1 && first > last) {
  1454. throw std::runtime_error("invalid range error");
  1455. }
  1456. ranges.emplace_back(std::make_pair(first, last));
  1457. }
  1458. });
  1459. return true;
  1460. }
  1461. return false;
  1462. } catch (...) { return false; }
  1463. }
  1464. inline std::string to_lower(const char *beg, const char *end) {
  1465. std::string out;
  1466. auto it = beg;
  1467. while (it != end) {
  1468. out += ::tolower(*it);
  1469. it++;
  1470. }
  1471. return out;
  1472. }
  1473. inline std::string make_multipart_data_boundary() {
  1474. static const char data[] =
  1475. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1476. std::random_device seed_gen;
  1477. std::mt19937 engine(seed_gen());
  1478. std::string result = "--cpp-httplib-multipart-data-";
  1479. for (auto i = 0; i < 16; i++) {
  1480. result += data[engine() % (sizeof(data) - 1)];
  1481. }
  1482. return result;
  1483. }
  1484. inline std::pair<size_t, size_t>
  1485. get_range_offset_and_length(const Request &req, size_t content_length,
  1486. size_t index) {
  1487. auto r = req.ranges[index];
  1488. if (r.first == -1 && r.second == -1) {
  1489. return std::make_pair(0, content_length);
  1490. }
  1491. if (r.first == -1) {
  1492. r.first = content_length - r.second;
  1493. r.second = content_length - 1;
  1494. }
  1495. if (r.second == -1) { r.second = content_length - 1; }
  1496. return std::make_pair(r.first, r.second - r.first + 1);
  1497. }
  1498. inline std::string make_content_range_header_field(size_t offset, size_t length,
  1499. size_t content_length) {
  1500. std::string field = "bytes ";
  1501. field += std::to_string(offset);
  1502. field += "-";
  1503. field += std::to_string(offset + length - 1);
  1504. field += "/";
  1505. field += std::to_string(content_length);
  1506. return field;
  1507. }
  1508. template <typename SToken, typename CToken, typename Content>
  1509. bool process_multipart_ranges_data(const Request &req, Response &res,
  1510. const std::string &boundary,
  1511. const std::string &content_type,
  1512. SToken stoken, CToken ctoken,
  1513. Content content) {
  1514. for (size_t i = 0; i < req.ranges.size(); i++) {
  1515. ctoken("--");
  1516. stoken(boundary);
  1517. ctoken("\r\n");
  1518. if (!content_type.empty()) {
  1519. ctoken("Content-Type: ");
  1520. stoken(content_type);
  1521. ctoken("\r\n");
  1522. }
  1523. auto offsets = detail::get_range_offset_and_length(req, res.body.size(), i);
  1524. auto offset = offsets.first;
  1525. auto length = offsets.second;
  1526. ctoken("Content-Range: ");
  1527. stoken(make_content_range_header_field(offset, length, res.body.size()));
  1528. ctoken("\r\n");
  1529. ctoken("\r\n");
  1530. if (!content(offset, length)) { return false; }
  1531. ctoken("\r\n");
  1532. }
  1533. ctoken("--");
  1534. stoken(boundary);
  1535. ctoken("--\r\n");
  1536. return true;
  1537. }
  1538. inline std::string make_multipart_ranges_data(const Request &req, Response &res,
  1539. const std::string &boundary,
  1540. const std::string &content_type) {
  1541. std::string data;
  1542. process_multipart_ranges_data(
  1543. req, res, boundary, content_type,
  1544. [&](const std::string &token) { data += token; },
  1545. [&](const char *token) { data += token; },
  1546. [&](size_t offset, size_t length) {
  1547. data += res.body.substr(offset, length);
  1548. return true;
  1549. });
  1550. return data;
  1551. }
  1552. inline size_t
  1553. get_multipart_ranges_data_length(const Request &req, Response &res,
  1554. const std::string &boundary,
  1555. const std::string &content_type) {
  1556. size_t data_length = 0;
  1557. process_multipart_ranges_data(
  1558. req, res, boundary, content_type,
  1559. [&](const std::string &token) { data_length += token.size(); },
  1560. [&](const char *token) { data_length += strlen(token); },
  1561. [&](size_t /*offset*/, size_t length) {
  1562. data_length += length;
  1563. return true;
  1564. });
  1565. return data_length;
  1566. }
  1567. inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
  1568. Response &res,
  1569. const std::string &boundary,
  1570. const std::string &content_type) {
  1571. return process_multipart_ranges_data(
  1572. req, res, boundary, content_type,
  1573. [&](const std::string &token) { strm.write(token); },
  1574. [&](const char *token) { strm.write(token); },
  1575. [&](size_t offset, size_t length) {
  1576. return detail::write_content(strm, res.content_provider, offset,
  1577. length) >= 0;
  1578. });
  1579. }
  1580. inline std::pair<size_t, size_t>
  1581. get_range_offset_and_length(const Request &req, const Response &res,
  1582. size_t index) {
  1583. auto r = req.ranges[index];
  1584. if (r.second == -1) { r.second = res.content_provider_resource_length - 1; }
  1585. return std::make_pair(r.first, r.second - r.first + 1);
  1586. }
  1587. #ifdef _WIN32
  1588. class WSInit {
  1589. public:
  1590. WSInit() {
  1591. WSADATA wsaData;
  1592. WSAStartup(0x0002, &wsaData);
  1593. }
  1594. ~WSInit() { WSACleanup(); }
  1595. };
  1596. static WSInit wsinit_;
  1597. #endif
  1598. } // namespace detail
  1599. // Header utilities
  1600. inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
  1601. std::string field = "bytes=";
  1602. auto i = 0;
  1603. for (auto r : ranges) {
  1604. if (i != 0) { field += ", "; }
  1605. if (r.first != -1) { field += std::to_string(r.first); }
  1606. field += '-';
  1607. if (r.second != -1) { field += std::to_string(r.second); }
  1608. i++;
  1609. }
  1610. return std::make_pair("Range", field);
  1611. }
  1612. inline std::pair<std::string, std::string>
  1613. make_basic_authentication_header(const std::string &username,
  1614. const std::string &password) {
  1615. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  1616. return std::make_pair("Authorization", field);
  1617. }
  1618. // Request implementation
  1619. inline bool Request::has_header(const char *key) const {
  1620. return detail::has_header(headers, key);
  1621. }
  1622. inline std::string Request::get_header_value(const char *key, size_t id) const {
  1623. return detail::get_header_value(headers, key, id, "");
  1624. }
  1625. inline size_t Request::get_header_value_count(const char *key) const {
  1626. auto r = headers.equal_range(key);
  1627. return std::distance(r.first, r.second);
  1628. }
  1629. inline void Request::set_header(const char *key, const char *val) {
  1630. headers.emplace(key, val);
  1631. }
  1632. inline void Request::set_header(const char *key, const std::string &val) {
  1633. headers.emplace(key, val);
  1634. }
  1635. inline bool Request::has_param(const char *key) const {
  1636. return params.find(key) != params.end();
  1637. }
  1638. inline std::string Request::get_param_value(const char *key, size_t id) const {
  1639. auto it = params.find(key);
  1640. std::advance(it, id);
  1641. if (it != params.end()) { return it->second; }
  1642. return std::string();
  1643. }
  1644. inline size_t Request::get_param_value_count(const char *key) const {
  1645. auto r = params.equal_range(key);
  1646. return std::distance(r.first, r.second);
  1647. }
  1648. inline bool Request::has_file(const char *key) const {
  1649. return files.find(key) != files.end();
  1650. }
  1651. inline MultipartFile Request::get_file_value(const char *key) const {
  1652. auto it = files.find(key);
  1653. if (it != files.end()) { return it->second; }
  1654. return MultipartFile();
  1655. }
  1656. // Response implementation
  1657. inline bool Response::has_header(const char *key) const {
  1658. return headers.find(key) != headers.end();
  1659. }
  1660. inline std::string Response::get_header_value(const char *key,
  1661. size_t id) const {
  1662. return detail::get_header_value(headers, key, id, "");
  1663. }
  1664. inline size_t Response::get_header_value_count(const char *key) const {
  1665. auto r = headers.equal_range(key);
  1666. return std::distance(r.first, r.second);
  1667. }
  1668. inline void Response::set_header(const char *key, const char *val) {
  1669. headers.emplace(key, val);
  1670. }
  1671. inline void Response::set_header(const char *key, const std::string &val) {
  1672. headers.emplace(key, val);
  1673. }
  1674. inline void Response::set_redirect(const char *url) {
  1675. set_header("Location", url);
  1676. status = 302;
  1677. }
  1678. inline void Response::set_content(const char *s, size_t n,
  1679. const char *content_type) {
  1680. body.assign(s, n);
  1681. set_header("Content-Type", content_type);
  1682. }
  1683. inline void Response::set_content(const std::string &s,
  1684. const char *content_type) {
  1685. body = s;
  1686. set_header("Content-Type", content_type);
  1687. }
  1688. inline void Response::set_content_provider(
  1689. size_t length,
  1690. std::function<void(size_t offset, size_t length, DataSink sink)> provider,
  1691. std::function<void()> resource_releaser) {
  1692. assert(length > 0);
  1693. content_provider_resource_length = length;
  1694. content_provider = [provider](size_t offset, size_t length, DataSink sink,
  1695. Done) { provider(offset, length, sink); };
  1696. content_provider_resource_releaser = resource_releaser;
  1697. }
  1698. inline void Response::set_chunked_content_provider(
  1699. std::function<void(size_t offset, DataSink sink, Done done)> provider,
  1700. std::function<void()> resource_releaser) {
  1701. content_provider_resource_length = 0;
  1702. content_provider = [provider](size_t offset, size_t, DataSink sink,
  1703. Done done) { provider(offset, sink, done); };
  1704. content_provider_resource_releaser = resource_releaser;
  1705. }
  1706. // Rstream implementation
  1707. template <typename... Args>
  1708. inline int Stream::write_format(const char *fmt, const Args &... args) {
  1709. const auto bufsiz = 2048;
  1710. char buf[bufsiz];
  1711. #if defined(_MSC_VER) && _MSC_VER < 1900
  1712. auto n = _snprintf_s(buf, bufsiz, bufsiz - 1, fmt, args...);
  1713. #else
  1714. auto n = snprintf(buf, bufsiz - 1, fmt, args...);
  1715. #endif
  1716. if (n <= 0) { return n; }
  1717. if (n >= bufsiz - 1) {
  1718. std::vector<char> glowable_buf(bufsiz);
  1719. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  1720. glowable_buf.resize(glowable_buf.size() * 2);
  1721. #if defined(_MSC_VER) && _MSC_VER < 1900
  1722. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(),
  1723. glowable_buf.size() - 1, fmt, args...);
  1724. #else
  1725. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  1726. #endif
  1727. }
  1728. return write(&glowable_buf[0], n);
  1729. } else {
  1730. return write(buf, n);
  1731. }
  1732. }
  1733. // Socket stream implementation
  1734. inline SocketStream::SocketStream(socket_t sock) : sock_(sock) {}
  1735. inline SocketStream::~SocketStream() {}
  1736. inline int SocketStream::read(char *ptr, size_t size) {
  1737. if (detail::select_read(sock_, CPPHTTPLIB_READ_TIMEOUT_SECOND,
  1738. CPPHTTPLIB_READ_TIMEOUT_USECOND) > 0) {
  1739. return recv(sock_, ptr, static_cast<int>(size), 0);
  1740. }
  1741. return -1;
  1742. }
  1743. inline int SocketStream::write(const char *ptr, size_t size) {
  1744. return send(sock_, ptr, static_cast<int>(size), 0);
  1745. }
  1746. inline int SocketStream::write(const char *ptr) {
  1747. return write(ptr, strlen(ptr));
  1748. }
  1749. inline int SocketStream::write(const std::string &s) {
  1750. return write(s.data(), s.size());
  1751. }
  1752. inline std::string SocketStream::get_remote_addr() const {
  1753. return detail::get_remote_addr(sock_);
  1754. }
  1755. // Buffer stream implementation
  1756. inline int BufferStream::read(char *ptr, size_t size) {
  1757. #if defined(_MSC_VER) && _MSC_VER < 1900
  1758. return static_cast<int>(buffer._Copy_s(ptr, size, size));
  1759. #else
  1760. return static_cast<int>(buffer.copy(ptr, size));
  1761. #endif
  1762. }
  1763. inline int BufferStream::write(const char *ptr, size_t size) {
  1764. buffer.append(ptr, size);
  1765. return static_cast<int>(size);
  1766. }
  1767. inline int BufferStream::write(const char *ptr) {
  1768. return write(ptr, strlen(ptr));
  1769. }
  1770. inline int BufferStream::write(const std::string &s) {
  1771. return write(s.data(), s.size());
  1772. }
  1773. inline std::string BufferStream::get_remote_addr() const { return ""; }
  1774. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  1775. // HTTP server implementation
  1776. inline Server::Server()
  1777. : keep_alive_max_count_(CPPHTTPLIB_KEEPALIVE_MAX_COUNT),
  1778. payload_max_length_(CPPHTTPLIB_PAYLOAD_MAX_LENGTH), is_running_(false),
  1779. svr_sock_(INVALID_SOCKET) {
  1780. #ifndef _WIN32
  1781. signal(SIGPIPE, SIG_IGN);
  1782. #endif
  1783. new_task_queue = [] {
  1784. #if CPPHTTPLIB_THREAD_POOL_COUNT > 0
  1785. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT);
  1786. #else
  1787. return new Threads();
  1788. #endif
  1789. };
  1790. }
  1791. inline Server::~Server() {}
  1792. inline Server &Server::Get(const char *pattern, Handler handler) {
  1793. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1794. return *this;
  1795. }
  1796. inline Server &Server::Post(const char *pattern, Handler handler) {
  1797. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1798. return *this;
  1799. }
  1800. inline Server &Server::Put(const char *pattern, Handler handler) {
  1801. put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1802. return *this;
  1803. }
  1804. inline Server &Server::Patch(const char *pattern, Handler handler) {
  1805. patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1806. return *this;
  1807. }
  1808. inline Server &Server::Delete(const char *pattern, Handler handler) {
  1809. delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1810. return *this;
  1811. }
  1812. inline Server &Server::Options(const char *pattern, Handler handler) {
  1813. options_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  1814. return *this;
  1815. }
  1816. inline bool Server::set_base_dir(const char *path) {
  1817. if (detail::is_dir(path)) {
  1818. base_dir_ = path;
  1819. return true;
  1820. }
  1821. return false;
  1822. }
  1823. inline void Server::set_file_request_handler(Handler handler) {
  1824. file_request_handler_ = handler;
  1825. }
  1826. inline void Server::set_error_handler(Handler handler) {
  1827. error_handler_ = handler;
  1828. }
  1829. inline void Server::set_logger(Logger logger) { logger_ = logger; }
  1830. inline void Server::set_keep_alive_max_count(size_t count) {
  1831. keep_alive_max_count_ = count;
  1832. }
  1833. inline void Server::set_payload_max_length(size_t length) {
  1834. payload_max_length_ = length;
  1835. }
  1836. inline int Server::bind_to_any_port(const char *host, int socket_flags) {
  1837. return bind_internal(host, 0, socket_flags);
  1838. }
  1839. inline bool Server::listen_after_bind() { return listen_internal(); }
  1840. inline bool Server::listen(const char *host, int port, int socket_flags) {
  1841. if (bind_internal(host, port, socket_flags) < 0) return false;
  1842. return listen_internal();
  1843. }
  1844. inline bool Server::is_running() const { return is_running_; }
  1845. inline void Server::stop() {
  1846. if (is_running_) {
  1847. assert(svr_sock_ != INVALID_SOCKET);
  1848. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  1849. detail::shutdown_socket(sock);
  1850. detail::close_socket(sock);
  1851. }
  1852. }
  1853. inline bool Server::parse_request_line(const char *s, Request &req) {
  1854. static std::regex re("(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) "
  1855. "(([^?]+)(?:\\?(.+?))?) (HTTP/1\\.[01])\r\n");
  1856. std::cmatch m;
  1857. if (std::regex_match(s, m, re)) {
  1858. req.version = std::string(m[5]);
  1859. req.method = std::string(m[1]);
  1860. req.target = std::string(m[2]);
  1861. req.path = detail::decode_url(m[3]);
  1862. // Parse query text
  1863. auto len = std::distance(m[4].first, m[4].second);
  1864. if (len > 0) { detail::parse_query_text(m[4], req.params); }
  1865. return true;
  1866. }
  1867. return false;
  1868. }
  1869. inline bool Server::write_response(Stream &strm, bool last_connection,
  1870. const Request &req, Response &res) {
  1871. assert(res.status != -1);
  1872. if (400 <= res.status && error_handler_) { error_handler_(req, res); }
  1873. // Response line
  1874. if (!strm.write_format("HTTP/1.1 %d %s\r\n", res.status,
  1875. detail::status_message(res.status))) {
  1876. return false;
  1877. }
  1878. // Headers
  1879. if (last_connection || req.get_header_value("Connection") == "close") {
  1880. res.set_header("Connection", "close");
  1881. }
  1882. if (!last_connection && req.get_header_value("Connection") == "Keep-Alive") {
  1883. res.set_header("Connection", "Keep-Alive");
  1884. }
  1885. if (!res.has_header("Content-Type")) {
  1886. res.set_header("Content-Type", "text/plain");
  1887. }
  1888. if (!res.has_header("Accept-Ranges")) {
  1889. res.set_header("Accept-Ranges", "bytes");
  1890. }
  1891. std::string content_type;
  1892. std::string boundary;
  1893. if (req.ranges.size() > 1) {
  1894. boundary = detail::make_multipart_data_boundary();
  1895. auto it = res.headers.find("Content-Type");
  1896. if (it != res.headers.end()) {
  1897. content_type = it->second;
  1898. res.headers.erase(it);
  1899. }
  1900. res.headers.emplace("Content-Type",
  1901. "multipart/byteranges; boundary=" + boundary);
  1902. }
  1903. if (res.body.empty()) {
  1904. if (res.content_provider_resource_length > 0) {
  1905. size_t length = 0;
  1906. if (req.ranges.empty()) {
  1907. length = res.content_provider_resource_length;
  1908. } else if (req.ranges.size() == 1) {
  1909. auto offsets = detail::get_range_offset_and_length(
  1910. req, res.content_provider_resource_length, 0);
  1911. auto offset = offsets.first;
  1912. length = offsets.second;
  1913. auto content_range = detail::make_content_range_header_field(
  1914. offset, length, res.content_provider_resource_length);
  1915. res.set_header("Content-Range", content_range);
  1916. } else {
  1917. length = detail::get_multipart_ranges_data_length(req, res, boundary,
  1918. content_type);
  1919. }
  1920. res.set_header("Content-Length", std::to_string(length));
  1921. } else {
  1922. if (res.content_provider) {
  1923. res.set_header("Transfer-Encoding", "chunked");
  1924. } else {
  1925. res.set_header("Content-Length", "0");
  1926. }
  1927. }
  1928. } else {
  1929. if (req.ranges.empty()) {
  1930. ;
  1931. } else if (req.ranges.size() == 1) {
  1932. auto offsets =
  1933. detail::get_range_offset_and_length(req, res.body.size(), 0);
  1934. auto offset = offsets.first;
  1935. auto length = offsets.second;
  1936. auto content_range = detail::make_content_range_header_field(
  1937. offset, length, res.body.size());
  1938. res.set_header("Content-Range", content_range);
  1939. res.body = res.body.substr(offset, length);
  1940. } else {
  1941. res.body =
  1942. detail::make_multipart_ranges_data(req, res, boundary, content_type);
  1943. }
  1944. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1945. // TODO: 'Accpet-Encoding' has gzip, not gzip;q=0
  1946. const auto &encodings = req.get_header_value("Accept-Encoding");
  1947. if (encodings.find("gzip") != std::string::npos &&
  1948. detail::can_compress(res.get_header_value("Content-Type"))) {
  1949. if (detail::compress(res.body)) {
  1950. res.set_header("Content-Encoding", "gzip");
  1951. }
  1952. }
  1953. #endif
  1954. auto length = std::to_string(res.body.size());
  1955. res.set_header("Content-Length", length);
  1956. }
  1957. if (!detail::write_headers(strm, res, Headers())) { return false; }
  1958. // Body
  1959. if (req.method != "HEAD") {
  1960. if (!res.body.empty()) {
  1961. if (!strm.write(res.body)) { return false; }
  1962. } else if (res.content_provider) {
  1963. if (!write_content_with_provider(strm, req, res, boundary,
  1964. content_type)) {
  1965. return false;
  1966. }
  1967. }
  1968. }
  1969. // Log
  1970. if (logger_) { logger_(req, res); }
  1971. return true;
  1972. }
  1973. inline bool
  1974. Server::write_content_with_provider(Stream &strm, const Request &req,
  1975. Response &res, const std::string &boundary,
  1976. const std::string &content_type) {
  1977. if (res.content_provider_resource_length) {
  1978. if (req.ranges.empty()) {
  1979. if (detail::write_content(strm, res.content_provider, 0,
  1980. res.content_provider_resource_length) < 0) {
  1981. return false;
  1982. }
  1983. } else if (req.ranges.size() == 1) {
  1984. auto offsets = detail::get_range_offset_and_length(
  1985. req, res.content_provider_resource_length, 0);
  1986. auto offset = offsets.first;
  1987. auto length = offsets.second;
  1988. if (detail::write_content(strm, res.content_provider, offset, length) <
  1989. 0) {
  1990. return false;
  1991. }
  1992. } else {
  1993. if (!detail::write_multipart_ranges_data(strm, req, res, boundary,
  1994. content_type)) {
  1995. return false;
  1996. }
  1997. }
  1998. } else {
  1999. if (detail::write_content_chunked(strm, res.content_provider) < 0) {
  2000. return false;
  2001. }
  2002. }
  2003. return true;
  2004. }
  2005. inline bool Server::handle_file_request(Request &req, Response &res) {
  2006. if (!base_dir_.empty() && detail::is_valid_path(req.path)) {
  2007. std::string path = base_dir_ + req.path;
  2008. if (!path.empty() && path.back() == '/') { path += "index.html"; }
  2009. if (detail::is_file(path)) {
  2010. detail::read_file(path, res.body);
  2011. auto type = detail::find_content_type(path);
  2012. if (type) { res.set_header("Content-Type", type); }
  2013. res.status = 200;
  2014. if (file_request_handler_) { file_request_handler_(req, res); }
  2015. return true;
  2016. }
  2017. }
  2018. return false;
  2019. }
  2020. inline socket_t Server::create_server_socket(const char *host, int port,
  2021. int socket_flags) const {
  2022. return detail::create_socket(
  2023. host, port,
  2024. [](socket_t sock, struct addrinfo &ai) -> bool {
  2025. if (::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen))) {
  2026. return false;
  2027. }
  2028. if (::listen(sock, 5)) { // Listen through 5 channels
  2029. return false;
  2030. }
  2031. return true;
  2032. },
  2033. socket_flags);
  2034. }
  2035. inline int Server::bind_internal(const char *host, int port, int socket_flags) {
  2036. if (!is_valid()) { return -1; }
  2037. svr_sock_ = create_server_socket(host, port, socket_flags);
  2038. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  2039. if (port == 0) {
  2040. struct sockaddr_storage address;
  2041. socklen_t len = sizeof(address);
  2042. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&address),
  2043. &len) == -1) {
  2044. return -1;
  2045. }
  2046. if (address.ss_family == AF_INET) {
  2047. return ntohs(reinterpret_cast<struct sockaddr_in *>(&address)->sin_port);
  2048. } else if (address.ss_family == AF_INET6) {
  2049. return ntohs(
  2050. reinterpret_cast<struct sockaddr_in6 *>(&address)->sin6_port);
  2051. } else {
  2052. return -1;
  2053. }
  2054. } else {
  2055. return port;
  2056. }
  2057. }
  2058. inline bool Server::listen_internal() {
  2059. auto ret = true;
  2060. is_running_ = true;
  2061. {
  2062. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  2063. for (;;) {
  2064. if (svr_sock_ == INVALID_SOCKET) {
  2065. // The server socket was closed by 'stop' method.
  2066. break;
  2067. }
  2068. auto val = detail::select_read(svr_sock_, 0, 100000);
  2069. if (val == 0) { // Timeout
  2070. continue;
  2071. }
  2072. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  2073. if (sock == INVALID_SOCKET) {
  2074. if (svr_sock_ != INVALID_SOCKET) {
  2075. detail::close_socket(svr_sock_);
  2076. ret = false;
  2077. } else {
  2078. ; // The server socket was closed by user.
  2079. }
  2080. break;
  2081. }
  2082. task_queue->enqueue([=]() { process_and_close_socket(sock); });
  2083. }
  2084. task_queue->shutdown();
  2085. }
  2086. is_running_ = false;
  2087. return ret;
  2088. }
  2089. inline bool Server::routing(Request &req, Response &res) {
  2090. if (req.method == "GET" && handle_file_request(req, res)) { return true; }
  2091. if (req.method == "GET" || req.method == "HEAD") {
  2092. return dispatch_request(req, res, get_handlers_);
  2093. } else if (req.method == "POST") {
  2094. return dispatch_request(req, res, post_handlers_);
  2095. } else if (req.method == "PUT") {
  2096. return dispatch_request(req, res, put_handlers_);
  2097. } else if (req.method == "PATCH") {
  2098. return dispatch_request(req, res, patch_handlers_);
  2099. } else if (req.method == "DELETE") {
  2100. return dispatch_request(req, res, delete_handlers_);
  2101. } else if (req.method == "OPTIONS") {
  2102. return dispatch_request(req, res, options_handlers_);
  2103. }
  2104. return false;
  2105. }
  2106. inline bool Server::dispatch_request(Request &req, Response &res,
  2107. Handlers &handlers) {
  2108. for (const auto &x : handlers) {
  2109. const auto &pattern = x.first;
  2110. const auto &handler = x.second;
  2111. if (std::regex_match(req.path, req.matches, pattern)) {
  2112. handler(req, res);
  2113. return true;
  2114. }
  2115. }
  2116. return false;
  2117. }
  2118. inline bool
  2119. Server::process_request(Stream &strm, bool last_connection,
  2120. bool &connection_close,
  2121. std::function<void(Request &)> setup_request) {
  2122. const auto bufsiz = 2048;
  2123. char buf[bufsiz];
  2124. detail::stream_line_reader reader(strm, buf, bufsiz);
  2125. // Connection has been closed on client
  2126. if (!reader.getline()) { return false; }
  2127. Request req;
  2128. Response res;
  2129. res.version = "HTTP/1.1";
  2130. // Check if the request URI doesn't exceed the limit
  2131. if (reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  2132. Headers dummy;
  2133. detail::read_headers(strm, dummy);
  2134. res.status = 414;
  2135. return write_response(strm, last_connection, req, res);
  2136. }
  2137. // Request line and headers
  2138. if (!parse_request_line(reader.ptr(), req) ||
  2139. !detail::read_headers(strm, req.headers)) {
  2140. res.status = 400;
  2141. return write_response(strm, last_connection, req, res);
  2142. }
  2143. if (req.get_header_value("Connection") == "close") {
  2144. connection_close = true;
  2145. }
  2146. if (req.version == "HTTP/1.0" &&
  2147. req.get_header_value("Connection") != "Keep-Alive") {
  2148. connection_close = true;
  2149. }
  2150. req.set_header("REMOTE_ADDR", strm.get_remote_addr());
  2151. // Body
  2152. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH") {
  2153. if (!detail::read_content(strm, req, payload_max_length_, res.status,
  2154. Progress(), [&](const char *buf, size_t n) {
  2155. if (req.body.size() + n > req.body.max_size()) {
  2156. return false;
  2157. }
  2158. req.body.append(buf, n);
  2159. return true;
  2160. })) {
  2161. return write_response(strm, last_connection, req, res);
  2162. }
  2163. const auto &content_type = req.get_header_value("Content-Type");
  2164. if (!content_type.find("application/x-www-form-urlencoded")) {
  2165. detail::parse_query_text(req.body, req.params);
  2166. } else if (!content_type.find("multipart/form-data")) {
  2167. std::string boundary;
  2168. if (!detail::parse_multipart_boundary(content_type, boundary) ||
  2169. !detail::parse_multipart_formdata(boundary, req.body, req.files)) {
  2170. res.status = 400;
  2171. return write_response(strm, last_connection, req, res);
  2172. }
  2173. }
  2174. }
  2175. if (req.has_header("Range")) {
  2176. const auto &range_header_value = req.get_header_value("Range");
  2177. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  2178. // TODO: error
  2179. }
  2180. }
  2181. if (setup_request) { setup_request(req); }
  2182. if (routing(req, res)) {
  2183. if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
  2184. } else {
  2185. res.status = 404;
  2186. }
  2187. return write_response(strm, last_connection, req, res);
  2188. }
  2189. inline bool Server::is_valid() const { return true; }
  2190. inline bool Server::process_and_close_socket(socket_t sock) {
  2191. return detail::process_and_close_socket(
  2192. false, sock, keep_alive_max_count_,
  2193. [this](Stream &strm, bool last_connection, bool &connection_close) {
  2194. return process_request(strm, last_connection, connection_close,
  2195. nullptr);
  2196. });
  2197. }
  2198. // HTTP client implementation
  2199. inline Client::Client(const char *host, int port, time_t timeout_sec)
  2200. : host_(host), port_(port), timeout_sec_(timeout_sec),
  2201. host_and_port_(host_ + ":" + std::to_string(port_)),
  2202. keep_alive_max_count_(CPPHTTPLIB_KEEPALIVE_MAX_COUNT),
  2203. follow_location_(false) {}
  2204. inline Client::~Client() {}
  2205. inline bool Client::is_valid() const { return true; }
  2206. inline socket_t Client::create_client_socket() const {
  2207. return detail::create_socket(
  2208. host_.c_str(), port_, [=](socket_t sock, struct addrinfo &ai) -> bool {
  2209. detail::set_nonblocking(sock, true);
  2210. auto ret = connect(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen));
  2211. if (ret < 0) {
  2212. if (detail::is_connection_error() ||
  2213. !detail::wait_until_socket_is_ready(sock, timeout_sec_, 0)) {
  2214. detail::close_socket(sock);
  2215. return false;
  2216. }
  2217. }
  2218. detail::set_nonblocking(sock, false);
  2219. return true;
  2220. });
  2221. }
  2222. inline bool Client::read_response_line(Stream &strm, Response &res) {
  2223. const auto bufsiz = 2048;
  2224. char buf[bufsiz];
  2225. detail::stream_line_reader reader(strm, buf, bufsiz);
  2226. if (!reader.getline()) { return false; }
  2227. const static std::regex re("(HTTP/1\\.[01]) (\\d+?) .*\r\n");
  2228. std::cmatch m;
  2229. if (std::regex_match(reader.ptr(), m, re)) {
  2230. res.version = std::string(m[1]);
  2231. res.status = std::stoi(std::string(m[2]));
  2232. }
  2233. return true;
  2234. }
  2235. inline bool Client::send(const Request &req, Response &res) {
  2236. if (req.path.empty()) { return false; }
  2237. auto sock = create_client_socket();
  2238. if (sock == INVALID_SOCKET) { return false; }
  2239. auto ret = process_and_close_socket(
  2240. sock, 1, [&](Stream &strm, bool last_connection, bool &connection_close) {
  2241. return process_request(strm, req, res, last_connection,
  2242. connection_close);
  2243. });
  2244. if (ret && follow_location_ && (300 < res.status && res.status < 400)) {
  2245. ret = redirect(req, res);
  2246. }
  2247. return ret;
  2248. }
  2249. inline bool Client::send(const std::vector<Request> &requests,
  2250. std::vector<Response> &responses) {
  2251. size_t i = 0;
  2252. while (i < requests.size()) {
  2253. auto sock = create_client_socket();
  2254. if (sock == INVALID_SOCKET) { return false; }
  2255. if (!process_and_close_socket(
  2256. sock, requests.size() - i,
  2257. [&](Stream &strm, bool last_connection, bool &connection_close) -> bool {
  2258. auto &req = requests[i];
  2259. auto res = Response();
  2260. i++;
  2261. if (req.path.empty()) { return false; }
  2262. auto ret = process_request(strm, req, res, last_connection,
  2263. connection_close);
  2264. if (ret && follow_location_ &&
  2265. (300 < res.status && res.status < 400)) {
  2266. ret = redirect(req, res);
  2267. }
  2268. if (ret) { responses.emplace_back(std::move(res)); }
  2269. return ret;
  2270. })) {
  2271. return false;
  2272. }
  2273. }
  2274. return true;
  2275. }
  2276. inline bool Client::redirect(const Request &req, Response &res) {
  2277. if (req.redirect_count == 0) { return false; }
  2278. auto location = res.get_header_value("location");
  2279. if (location.empty()) { return false; }
  2280. std::regex re(
  2281. R"(^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
  2282. auto scheme = is_ssl() ? "https" : "http";
  2283. std::smatch m;
  2284. if (regex_match(location, m, re)) {
  2285. auto next_scheme = m[1].str();
  2286. auto next_host = m[2].str();
  2287. auto next_path = m[3].str();
  2288. if (next_host.empty()) { next_host = host_; }
  2289. if (next_path.empty()) { next_path = "/"; }
  2290. if (next_scheme == scheme && next_host == host_) {
  2291. return detail::redirect(*this, req, res, next_path);
  2292. } else {
  2293. if (next_scheme == "https") {
  2294. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2295. SSLClient cli(next_host.c_str());
  2296. cli.follow_location(true);
  2297. return detail::redirect(cli, req, res, next_path);
  2298. #else
  2299. return false;
  2300. #endif
  2301. } else {
  2302. Client cli(next_host.c_str());
  2303. cli.follow_location(true);
  2304. return detail::redirect(cli, req, res, next_path);
  2305. }
  2306. }
  2307. }
  2308. return false;
  2309. }
  2310. inline void Client::write_request(Stream &strm, const Request &req,
  2311. bool last_connection) {
  2312. BufferStream bstrm;
  2313. // Request line
  2314. auto path = detail::encode_url(req.path);
  2315. bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
  2316. // Additonal headers
  2317. Headers headers;
  2318. if (last_connection) { headers.emplace("Connection", "close"); }
  2319. if (!req.has_header("Host")) {
  2320. if (is_ssl()) {
  2321. if (port_ == 443) {
  2322. headers.emplace("Host", host_);
  2323. } else {
  2324. headers.emplace("Host", host_and_port_);
  2325. }
  2326. } else {
  2327. if (port_ == 80) {
  2328. headers.emplace("Host", host_);
  2329. } else {
  2330. headers.emplace("Host", host_and_port_);
  2331. }
  2332. }
  2333. }
  2334. if (!req.has_header("Accept")) { headers.emplace("Accept", "*/*"); }
  2335. if (!req.has_header("User-Agent")) {
  2336. headers.emplace("User-Agent", "cpp-httplib/0.2");
  2337. }
  2338. if (req.body.empty()) {
  2339. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH") {
  2340. headers.emplace("Content-Length", "0");
  2341. }
  2342. } else {
  2343. if (!req.has_header("Content-Type")) {
  2344. headers.emplace("Content-Type", "text/plain");
  2345. }
  2346. if (!req.has_header("Content-Length")) {
  2347. auto length = std::to_string(req.body.size());
  2348. headers.emplace("Content-Length", length);
  2349. }
  2350. }
  2351. detail::write_headers(bstrm, req, headers);
  2352. // Body
  2353. if (!req.body.empty()) { bstrm.write(req.body); }
  2354. // Flush buffer
  2355. auto &data = bstrm.get_buffer();
  2356. strm.write(data.data(), data.size());
  2357. }
  2358. inline bool Client::process_request(Stream &strm, const Request &req,
  2359. Response &res, bool last_connection,
  2360. bool &connection_close) {
  2361. // Send request
  2362. write_request(strm, req, last_connection);
  2363. // Receive response and headers
  2364. if (!read_response_line(strm, res) ||
  2365. !detail::read_headers(strm, res.headers)) {
  2366. return false;
  2367. }
  2368. if (res.get_header_value("Connection") == "close" ||
  2369. res.version == "HTTP/1.0") {
  2370. connection_close = true;
  2371. }
  2372. if (req.response_handler) {
  2373. if (!req.response_handler(res)) { return false; }
  2374. }
  2375. // Body
  2376. if (req.method != "HEAD") {
  2377. detail::ContentReceiverCore out = [&](const char *buf, size_t n) {
  2378. if (res.body.size() + n > res.body.max_size()) { return false; }
  2379. res.body.append(buf, n);
  2380. return true;
  2381. };
  2382. if (req.content_receiver) {
  2383. auto offset = std::make_shared<size_t>();
  2384. auto length = get_header_value_uint64(res.headers, "Content-Length", 0);
  2385. auto receiver = req.content_receiver;
  2386. out = [offset, length, receiver](const char *buf, size_t n) {
  2387. auto ret = receiver(buf, n, *offset, length);
  2388. (*offset) += n;
  2389. return ret;
  2390. };
  2391. }
  2392. int dummy_status;
  2393. if (!detail::read_content(strm, res, std::numeric_limits<size_t>::max(),
  2394. dummy_status, req.progress, out)) {
  2395. return false;
  2396. }
  2397. }
  2398. return true;
  2399. }
  2400. inline bool Client::process_and_close_socket(
  2401. socket_t sock, size_t request_count,
  2402. std::function<bool(Stream &strm, bool last_connection,
  2403. bool &connection_close)>
  2404. callback) {
  2405. request_count = std::min(request_count, keep_alive_max_count_);
  2406. return detail::process_and_close_socket(true, sock, request_count, callback);
  2407. }
  2408. inline bool Client::is_ssl() const { return false; }
  2409. inline std::shared_ptr<Response> Client::Get(const char *path) {
  2410. Progress dummy;
  2411. return Get(path, Headers(), dummy);
  2412. }
  2413. inline std::shared_ptr<Response> Client::Get(const char *path,
  2414. Progress progress) {
  2415. return Get(path, Headers(), progress);
  2416. }
  2417. inline std::shared_ptr<Response> Client::Get(const char *path,
  2418. const Headers &headers) {
  2419. Progress dummy;
  2420. return Get(path, headers, dummy);
  2421. }
  2422. inline std::shared_ptr<Response>
  2423. Client::Get(const char *path, const Headers &headers, Progress progress) {
  2424. Request req;
  2425. req.method = "GET";
  2426. req.path = path;
  2427. req.headers = headers;
  2428. req.progress = progress;
  2429. auto res = std::make_shared<Response>();
  2430. return send(req, *res) ? res : nullptr;
  2431. }
  2432. inline std::shared_ptr<Response> Client::Get(const char *path,
  2433. ContentReceiver content_receiver) {
  2434. Progress dummy;
  2435. return Get(path, Headers(), nullptr, content_receiver, dummy);
  2436. }
  2437. inline std::shared_ptr<Response> Client::Get(const char *path,
  2438. ContentReceiver content_receiver,
  2439. Progress progress) {
  2440. return Get(path, Headers(), nullptr, content_receiver, progress);
  2441. }
  2442. inline std::shared_ptr<Response> Client::Get(const char *path,
  2443. const Headers &headers,
  2444. ContentReceiver content_receiver) {
  2445. Progress dummy;
  2446. return Get(path, headers, nullptr, content_receiver, dummy);
  2447. }
  2448. inline std::shared_ptr<Response> Client::Get(const char *path,
  2449. const Headers &headers,
  2450. ContentReceiver content_receiver,
  2451. Progress progress) {
  2452. return Get(path, headers, nullptr, content_receiver, progress);
  2453. }
  2454. inline std::shared_ptr<Response> Client::Get(const char *path,
  2455. const Headers &headers,
  2456. ResponseHandler response_handler,
  2457. ContentReceiver content_receiver) {
  2458. Progress dummy;
  2459. return Get(path, headers, response_handler, content_receiver, dummy);
  2460. }
  2461. inline std::shared_ptr<Response> Client::Get(const char *path,
  2462. const Headers &headers,
  2463. ResponseHandler response_handler,
  2464. ContentReceiver content_receiver,
  2465. Progress progress) {
  2466. Request req;
  2467. req.method = "GET";
  2468. req.path = path;
  2469. req.headers = headers;
  2470. req.response_handler = response_handler;
  2471. req.content_receiver = content_receiver;
  2472. req.progress = progress;
  2473. auto res = std::make_shared<Response>();
  2474. return send(req, *res) ? res : nullptr;
  2475. }
  2476. inline std::shared_ptr<Response> Client::Head(const char *path) {
  2477. return Head(path, Headers());
  2478. }
  2479. inline std::shared_ptr<Response> Client::Head(const char *path,
  2480. const Headers &headers) {
  2481. Request req;
  2482. req.method = "HEAD";
  2483. req.headers = headers;
  2484. req.path = path;
  2485. auto res = std::make_shared<Response>();
  2486. return send(req, *res) ? res : nullptr;
  2487. }
  2488. inline std::shared_ptr<Response> Client::Post(const char *path,
  2489. const std::string &body,
  2490. const char *content_type) {
  2491. return Post(path, Headers(), body, content_type);
  2492. }
  2493. inline std::shared_ptr<Response> Client::Post(const char *path,
  2494. const Headers &headers,
  2495. const std::string &body,
  2496. const char *content_type) {
  2497. Request req;
  2498. req.method = "POST";
  2499. req.headers = headers;
  2500. req.path = path;
  2501. req.headers.emplace("Content-Type", content_type);
  2502. req.body = body;
  2503. auto res = std::make_shared<Response>();
  2504. return send(req, *res) ? res : nullptr;
  2505. }
  2506. inline std::shared_ptr<Response> Client::Post(const char *path,
  2507. const Params &params) {
  2508. return Post(path, Headers(), params);
  2509. }
  2510. inline std::shared_ptr<Response>
  2511. Client::Post(const char *path, const Headers &headers, const Params &params) {
  2512. std::string query;
  2513. for (auto it = params.begin(); it != params.end(); ++it) {
  2514. if (it != params.begin()) { query += "&"; }
  2515. query += it->first;
  2516. query += "=";
  2517. query += detail::encode_url(it->second);
  2518. }
  2519. return Post(path, headers, query, "application/x-www-form-urlencoded");
  2520. }
  2521. inline std::shared_ptr<Response>
  2522. Client::Post(const char *path, const MultipartFormDataItems &items) {
  2523. return Post(path, Headers(), items);
  2524. }
  2525. inline std::shared_ptr<Response>
  2526. Client::Post(const char *path, const Headers &headers,
  2527. const MultipartFormDataItems &items) {
  2528. Request req;
  2529. req.method = "POST";
  2530. req.headers = headers;
  2531. req.path = path;
  2532. auto boundary = detail::make_multipart_data_boundary();
  2533. req.headers.emplace("Content-Type",
  2534. "multipart/form-data; boundary=" + boundary);
  2535. for (const auto &item : items) {
  2536. req.body += "--" + boundary + "\r\n";
  2537. req.body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2538. if (!item.filename.empty()) {
  2539. req.body += "; filename=\"" + item.filename + "\"";
  2540. }
  2541. req.body += "\r\n";
  2542. if (!item.content_type.empty()) {
  2543. req.body += "Content-Type: " + item.content_type + "\r\n";
  2544. }
  2545. req.body += "\r\n";
  2546. req.body += item.content + "\r\n";
  2547. }
  2548. req.body += "--" + boundary + "--\r\n";
  2549. auto res = std::make_shared<Response>();
  2550. return send(req, *res) ? res : nullptr;
  2551. }
  2552. inline std::shared_ptr<Response> Client::Put(const char *path,
  2553. const std::string &body,
  2554. const char *content_type) {
  2555. return Put(path, Headers(), body, content_type);
  2556. }
  2557. inline std::shared_ptr<Response> Client::Put(const char *path,
  2558. const Headers &headers,
  2559. const std::string &body,
  2560. const char *content_type) {
  2561. Request req;
  2562. req.method = "PUT";
  2563. req.headers = headers;
  2564. req.path = path;
  2565. req.headers.emplace("Content-Type", content_type);
  2566. req.body = body;
  2567. auto res = std::make_shared<Response>();
  2568. return send(req, *res) ? res : nullptr;
  2569. }
  2570. inline std::shared_ptr<Response> Client::Patch(const char *path,
  2571. const std::string &body,
  2572. const char *content_type) {
  2573. return Patch(path, Headers(), body, content_type);
  2574. }
  2575. inline std::shared_ptr<Response> Client::Patch(const char *path,
  2576. const Headers &headers,
  2577. const std::string &body,
  2578. const char *content_type) {
  2579. Request req;
  2580. req.method = "PATCH";
  2581. req.headers = headers;
  2582. req.path = path;
  2583. req.headers.emplace("Content-Type", content_type);
  2584. req.body = body;
  2585. auto res = std::make_shared<Response>();
  2586. return send(req, *res) ? res : nullptr;
  2587. }
  2588. inline std::shared_ptr<Response> Client::Delete(const char *path) {
  2589. return Delete(path, Headers(), std::string(), nullptr);
  2590. }
  2591. inline std::shared_ptr<Response> Client::Delete(const char *path,
  2592. const std::string &body,
  2593. const char *content_type) {
  2594. return Delete(path, Headers(), body, content_type);
  2595. }
  2596. inline std::shared_ptr<Response> Client::Delete(const char *path,
  2597. const Headers &headers) {
  2598. return Delete(path, headers, std::string(), nullptr);
  2599. }
  2600. inline std::shared_ptr<Response> Client::Delete(const char *path,
  2601. const Headers &headers,
  2602. const std::string &body,
  2603. const char *content_type) {
  2604. Request req;
  2605. req.method = "DELETE";
  2606. req.headers = headers;
  2607. req.path = path;
  2608. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  2609. req.body = body;
  2610. auto res = std::make_shared<Response>();
  2611. return send(req, *res) ? res : nullptr;
  2612. }
  2613. inline std::shared_ptr<Response> Client::Options(const char *path) {
  2614. return Options(path, Headers());
  2615. }
  2616. inline std::shared_ptr<Response> Client::Options(const char *path,
  2617. const Headers &headers) {
  2618. Request req;
  2619. req.method = "OPTIONS";
  2620. req.path = path;
  2621. req.headers = headers;
  2622. auto res = std::make_shared<Response>();
  2623. return send(req, *res) ? res : nullptr;
  2624. }
  2625. inline void Client::set_keep_alive_max_count(size_t count) {
  2626. keep_alive_max_count_ = count;
  2627. }
  2628. inline void Client::follow_location(bool on) { follow_location_ = on; }
  2629. /*
  2630. * SSL Implementation
  2631. */
  2632. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2633. namespace detail {
  2634. template <typename U, typename V, typename T>
  2635. inline bool process_and_close_socket_ssl(bool is_client_request, socket_t sock,
  2636. size_t keep_alive_max_count,
  2637. SSL_CTX *ctx, std::mutex &ctx_mutex,
  2638. U SSL_connect_or_accept, V setup,
  2639. T callback) {
  2640. assert(keep_alive_max_count > 0);
  2641. SSL *ssl = nullptr;
  2642. {
  2643. std::lock_guard<std::mutex> guard(ctx_mutex);
  2644. ssl = SSL_new(ctx);
  2645. }
  2646. if (!ssl) {
  2647. close_socket(sock);
  2648. return false;
  2649. }
  2650. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  2651. SSL_set_bio(ssl, bio, bio);
  2652. if (!setup(ssl)) {
  2653. SSL_shutdown(ssl);
  2654. {
  2655. std::lock_guard<std::mutex> guard(ctx_mutex);
  2656. SSL_free(ssl);
  2657. }
  2658. close_socket(sock);
  2659. return false;
  2660. }
  2661. bool ret = false;
  2662. if (SSL_connect_or_accept(ssl) == 1) {
  2663. if (keep_alive_max_count > 1) {
  2664. auto count = keep_alive_max_count;
  2665. while (count > 0 &&
  2666. (is_client_request ||
  2667. detail::select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  2668. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
  2669. SSLSocketStream strm(sock, ssl);
  2670. auto last_connection = count == 1;
  2671. auto connection_close = false;
  2672. ret = callback(ssl, strm, last_connection, connection_close);
  2673. if (!ret || connection_close) { break; }
  2674. count--;
  2675. }
  2676. } else {
  2677. SSLSocketStream strm(sock, ssl);
  2678. auto dummy_connection_close = false;
  2679. ret = callback(ssl, strm, true, dummy_connection_close);
  2680. }
  2681. }
  2682. SSL_shutdown(ssl);
  2683. {
  2684. std::lock_guard<std::mutex> guard(ctx_mutex);
  2685. SSL_free(ssl);
  2686. }
  2687. close_socket(sock);
  2688. return ret;
  2689. }
  2690. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  2691. static std::shared_ptr<std::vector<std::mutex>> openSSL_locks_;
  2692. class SSLThreadLocks {
  2693. public:
  2694. SSLThreadLocks() {
  2695. openSSL_locks_ =
  2696. std::make_shared<std::vector<std::mutex>>(CRYPTO_num_locks());
  2697. CRYPTO_set_locking_callback(locking_callback);
  2698. }
  2699. ~SSLThreadLocks() { CRYPTO_set_locking_callback(nullptr); }
  2700. private:
  2701. static void locking_callback(int mode, int type, const char * /*file*/,
  2702. int /*line*/) {
  2703. auto &locks = *openSSL_locks_;
  2704. if (mode & CRYPTO_LOCK) {
  2705. locks[type].lock();
  2706. } else {
  2707. locks[type].unlock();
  2708. }
  2709. }
  2710. };
  2711. #endif
  2712. class SSLInit {
  2713. public:
  2714. SSLInit() {
  2715. SSL_load_error_strings();
  2716. SSL_library_init();
  2717. }
  2718. ~SSLInit() { ERR_free_strings(); }
  2719. private:
  2720. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  2721. SSLThreadLocks thread_init_;
  2722. #endif
  2723. };
  2724. static SSLInit sslinit_;
  2725. } // namespace detail
  2726. // SSL socket stream implementation
  2727. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl)
  2728. : sock_(sock), ssl_(ssl) {}
  2729. inline SSLSocketStream::~SSLSocketStream() {}
  2730. inline int SSLSocketStream::read(char *ptr, size_t size) {
  2731. if (SSL_pending(ssl_) > 0 ||
  2732. detail::select_read(sock_, CPPHTTPLIB_READ_TIMEOUT_SECOND,
  2733. CPPHTTPLIB_READ_TIMEOUT_USECOND) > 0) {
  2734. return SSL_read(ssl_, ptr, static_cast<int>(size));
  2735. }
  2736. return -1;
  2737. }
  2738. inline int SSLSocketStream::write(const char *ptr, size_t size) {
  2739. return SSL_write(ssl_, ptr, static_cast<int>(size));
  2740. }
  2741. inline int SSLSocketStream::write(const char *ptr) {
  2742. return write(ptr, strlen(ptr));
  2743. }
  2744. inline int SSLSocketStream::write(const std::string &s) {
  2745. return write(s.data(), s.size());
  2746. }
  2747. inline std::string SSLSocketStream::get_remote_addr() const {
  2748. return detail::get_remote_addr(sock_);
  2749. }
  2750. // SSL HTTP server implementation
  2751. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  2752. const char *client_ca_cert_file_path,
  2753. const char *client_ca_cert_dir_path) {
  2754. ctx_ = SSL_CTX_new(SSLv23_server_method());
  2755. if (ctx_) {
  2756. SSL_CTX_set_options(ctx_,
  2757. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  2758. SSL_OP_NO_COMPRESSION |
  2759. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  2760. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  2761. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  2762. // EC_KEY_free(ecdh);
  2763. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  2764. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  2765. 1) {
  2766. SSL_CTX_free(ctx_);
  2767. ctx_ = nullptr;
  2768. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  2769. // if (client_ca_cert_file_path) {
  2770. // auto list = SSL_load_client_CA_file(client_ca_cert_file_path);
  2771. // SSL_CTX_set_client_CA_list(ctx_, list);
  2772. // }
  2773. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  2774. client_ca_cert_dir_path);
  2775. SSL_CTX_set_verify(
  2776. ctx_,
  2777. SSL_VERIFY_PEER |
  2778. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  2779. nullptr);
  2780. }
  2781. }
  2782. }
  2783. inline SSLServer::~SSLServer() {
  2784. if (ctx_) { SSL_CTX_free(ctx_); }
  2785. }
  2786. inline bool SSLServer::is_valid() const { return ctx_; }
  2787. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  2788. return detail::process_and_close_socket_ssl(
  2789. false, sock, keep_alive_max_count_, ctx_, ctx_mutex_, SSL_accept,
  2790. [](SSL * /*ssl*/) { return true; },
  2791. [this](SSL *ssl, Stream &strm, bool last_connection,
  2792. bool &connection_close) {
  2793. return process_request(strm, last_connection, connection_close,
  2794. [&](Request &req) { req.ssl = ssl; });
  2795. });
  2796. }
  2797. // SSL HTTP client implementation
  2798. inline SSLClient::SSLClient(const char *host, int port, time_t timeout_sec,
  2799. const char *client_cert_path,
  2800. const char *client_key_path)
  2801. : Client(host, port, timeout_sec) {
  2802. ctx_ = SSL_CTX_new(SSLv23_client_method());
  2803. detail::split(&host_[0], &host_[host_.size()], '.',
  2804. [&](const char *b, const char *e) {
  2805. host_components_.emplace_back(std::string(b, e));
  2806. });
  2807. if (client_cert_path && client_key_path) {
  2808. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path,
  2809. SSL_FILETYPE_PEM) != 1 ||
  2810. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path, SSL_FILETYPE_PEM) !=
  2811. 1) {
  2812. SSL_CTX_free(ctx_);
  2813. ctx_ = nullptr;
  2814. }
  2815. }
  2816. }
  2817. inline SSLClient::~SSLClient() {
  2818. if (ctx_) { SSL_CTX_free(ctx_); }
  2819. }
  2820. inline bool SSLClient::is_valid() const { return ctx_; }
  2821. inline void SSLClient::set_ca_cert_path(const char *ca_cert_file_path,
  2822. const char *ca_cert_dir_path) {
  2823. if (ca_cert_file_path) { ca_cert_file_path_ = ca_cert_file_path; }
  2824. if (ca_cert_dir_path) { ca_cert_dir_path_ = ca_cert_dir_path; }
  2825. }
  2826. inline void SSLClient::enable_server_certificate_verification(bool enabled) {
  2827. server_certificate_verification_ = enabled;
  2828. }
  2829. inline long SSLClient::get_openssl_verify_result() const {
  2830. return verify_result_;
  2831. }
  2832. inline SSL_CTX* SSLClient::ssl_context() const noexcept {
  2833. return ctx_;
  2834. }
  2835. inline bool SSLClient::process_and_close_socket(
  2836. socket_t sock, size_t request_count,
  2837. std::function<bool(Stream &strm, bool last_connection,
  2838. bool &connection_close)>
  2839. callback) {
  2840. request_count = std::min(request_count, keep_alive_max_count_);
  2841. return is_valid() &&
  2842. detail::process_and_close_socket_ssl(
  2843. true, sock, request_count, ctx_, ctx_mutex_,
  2844. [&](SSL *ssl) {
  2845. if (ca_cert_file_path_.empty()) {
  2846. SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, nullptr);
  2847. } else {
  2848. if (!SSL_CTX_load_verify_locations(
  2849. ctx_, ca_cert_file_path_.c_str(), nullptr)) {
  2850. return false;
  2851. }
  2852. SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER, nullptr);
  2853. }
  2854. if (SSL_connect(ssl) != 1) { return false; }
  2855. if (server_certificate_verification_) {
  2856. verify_result_ = SSL_get_verify_result(ssl);
  2857. if (verify_result_ != X509_V_OK) { return false; }
  2858. auto server_cert = SSL_get_peer_certificate(ssl);
  2859. if (server_cert == nullptr) { return false; }
  2860. if (!verify_host(server_cert)) {
  2861. X509_free(server_cert);
  2862. return false;
  2863. }
  2864. X509_free(server_cert);
  2865. }
  2866. return true;
  2867. },
  2868. [&](SSL *ssl) {
  2869. SSL_set_tlsext_host_name(ssl, host_.c_str());
  2870. return true;
  2871. },
  2872. [&](SSL * /*ssl*/, Stream &strm, bool last_connection,
  2873. bool &connection_close) {
  2874. return callback(strm, last_connection, connection_close);
  2875. });
  2876. }
  2877. inline bool SSLClient::is_ssl() const { return true; }
  2878. inline bool SSLClient::verify_host(X509 *server_cert) const {
  2879. /* Quote from RFC2818 section 3.1 "Server Identity"
  2880. If a subjectAltName extension of type dNSName is present, that MUST
  2881. be used as the identity. Otherwise, the (most specific) Common Name
  2882. field in the Subject field of the certificate MUST be used. Although
  2883. the use of the Common Name is existing practice, it is deprecated and
  2884. Certification Authorities are encouraged to use the dNSName instead.
  2885. Matching is performed using the matching rules specified by
  2886. [RFC2459]. If more than one identity of a given type is present in
  2887. the certificate (e.g., more than one dNSName name, a match in any one
  2888. of the set is considered acceptable.) Names may contain the wildcard
  2889. character * which is considered to match any single domain name
  2890. component or component fragment. E.g., *.a.com matches foo.a.com but
  2891. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  2892. In some cases, the URI is specified as an IP address rather than a
  2893. hostname. In this case, the iPAddress subjectAltName must be present
  2894. in the certificate and must exactly match the IP in the URI.
  2895. */
  2896. return verify_host_with_subject_alt_name(server_cert) ||
  2897. verify_host_with_common_name(server_cert);
  2898. }
  2899. inline bool
  2900. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  2901. auto ret = false;
  2902. auto type = GEN_DNS;
  2903. struct in6_addr addr6;
  2904. struct in_addr addr;
  2905. size_t addr_len = 0;
  2906. #ifndef __MINGW32__
  2907. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  2908. type = GEN_IPADD;
  2909. addr_len = sizeof(struct in6_addr);
  2910. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  2911. type = GEN_IPADD;
  2912. addr_len = sizeof(struct in_addr);
  2913. }
  2914. #endif
  2915. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  2916. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  2917. if (alt_names) {
  2918. auto dsn_matched = false;
  2919. auto ip_mached = false;
  2920. auto count = sk_GENERAL_NAME_num(alt_names);
  2921. for (auto i = 0; i < count && !dsn_matched; i++) {
  2922. auto val = sk_GENERAL_NAME_value(alt_names, i);
  2923. if (val->type == type) {
  2924. auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);
  2925. auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);
  2926. if (strlen(name) == name_len) {
  2927. switch (type) {
  2928. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  2929. case GEN_IPADD:
  2930. if (!memcmp(&addr6, name, addr_len) ||
  2931. !memcmp(&addr, name, addr_len)) {
  2932. ip_mached = true;
  2933. }
  2934. break;
  2935. }
  2936. }
  2937. }
  2938. }
  2939. if (dsn_matched || ip_mached) { ret = true; }
  2940. }
  2941. GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);
  2942. return ret;
  2943. }
  2944. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  2945. const auto subject_name = X509_get_subject_name(server_cert);
  2946. if (subject_name != nullptr) {
  2947. char name[BUFSIZ];
  2948. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  2949. name, sizeof(name));
  2950. if (name_len != -1) { return check_host_name(name, name_len); }
  2951. }
  2952. return false;
  2953. }
  2954. inline bool SSLClient::check_host_name(const char *pattern,
  2955. size_t pattern_len) const {
  2956. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  2957. // Wildcard match
  2958. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  2959. std::vector<std::string> pattern_components;
  2960. detail::split(&pattern[0], &pattern[pattern_len], '.',
  2961. [&](const char *b, const char *e) {
  2962. pattern_components.emplace_back(std::string(b, e));
  2963. });
  2964. if (host_components_.size() != pattern_components.size()) { return false; }
  2965. auto itr = pattern_components.begin();
  2966. for (const auto &h : host_components_) {
  2967. auto &p = *itr;
  2968. if (p != h && p != "*") {
  2969. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  2970. !p.compare(0, p.size() - 1, h));
  2971. if (!partial_match) { return false; }
  2972. }
  2973. ++itr;
  2974. }
  2975. return true;
  2976. }
  2977. #endif
  2978. } // namespace httplib
  2979. #endif // CPPHTTPLIB_HTTPLIB_H