httplib.h 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2020 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. /*
  10. * Configuration
  11. */
  12. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  13. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  14. #endif
  15. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND
  16. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  17. #endif
  18. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  19. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  20. #endif
  21. #ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND
  22. #define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
  23. #endif
  24. #ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND
  25. #define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
  26. #endif
  27. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  28. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  29. #endif
  30. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  31. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  32. #endif
  33. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  34. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (std::numeric_limits<size_t>::max)()
  35. #endif
  36. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  37. #define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
  38. #endif
  39. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  40. // if hardware_concurrency() outputs 0 we still wants to use threads for this.
  41. // -1 because we have one thread already in the main function.
  42. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  43. (std::thread::hardware_concurrency() \
  44. ? std::thread::hardware_concurrency() - 1 \
  45. : 2)
  46. #endif
  47. /*
  48. * Headers
  49. */
  50. #ifdef _WIN32
  51. #ifndef _CRT_SECURE_NO_WARNINGS
  52. #define _CRT_SECURE_NO_WARNINGS
  53. #endif //_CRT_SECURE_NO_WARNINGS
  54. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  55. #define _CRT_NONSTDC_NO_DEPRECATE
  56. #endif //_CRT_NONSTDC_NO_DEPRECATE
  57. #if defined(_MSC_VER)
  58. #ifdef _WIN64
  59. using ssize_t = __int64;
  60. #else
  61. using ssize_t = int;
  62. #endif
  63. #if _MSC_VER < 1900
  64. #define snprintf _snprintf_s
  65. #endif
  66. #endif // _MSC_VER
  67. #ifndef S_ISREG
  68. #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
  69. #endif // S_ISREG
  70. #ifndef S_ISDIR
  71. #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
  72. #endif // S_ISDIR
  73. #ifndef NOMINMAX
  74. #define NOMINMAX
  75. #endif // NOMINMAX
  76. #include <io.h>
  77. #include <winsock2.h>
  78. #include <ws2tcpip.h>
  79. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  80. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  81. #endif
  82. #ifdef _MSC_VER
  83. #pragma comment(lib, "ws2_32.lib")
  84. #endif
  85. #ifndef strcasecmp
  86. #define strcasecmp _stricmp
  87. #endif // strcasecmp
  88. using socket_t = SOCKET;
  89. #ifdef CPPHTTPLIB_USE_POLL
  90. #define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
  91. #endif
  92. #else // not _WIN32
  93. #include <arpa/inet.h>
  94. #include <cstring>
  95. #include <ifaddrs.h>
  96. #include <netdb.h>
  97. #include <netinet/in.h>
  98. #ifdef CPPHTTPLIB_USE_POLL
  99. #include <poll.h>
  100. #endif
  101. #include <csignal>
  102. #include <pthread.h>
  103. #include <sys/select.h>
  104. #include <sys/socket.h>
  105. #include <unistd.h>
  106. using socket_t = int;
  107. #define INVALID_SOCKET (-1)
  108. #endif //_WIN32
  109. #include <array>
  110. #include <atomic>
  111. #include <cassert>
  112. #include <condition_variable>
  113. #include <errno.h>
  114. #include <fcntl.h>
  115. #include <fstream>
  116. #include <functional>
  117. #include <list>
  118. #include <map>
  119. #include <memory>
  120. #include <mutex>
  121. #include <random>
  122. #include <regex>
  123. #include <string>
  124. #include <sys/stat.h>
  125. #include <thread>
  126. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  127. #include <openssl/err.h>
  128. #include <openssl/md5.h>
  129. #include <openssl/ssl.h>
  130. #include <openssl/x509v3.h>
  131. #include <iomanip>
  132. #include <sstream>
  133. // #if OPENSSL_VERSION_NUMBER < 0x1010100fL
  134. // #error Sorry, OpenSSL versions prior to 1.1.1 are not supported
  135. // #endif
  136. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  137. #include <openssl/crypto.h>
  138. inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
  139. return M_ASN1_STRING_data(asn1);
  140. }
  141. #endif
  142. #endif
  143. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  144. #include <zlib.h>
  145. #endif
  146. /*
  147. * Declaration
  148. */
  149. namespace httplib {
  150. namespace detail {
  151. struct ci {
  152. bool operator()(const std::string &s1, const std::string &s2) const {
  153. return std::lexicographical_compare(
  154. s1.begin(), s1.end(), s2.begin(), s2.end(),
  155. [](char c1, char c2) { return ::tolower(c1) < ::tolower(c2); });
  156. }
  157. };
  158. } // namespace detail
  159. using Headers = std::multimap<std::string, std::string, detail::ci>;
  160. using Params = std::multimap<std::string, std::string>;
  161. using Match = std::smatch;
  162. using Progress = std::function<bool(uint64_t current, uint64_t total)>;
  163. struct Response;
  164. using ResponseHandler = std::function<bool(const Response &response)>;
  165. struct MultipartFormData {
  166. std::string name;
  167. std::string content;
  168. std::string filename;
  169. std::string content_type;
  170. };
  171. using MultipartFormDataItems = std::vector<MultipartFormData>;
  172. using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
  173. class DataSink {
  174. public:
  175. DataSink() = default;
  176. DataSink(const DataSink &) = delete;
  177. DataSink &operator=(const DataSink &) = delete;
  178. DataSink(DataSink &&) = delete;
  179. DataSink &operator=(DataSink &&) = delete;
  180. std::function<void(const char *data, size_t data_len)> write;
  181. std::function<void()> done;
  182. std::function<bool()> is_writable;
  183. };
  184. using ContentProvider =
  185. std::function<void(size_t offset, size_t length, DataSink &sink)>;
  186. using ContentReceiver =
  187. std::function<bool(const char *data, size_t data_length)>;
  188. using MultipartContentHeader =
  189. std::function<bool(const MultipartFormData &file)>;
  190. class ContentReader {
  191. public:
  192. using Reader = std::function<bool(ContentReceiver receiver)>;
  193. using MultipartReader = std::function<bool(MultipartContentHeader header,
  194. ContentReceiver receiver)>;
  195. ContentReader(Reader reader, MultipartReader muitlpart_reader)
  196. : reader_(reader), muitlpart_reader_(muitlpart_reader) {}
  197. bool operator()(MultipartContentHeader header,
  198. ContentReceiver receiver) const {
  199. return muitlpart_reader_(header, receiver);
  200. }
  201. bool operator()(ContentReceiver receiver) const { return reader_(receiver); }
  202. Reader reader_;
  203. MultipartReader muitlpart_reader_;
  204. };
  205. using Range = std::pair<ssize_t, ssize_t>;
  206. using Ranges = std::vector<Range>;
  207. struct Request {
  208. std::string method;
  209. std::string path;
  210. Headers headers;
  211. std::string body;
  212. // for server
  213. std::string version;
  214. std::string target;
  215. Params params;
  216. MultipartFormDataMap files;
  217. Ranges ranges;
  218. Match matches;
  219. // for client
  220. size_t redirect_count = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  221. ResponseHandler response_handler;
  222. ContentReceiver content_receiver;
  223. Progress progress;
  224. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  225. const SSL *ssl;
  226. #endif
  227. bool has_header(const char *key) const;
  228. std::string get_header_value(const char *key, size_t id = 0) const;
  229. size_t get_header_value_count(const char *key) const;
  230. void set_header(const char *key, const char *val);
  231. void set_header(const char *key, const std::string &val);
  232. bool has_param(const char *key) const;
  233. std::string get_param_value(const char *key, size_t id = 0) const;
  234. size_t get_param_value_count(const char *key) const;
  235. bool is_multipart_form_data() const;
  236. bool has_file(const char *key) const;
  237. MultipartFormData get_file_value(const char *key) const;
  238. // private members...
  239. size_t content_length;
  240. ContentProvider content_provider;
  241. };
  242. struct Response {
  243. std::string version;
  244. int status = -1;
  245. Headers headers;
  246. std::string body;
  247. bool has_header(const char *key) const;
  248. std::string get_header_value(const char *key, size_t id = 0) const;
  249. size_t get_header_value_count(const char *key) const;
  250. void set_header(const char *key, const char *val);
  251. void set_header(const char *key, const std::string &val);
  252. void set_redirect(const char *url);
  253. void set_content(const char *s, size_t n, const char *content_type);
  254. void set_content(const std::string &s, const char *content_type);
  255. void set_content_provider(
  256. size_t length,
  257. std::function<void(size_t offset, size_t length, DataSink &sink)>
  258. provider,
  259. std::function<void()> resource_releaser = [] {});
  260. void set_chunked_content_provider(
  261. std::function<void(size_t offset, DataSink &sink)> provider,
  262. std::function<void()> resource_releaser = [] {});
  263. Response() = default;
  264. Response(const Response &) = default;
  265. Response &operator=(const Response &) = default;
  266. Response(Response &&) = default;
  267. Response &operator=(Response &&) = default;
  268. ~Response() {
  269. if (content_provider_resource_releaser) {
  270. content_provider_resource_releaser();
  271. }
  272. }
  273. // private members...
  274. size_t content_length = 0;
  275. ContentProvider content_provider;
  276. std::function<void()> content_provider_resource_releaser;
  277. };
  278. class Stream {
  279. public:
  280. virtual ~Stream() = default;
  281. virtual bool is_readable() const = 0;
  282. virtual bool is_writable() const = 0;
  283. virtual int read(char *ptr, size_t size) = 0;
  284. virtual int write(const char *ptr, size_t size) = 0;
  285. virtual std::string get_remote_addr() const = 0;
  286. template <typename... Args>
  287. int write_format(const char *fmt, const Args &... args);
  288. int write(const char *ptr);
  289. int write(const std::string &s);
  290. };
  291. class TaskQueue {
  292. public:
  293. TaskQueue() = default;
  294. virtual ~TaskQueue() = default;
  295. virtual void enqueue(std::function<void()> fn) = 0;
  296. virtual void shutdown() = 0;
  297. };
  298. class ThreadPool : public TaskQueue {
  299. public:
  300. explicit ThreadPool(size_t n) : shutdown_(false) {
  301. while (n) {
  302. threads_.emplace_back(worker(*this));
  303. n--;
  304. }
  305. }
  306. ThreadPool(const ThreadPool &) = delete;
  307. ~ThreadPool() override = default;
  308. void enqueue(std::function<void()> fn) override {
  309. std::unique_lock<std::mutex> lock(mutex_);
  310. jobs_.push_back(fn);
  311. cond_.notify_one();
  312. }
  313. void shutdown() override {
  314. // Stop all worker threads...
  315. {
  316. std::unique_lock<std::mutex> lock(mutex_);
  317. shutdown_ = true;
  318. }
  319. cond_.notify_all();
  320. // Join...
  321. for (auto &t : threads_) {
  322. t.join();
  323. }
  324. }
  325. private:
  326. struct worker {
  327. explicit worker(ThreadPool &pool) : pool_(pool) {}
  328. void operator()() {
  329. for (;;) {
  330. std::function<void()> fn;
  331. {
  332. std::unique_lock<std::mutex> lock(pool_.mutex_);
  333. pool_.cond_.wait(
  334. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  335. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  336. fn = pool_.jobs_.front();
  337. pool_.jobs_.pop_front();
  338. }
  339. assert(true == static_cast<bool>(fn));
  340. fn();
  341. }
  342. }
  343. ThreadPool &pool_;
  344. };
  345. friend struct worker;
  346. std::vector<std::thread> threads_;
  347. std::list<std::function<void()>> jobs_;
  348. bool shutdown_;
  349. std::condition_variable cond_;
  350. std::mutex mutex_;
  351. };
  352. using Logger = std::function<void(const Request &, const Response &)>;
  353. class Server {
  354. public:
  355. using Handler = std::function<void(const Request &, Response &)>;
  356. using HandlerWithContentReader = std::function<void(
  357. const Request &, Response &, const ContentReader &content_reader)>;
  358. Server();
  359. virtual ~Server();
  360. virtual bool is_valid() const;
  361. Server &Get(const char *pattern, Handler handler);
  362. Server &Post(const char *pattern, Handler handler);
  363. Server &Post(const char *pattern, HandlerWithContentReader handler);
  364. Server &Put(const char *pattern, Handler handler);
  365. Server &Put(const char *pattern, HandlerWithContentReader handler);
  366. Server &Patch(const char *pattern, Handler handler);
  367. Server &Patch(const char *pattern, HandlerWithContentReader handler);
  368. Server &Delete(const char *pattern, Handler handler);
  369. Server &Options(const char *pattern, Handler handler);
  370. [[deprecated]] bool set_base_dir(const char *dir,
  371. const char *mount_point = nullptr);
  372. bool set_mount_point(const char *mount_point, const char *dir);
  373. bool remove_mount_point(const char *mount_point);
  374. void set_file_extension_and_mimetype_mapping(const char *ext,
  375. const char *mime);
  376. void set_file_request_handler(Handler handler);
  377. void set_error_handler(Handler handler);
  378. void set_logger(Logger logger);
  379. void set_keep_alive_max_count(size_t count);
  380. void set_read_timeout(time_t sec, time_t usec);
  381. void set_payload_max_length(size_t length);
  382. bool bind_to_port(const char *host, int port, int socket_flags = 0);
  383. int bind_to_any_port(const char *host, int socket_flags = 0);
  384. bool listen_after_bind();
  385. bool listen(const char *host, int port, int socket_flags = 0);
  386. bool is_running() const;
  387. void stop();
  388. std::function<TaskQueue *(void)> new_task_queue;
  389. protected:
  390. bool process_request(Stream &strm, bool last_connection,
  391. bool &connection_close,
  392. const std::function<void(Request &)> &setup_request);
  393. size_t keep_alive_max_count_;
  394. time_t read_timeout_sec_;
  395. time_t read_timeout_usec_;
  396. size_t payload_max_length_;
  397. private:
  398. using Handlers = std::vector<std::pair<std::regex, Handler>>;
  399. using HandlersForContentReader =
  400. std::vector<std::pair<std::regex, HandlerWithContentReader>>;
  401. socket_t create_server_socket(const char *host, int port,
  402. int socket_flags) const;
  403. int bind_internal(const char *host, int port, int socket_flags);
  404. bool listen_internal();
  405. bool routing(Request &req, Response &res, Stream &strm, bool last_connection);
  406. bool handle_file_request(Request &req, Response &res, bool head = false);
  407. bool dispatch_request(Request &req, Response &res, Handlers &handlers);
  408. bool dispatch_request_for_content_reader(Request &req, Response &res,
  409. ContentReader content_reader,
  410. HandlersForContentReader &handlers);
  411. bool parse_request_line(const char *s, Request &req);
  412. bool write_response(Stream &strm, bool last_connection, const Request &req,
  413. Response &res);
  414. bool write_content_with_provider(Stream &strm, const Request &req,
  415. Response &res, const std::string &boundary,
  416. const std::string &content_type);
  417. bool read_content(Stream &strm, bool last_connection, Request &req,
  418. Response &res);
  419. bool read_content_with_content_receiver(
  420. Stream &strm, bool last_connection, Request &req, Response &res,
  421. ContentReceiver receiver, MultipartContentHeader multipart_header,
  422. ContentReceiver multipart_receiver);
  423. bool read_content_core(Stream &strm, bool last_connection, Request &req,
  424. Response &res, ContentReceiver receiver,
  425. MultipartContentHeader mulitpart_header,
  426. ContentReceiver multipart_receiver);
  427. virtual bool process_and_close_socket(socket_t sock);
  428. std::atomic<bool> is_running_;
  429. std::atomic<socket_t> svr_sock_;
  430. std::vector<std::pair<std::string, std::string>> base_dirs_;
  431. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  432. Handler file_request_handler_;
  433. Handlers get_handlers_;
  434. Handlers post_handlers_;
  435. HandlersForContentReader post_handlers_for_content_reader_;
  436. Handlers put_handlers_;
  437. HandlersForContentReader put_handlers_for_content_reader_;
  438. Handlers patch_handlers_;
  439. HandlersForContentReader patch_handlers_for_content_reader_;
  440. Handlers delete_handlers_;
  441. Handlers options_handlers_;
  442. Handler error_handler_;
  443. Logger logger_;
  444. };
  445. class Client {
  446. public:
  447. explicit Client(const std::string &host, int port = 80,
  448. const std::string &client_cert_path = std::string(),
  449. const std::string &client_key_path = std::string());
  450. virtual ~Client();
  451. virtual bool is_valid() const;
  452. std::shared_ptr<Response> Get(const char *path);
  453. std::shared_ptr<Response> Get(const char *path, const Headers &headers);
  454. std::shared_ptr<Response> Get(const char *path, Progress progress);
  455. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  456. Progress progress);
  457. std::shared_ptr<Response> Get(const char *path,
  458. ContentReceiver content_receiver);
  459. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  460. ContentReceiver content_receiver);
  461. std::shared_ptr<Response>
  462. Get(const char *path, ContentReceiver content_receiver, Progress progress);
  463. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  464. ContentReceiver content_receiver,
  465. Progress progress);
  466. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  467. ResponseHandler response_handler,
  468. ContentReceiver content_receiver);
  469. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  470. ResponseHandler response_handler,
  471. ContentReceiver content_receiver,
  472. Progress progress);
  473. std::shared_ptr<Response> Head(const char *path);
  474. std::shared_ptr<Response> Head(const char *path, const Headers &headers);
  475. std::shared_ptr<Response> Post(const char *path, const std::string &body,
  476. const char *content_type);
  477. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  478. const std::string &body,
  479. const char *content_type);
  480. std::shared_ptr<Response> Post(const char *path, size_t content_length,
  481. ContentProvider content_provider,
  482. const char *content_type);
  483. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  484. size_t content_length,
  485. ContentProvider content_provider,
  486. const char *content_type);
  487. std::shared_ptr<Response> Post(const char *path, const Params &params);
  488. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  489. const Params &params);
  490. std::shared_ptr<Response> Post(const char *path,
  491. const MultipartFormDataItems &items);
  492. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  493. const MultipartFormDataItems &items);
  494. std::shared_ptr<Response> Put(const char *path, const std::string &body,
  495. const char *content_type);
  496. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  497. const std::string &body,
  498. const char *content_type);
  499. std::shared_ptr<Response> Put(const char *path, size_t content_length,
  500. ContentProvider content_provider,
  501. const char *content_type);
  502. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  503. size_t content_length,
  504. ContentProvider content_provider,
  505. const char *content_type);
  506. std::shared_ptr<Response> Put(const char *path, const Params &params);
  507. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  508. const Params &params);
  509. std::shared_ptr<Response> Patch(const char *path, const std::string &body,
  510. const char *content_type);
  511. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  512. const std::string &body,
  513. const char *content_type);
  514. std::shared_ptr<Response> Patch(const char *path, size_t content_length,
  515. ContentProvider content_provider,
  516. const char *content_type);
  517. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  518. size_t content_length,
  519. ContentProvider content_provider,
  520. const char *content_type);
  521. std::shared_ptr<Response> Delete(const char *path);
  522. std::shared_ptr<Response> Delete(const char *path, const std::string &body,
  523. const char *content_type);
  524. std::shared_ptr<Response> Delete(const char *path, const Headers &headers);
  525. std::shared_ptr<Response> Delete(const char *path, const Headers &headers,
  526. const std::string &body,
  527. const char *content_type);
  528. std::shared_ptr<Response> Options(const char *path);
  529. std::shared_ptr<Response> Options(const char *path, const Headers &headers);
  530. bool send(const Request &req, Response &res);
  531. bool send(const std::vector<Request> &requests,
  532. std::vector<Response> &responses);
  533. void set_timeout_sec(time_t timeout_sec);
  534. void set_read_timeout(time_t sec, time_t usec);
  535. void set_keep_alive_max_count(size_t count);
  536. void set_basic_auth(const char *username, const char *password);
  537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  538. void set_digest_auth(const char *username, const char *password);
  539. #endif
  540. void set_follow_location(bool on);
  541. void set_compress(bool on);
  542. void set_interface(const char *intf);
  543. void set_proxy(const char *host, int port);
  544. void set_proxy_basic_auth(const char *username, const char *password);
  545. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  546. void set_proxy_digest_auth(const char *username, const char *password);
  547. #endif
  548. void set_logger(Logger logger);
  549. protected:
  550. bool process_request(Stream &strm, const Request &req, Response &res,
  551. bool last_connection, bool &connection_close);
  552. const std::string host_;
  553. const int port_;
  554. const std::string host_and_port_;
  555. // Settings
  556. std::string client_cert_path_;
  557. std::string client_key_path_;
  558. time_t timeout_sec_ = 300;
  559. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  560. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  561. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  562. std::string basic_auth_username_;
  563. std::string basic_auth_password_;
  564. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  565. std::string digest_auth_username_;
  566. std::string digest_auth_password_;
  567. #endif
  568. bool follow_location_ = false;
  569. bool compress_ = false;
  570. std::string interface_;
  571. std::string proxy_host_;
  572. int proxy_port_;
  573. std::string proxy_basic_auth_username_;
  574. std::string proxy_basic_auth_password_;
  575. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  576. std::string proxy_digest_auth_username_;
  577. std::string proxy_digest_auth_password_;
  578. #endif
  579. Logger logger_;
  580. void copy_settings(const Client &rhs) {
  581. client_cert_path_ = rhs.client_cert_path_;
  582. client_key_path_ = rhs.client_key_path_;
  583. timeout_sec_ = rhs.timeout_sec_;
  584. read_timeout_sec_ = rhs.read_timeout_sec_;
  585. read_timeout_usec_ = rhs.read_timeout_usec_;
  586. keep_alive_max_count_ = rhs.keep_alive_max_count_;
  587. basic_auth_username_ = rhs.basic_auth_username_;
  588. basic_auth_password_ = rhs.basic_auth_password_;
  589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  590. digest_auth_username_ = rhs.digest_auth_username_;
  591. digest_auth_password_ = rhs.digest_auth_password_;
  592. #endif
  593. follow_location_ = rhs.follow_location_;
  594. compress_ = rhs.compress_;
  595. interface_ = rhs.interface_;
  596. proxy_host_ = rhs.proxy_host_;
  597. proxy_port_ = rhs.proxy_port_;
  598. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  599. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  600. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  601. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  602. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  603. #endif
  604. logger_ = rhs.logger_;
  605. }
  606. private:
  607. socket_t create_client_socket() const;
  608. bool read_response_line(Stream &strm, Response &res);
  609. bool write_request(Stream &strm, const Request &req, bool last_connection);
  610. bool redirect(const Request &req, Response &res);
  611. bool handle_request(Stream &strm, const Request &req, Response &res,
  612. bool last_connection, bool &connection_close);
  613. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  614. bool connect(socket_t sock, Response &res, bool &error);
  615. #endif
  616. std::shared_ptr<Response> send_with_content_provider(
  617. const char *method, const char *path, const Headers &headers,
  618. const std::string &body, size_t content_length,
  619. ContentProvider content_provider, const char *content_type);
  620. virtual bool process_and_close_socket(
  621. socket_t sock, size_t request_count,
  622. std::function<bool(Stream &strm, bool last_connection,
  623. bool &connection_close)>
  624. callback);
  625. virtual bool is_ssl() const;
  626. };
  627. inline void Get(std::vector<Request> &requests, const char *path,
  628. const Headers &headers) {
  629. Request req;
  630. req.method = "GET";
  631. req.path = path;
  632. req.headers = headers;
  633. requests.emplace_back(std::move(req));
  634. }
  635. inline void Get(std::vector<Request> &requests, const char *path) {
  636. Get(requests, path, Headers());
  637. }
  638. inline void Post(std::vector<Request> &requests, const char *path,
  639. const Headers &headers, const std::string &body,
  640. const char *content_type) {
  641. Request req;
  642. req.method = "POST";
  643. req.path = path;
  644. req.headers = headers;
  645. req.headers.emplace("Content-Type", content_type);
  646. req.body = body;
  647. requests.emplace_back(std::move(req));
  648. }
  649. inline void Post(std::vector<Request> &requests, const char *path,
  650. const std::string &body, const char *content_type) {
  651. Post(requests, path, Headers(), body, content_type);
  652. }
  653. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  654. class SSLServer : public Server {
  655. public:
  656. SSLServer(const char *cert_path, const char *private_key_path,
  657. const char *client_ca_cert_file_path = nullptr,
  658. const char *client_ca_cert_dir_path = nullptr);
  659. virtual ~SSLServer();
  660. virtual bool is_valid() const;
  661. private:
  662. virtual bool process_and_close_socket(socket_t sock);
  663. SSL_CTX *ctx_;
  664. std::mutex ctx_mutex_;
  665. };
  666. class SSLClient : public Client {
  667. public:
  668. SSLClient(const std::string &host, int port = 443,
  669. const std::string &client_cert_path = std::string(),
  670. const std::string &client_key_path = std::string());
  671. virtual ~SSLClient();
  672. virtual bool is_valid() const;
  673. void set_ca_cert_path(const char *ca_ceert_file_path,
  674. const char *ca_cert_dir_path = nullptr);
  675. void enable_server_certificate_verification(bool enabled);
  676. long get_openssl_verify_result() const;
  677. SSL_CTX *ssl_context() const noexcept;
  678. private:
  679. virtual bool process_and_close_socket(
  680. socket_t sock, size_t request_count,
  681. std::function<bool(Stream &strm, bool last_connection,
  682. bool &connection_close)>
  683. callback);
  684. virtual bool is_ssl() const;
  685. bool verify_host(X509 *server_cert) const;
  686. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  687. bool verify_host_with_common_name(X509 *server_cert) const;
  688. bool check_host_name(const char *pattern, size_t pattern_len) const;
  689. SSL_CTX *ctx_;
  690. std::mutex ctx_mutex_;
  691. std::vector<std::string> host_components_;
  692. std::string ca_cert_file_path_;
  693. std::string ca_cert_dir_path_;
  694. bool server_certificate_verification_ = false;
  695. long verify_result_ = 0;
  696. };
  697. #endif
  698. // ----------------------------------------------------------------------------
  699. /*
  700. * Implementation
  701. */
  702. namespace detail {
  703. inline bool is_hex(char c, int &v) {
  704. if (0x20 <= c && isdigit(c)) {
  705. v = c - '0';
  706. return true;
  707. } else if ('A' <= c && c <= 'F') {
  708. v = c - 'A' + 10;
  709. return true;
  710. } else if ('a' <= c && c <= 'f') {
  711. v = c - 'a' + 10;
  712. return true;
  713. }
  714. return false;
  715. }
  716. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  717. int &val) {
  718. if (i >= s.size()) { return false; }
  719. val = 0;
  720. for (; cnt; i++, cnt--) {
  721. if (!s[i]) { return false; }
  722. int v = 0;
  723. if (is_hex(s[i], v)) {
  724. val = val * 16 + v;
  725. } else {
  726. return false;
  727. }
  728. }
  729. return true;
  730. }
  731. inline std::string from_i_to_hex(size_t n) {
  732. const char *charset = "0123456789abcdef";
  733. std::string ret;
  734. do {
  735. ret = charset[n & 15] + ret;
  736. n >>= 4;
  737. } while (n > 0);
  738. return ret;
  739. }
  740. inline size_t to_utf8(int code, char *buff) {
  741. if (code < 0x0080) {
  742. buff[0] = (code & 0x7F);
  743. return 1;
  744. } else if (code < 0x0800) {
  745. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  746. buff[1] = (0x80 | (code & 0x3F));
  747. return 2;
  748. } else if (code < 0xD800) {
  749. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  750. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  751. buff[2] = (0x80 | (code & 0x3F));
  752. return 3;
  753. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  754. return 0;
  755. } else if (code < 0x10000) {
  756. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  757. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  758. buff[2] = (0x80 | (code & 0x3F));
  759. return 3;
  760. } else if (code < 0x110000) {
  761. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  762. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  763. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  764. buff[3] = (0x80 | (code & 0x3F));
  765. return 4;
  766. }
  767. // NOTREACHED
  768. return 0;
  769. }
  770. // NOTE: This code came up with the following stackoverflow post:
  771. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  772. inline std::string base64_encode(const std::string &in) {
  773. static const auto lookup =
  774. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  775. std::string out;
  776. out.reserve(in.size());
  777. int val = 0;
  778. int valb = -6;
  779. for (uint8_t c : in) {
  780. val = (val << 8) + c;
  781. valb += 8;
  782. while (valb >= 0) {
  783. out.push_back(lookup[(val >> valb) & 0x3F]);
  784. valb -= 6;
  785. }
  786. }
  787. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  788. while (out.size() % 4) {
  789. out.push_back('=');
  790. }
  791. return out;
  792. }
  793. inline bool is_file(const std::string &path) {
  794. struct stat st;
  795. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  796. }
  797. inline bool is_dir(const std::string &path) {
  798. struct stat st;
  799. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  800. }
  801. inline bool is_valid_path(const std::string &path) {
  802. size_t level = 0;
  803. size_t i = 0;
  804. // Skip slash
  805. while (i < path.size() && path[i] == '/') {
  806. i++;
  807. }
  808. while (i < path.size()) {
  809. // Read component
  810. auto beg = i;
  811. while (i < path.size() && path[i] != '/') {
  812. i++;
  813. }
  814. auto len = i - beg;
  815. assert(len > 0);
  816. if (!path.compare(beg, len, ".")) {
  817. ;
  818. } else if (!path.compare(beg, len, "..")) {
  819. if (level == 0) { return false; }
  820. level--;
  821. } else {
  822. level++;
  823. }
  824. // Skip slash
  825. while (i < path.size() && path[i] == '/') {
  826. i++;
  827. }
  828. }
  829. return true;
  830. }
  831. inline void read_file(const std::string &path, std::string &out) {
  832. std::ifstream fs(path, std::ios_base::binary);
  833. fs.seekg(0, std::ios_base::end);
  834. auto size = fs.tellg();
  835. fs.seekg(0);
  836. out.resize(static_cast<size_t>(size));
  837. fs.read(&out[0], size);
  838. }
  839. inline std::string file_extension(const std::string &path) {
  840. std::smatch m;
  841. static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  842. if (std::regex_search(path, m, re)) { return m[1].str(); }
  843. return std::string();
  844. }
  845. template <class Fn> void split(const char *b, const char *e, char d, Fn fn) {
  846. int i = 0;
  847. int beg = 0;
  848. while (e ? (b + i != e) : (b[i] != '\0')) {
  849. if (b[i] == d) {
  850. fn(&b[beg], &b[i]);
  851. beg = i + 1;
  852. }
  853. i++;
  854. }
  855. if (i) { fn(&b[beg], &b[i]); }
  856. }
  857. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  858. // to store data. The call can set memory on stack for performance.
  859. class stream_line_reader {
  860. public:
  861. stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size)
  862. : strm_(strm), fixed_buffer_(fixed_buffer),
  863. fixed_buffer_size_(fixed_buffer_size) {}
  864. const char *ptr() const {
  865. if (glowable_buffer_.empty()) {
  866. return fixed_buffer_;
  867. } else {
  868. return glowable_buffer_.data();
  869. }
  870. }
  871. size_t size() const {
  872. if (glowable_buffer_.empty()) {
  873. return fixed_buffer_used_size_;
  874. } else {
  875. return glowable_buffer_.size();
  876. }
  877. }
  878. bool end_with_crlf() const {
  879. auto end = ptr() + size();
  880. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  881. }
  882. bool getline() {
  883. fixed_buffer_used_size_ = 0;
  884. glowable_buffer_.clear();
  885. for (size_t i = 0;; i++) {
  886. char byte;
  887. auto n = strm_.read(&byte, 1);
  888. if (n < 0) {
  889. return false;
  890. } else if (n == 0) {
  891. if (i == 0) {
  892. return false;
  893. } else {
  894. break;
  895. }
  896. }
  897. append(byte);
  898. if (byte == '\n') { break; }
  899. }
  900. return true;
  901. }
  902. private:
  903. void append(char c) {
  904. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  905. fixed_buffer_[fixed_buffer_used_size_++] = c;
  906. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  907. } else {
  908. if (glowable_buffer_.empty()) {
  909. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  910. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  911. }
  912. glowable_buffer_ += c;
  913. }
  914. }
  915. Stream &strm_;
  916. char *fixed_buffer_;
  917. const size_t fixed_buffer_size_;
  918. size_t fixed_buffer_used_size_ = 0;
  919. std::string glowable_buffer_;
  920. };
  921. inline int close_socket(socket_t sock) {
  922. #ifdef _WIN32
  923. return closesocket(sock);
  924. #else
  925. return close(sock);
  926. #endif
  927. }
  928. inline int select_read(socket_t sock, time_t sec, time_t usec) {
  929. #ifdef CPPHTTPLIB_USE_POLL
  930. struct pollfd pfd_read;
  931. pfd_read.fd = sock;
  932. pfd_read.events = POLLIN;
  933. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  934. return poll(&pfd_read, 1, timeout);
  935. #else
  936. fd_set fds;
  937. FD_ZERO(&fds);
  938. FD_SET(sock, &fds);
  939. timeval tv;
  940. tv.tv_sec = static_cast<long>(sec);
  941. tv.tv_usec = static_cast<long>(usec);
  942. return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
  943. #endif
  944. }
  945. inline int select_write(socket_t sock, time_t sec, time_t usec) {
  946. #ifdef CPPHTTPLIB_USE_POLL
  947. struct pollfd pfd_read;
  948. pfd_read.fd = sock;
  949. pfd_read.events = POLLOUT;
  950. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  951. return poll(&pfd_read, 1, timeout);
  952. #else
  953. fd_set fds;
  954. FD_ZERO(&fds);
  955. FD_SET(sock, &fds);
  956. timeval tv;
  957. tv.tv_sec = static_cast<long>(sec);
  958. tv.tv_usec = static_cast<long>(usec);
  959. return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);
  960. #endif
  961. }
  962. inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
  963. #ifdef CPPHTTPLIB_USE_POLL
  964. struct pollfd pfd_read;
  965. pfd_read.fd = sock;
  966. pfd_read.events = POLLIN | POLLOUT;
  967. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  968. if (poll(&pfd_read, 1, timeout) > 0 &&
  969. pfd_read.revents & (POLLIN | POLLOUT)) {
  970. int error = 0;
  971. socklen_t len = sizeof(error);
  972. return getsockopt(sock, SOL_SOCKET, SO_ERROR,
  973. reinterpret_cast<char *>(&error), &len) >= 0 &&
  974. !error;
  975. }
  976. return false;
  977. #else
  978. fd_set fdsr;
  979. FD_ZERO(&fdsr);
  980. FD_SET(sock, &fdsr);
  981. auto fdsw = fdsr;
  982. auto fdse = fdsr;
  983. timeval tv;
  984. tv.tv_sec = static_cast<long>(sec);
  985. tv.tv_usec = static_cast<long>(usec);
  986. if (select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv) > 0 &&
  987. (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  988. int error = 0;
  989. socklen_t len = sizeof(error);
  990. return getsockopt(sock, SOL_SOCKET, SO_ERROR,
  991. reinterpret_cast<char *>(&error), &len) >= 0 &&
  992. !error;
  993. }
  994. return false;
  995. #endif
  996. }
  997. class SocketStream : public Stream {
  998. public:
  999. SocketStream(socket_t sock, time_t read_timeout_sec,
  1000. time_t read_timeout_usec);
  1001. ~SocketStream() override;
  1002. bool is_readable() const override;
  1003. bool is_writable() const override;
  1004. int read(char *ptr, size_t size) override;
  1005. int write(const char *ptr, size_t size) override;
  1006. std::string get_remote_addr() const override;
  1007. private:
  1008. socket_t sock_;
  1009. time_t read_timeout_sec_;
  1010. time_t read_timeout_usec_;
  1011. };
  1012. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1013. class SSLSocketStream : public Stream {
  1014. public:
  1015. SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
  1016. time_t read_timeout_usec);
  1017. virtual ~SSLSocketStream();
  1018. bool is_readable() const override;
  1019. bool is_writable() const override;
  1020. int read(char *ptr, size_t size) override;
  1021. int write(const char *ptr, size_t size) override;
  1022. std::string get_remote_addr() const override;
  1023. private:
  1024. socket_t sock_;
  1025. SSL *ssl_;
  1026. time_t read_timeout_sec_;
  1027. time_t read_timeout_usec_;
  1028. };
  1029. #endif
  1030. class BufferStream : public Stream {
  1031. public:
  1032. BufferStream() = default;
  1033. ~BufferStream() override = default;
  1034. bool is_readable() const override;
  1035. bool is_writable() const override;
  1036. int read(char *ptr, size_t size) override;
  1037. int write(const char *ptr, size_t size) override;
  1038. std::string get_remote_addr() const override;
  1039. const std::string &get_buffer() const;
  1040. private:
  1041. std::string buffer;
  1042. int position = 0;
  1043. };
  1044. template <typename T>
  1045. inline bool process_socket(bool is_client_request, socket_t sock,
  1046. size_t keep_alive_max_count, time_t read_timeout_sec,
  1047. time_t read_timeout_usec, T callback) {
  1048. assert(keep_alive_max_count > 0);
  1049. auto ret = false;
  1050. if (keep_alive_max_count > 1) {
  1051. auto count = keep_alive_max_count;
  1052. while (count > 0 &&
  1053. (is_client_request ||
  1054. select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1055. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
  1056. SocketStream strm(sock, read_timeout_sec, read_timeout_usec);
  1057. auto last_connection = count == 1;
  1058. auto connection_close = false;
  1059. ret = callback(strm, last_connection, connection_close);
  1060. if (!ret || connection_close) { break; }
  1061. count--;
  1062. }
  1063. } else { // keep_alive_max_count is 0 or 1
  1064. SocketStream strm(sock, read_timeout_sec, read_timeout_usec);
  1065. auto dummy_connection_close = false;
  1066. ret = callback(strm, true, dummy_connection_close);
  1067. }
  1068. return ret;
  1069. }
  1070. template <typename T>
  1071. inline bool process_and_close_socket(bool is_client_request, socket_t sock,
  1072. size_t keep_alive_max_count,
  1073. time_t read_timeout_sec,
  1074. time_t read_timeout_usec, T callback) {
  1075. auto ret = process_socket(is_client_request, sock, keep_alive_max_count,
  1076. read_timeout_sec, read_timeout_usec, callback);
  1077. close_socket(sock);
  1078. return ret;
  1079. }
  1080. inline int shutdown_socket(socket_t sock) {
  1081. #ifdef _WIN32
  1082. return shutdown(sock, SD_BOTH);
  1083. #else
  1084. return shutdown(sock, SHUT_RDWR);
  1085. #endif
  1086. }
  1087. template <typename Fn>
  1088. socket_t create_socket(const char *host, int port, Fn fn,
  1089. int socket_flags = 0) {
  1090. #ifdef _WIN32
  1091. #define SO_SYNCHRONOUS_NONALERT 0x20
  1092. #define SO_OPENTYPE 0x7008
  1093. int opt = SO_SYNCHRONOUS_NONALERT;
  1094. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&opt,
  1095. sizeof(opt));
  1096. #endif
  1097. // Get address info
  1098. struct addrinfo hints;
  1099. struct addrinfo *result;
  1100. memset(&hints, 0, sizeof(struct addrinfo));
  1101. hints.ai_family = AF_UNSPEC;
  1102. hints.ai_socktype = SOCK_STREAM;
  1103. hints.ai_flags = socket_flags;
  1104. hints.ai_protocol = 0;
  1105. auto service = std::to_string(port);
  1106. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  1107. return INVALID_SOCKET;
  1108. }
  1109. for (auto rp = result; rp; rp = rp->ai_next) {
  1110. // Create a socket
  1111. #ifdef _WIN32
  1112. auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
  1113. nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT);
  1114. /**
  1115. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  1116. * and above the socket creation fails on older Windows Systems.
  1117. *
  1118. * Let's try to create a socket the old way in this case.
  1119. *
  1120. * Reference:
  1121. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  1122. *
  1123. * WSA_FLAG_NO_HANDLE_INHERIT:
  1124. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  1125. * SP1, and later
  1126. *
  1127. */
  1128. if (sock == INVALID_SOCKET) {
  1129. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1130. }
  1131. #else
  1132. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1133. #endif
  1134. if (sock == INVALID_SOCKET) { continue; }
  1135. #ifndef _WIN32
  1136. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; }
  1137. #endif
  1138. // Make 'reuse address' option available
  1139. int yes = 1;
  1140. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
  1141. sizeof(yes));
  1142. #ifdef SO_REUSEPORT
  1143. setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<char *>(&yes),
  1144. sizeof(yes));
  1145. #endif
  1146. // bind or connect
  1147. if (fn(sock, *rp)) {
  1148. freeaddrinfo(result);
  1149. return sock;
  1150. }
  1151. close_socket(sock);
  1152. }
  1153. freeaddrinfo(result);
  1154. return INVALID_SOCKET;
  1155. }
  1156. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  1157. #ifdef _WIN32
  1158. auto flags = nonblocking ? 1UL : 0UL;
  1159. ioctlsocket(sock, FIONBIO, &flags);
  1160. #else
  1161. auto flags = fcntl(sock, F_GETFL, 0);
  1162. fcntl(sock, F_SETFL,
  1163. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  1164. #endif
  1165. }
  1166. inline bool is_connection_error() {
  1167. #ifdef _WIN32
  1168. return WSAGetLastError() != WSAEWOULDBLOCK;
  1169. #else
  1170. return errno != EINPROGRESS;
  1171. #endif
  1172. }
  1173. inline bool bind_ip_address(socket_t sock, const char *host) {
  1174. struct addrinfo hints;
  1175. struct addrinfo *result;
  1176. memset(&hints, 0, sizeof(struct addrinfo));
  1177. hints.ai_family = AF_UNSPEC;
  1178. hints.ai_socktype = SOCK_STREAM;
  1179. hints.ai_protocol = 0;
  1180. if (getaddrinfo(host, "0", &hints, &result)) { return false; }
  1181. auto ret = false;
  1182. for (auto rp = result; rp; rp = rp->ai_next) {
  1183. const auto &ai = *rp;
  1184. if (!::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen))) {
  1185. ret = true;
  1186. break;
  1187. }
  1188. }
  1189. freeaddrinfo(result);
  1190. return ret;
  1191. }
  1192. inline std::string if2ip(const std::string &ifn) {
  1193. #ifndef _WIN32
  1194. struct ifaddrs *ifap;
  1195. getifaddrs(&ifap);
  1196. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  1197. if (ifa->ifa_addr && ifn == ifa->ifa_name) {
  1198. if (ifa->ifa_addr->sa_family == AF_INET) {
  1199. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  1200. char buf[INET_ADDRSTRLEN];
  1201. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  1202. freeifaddrs(ifap);
  1203. return std::string(buf, INET_ADDRSTRLEN);
  1204. }
  1205. }
  1206. }
  1207. }
  1208. freeifaddrs(ifap);
  1209. #endif
  1210. return std::string();
  1211. }
  1212. inline socket_t create_client_socket(const char *host, int port,
  1213. time_t timeout_sec,
  1214. const std::string &intf) {
  1215. return create_socket(
  1216. host, port, [&](socket_t sock, struct addrinfo &ai) -> bool {
  1217. if (!intf.empty()) {
  1218. auto ip = if2ip(intf);
  1219. if (ip.empty()) { ip = intf; }
  1220. if (!bind_ip_address(sock, ip.c_str())) { return false; }
  1221. }
  1222. set_nonblocking(sock, true);
  1223. auto ret = ::connect(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen));
  1224. if (ret < 0) {
  1225. if (is_connection_error() ||
  1226. !wait_until_socket_is_ready(sock, timeout_sec, 0)) {
  1227. close_socket(sock);
  1228. return false;
  1229. }
  1230. }
  1231. set_nonblocking(sock, false);
  1232. return true;
  1233. });
  1234. }
  1235. inline std::string get_remote_addr(socket_t sock) {
  1236. struct sockaddr_storage addr;
  1237. socklen_t len = sizeof(addr);
  1238. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr), &len)) {
  1239. std::array<char, NI_MAXHOST> ipstr{};
  1240. if (!getnameinfo(reinterpret_cast<struct sockaddr *>(&addr), len,
  1241. ipstr.data(), ipstr.size(), nullptr, 0, NI_NUMERICHOST)) {
  1242. return ipstr.data();
  1243. }
  1244. }
  1245. return std::string();
  1246. }
  1247. inline const char *
  1248. find_content_type(const std::string &path,
  1249. const std::map<std::string, std::string> &user_data) {
  1250. auto ext = file_extension(path);
  1251. auto it = user_data.find(ext);
  1252. if (it != user_data.end()) { return it->second.c_str(); }
  1253. if (ext == "txt") {
  1254. return "text/plain";
  1255. } else if (ext == "html" || ext == "htm") {
  1256. return "text/html";
  1257. } else if (ext == "css") {
  1258. return "text/css";
  1259. } else if (ext == "jpeg" || ext == "jpg") {
  1260. return "image/jpg";
  1261. } else if (ext == "png") {
  1262. return "image/png";
  1263. } else if (ext == "gif") {
  1264. return "image/gif";
  1265. } else if (ext == "svg") {
  1266. return "image/svg+xml";
  1267. } else if (ext == "ico") {
  1268. return "image/x-icon";
  1269. } else if (ext == "json") {
  1270. return "application/json";
  1271. } else if (ext == "pdf") {
  1272. return "application/pdf";
  1273. } else if (ext == "js") {
  1274. return "application/javascript";
  1275. } else if (ext == "wasm") {
  1276. return "application/wasm";
  1277. } else if (ext == "xml") {
  1278. return "application/xml";
  1279. } else if (ext == "xhtml") {
  1280. return "application/xhtml+xml";
  1281. }
  1282. return nullptr;
  1283. }
  1284. inline const char *status_message(int status) {
  1285. switch (status) {
  1286. case 200: return "OK";
  1287. case 202: return "Accepted";
  1288. case 204: return "No Content";
  1289. case 206: return "Partial Content";
  1290. case 301: return "Moved Permanently";
  1291. case 302: return "Found";
  1292. case 303: return "See Other";
  1293. case 304: return "Not Modified";
  1294. case 400: return "Bad Request";
  1295. case 401: return "Unauthorized";
  1296. case 403: return "Forbidden";
  1297. case 404: return "Not Found";
  1298. case 413: return "Payload Too Large";
  1299. case 414: return "Request-URI Too Long";
  1300. case 415: return "Unsupported Media Type";
  1301. case 416: return "Range Not Satisfiable";
  1302. case 503: return "Service Unavailable";
  1303. default:
  1304. case 500: return "Internal Server Error";
  1305. }
  1306. }
  1307. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1308. inline bool can_compress(const std::string &content_type) {
  1309. return !content_type.find("text/") || content_type == "image/svg+xml" ||
  1310. content_type == "application/javascript" ||
  1311. content_type == "application/json" ||
  1312. content_type == "application/xml" ||
  1313. content_type == "application/xhtml+xml";
  1314. }
  1315. inline bool compress(std::string &content) {
  1316. z_stream strm;
  1317. strm.zalloc = Z_NULL;
  1318. strm.zfree = Z_NULL;
  1319. strm.opaque = Z_NULL;
  1320. auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  1321. Z_DEFAULT_STRATEGY);
  1322. if (ret != Z_OK) { return false; }
  1323. strm.avail_in = content.size();
  1324. strm.next_in =
  1325. const_cast<Bytef *>(reinterpret_cast<const Bytef *>(content.data()));
  1326. std::string compressed;
  1327. std::array<char, 16384> buff{};
  1328. do {
  1329. strm.avail_out = buff.size();
  1330. strm.next_out = reinterpret_cast<Bytef *>(buff.data());
  1331. ret = deflate(&strm, Z_FINISH);
  1332. assert(ret != Z_STREAM_ERROR);
  1333. compressed.append(buff.data(), buff.size() - strm.avail_out);
  1334. } while (strm.avail_out == 0);
  1335. assert(ret == Z_STREAM_END);
  1336. assert(strm.avail_in == 0);
  1337. content.swap(compressed);
  1338. deflateEnd(&strm);
  1339. return true;
  1340. }
  1341. class decompressor {
  1342. public:
  1343. decompressor() {
  1344. strm.zalloc = Z_NULL;
  1345. strm.zfree = Z_NULL;
  1346. strm.opaque = Z_NULL;
  1347. // 15 is the value of wbits, which should be at the maximum possible value
  1348. // to ensure that any gzip stream can be decoded. The offset of 16 specifies
  1349. // that the stream to decompress will be formatted with a gzip wrapper.
  1350. is_valid_ = inflateInit2(&strm, 16 + 15) == Z_OK;
  1351. }
  1352. ~decompressor() { inflateEnd(&strm); }
  1353. bool is_valid() const { return is_valid_; }
  1354. template <typename T>
  1355. bool decompress(const char *data, size_t data_length, T callback) {
  1356. int ret = Z_OK;
  1357. strm.avail_in = data_length;
  1358. strm.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  1359. std::array<char, 16384> buff{};
  1360. do {
  1361. strm.avail_out = buff.size();
  1362. strm.next_out = reinterpret_cast<Bytef *>(buff.data());
  1363. ret = inflate(&strm, Z_NO_FLUSH);
  1364. assert(ret != Z_STREAM_ERROR);
  1365. switch (ret) {
  1366. case Z_NEED_DICT:
  1367. case Z_DATA_ERROR:
  1368. case Z_MEM_ERROR: inflateEnd(&strm); return false;
  1369. }
  1370. if (!callback(buff.data(), buff.size() - strm.avail_out)) {
  1371. return false;
  1372. }
  1373. } while (strm.avail_out == 0);
  1374. return ret == Z_OK || ret == Z_STREAM_END;
  1375. }
  1376. private:
  1377. bool is_valid_;
  1378. z_stream strm;
  1379. };
  1380. #endif
  1381. inline bool has_header(const Headers &headers, const char *key) {
  1382. return headers.find(key) != headers.end();
  1383. }
  1384. inline const char *get_header_value(const Headers &headers, const char *key,
  1385. size_t id = 0, const char *def = nullptr) {
  1386. auto it = headers.find(key);
  1387. std::advance(it, id);
  1388. if (it != headers.end()) { return it->second.c_str(); }
  1389. return def;
  1390. }
  1391. inline uint64_t get_header_value_uint64(const Headers &headers, const char *key,
  1392. int def = 0) {
  1393. auto it = headers.find(key);
  1394. if (it != headers.end()) {
  1395. return std::strtoull(it->second.data(), nullptr, 10);
  1396. }
  1397. return def;
  1398. }
  1399. inline bool read_headers(Stream &strm, Headers &headers) {
  1400. const auto bufsiz = 2048;
  1401. char buf[bufsiz];
  1402. stream_line_reader line_reader(strm, buf, bufsiz);
  1403. for (;;) {
  1404. if (!line_reader.getline()) { return false; }
  1405. // Check if the line ends with CRLF.
  1406. if (line_reader.end_with_crlf()) {
  1407. // Blank line indicates end of headers.
  1408. if (line_reader.size() == 2) { break; }
  1409. } else {
  1410. continue; // Skip invalid line.
  1411. }
  1412. // Skip trailing spaces and tabs.
  1413. auto end = line_reader.ptr() + line_reader.size() - 2;
  1414. while (line_reader.ptr() < end && (end[-1] == ' ' || end[-1] == '\t')) {
  1415. end--;
  1416. }
  1417. // Horizontal tab and ' ' are considered whitespace and are ignored when on
  1418. // the left or right side of the header value:
  1419. // - https://stackoverflow.com/questions/50179659/
  1420. // - https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
  1421. static const std::regex re(R"((.+?):[\t ]*(.+))");
  1422. std::cmatch m;
  1423. if (std::regex_match(line_reader.ptr(), end, m, re)) {
  1424. auto key = std::string(m[1]);
  1425. auto val = std::string(m[2]);
  1426. headers.emplace(key, val);
  1427. }
  1428. }
  1429. return true;
  1430. }
  1431. inline bool read_content_with_length(Stream &strm, uint64_t len,
  1432. Progress progress, ContentReceiver out) {
  1433. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1434. uint64_t r = 0;
  1435. while (r < len) {
  1436. auto read_len = static_cast<size_t>(len - r);
  1437. auto n = strm.read(buf, std::min(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1438. if (n <= 0) { return false; }
  1439. if (!out(buf, n)) { return false; }
  1440. r += n;
  1441. if (progress) {
  1442. if (!progress(r, len)) { return false; }
  1443. }
  1444. }
  1445. return true;
  1446. }
  1447. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  1448. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1449. uint64_t r = 0;
  1450. while (r < len) {
  1451. auto read_len = static_cast<size_t>(len - r);
  1452. auto n = strm.read(buf, std::min(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1453. if (n <= 0) { return; }
  1454. r += n;
  1455. }
  1456. }
  1457. inline bool read_content_without_length(Stream &strm, ContentReceiver out) {
  1458. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1459. for (;;) {
  1460. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  1461. if (n < 0) {
  1462. return false;
  1463. } else if (n == 0) {
  1464. return true;
  1465. }
  1466. if (!out(buf, n)) { return false; }
  1467. }
  1468. return true;
  1469. }
  1470. inline bool read_content_chunked(Stream &strm, ContentReceiver out) {
  1471. const auto bufsiz = 16;
  1472. char buf[bufsiz];
  1473. stream_line_reader line_reader(strm, buf, bufsiz);
  1474. if (!line_reader.getline()) { return false; }
  1475. auto chunk_len = std::stoi(line_reader.ptr(), 0, 16);
  1476. while (chunk_len > 0) {
  1477. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  1478. return false;
  1479. }
  1480. if (!line_reader.getline()) { return false; }
  1481. if (strcmp(line_reader.ptr(), "\r\n")) { break; }
  1482. if (!line_reader.getline()) { return false; }
  1483. chunk_len = std::stoi(line_reader.ptr(), 0, 16);
  1484. }
  1485. if (chunk_len == 0) {
  1486. // Reader terminator after chunks
  1487. if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n"))
  1488. return false;
  1489. }
  1490. return true;
  1491. }
  1492. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  1493. return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""),
  1494. "chunked");
  1495. }
  1496. template <typename T>
  1497. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  1498. Progress progress, ContentReceiver receiver) {
  1499. ContentReceiver out = [&](const char *buf, size_t n) {
  1500. return receiver(buf, n);
  1501. };
  1502. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1503. decompressor decompressor;
  1504. if (!decompressor.is_valid()) {
  1505. status = 500;
  1506. return false;
  1507. }
  1508. if (x.get_header_value("Content-Encoding") == "gzip") {
  1509. out = [&](const char *buf, size_t n) {
  1510. return decompressor.decompress(
  1511. buf, n, [&](const char *buf, size_t n) { return receiver(buf, n); });
  1512. };
  1513. }
  1514. #else
  1515. if (x.get_header_value("Content-Encoding") == "gzip") {
  1516. status = 415;
  1517. return false;
  1518. }
  1519. #endif
  1520. auto ret = true;
  1521. auto exceed_payload_max_length = false;
  1522. if (is_chunked_transfer_encoding(x.headers)) {
  1523. ret = read_content_chunked(strm, out);
  1524. } else if (!has_header(x.headers, "Content-Length")) {
  1525. ret = read_content_without_length(strm, out);
  1526. } else {
  1527. auto len = get_header_value_uint64(x.headers, "Content-Length", 0);
  1528. if (len > payload_max_length) {
  1529. exceed_payload_max_length = true;
  1530. skip_content_with_length(strm, len);
  1531. ret = false;
  1532. } else if (len > 0) {
  1533. ret = read_content_with_length(strm, len, progress, out);
  1534. }
  1535. }
  1536. if (!ret) { status = exceed_payload_max_length ? 413 : 400; }
  1537. return ret;
  1538. }
  1539. template <typename T>
  1540. inline int write_headers(Stream &strm, const T &info, const Headers &headers) {
  1541. auto write_len = 0;
  1542. for (const auto &x : info.headers) {
  1543. auto len =
  1544. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  1545. if (len < 0) { return len; }
  1546. write_len += len;
  1547. }
  1548. for (const auto &x : headers) {
  1549. auto len =
  1550. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  1551. if (len < 0) { return len; }
  1552. write_len += len;
  1553. }
  1554. auto len = strm.write("\r\n");
  1555. if (len < 0) { return len; }
  1556. write_len += len;
  1557. return write_len;
  1558. }
  1559. inline ssize_t write_content(Stream &strm, ContentProvider content_provider,
  1560. size_t offset, size_t length) {
  1561. size_t begin_offset = offset;
  1562. size_t end_offset = offset + length;
  1563. while (offset < end_offset) {
  1564. ssize_t written_length = 0;
  1565. DataSink data_sink;
  1566. data_sink.write = [&](const char *d, size_t l) {
  1567. offset += l;
  1568. written_length = strm.write(d, l);
  1569. };
  1570. data_sink.done = [&](void) { written_length = -1; };
  1571. data_sink.is_writable = [&](void) { return strm.is_writable(); };
  1572. content_provider(offset, end_offset - offset, data_sink);
  1573. if (written_length < 0) { return written_length; }
  1574. }
  1575. return static_cast<ssize_t>(offset - begin_offset);
  1576. }
  1577. template <typename T>
  1578. inline ssize_t write_content_chunked(Stream &strm,
  1579. ContentProvider content_provider,
  1580. T is_shutting_down) {
  1581. size_t offset = 0;
  1582. auto data_available = true;
  1583. ssize_t total_written_length = 0;
  1584. while (data_available && !is_shutting_down()) {
  1585. ssize_t written_length = 0;
  1586. DataSink data_sink;
  1587. data_sink.write = [&](const char *d, size_t l) {
  1588. data_available = l > 0;
  1589. offset += l;
  1590. // Emit chunked response header and footer for each chunk
  1591. auto chunk = from_i_to_hex(l) + "\r\n" + std::string(d, l) + "\r\n";
  1592. written_length = strm.write(chunk);
  1593. };
  1594. data_sink.done = [&](void) {
  1595. data_available = false;
  1596. written_length = strm.write("0\r\n\r\n");
  1597. };
  1598. data_sink.is_writable = [&](void) { return strm.is_writable(); };
  1599. content_provider(offset, 0, data_sink);
  1600. if (written_length < 0) { return written_length; }
  1601. total_written_length += written_length;
  1602. }
  1603. return total_written_length;
  1604. }
  1605. template <typename T>
  1606. inline bool redirect(T &cli, const Request &req, Response &res,
  1607. const std::string &path) {
  1608. Request new_req = req;
  1609. new_req.path = path;
  1610. new_req.redirect_count -= 1;
  1611. Response new_res;
  1612. auto ret = cli.send(new_req, new_res);
  1613. if (ret) { res = new_res; }
  1614. return ret;
  1615. }
  1616. inline std::string encode_url(const std::string &s) {
  1617. std::string result;
  1618. for (auto i = 0; s[i]; i++) {
  1619. switch (s[i]) {
  1620. case ' ': result += "%20"; break;
  1621. case '+': result += "%2B"; break;
  1622. case '\r': result += "%0D"; break;
  1623. case '\n': result += "%0A"; break;
  1624. case '\'': result += "%27"; break;
  1625. case ',': result += "%2C"; break;
  1626. // case ':': result += "%3A"; break; // ok? probably...
  1627. case ';': result += "%3B"; break;
  1628. default:
  1629. auto c = static_cast<uint8_t>(s[i]);
  1630. if (c >= 0x80) {
  1631. result += '%';
  1632. char hex[4];
  1633. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  1634. assert(len == 2);
  1635. result.append(hex, len);
  1636. } else {
  1637. result += s[i];
  1638. }
  1639. break;
  1640. }
  1641. }
  1642. return result;
  1643. }
  1644. inline std::string decode_url(const std::string &s) {
  1645. std::string result;
  1646. for (size_t i = 0; i < s.size(); i++) {
  1647. if (s[i] == '%' && i + 1 < s.size()) {
  1648. if (s[i + 1] == 'u') {
  1649. int val = 0;
  1650. if (from_hex_to_i(s, i + 2, 4, val)) {
  1651. // 4 digits Unicode codes
  1652. char buff[4];
  1653. size_t len = to_utf8(val, buff);
  1654. if (len > 0) { result.append(buff, len); }
  1655. i += 5; // 'u0000'
  1656. } else {
  1657. result += s[i];
  1658. }
  1659. } else {
  1660. int val = 0;
  1661. if (from_hex_to_i(s, i + 1, 2, val)) {
  1662. // 2 digits hex codes
  1663. result += static_cast<char>(val);
  1664. i += 2; // '00'
  1665. } else {
  1666. result += s[i];
  1667. }
  1668. }
  1669. } else if (s[i] == '+') {
  1670. result += ' ';
  1671. } else {
  1672. result += s[i];
  1673. }
  1674. }
  1675. return result;
  1676. }
  1677. inline void parse_query_text(const std::string &s, Params &params) {
  1678. split(&s[0], &s[s.size()], '&', [&](const char *b, const char *e) {
  1679. std::string key;
  1680. std::string val;
  1681. split(b, e, '=', [&](const char *b2, const char *e2) {
  1682. if (key.empty()) {
  1683. key.assign(b2, e2);
  1684. } else {
  1685. val.assign(b2, e2);
  1686. }
  1687. });
  1688. params.emplace(key, decode_url(val));
  1689. });
  1690. }
  1691. inline bool parse_multipart_boundary(const std::string &content_type,
  1692. std::string &boundary) {
  1693. auto pos = content_type.find("boundary=");
  1694. if (pos == std::string::npos) { return false; }
  1695. boundary = content_type.substr(pos + 9);
  1696. return true;
  1697. }
  1698. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  1699. static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
  1700. std::smatch m;
  1701. if (std::regex_match(s, m, re_first_range)) {
  1702. auto pos = m.position(1);
  1703. auto len = m.length(1);
  1704. bool all_valid_ranges = true;
  1705. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  1706. if (!all_valid_ranges) return;
  1707. static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
  1708. std::cmatch cm;
  1709. if (std::regex_match(b, e, cm, re_another_range)) {
  1710. ssize_t first = -1;
  1711. if (!cm.str(1).empty()) {
  1712. first = static_cast<ssize_t>(std::stoll(cm.str(1)));
  1713. }
  1714. ssize_t last = -1;
  1715. if (!cm.str(2).empty()) {
  1716. last = static_cast<ssize_t>(std::stoll(cm.str(2)));
  1717. }
  1718. if (first != -1 && last != -1 && first > last) {
  1719. all_valid_ranges = false;
  1720. return;
  1721. }
  1722. ranges.emplace_back(std::make_pair(first, last));
  1723. }
  1724. });
  1725. return all_valid_ranges;
  1726. }
  1727. return false;
  1728. }
  1729. class MultipartFormDataParser {
  1730. public:
  1731. MultipartFormDataParser() {}
  1732. void set_boundary(const std::string &boundary) { boundary_ = boundary; }
  1733. bool is_valid() const { return is_valid_; }
  1734. template <typename T, typename U>
  1735. bool parse(const char *buf, size_t n, T content_callback, U header_callback) {
  1736. static const std::regex re_content_type(R"(^Content-Type:\s*(.*?)\s*$)",
  1737. std::regex_constants::icase);
  1738. static const std::regex re_content_disposition(
  1739. "^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename="
  1740. "\"(.*?)\")?\\s*$",
  1741. std::regex_constants::icase);
  1742. buf_.append(buf, n); // TODO: performance improvement
  1743. while (!buf_.empty()) {
  1744. switch (state_) {
  1745. case 0: { // Initial boundary
  1746. auto pattern = dash_ + boundary_ + crlf_;
  1747. if (pattern.size() > buf_.size()) { return true; }
  1748. auto pos = buf_.find(pattern);
  1749. if (pos != 0) {
  1750. is_done_ = true;
  1751. return false;
  1752. }
  1753. buf_.erase(0, pattern.size());
  1754. off_ += pattern.size();
  1755. state_ = 1;
  1756. break;
  1757. }
  1758. case 1: { // New entry
  1759. clear_file_info();
  1760. state_ = 2;
  1761. break;
  1762. }
  1763. case 2: { // Headers
  1764. auto pos = buf_.find(crlf_);
  1765. while (pos != std::string::npos) {
  1766. // Empty line
  1767. if (pos == 0) {
  1768. if (!header_callback(file_)) {
  1769. is_valid_ = false;
  1770. is_done_ = false;
  1771. return false;
  1772. }
  1773. buf_.erase(0, crlf_.size());
  1774. off_ += crlf_.size();
  1775. state_ = 3;
  1776. break;
  1777. }
  1778. auto header = buf_.substr(0, pos);
  1779. {
  1780. std::smatch m;
  1781. if (std::regex_match(header, m, re_content_type)) {
  1782. file_.content_type = m[1];
  1783. } else if (std::regex_match(header, m, re_content_disposition)) {
  1784. file_.name = m[1];
  1785. file_.filename = m[2];
  1786. }
  1787. }
  1788. buf_.erase(0, pos + crlf_.size());
  1789. off_ += pos + crlf_.size();
  1790. pos = buf_.find(crlf_);
  1791. }
  1792. break;
  1793. }
  1794. case 3: { // Body
  1795. {
  1796. auto pattern = crlf_ + dash_;
  1797. if (pattern.size() > buf_.size()) { return true; }
  1798. auto pos = buf_.find(pattern);
  1799. if (pos == std::string::npos) { pos = buf_.size(); }
  1800. if (!content_callback(buf_.data(), pos)) {
  1801. is_valid_ = false;
  1802. is_done_ = false;
  1803. return false;
  1804. }
  1805. off_ += pos;
  1806. buf_.erase(0, pos);
  1807. }
  1808. {
  1809. auto pattern = crlf_ + dash_ + boundary_;
  1810. if (pattern.size() > buf_.size()) { return true; }
  1811. auto pos = buf_.find(pattern);
  1812. if (pos != std::string::npos) {
  1813. if (!content_callback(buf_.data(), pos)) {
  1814. is_valid_ = false;
  1815. is_done_ = false;
  1816. return false;
  1817. }
  1818. off_ += pos + pattern.size();
  1819. buf_.erase(0, pos + pattern.size());
  1820. state_ = 4;
  1821. } else {
  1822. if (!content_callback(buf_.data(), pattern.size())) {
  1823. is_valid_ = false;
  1824. is_done_ = false;
  1825. return false;
  1826. }
  1827. off_ += pattern.size();
  1828. buf_.erase(0, pattern.size());
  1829. }
  1830. }
  1831. break;
  1832. }
  1833. case 4: { // Boundary
  1834. if (crlf_.size() > buf_.size()) { return true; }
  1835. if (buf_.find(crlf_) == 0) {
  1836. buf_.erase(0, crlf_.size());
  1837. off_ += crlf_.size();
  1838. state_ = 1;
  1839. } else {
  1840. auto pattern = dash_ + crlf_;
  1841. if (pattern.size() > buf_.size()) { return true; }
  1842. if (buf_.find(pattern) == 0) {
  1843. buf_.erase(0, pattern.size());
  1844. off_ += pattern.size();
  1845. is_valid_ = true;
  1846. state_ = 5;
  1847. } else {
  1848. is_done_ = true;
  1849. return true;
  1850. }
  1851. }
  1852. break;
  1853. }
  1854. case 5: { // Done
  1855. is_valid_ = false;
  1856. return false;
  1857. }
  1858. }
  1859. }
  1860. return true;
  1861. }
  1862. private:
  1863. void clear_file_info() {
  1864. file_.name.clear();
  1865. file_.filename.clear();
  1866. file_.content_type.clear();
  1867. }
  1868. const std::string dash_ = "--";
  1869. const std::string crlf_ = "\r\n";
  1870. std::string boundary_;
  1871. std::string buf_;
  1872. size_t state_ = 0;
  1873. size_t is_valid_ = false;
  1874. size_t is_done_ = false;
  1875. size_t off_ = 0;
  1876. MultipartFormData file_;
  1877. };
  1878. inline std::string to_lower(const char *beg, const char *end) {
  1879. std::string out;
  1880. auto it = beg;
  1881. while (it != end) {
  1882. out += static_cast<char>(::tolower(*it));
  1883. it++;
  1884. }
  1885. return out;
  1886. }
  1887. inline std::string make_multipart_data_boundary() {
  1888. static const char data[] =
  1889. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1890. std::random_device seed_gen;
  1891. std::mt19937 engine(seed_gen());
  1892. std::string result = "--cpp-httplib-multipart-data-";
  1893. for (auto i = 0; i < 16; i++) {
  1894. result += data[engine() % (sizeof(data) - 1)];
  1895. }
  1896. return result;
  1897. }
  1898. inline std::pair<size_t, size_t>
  1899. get_range_offset_and_length(const Request &req, size_t content_length,
  1900. size_t index) {
  1901. auto r = req.ranges[index];
  1902. if (r.first == -1 && r.second == -1) {
  1903. return std::make_pair(0, content_length);
  1904. }
  1905. if (r.first == -1) {
  1906. r.first = content_length - r.second;
  1907. r.second = content_length - 1;
  1908. }
  1909. if (r.second == -1) { r.second = content_length - 1; }
  1910. return std::make_pair(r.first, r.second - r.first + 1);
  1911. }
  1912. inline std::string make_content_range_header_field(size_t offset, size_t length,
  1913. size_t content_length) {
  1914. std::string field = "bytes ";
  1915. field += std::to_string(offset);
  1916. field += "-";
  1917. field += std::to_string(offset + length - 1);
  1918. field += "/";
  1919. field += std::to_string(content_length);
  1920. return field;
  1921. }
  1922. template <typename SToken, typename CToken, typename Content>
  1923. bool process_multipart_ranges_data(const Request &req, Response &res,
  1924. const std::string &boundary,
  1925. const std::string &content_type,
  1926. SToken stoken, CToken ctoken,
  1927. Content content) {
  1928. for (size_t i = 0; i < req.ranges.size(); i++) {
  1929. ctoken("--");
  1930. stoken(boundary);
  1931. ctoken("\r\n");
  1932. if (!content_type.empty()) {
  1933. ctoken("Content-Type: ");
  1934. stoken(content_type);
  1935. ctoken("\r\n");
  1936. }
  1937. auto offsets = get_range_offset_and_length(req, res.body.size(), i);
  1938. auto offset = offsets.first;
  1939. auto length = offsets.second;
  1940. ctoken("Content-Range: ");
  1941. stoken(make_content_range_header_field(offset, length, res.body.size()));
  1942. ctoken("\r\n");
  1943. ctoken("\r\n");
  1944. if (!content(offset, length)) { return false; }
  1945. ctoken("\r\n");
  1946. }
  1947. ctoken("--");
  1948. stoken(boundary);
  1949. ctoken("--\r\n");
  1950. return true;
  1951. }
  1952. inline std::string make_multipart_ranges_data(const Request &req, Response &res,
  1953. const std::string &boundary,
  1954. const std::string &content_type) {
  1955. std::string data;
  1956. process_multipart_ranges_data(
  1957. req, res, boundary, content_type,
  1958. [&](const std::string &token) { data += token; },
  1959. [&](const char *token) { data += token; },
  1960. [&](size_t offset, size_t length) {
  1961. data += res.body.substr(offset, length);
  1962. return true;
  1963. });
  1964. return data;
  1965. }
  1966. inline size_t
  1967. get_multipart_ranges_data_length(const Request &req, Response &res,
  1968. const std::string &boundary,
  1969. const std::string &content_type) {
  1970. size_t data_length = 0;
  1971. process_multipart_ranges_data(
  1972. req, res, boundary, content_type,
  1973. [&](const std::string &token) { data_length += token.size(); },
  1974. [&](const char *token) { data_length += strlen(token); },
  1975. [&](size_t /*offset*/, size_t length) {
  1976. data_length += length;
  1977. return true;
  1978. });
  1979. return data_length;
  1980. }
  1981. inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
  1982. Response &res,
  1983. const std::string &boundary,
  1984. const std::string &content_type) {
  1985. return process_multipart_ranges_data(
  1986. req, res, boundary, content_type,
  1987. [&](const std::string &token) { strm.write(token); },
  1988. [&](const char *token) { strm.write(token); },
  1989. [&](size_t offset, size_t length) {
  1990. return write_content(strm, res.content_provider, offset, length) >= 0;
  1991. });
  1992. }
  1993. inline std::pair<size_t, size_t>
  1994. get_range_offset_and_length(const Request &req, const Response &res,
  1995. size_t index) {
  1996. auto r = req.ranges[index];
  1997. if (r.second == -1) { r.second = res.content_length - 1; }
  1998. return std::make_pair(r.first, r.second - r.first + 1);
  1999. }
  2000. inline bool expect_content(const Request &req) {
  2001. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  2002. req.method == "PRI") {
  2003. return true;
  2004. }
  2005. // TODO: check if Content-Length is set
  2006. return false;
  2007. }
  2008. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2009. template <typename CTX, typename Init, typename Update, typename Final>
  2010. inline std::string message_digest(const std::string &s, Init init,
  2011. Update update, Final final,
  2012. size_t digest_length) {
  2013. using namespace std;
  2014. std::vector<unsigned char> md(digest_length, 0);
  2015. CTX ctx;
  2016. init(&ctx);
  2017. update(&ctx, s.data(), s.size());
  2018. final(md.data(), &ctx);
  2019. stringstream ss;
  2020. for (auto c : md) {
  2021. ss << setfill('0') << setw(2) << hex << (unsigned int)c;
  2022. }
  2023. return ss.str();
  2024. }
  2025. inline std::string MD5(const std::string &s) {
  2026. return message_digest<MD5_CTX>(s, MD5_Init, MD5_Update, MD5_Final,
  2027. MD5_DIGEST_LENGTH);
  2028. }
  2029. inline std::string SHA_256(const std::string &s) {
  2030. return message_digest<SHA256_CTX>(s, SHA256_Init, SHA256_Update, SHA256_Final,
  2031. SHA256_DIGEST_LENGTH);
  2032. }
  2033. inline std::string SHA_512(const std::string &s) {
  2034. return message_digest<SHA512_CTX>(s, SHA512_Init, SHA512_Update, SHA512_Final,
  2035. SHA512_DIGEST_LENGTH);
  2036. }
  2037. #endif
  2038. #ifdef _WIN32
  2039. class WSInit {
  2040. public:
  2041. WSInit() {
  2042. WSADATA wsaData;
  2043. WSAStartup(0x0002, &wsaData);
  2044. }
  2045. ~WSInit() { WSACleanup(); }
  2046. };
  2047. static WSInit wsinit_;
  2048. #endif
  2049. } // namespace detail
  2050. // Header utilities
  2051. inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
  2052. std::string field = "bytes=";
  2053. auto i = 0;
  2054. for (auto r : ranges) {
  2055. if (i != 0) { field += ", "; }
  2056. if (r.first != -1) { field += std::to_string(r.first); }
  2057. field += '-';
  2058. if (r.second != -1) { field += std::to_string(r.second); }
  2059. i++;
  2060. }
  2061. return std::make_pair("Range", field);
  2062. }
  2063. inline std::pair<std::string, std::string>
  2064. make_basic_authentication_header(const std::string &username,
  2065. const std::string &password,
  2066. bool is_proxy = false) {
  2067. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  2068. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2069. return std::make_pair(key, field);
  2070. }
  2071. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2072. inline std::pair<std::string, std::string> make_digest_authentication_header(
  2073. const Request &req, const std::map<std::string, std::string> &auth,
  2074. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  2075. const std::string &password, bool is_proxy = false) {
  2076. using namespace std;
  2077. string nc;
  2078. {
  2079. stringstream ss;
  2080. ss << setfill('0') << setw(8) << hex << cnonce_count;
  2081. nc = ss.str();
  2082. }
  2083. auto qop = auth.at("qop");
  2084. if (qop.find("auth-int") != std::string::npos) {
  2085. qop = "auth-int";
  2086. } else {
  2087. qop = "auth";
  2088. }
  2089. std::string algo = "MD5";
  2090. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  2091. string response;
  2092. {
  2093. auto H = algo == "SHA-256"
  2094. ? detail::SHA_256
  2095. : algo == "SHA-512" ? detail::SHA_512 : detail::MD5;
  2096. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  2097. auto A2 = req.method + ":" + req.path;
  2098. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  2099. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  2100. ":" + qop + ":" + H(A2));
  2101. }
  2102. auto field = "Digest username=\"hello\", realm=\"" + auth.at("realm") +
  2103. "\", nonce=\"" + auth.at("nonce") + "\", uri=\"" + req.path +
  2104. "\", algorithm=" + algo + ", qop=" + qop + ", nc=\"" + nc +
  2105. "\", cnonce=\"" + cnonce + "\", response=\"" + response + "\"";
  2106. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2107. return std::make_pair(key, field);
  2108. }
  2109. #endif
  2110. inline bool parse_www_authenticate(const httplib::Response &res,
  2111. std::map<std::string, std::string> &auth,
  2112. bool is_proxy) {
  2113. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  2114. if (res.has_header(auth_key)) {
  2115. static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  2116. auto s = res.get_header_value(auth_key);
  2117. auto pos = s.find(' ');
  2118. if (pos != std::string::npos) {
  2119. auto type = s.substr(0, pos);
  2120. if (type == "Basic") {
  2121. return false;
  2122. } else if (type == "Digest") {
  2123. s = s.substr(pos + 1);
  2124. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  2125. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  2126. auto m = *i;
  2127. auto key = s.substr(m.position(1), m.length(1));
  2128. auto val = m.length(2) > 0 ? s.substr(m.position(2), m.length(2))
  2129. : s.substr(m.position(3), m.length(3));
  2130. auth[key] = val;
  2131. }
  2132. return true;
  2133. }
  2134. }
  2135. }
  2136. return false;
  2137. }
  2138. // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240
  2139. inline std::string random_string(size_t length) {
  2140. auto randchar = []() -> char {
  2141. const char charset[] = "0123456789"
  2142. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2143. "abcdefghijklmnopqrstuvwxyz";
  2144. const size_t max_index = (sizeof(charset) - 1);
  2145. return charset[rand() % max_index];
  2146. };
  2147. std::string str(length, 0);
  2148. std::generate_n(str.begin(), length, randchar);
  2149. return str;
  2150. }
  2151. // Request implementation
  2152. inline bool Request::has_header(const char *key) const {
  2153. return detail::has_header(headers, key);
  2154. }
  2155. inline std::string Request::get_header_value(const char *key, size_t id) const {
  2156. return detail::get_header_value(headers, key, id, "");
  2157. }
  2158. inline size_t Request::get_header_value_count(const char *key) const {
  2159. auto r = headers.equal_range(key);
  2160. return std::distance(r.first, r.second);
  2161. }
  2162. inline void Request::set_header(const char *key, const char *val) {
  2163. headers.emplace(key, val);
  2164. }
  2165. inline void Request::set_header(const char *key, const std::string &val) {
  2166. headers.emplace(key, val);
  2167. }
  2168. inline bool Request::has_param(const char *key) const {
  2169. return params.find(key) != params.end();
  2170. }
  2171. inline std::string Request::get_param_value(const char *key, size_t id) const {
  2172. auto it = params.find(key);
  2173. std::advance(it, id);
  2174. if (it != params.end()) { return it->second; }
  2175. return std::string();
  2176. }
  2177. inline size_t Request::get_param_value_count(const char *key) const {
  2178. auto r = params.equal_range(key);
  2179. return std::distance(r.first, r.second);
  2180. }
  2181. inline bool Request::is_multipart_form_data() const {
  2182. const auto &content_type = get_header_value("Content-Type");
  2183. return !content_type.find("multipart/form-data");
  2184. }
  2185. inline bool Request::has_file(const char *key) const {
  2186. return files.find(key) != files.end();
  2187. }
  2188. inline MultipartFormData Request::get_file_value(const char *key) const {
  2189. auto it = files.find(key);
  2190. if (it != files.end()) { return it->second; }
  2191. return MultipartFormData();
  2192. }
  2193. // Response implementation
  2194. inline bool Response::has_header(const char *key) const {
  2195. return headers.find(key) != headers.end();
  2196. }
  2197. inline std::string Response::get_header_value(const char *key,
  2198. size_t id) const {
  2199. return detail::get_header_value(headers, key, id, "");
  2200. }
  2201. inline size_t Response::get_header_value_count(const char *key) const {
  2202. auto r = headers.equal_range(key);
  2203. return std::distance(r.first, r.second);
  2204. }
  2205. inline void Response::set_header(const char *key, const char *val) {
  2206. headers.emplace(key, val);
  2207. }
  2208. inline void Response::set_header(const char *key, const std::string &val) {
  2209. headers.emplace(key, val);
  2210. }
  2211. inline void Response::set_redirect(const char *url) {
  2212. set_header("Location", url);
  2213. status = 302;
  2214. }
  2215. inline void Response::set_content(const char *s, size_t n,
  2216. const char *content_type) {
  2217. body.assign(s, n);
  2218. set_header("Content-Type", content_type);
  2219. }
  2220. inline void Response::set_content(const std::string &s,
  2221. const char *content_type) {
  2222. body = s;
  2223. set_header("Content-Type", content_type);
  2224. }
  2225. inline void Response::set_content_provider(
  2226. size_t in_length,
  2227. std::function<void(size_t offset, size_t length, DataSink &sink)> provider,
  2228. std::function<void()> resource_releaser) {
  2229. assert(in_length > 0);
  2230. content_length = in_length;
  2231. content_provider = [provider](size_t offset, size_t length, DataSink &sink) {
  2232. provider(offset, length, sink);
  2233. };
  2234. content_provider_resource_releaser = resource_releaser;
  2235. }
  2236. inline void Response::set_chunked_content_provider(
  2237. std::function<void(size_t offset, DataSink &sink)> provider,
  2238. std::function<void()> resource_releaser) {
  2239. content_length = 0;
  2240. content_provider = [provider](size_t offset, size_t, DataSink &sink) {
  2241. provider(offset, sink);
  2242. };
  2243. content_provider_resource_releaser = resource_releaser;
  2244. }
  2245. // Rstream implementation
  2246. inline int Stream::write(const char *ptr) { return write(ptr, strlen(ptr)); }
  2247. inline int Stream::write(const std::string &s) {
  2248. return write(s.data(), s.size());
  2249. }
  2250. template <typename... Args>
  2251. inline int Stream::write_format(const char *fmt, const Args &... args) {
  2252. std::array<char, 2048> buf;
  2253. #if defined(_MSC_VER) && _MSC_VER < 1900
  2254. auto n = _snprintf_s(buf, bufsiz, buf.size() - 1, fmt, args...);
  2255. #else
  2256. auto n = snprintf(buf.data(), buf.size() - 1, fmt, args...);
  2257. #endif
  2258. if (n <= 0) { return n; }
  2259. if (n >= static_cast<int>(buf.size()) - 1) {
  2260. std::vector<char> glowable_buf(buf.size());
  2261. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  2262. glowable_buf.resize(glowable_buf.size() * 2);
  2263. #if defined(_MSC_VER) && _MSC_VER < 1900
  2264. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(),
  2265. glowable_buf.size() - 1, fmt, args...);
  2266. #else
  2267. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  2268. #endif
  2269. }
  2270. return write(&glowable_buf[0], n);
  2271. } else {
  2272. return write(buf.data(), n);
  2273. }
  2274. }
  2275. namespace detail {
  2276. // Socket stream implementation
  2277. inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
  2278. time_t read_timeout_usec)
  2279. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  2280. read_timeout_usec_(read_timeout_usec) {}
  2281. inline SocketStream::~SocketStream() {}
  2282. inline bool SocketStream::is_readable() const {
  2283. return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  2284. }
  2285. inline bool SocketStream::is_writable() const {
  2286. return detail::select_write(sock_, 0, 0) > 0;
  2287. }
  2288. inline int SocketStream::read(char *ptr, size_t size) {
  2289. if (is_readable()) { return recv(sock_, ptr, static_cast<int>(size), 0); }
  2290. return -1;
  2291. }
  2292. inline int SocketStream::write(const char *ptr, size_t size) {
  2293. if (is_writable()) { return send(sock_, ptr, static_cast<int>(size), 0); }
  2294. return -1;
  2295. }
  2296. inline std::string SocketStream::get_remote_addr() const {
  2297. return detail::get_remote_addr(sock_);
  2298. }
  2299. // Buffer stream implementation
  2300. inline bool BufferStream::is_readable() const { return true; }
  2301. inline bool BufferStream::is_writable() const { return true; }
  2302. inline int BufferStream::read(char *ptr, size_t size) {
  2303. #if defined(_MSC_VER) && _MSC_VER < 1900
  2304. int len_read = static_cast<int>(buffer._Copy_s(ptr, size, size, position));
  2305. #else
  2306. int len_read = static_cast<int>(buffer.copy(ptr, size, position));
  2307. #endif
  2308. position += len_read;
  2309. return len_read;
  2310. }
  2311. inline int BufferStream::write(const char *ptr, size_t size) {
  2312. buffer.append(ptr, size);
  2313. return static_cast<int>(size);
  2314. }
  2315. inline std::string BufferStream::get_remote_addr() const { return ""; }
  2316. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  2317. } // namespace detail
  2318. // HTTP server implementation
  2319. inline Server::Server()
  2320. : keep_alive_max_count_(CPPHTTPLIB_KEEPALIVE_MAX_COUNT),
  2321. read_timeout_sec_(CPPHTTPLIB_READ_TIMEOUT_SECOND),
  2322. read_timeout_usec_(CPPHTTPLIB_READ_TIMEOUT_USECOND),
  2323. payload_max_length_(CPPHTTPLIB_PAYLOAD_MAX_LENGTH), is_running_(false),
  2324. svr_sock_(INVALID_SOCKET) {
  2325. #ifndef _WIN32
  2326. signal(SIGPIPE, SIG_IGN);
  2327. #endif
  2328. new_task_queue = [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); };
  2329. }
  2330. inline Server::~Server() {}
  2331. inline Server &Server::Get(const char *pattern, Handler handler) {
  2332. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2333. return *this;
  2334. }
  2335. inline Server &Server::Post(const char *pattern, Handler handler) {
  2336. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2337. return *this;
  2338. }
  2339. inline Server &Server::Post(const char *pattern,
  2340. HandlerWithContentReader handler) {
  2341. post_handlers_for_content_reader_.push_back(
  2342. std::make_pair(std::regex(pattern), handler));
  2343. return *this;
  2344. }
  2345. inline Server &Server::Put(const char *pattern, Handler handler) {
  2346. put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2347. return *this;
  2348. }
  2349. inline Server &Server::Put(const char *pattern,
  2350. HandlerWithContentReader handler) {
  2351. put_handlers_for_content_reader_.push_back(
  2352. std::make_pair(std::regex(pattern), handler));
  2353. return *this;
  2354. }
  2355. inline Server &Server::Patch(const char *pattern, Handler handler) {
  2356. patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2357. return *this;
  2358. }
  2359. inline Server &Server::Patch(const char *pattern,
  2360. HandlerWithContentReader handler) {
  2361. patch_handlers_for_content_reader_.push_back(
  2362. std::make_pair(std::regex(pattern), handler));
  2363. return *this;
  2364. }
  2365. inline Server &Server::Delete(const char *pattern, Handler handler) {
  2366. delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2367. return *this;
  2368. }
  2369. inline Server &Server::Options(const char *pattern, Handler handler) {
  2370. options_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2371. return *this;
  2372. }
  2373. inline bool Server::set_base_dir(const char *dir, const char *mount_point) {
  2374. return set_mount_point(mount_point, dir);
  2375. }
  2376. inline bool Server::set_mount_point(const char *mount_point, const char *dir) {
  2377. if (detail::is_dir(dir)) {
  2378. std::string mnt = mount_point ? mount_point : "/";
  2379. if (!mnt.empty() && mnt[0] == '/') {
  2380. base_dirs_.emplace_back(mnt, dir);
  2381. return true;
  2382. }
  2383. }
  2384. return false;
  2385. }
  2386. inline bool Server::remove_mount_point(const char *mount_point) {
  2387. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  2388. if (it->first == mount_point) {
  2389. base_dirs_.erase(it);
  2390. return true;
  2391. }
  2392. }
  2393. return false;
  2394. }
  2395. inline void Server::set_file_extension_and_mimetype_mapping(const char *ext,
  2396. const char *mime) {
  2397. file_extension_and_mimetype_map_[ext] = mime;
  2398. }
  2399. inline void Server::set_file_request_handler(Handler handler) {
  2400. file_request_handler_ = std::move(handler);
  2401. }
  2402. inline void Server::set_error_handler(Handler handler) {
  2403. error_handler_ = std::move(handler);
  2404. }
  2405. inline void Server::set_logger(Logger logger) { logger_ = std::move(logger); }
  2406. inline void Server::set_keep_alive_max_count(size_t count) {
  2407. keep_alive_max_count_ = count;
  2408. }
  2409. inline void Server::set_read_timeout(time_t sec, time_t usec) {
  2410. read_timeout_sec_ = sec;
  2411. read_timeout_usec_ = usec;
  2412. }
  2413. inline void Server::set_payload_max_length(size_t length) {
  2414. payload_max_length_ = length;
  2415. }
  2416. inline bool Server::bind_to_port(const char *host, int port, int socket_flags) {
  2417. if (bind_internal(host, port, socket_flags) < 0) return false;
  2418. return true;
  2419. }
  2420. inline int Server::bind_to_any_port(const char *host, int socket_flags) {
  2421. return bind_internal(host, 0, socket_flags);
  2422. }
  2423. inline bool Server::listen_after_bind() { return listen_internal(); }
  2424. inline bool Server::listen(const char *host, int port, int socket_flags) {
  2425. return bind_to_port(host, port, socket_flags) && listen_internal();
  2426. }
  2427. inline bool Server::is_running() const { return is_running_; }
  2428. inline void Server::stop() {
  2429. if (is_running_) {
  2430. assert(svr_sock_ != INVALID_SOCKET);
  2431. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  2432. detail::shutdown_socket(sock);
  2433. detail::close_socket(sock);
  2434. }
  2435. }
  2436. inline bool Server::parse_request_line(const char *s, Request &req) {
  2437. const static std::regex re(
  2438. "(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI) "
  2439. "(([^?]+)(?:\\?(.*?))?) (HTTP/1\\.[01])\r\n");
  2440. std::cmatch m;
  2441. if (std::regex_match(s, m, re)) {
  2442. req.version = std::string(m[5]);
  2443. req.method = std::string(m[1]);
  2444. req.target = std::string(m[2]);
  2445. req.path = detail::decode_url(m[3]);
  2446. // Parse query text
  2447. auto len = std::distance(m[4].first, m[4].second);
  2448. if (len > 0) { detail::parse_query_text(m[4], req.params); }
  2449. return true;
  2450. }
  2451. return false;
  2452. }
  2453. inline bool Server::write_response(Stream &strm, bool last_connection,
  2454. const Request &req, Response &res) {
  2455. assert(res.status != -1);
  2456. if (400 <= res.status && error_handler_) { error_handler_(req, res); }
  2457. // Response line
  2458. if (!strm.write_format("HTTP/1.1 %d %s\r\n", res.status,
  2459. detail::status_message(res.status))) {
  2460. return false;
  2461. }
  2462. // Headers
  2463. if (last_connection || req.get_header_value("Connection") == "close") {
  2464. res.set_header("Connection", "close");
  2465. }
  2466. if (!last_connection && req.get_header_value("Connection") == "Keep-Alive") {
  2467. res.set_header("Connection", "Keep-Alive");
  2468. }
  2469. if (!res.has_header("Content-Type")) {
  2470. res.set_header("Content-Type", "text/plain");
  2471. }
  2472. if (!res.has_header("Accept-Ranges")) {
  2473. res.set_header("Accept-Ranges", "bytes");
  2474. }
  2475. std::string content_type;
  2476. std::string boundary;
  2477. if (req.ranges.size() > 1) {
  2478. boundary = detail::make_multipart_data_boundary();
  2479. auto it = res.headers.find("Content-Type");
  2480. if (it != res.headers.end()) {
  2481. content_type = it->second;
  2482. res.headers.erase(it);
  2483. }
  2484. res.headers.emplace("Content-Type",
  2485. "multipart/byteranges; boundary=" + boundary);
  2486. }
  2487. if (res.body.empty()) {
  2488. if (res.content_length > 0) {
  2489. size_t length = 0;
  2490. if (req.ranges.empty()) {
  2491. length = res.content_length;
  2492. } else if (req.ranges.size() == 1) {
  2493. auto offsets =
  2494. detail::get_range_offset_and_length(req, res.content_length, 0);
  2495. auto offset = offsets.first;
  2496. length = offsets.second;
  2497. auto content_range = detail::make_content_range_header_field(
  2498. offset, length, res.content_length);
  2499. res.set_header("Content-Range", content_range);
  2500. } else {
  2501. length = detail::get_multipart_ranges_data_length(req, res, boundary,
  2502. content_type);
  2503. }
  2504. res.set_header("Content-Length", std::to_string(length));
  2505. } else {
  2506. if (res.content_provider) {
  2507. res.set_header("Transfer-Encoding", "chunked");
  2508. } else {
  2509. res.set_header("Content-Length", "0");
  2510. }
  2511. }
  2512. } else {
  2513. if (req.ranges.empty()) {
  2514. ;
  2515. } else if (req.ranges.size() == 1) {
  2516. auto offsets =
  2517. detail::get_range_offset_and_length(req, res.body.size(), 0);
  2518. auto offset = offsets.first;
  2519. auto length = offsets.second;
  2520. auto content_range = detail::make_content_range_header_field(
  2521. offset, length, res.body.size());
  2522. res.set_header("Content-Range", content_range);
  2523. res.body = res.body.substr(offset, length);
  2524. } else {
  2525. res.body =
  2526. detail::make_multipart_ranges_data(req, res, boundary, content_type);
  2527. }
  2528. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2529. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  2530. const auto &encodings = req.get_header_value("Accept-Encoding");
  2531. if (encodings.find("gzip") != std::string::npos &&
  2532. detail::can_compress(res.get_header_value("Content-Type"))) {
  2533. if (detail::compress(res.body)) {
  2534. res.set_header("Content-Encoding", "gzip");
  2535. }
  2536. }
  2537. #endif
  2538. auto length = std::to_string(res.body.size());
  2539. res.set_header("Content-Length", length);
  2540. }
  2541. if (!detail::write_headers(strm, res, Headers())) { return false; }
  2542. // Body
  2543. if (req.method != "HEAD") {
  2544. if (!res.body.empty()) {
  2545. if (!strm.write(res.body)) { return false; }
  2546. } else if (res.content_provider) {
  2547. if (!write_content_with_provider(strm, req, res, boundary,
  2548. content_type)) {
  2549. return false;
  2550. }
  2551. }
  2552. }
  2553. // Log
  2554. if (logger_) { logger_(req, res); }
  2555. return true;
  2556. }
  2557. inline bool
  2558. Server::write_content_with_provider(Stream &strm, const Request &req,
  2559. Response &res, const std::string &boundary,
  2560. const std::string &content_type) {
  2561. if (res.content_length) {
  2562. if (req.ranges.empty()) {
  2563. if (detail::write_content(strm, res.content_provider, 0,
  2564. res.content_length) < 0) {
  2565. return false;
  2566. }
  2567. } else if (req.ranges.size() == 1) {
  2568. auto offsets =
  2569. detail::get_range_offset_and_length(req, res.content_length, 0);
  2570. auto offset = offsets.first;
  2571. auto length = offsets.second;
  2572. if (detail::write_content(strm, res.content_provider, offset, length) <
  2573. 0) {
  2574. return false;
  2575. }
  2576. } else {
  2577. if (!detail::write_multipart_ranges_data(strm, req, res, boundary,
  2578. content_type)) {
  2579. return false;
  2580. }
  2581. }
  2582. } else {
  2583. auto is_shutting_down = [this]() {
  2584. return this->svr_sock_ == INVALID_SOCKET;
  2585. };
  2586. if (detail::write_content_chunked(strm, res.content_provider,
  2587. is_shutting_down) < 0) {
  2588. return false;
  2589. }
  2590. }
  2591. return true;
  2592. }
  2593. inline bool Server::read_content(Stream &strm, bool last_connection,
  2594. Request &req, Response &res) {
  2595. MultipartFormDataMap::iterator cur;
  2596. auto ret = read_content_core(
  2597. strm, last_connection, req, res,
  2598. // Regular
  2599. [&](const char *buf, size_t n) {
  2600. if (req.body.size() + n > req.body.max_size()) { return false; }
  2601. req.body.append(buf, n);
  2602. return true;
  2603. },
  2604. // Multipart
  2605. [&](const MultipartFormData &file) {
  2606. cur = req.files.emplace(file.name, file);
  2607. return true;
  2608. },
  2609. [&](const char *buf, size_t n) {
  2610. auto &content = cur->second.content;
  2611. if (content.size() + n > content.max_size()) { return false; }
  2612. content.append(buf, n);
  2613. return true;
  2614. });
  2615. const auto &content_type = req.get_header_value("Content-Type");
  2616. if (!content_type.find("application/x-www-form-urlencoded")) {
  2617. detail::parse_query_text(req.body, req.params);
  2618. }
  2619. return ret;
  2620. }
  2621. inline bool Server::read_content_with_content_receiver(
  2622. Stream &strm, bool last_connection, Request &req, Response &res,
  2623. ContentReceiver receiver, MultipartContentHeader multipart_header,
  2624. ContentReceiver multipart_receiver) {
  2625. return read_content_core(strm, last_connection, req, res, receiver,
  2626. multipart_header, multipart_receiver);
  2627. }
  2628. inline bool Server::read_content_core(Stream &strm, bool last_connection,
  2629. Request &req, Response &res,
  2630. ContentReceiver receiver,
  2631. MultipartContentHeader mulitpart_header,
  2632. ContentReceiver multipart_receiver) {
  2633. detail::MultipartFormDataParser multipart_form_data_parser;
  2634. ContentReceiver out;
  2635. if (req.is_multipart_form_data()) {
  2636. const auto &content_type = req.get_header_value("Content-Type");
  2637. std::string boundary;
  2638. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  2639. res.status = 400;
  2640. return write_response(strm, last_connection, req, res);
  2641. }
  2642. multipart_form_data_parser.set_boundary(boundary);
  2643. out = [&](const char *buf, size_t n) {
  2644. return multipart_form_data_parser.parse(buf, n, multipart_receiver,
  2645. mulitpart_header);
  2646. };
  2647. } else {
  2648. out = receiver;
  2649. }
  2650. if (!detail::read_content(strm, req, payload_max_length_, res.status,
  2651. Progress(), out)) {
  2652. return write_response(strm, last_connection, req, res);
  2653. }
  2654. if (req.is_multipart_form_data()) {
  2655. if (!multipart_form_data_parser.is_valid()) {
  2656. res.status = 400;
  2657. return write_response(strm, last_connection, req, res);
  2658. }
  2659. }
  2660. return true;
  2661. }
  2662. inline bool Server::handle_file_request(Request &req, Response &res,
  2663. bool head) {
  2664. for (const auto &kv : base_dirs_) {
  2665. const auto &mount_point = kv.first;
  2666. const auto &base_dir = kv.second;
  2667. // Prefix match
  2668. if (!req.path.find(mount_point)) {
  2669. std::string sub_path = "/" + req.path.substr(mount_point.size());
  2670. if (detail::is_valid_path(sub_path)) {
  2671. auto path = base_dir + sub_path;
  2672. if (path.back() == '/') { path += "index.html"; }
  2673. if (detail::is_file(path)) {
  2674. detail::read_file(path, res.body);
  2675. auto type =
  2676. detail::find_content_type(path, file_extension_and_mimetype_map_);
  2677. if (type) { res.set_header("Content-Type", type); }
  2678. res.status = 200;
  2679. if (!head && file_request_handler_) {
  2680. file_request_handler_(req, res);
  2681. }
  2682. return true;
  2683. }
  2684. }
  2685. }
  2686. }
  2687. return false;
  2688. }
  2689. inline socket_t Server::create_server_socket(const char *host, int port,
  2690. int socket_flags) const {
  2691. return detail::create_socket(
  2692. host, port,
  2693. [](socket_t sock, struct addrinfo &ai) -> bool {
  2694. if (::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen))) {
  2695. return false;
  2696. }
  2697. if (::listen(sock, 5)) { // Listen through 5 channels
  2698. return false;
  2699. }
  2700. return true;
  2701. },
  2702. socket_flags);
  2703. }
  2704. inline int Server::bind_internal(const char *host, int port, int socket_flags) {
  2705. if (!is_valid()) { return -1; }
  2706. svr_sock_ = create_server_socket(host, port, socket_flags);
  2707. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  2708. if (port == 0) {
  2709. struct sockaddr_storage address;
  2710. socklen_t len = sizeof(address);
  2711. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&address),
  2712. &len) == -1) {
  2713. return -1;
  2714. }
  2715. if (address.ss_family == AF_INET) {
  2716. return ntohs(reinterpret_cast<struct sockaddr_in *>(&address)->sin_port);
  2717. } else if (address.ss_family == AF_INET6) {
  2718. return ntohs(
  2719. reinterpret_cast<struct sockaddr_in6 *>(&address)->sin6_port);
  2720. } else {
  2721. return -1;
  2722. }
  2723. } else {
  2724. return port;
  2725. }
  2726. }
  2727. inline bool Server::listen_internal() {
  2728. auto ret = true;
  2729. is_running_ = true;
  2730. {
  2731. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  2732. for (;;) {
  2733. if (svr_sock_ == INVALID_SOCKET) {
  2734. // The server socket was closed by 'stop' method.
  2735. break;
  2736. }
  2737. auto val = detail::select_read(svr_sock_, 0, 100000);
  2738. if (val == 0) { // Timeout
  2739. continue;
  2740. }
  2741. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  2742. if (sock == INVALID_SOCKET) {
  2743. if (errno == EMFILE) {
  2744. // The per-process limit of open file descriptors has been reached.
  2745. // Try to accept new connections after a short sleep.
  2746. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2747. continue;
  2748. }
  2749. if (svr_sock_ != INVALID_SOCKET) {
  2750. detail::close_socket(svr_sock_);
  2751. ret = false;
  2752. } else {
  2753. ; // The server socket was closed by user.
  2754. }
  2755. break;
  2756. }
  2757. task_queue->enqueue([=]() { process_and_close_socket(sock); });
  2758. }
  2759. task_queue->shutdown();
  2760. }
  2761. is_running_ = false;
  2762. return ret;
  2763. }
  2764. inline bool Server::routing(Request &req, Response &res, Stream &strm,
  2765. bool last_connection) {
  2766. // File handler
  2767. bool is_head_request = req.method == "HEAD";
  2768. if ((req.method == "GET" || is_head_request) &&
  2769. handle_file_request(req, res, is_head_request)) {
  2770. return true;
  2771. }
  2772. if (detail::expect_content(req)) {
  2773. // Content reader handler
  2774. {
  2775. ContentReader reader(
  2776. [&](ContentReceiver receiver) {
  2777. return read_content_with_content_receiver(
  2778. strm, last_connection, req, res, receiver, nullptr, nullptr);
  2779. },
  2780. [&](MultipartContentHeader header, ContentReceiver receiver) {
  2781. return read_content_with_content_receiver(
  2782. strm, last_connection, req, res, nullptr, header, receiver);
  2783. });
  2784. if (req.method == "POST") {
  2785. if (dispatch_request_for_content_reader(
  2786. req, res, reader, post_handlers_for_content_reader_)) {
  2787. return true;
  2788. }
  2789. } else if (req.method == "PUT") {
  2790. if (dispatch_request_for_content_reader(
  2791. req, res, reader, put_handlers_for_content_reader_)) {
  2792. return true;
  2793. }
  2794. } else if (req.method == "PATCH") {
  2795. if (dispatch_request_for_content_reader(
  2796. req, res, reader, patch_handlers_for_content_reader_)) {
  2797. return true;
  2798. }
  2799. }
  2800. }
  2801. // Read content into `req.body`
  2802. if (!read_content(strm, last_connection, req, res)) { return false; }
  2803. }
  2804. // Regular handler
  2805. if (req.method == "GET" || req.method == "HEAD") {
  2806. return dispatch_request(req, res, get_handlers_);
  2807. } else if (req.method == "POST") {
  2808. return dispatch_request(req, res, post_handlers_);
  2809. } else if (req.method == "PUT") {
  2810. return dispatch_request(req, res, put_handlers_);
  2811. } else if (req.method == "DELETE") {
  2812. return dispatch_request(req, res, delete_handlers_);
  2813. } else if (req.method == "OPTIONS") {
  2814. return dispatch_request(req, res, options_handlers_);
  2815. } else if (req.method == "PATCH") {
  2816. return dispatch_request(req, res, patch_handlers_);
  2817. }
  2818. res.status = 400;
  2819. return false;
  2820. }
  2821. inline bool Server::dispatch_request(Request &req, Response &res,
  2822. Handlers &handlers) {
  2823. for (const auto &x : handlers) {
  2824. const auto &pattern = x.first;
  2825. const auto &handler = x.second;
  2826. if (std::regex_match(req.path, req.matches, pattern)) {
  2827. handler(req, res);
  2828. return true;
  2829. }
  2830. }
  2831. return false;
  2832. }
  2833. inline bool Server::dispatch_request_for_content_reader(
  2834. Request &req, Response &res, ContentReader content_reader,
  2835. HandlersForContentReader &handlers) {
  2836. for (const auto &x : handlers) {
  2837. const auto &pattern = x.first;
  2838. const auto &handler = x.second;
  2839. if (std::regex_match(req.path, req.matches, pattern)) {
  2840. handler(req, res, content_reader);
  2841. return true;
  2842. }
  2843. }
  2844. return false;
  2845. }
  2846. inline bool
  2847. Server::process_request(Stream &strm, bool last_connection,
  2848. bool &connection_close,
  2849. const std::function<void(Request &)> &setup_request) {
  2850. std::array<char, 2048> buf{};
  2851. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  2852. // Connection has been closed on client
  2853. if (!line_reader.getline()) { return false; }
  2854. Request req;
  2855. Response res;
  2856. res.version = "HTTP/1.1";
  2857. // Check if the request URI doesn't exceed the limit
  2858. if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  2859. Headers dummy;
  2860. detail::read_headers(strm, dummy);
  2861. res.status = 414;
  2862. return write_response(strm, last_connection, req, res);
  2863. }
  2864. // Request line and headers
  2865. if (!parse_request_line(line_reader.ptr(), req) ||
  2866. !detail::read_headers(strm, req.headers)) {
  2867. res.status = 400;
  2868. return write_response(strm, last_connection, req, res);
  2869. }
  2870. if (req.get_header_value("Connection") == "close") {
  2871. connection_close = true;
  2872. }
  2873. if (req.version == "HTTP/1.0" &&
  2874. req.get_header_value("Connection") != "Keep-Alive") {
  2875. connection_close = true;
  2876. }
  2877. req.set_header("REMOTE_ADDR", strm.get_remote_addr());
  2878. if (req.has_header("Range")) {
  2879. const auto &range_header_value = req.get_header_value("Range");
  2880. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  2881. // TODO: error
  2882. }
  2883. }
  2884. if (setup_request) { setup_request(req); }
  2885. // Rounting
  2886. if (routing(req, res, strm, last_connection)) {
  2887. if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
  2888. } else {
  2889. if (res.status == -1) { res.status = 404; }
  2890. }
  2891. return write_response(strm, last_connection, req, res);
  2892. }
  2893. inline bool Server::is_valid() const { return true; }
  2894. inline bool Server::process_and_close_socket(socket_t sock) {
  2895. return detail::process_and_close_socket(
  2896. false, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
  2897. [this](Stream &strm, bool last_connection, bool &connection_close) {
  2898. return process_request(strm, last_connection, connection_close,
  2899. nullptr);
  2900. });
  2901. }
  2902. // HTTP client implementation
  2903. inline Client::Client(const std::string &host, int port,
  2904. const std::string &client_cert_path,
  2905. const std::string &client_key_path)
  2906. : host_(host), port_(port),
  2907. host_and_port_(host_ + ":" + std::to_string(port_)),
  2908. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  2909. inline Client::~Client() {}
  2910. inline bool Client::is_valid() const { return true; }
  2911. inline socket_t Client::create_client_socket() const {
  2912. if (!proxy_host_.empty()) {
  2913. return detail::create_client_socket(proxy_host_.c_str(), proxy_port_,
  2914. timeout_sec_, interface_);
  2915. }
  2916. return detail::create_client_socket(host_.c_str(), port_, timeout_sec_,
  2917. interface_);
  2918. }
  2919. inline bool Client::read_response_line(Stream &strm, Response &res) {
  2920. std::array<char, 2048> buf;
  2921. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  2922. if (!line_reader.getline()) { return false; }
  2923. const static std::regex re("(HTTP/1\\.[01]) (\\d+?) .*\r\n");
  2924. std::cmatch m;
  2925. if (std::regex_match(line_reader.ptr(), m, re)) {
  2926. res.version = std::string(m[1]);
  2927. res.status = std::stoi(std::string(m[2]));
  2928. }
  2929. return true;
  2930. }
  2931. inline bool Client::send(const Request &req, Response &res) {
  2932. auto sock = create_client_socket();
  2933. if (sock == INVALID_SOCKET) { return false; }
  2934. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2935. if (is_ssl() && !proxy_host_.empty()) {
  2936. bool error;
  2937. if (!connect(sock, res, error)) { return error; }
  2938. }
  2939. #endif
  2940. return process_and_close_socket(
  2941. sock, 1, [&](Stream &strm, bool last_connection, bool &connection_close) {
  2942. return handle_request(strm, req, res, last_connection,
  2943. connection_close);
  2944. });
  2945. }
  2946. inline bool Client::send(const std::vector<Request> &requests,
  2947. std::vector<Response> &responses) {
  2948. size_t i = 0;
  2949. while (i < requests.size()) {
  2950. auto sock = create_client_socket();
  2951. if (sock == INVALID_SOCKET) { return false; }
  2952. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2953. if (is_ssl() && !proxy_host_.empty()) {
  2954. Response res;
  2955. bool error;
  2956. if (!connect(sock, res, error)) { return false; }
  2957. }
  2958. #endif
  2959. if (!process_and_close_socket(sock, requests.size() - i,
  2960. [&](Stream &strm, bool last_connection,
  2961. bool &connection_close) -> bool {
  2962. auto &req = requests[i++];
  2963. auto res = Response();
  2964. auto ret = handle_request(strm, req, res,
  2965. last_connection,
  2966. connection_close);
  2967. if (ret) {
  2968. responses.emplace_back(std::move(res));
  2969. }
  2970. return ret;
  2971. })) {
  2972. return false;
  2973. }
  2974. }
  2975. return true;
  2976. }
  2977. inline bool Client::handle_request(Stream &strm, const Request &req,
  2978. Response &res, bool last_connection,
  2979. bool &connection_close) {
  2980. if (req.path.empty()) { return false; }
  2981. bool ret;
  2982. if (!is_ssl() && !proxy_host_.empty()) {
  2983. auto req2 = req;
  2984. req2.path = "http://" + host_and_port_ + req.path;
  2985. ret = process_request(strm, req2, res, last_connection, connection_close);
  2986. } else {
  2987. ret = process_request(strm, req, res, last_connection, connection_close);
  2988. }
  2989. if (!ret) { return false; }
  2990. if (300 < res.status && res.status < 400 && follow_location_) {
  2991. ret = redirect(req, res);
  2992. }
  2993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2994. if (res.status == 401 || res.status == 407) {
  2995. auto is_proxy = res.status == 407;
  2996. const auto &username =
  2997. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  2998. const auto &password =
  2999. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  3000. if (!username.empty() && !password.empty()) {
  3001. std::map<std::string, std::string> auth;
  3002. if (parse_www_authenticate(res, auth, is_proxy)) {
  3003. Request new_req = req;
  3004. auto key = is_proxy ? "Proxy-Authorization" : "WWW-Authorization";
  3005. new_req.headers.erase(key);
  3006. new_req.headers.insert(make_digest_authentication_header(
  3007. req, auth, 1, random_string(10), username, password, is_proxy));
  3008. Response new_res;
  3009. ret = send(new_req, new_res);
  3010. if (ret) { res = new_res; }
  3011. }
  3012. }
  3013. }
  3014. #endif
  3015. return ret;
  3016. }
  3017. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3018. inline bool Client::connect(socket_t sock, Response &res, bool &error) {
  3019. error = true;
  3020. Response res2;
  3021. if (!detail::process_socket(
  3022. true, sock, 1, read_timeout_sec_, read_timeout_usec_,
  3023. [&](Stream &strm, bool /*last_connection*/, bool &connection_close) {
  3024. Request req2;
  3025. req2.method = "CONNECT";
  3026. req2.path = host_and_port_;
  3027. return process_request(strm, req2, res2, false, connection_close);
  3028. })) {
  3029. detail::close_socket(sock);
  3030. error = false;
  3031. return false;
  3032. }
  3033. if (res2.status == 407) {
  3034. if (!proxy_digest_auth_username_.empty() &&
  3035. !proxy_digest_auth_password_.empty()) {
  3036. std::map<std::string, std::string> auth;
  3037. if (parse_www_authenticate(res2, auth, true)) {
  3038. Response res3;
  3039. if (!detail::process_socket(
  3040. true, sock, 1, read_timeout_sec_, read_timeout_usec_,
  3041. [&](Stream &strm, bool /*last_connection*/,
  3042. bool &connection_close) {
  3043. Request req3;
  3044. req3.method = "CONNECT";
  3045. req3.path = host_and_port_;
  3046. req3.headers.insert(make_digest_authentication_header(
  3047. req3, auth, 1, random_string(10),
  3048. proxy_digest_auth_username_, proxy_digest_auth_password_,
  3049. true));
  3050. return process_request(strm, req3, res3, false,
  3051. connection_close);
  3052. })) {
  3053. detail::close_socket(sock);
  3054. error = false;
  3055. return false;
  3056. }
  3057. }
  3058. } else {
  3059. res = res2;
  3060. return false;
  3061. }
  3062. }
  3063. return true;
  3064. }
  3065. #endif
  3066. inline bool Client::redirect(const Request &req, Response &res) {
  3067. if (req.redirect_count == 0) { return false; }
  3068. auto location = res.get_header_value("location");
  3069. if (location.empty()) { return false; }
  3070. const static std::regex re(
  3071. R"(^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
  3072. std::smatch m;
  3073. if (!regex_match(location, m, re)) { return false; }
  3074. auto scheme = is_ssl() ? "https" : "http";
  3075. auto next_scheme = m[1].str();
  3076. auto next_host = m[2].str();
  3077. auto next_path = m[3].str();
  3078. if (next_scheme.empty()) { next_scheme = scheme; }
  3079. if (next_scheme.empty()) { next_scheme = scheme; }
  3080. if (next_host.empty()) { next_host = host_; }
  3081. if (next_path.empty()) { next_path = "/"; }
  3082. if (next_scheme == scheme && next_host == host_) {
  3083. return detail::redirect(*this, req, res, next_path);
  3084. } else {
  3085. if (next_scheme == "https") {
  3086. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3087. SSLClient cli(next_host.c_str());
  3088. cli.copy_settings(*this);
  3089. return detail::redirect(cli, req, res, next_path);
  3090. #else
  3091. return false;
  3092. #endif
  3093. } else {
  3094. Client cli(next_host.c_str());
  3095. cli.copy_settings(*this);
  3096. return detail::redirect(cli, req, res, next_path);
  3097. }
  3098. }
  3099. }
  3100. inline bool Client::write_request(Stream &strm, const Request &req,
  3101. bool last_connection) {
  3102. detail::BufferStream bstrm;
  3103. // Request line
  3104. const auto &path = detail::encode_url(req.path);
  3105. bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
  3106. // Additonal headers
  3107. Headers headers;
  3108. if (last_connection) { headers.emplace("Connection", "close"); }
  3109. if (!req.has_header("Host")) {
  3110. if (is_ssl()) {
  3111. if (port_ == 443) {
  3112. headers.emplace("Host", host_);
  3113. } else {
  3114. headers.emplace("Host", host_and_port_);
  3115. }
  3116. } else {
  3117. if (port_ == 80) {
  3118. headers.emplace("Host", host_);
  3119. } else {
  3120. headers.emplace("Host", host_and_port_);
  3121. }
  3122. }
  3123. }
  3124. if (!req.has_header("Accept")) { headers.emplace("Accept", "*/*"); }
  3125. if (!req.has_header("User-Agent")) {
  3126. headers.emplace("User-Agent", "cpp-httplib/0.5");
  3127. }
  3128. if (req.body.empty()) {
  3129. if (req.content_provider) {
  3130. auto length = std::to_string(req.content_length);
  3131. headers.emplace("Content-Length", length);
  3132. } else {
  3133. headers.emplace("Content-Length", "0");
  3134. }
  3135. } else {
  3136. if (!req.has_header("Content-Type")) {
  3137. headers.emplace("Content-Type", "text/plain");
  3138. }
  3139. if (!req.has_header("Content-Length")) {
  3140. auto length = std::to_string(req.body.size());
  3141. headers.emplace("Content-Length", length);
  3142. }
  3143. }
  3144. if (!basic_auth_username_.empty() && !basic_auth_password_.empty()) {
  3145. headers.insert(make_basic_authentication_header(
  3146. basic_auth_username_, basic_auth_password_, false));
  3147. }
  3148. if (!proxy_basic_auth_username_.empty() &&
  3149. !proxy_basic_auth_password_.empty()) {
  3150. headers.insert(make_basic_authentication_header(
  3151. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  3152. }
  3153. detail::write_headers(bstrm, req, headers);
  3154. // Flush buffer
  3155. auto &data = bstrm.get_buffer();
  3156. strm.write(data.data(), data.size());
  3157. // Body
  3158. if (req.body.empty()) {
  3159. if (req.content_provider) {
  3160. size_t offset = 0;
  3161. size_t end_offset = req.content_length;
  3162. DataSink data_sink;
  3163. data_sink.write = [&](const char *d, size_t l) {
  3164. auto written_length = strm.write(d, l);
  3165. offset += written_length;
  3166. };
  3167. data_sink.is_writable = [&](void) { return strm.is_writable(); };
  3168. while (offset < end_offset) {
  3169. req.content_provider(offset, end_offset - offset, data_sink);
  3170. }
  3171. }
  3172. } else {
  3173. strm.write(req.body);
  3174. }
  3175. return true;
  3176. }
  3177. inline std::shared_ptr<Response> Client::send_with_content_provider(
  3178. const char *method, const char *path, const Headers &headers,
  3179. const std::string &body, size_t content_length,
  3180. ContentProvider content_provider, const char *content_type) {
  3181. Request req;
  3182. req.method = method;
  3183. req.headers = headers;
  3184. req.path = path;
  3185. req.headers.emplace("Content-Type", content_type);
  3186. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3187. if (compress_) {
  3188. if (content_provider) {
  3189. size_t offset = 0;
  3190. DataSink data_sink;
  3191. data_sink.write = [&](const char *data, size_t data_len) {
  3192. req.body.append(data, data_len);
  3193. offset += data_len;
  3194. };
  3195. data_sink.is_writable = [&](void) { return true; };
  3196. while (offset < content_length) {
  3197. content_provider(offset, content_length - offset, data_sink);
  3198. }
  3199. } else {
  3200. req.body = body;
  3201. }
  3202. if (!detail::compress(req.body)) { return nullptr; }
  3203. req.headers.emplace("Content-Encoding", "gzip");
  3204. } else
  3205. #endif
  3206. {
  3207. if (content_provider) {
  3208. req.content_length = content_length;
  3209. req.content_provider = content_provider;
  3210. } else {
  3211. req.body = body;
  3212. }
  3213. }
  3214. auto res = std::make_shared<Response>();
  3215. return send(req, *res) ? res : nullptr;
  3216. }
  3217. inline bool Client::process_request(Stream &strm, const Request &req,
  3218. Response &res, bool last_connection,
  3219. bool &connection_close) {
  3220. // Send request
  3221. if (!write_request(strm, req, last_connection)) { return false; }
  3222. // Receive response and headers
  3223. if (!read_response_line(strm, res) ||
  3224. !detail::read_headers(strm, res.headers)) {
  3225. return false;
  3226. }
  3227. if (res.get_header_value("Connection") == "close" ||
  3228. res.version == "HTTP/1.0") {
  3229. connection_close = true;
  3230. }
  3231. if (req.response_handler) {
  3232. if (!req.response_handler(res)) { return false; }
  3233. }
  3234. // Body
  3235. if (req.method != "HEAD" && req.method != "CONNECT") {
  3236. ContentReceiver out = [&](const char *buf, size_t n) {
  3237. if (res.body.size() + n > res.body.max_size()) { return false; }
  3238. res.body.append(buf, n);
  3239. return true;
  3240. };
  3241. if (req.content_receiver) {
  3242. out = [&](const char *buf, size_t n) {
  3243. return req.content_receiver(buf, n);
  3244. };
  3245. }
  3246. int dummy_status;
  3247. if (!detail::read_content(strm, res, std::numeric_limits<size_t>::max(),
  3248. dummy_status, req.progress, out)) {
  3249. return false;
  3250. }
  3251. }
  3252. // Log
  3253. if (logger_) { logger_(req, res); }
  3254. return true;
  3255. }
  3256. inline bool Client::process_and_close_socket(
  3257. socket_t sock, size_t request_count,
  3258. std::function<bool(Stream &strm, bool last_connection,
  3259. bool &connection_close)>
  3260. callback) {
  3261. request_count = std::min(request_count, keep_alive_max_count_);
  3262. return detail::process_and_close_socket(true, sock, request_count,
  3263. read_timeout_sec_, read_timeout_usec_,
  3264. callback);
  3265. }
  3266. inline bool Client::is_ssl() const { return false; }
  3267. inline std::shared_ptr<Response> Client::Get(const char *path) {
  3268. return Get(path, Headers(), Progress());
  3269. }
  3270. inline std::shared_ptr<Response> Client::Get(const char *path,
  3271. Progress progress) {
  3272. return Get(path, Headers(), std::move(progress));
  3273. }
  3274. inline std::shared_ptr<Response> Client::Get(const char *path,
  3275. const Headers &headers) {
  3276. return Get(path, headers, Progress());
  3277. }
  3278. inline std::shared_ptr<Response>
  3279. Client::Get(const char *path, const Headers &headers, Progress progress) {
  3280. Request req;
  3281. req.method = "GET";
  3282. req.path = path;
  3283. req.headers = headers;
  3284. req.progress = std::move(progress);
  3285. auto res = std::make_shared<Response>();
  3286. return send(req, *res) ? res : nullptr;
  3287. }
  3288. inline std::shared_ptr<Response> Client::Get(const char *path,
  3289. ContentReceiver content_receiver) {
  3290. return Get(path, Headers(), nullptr, std::move(content_receiver), Progress());
  3291. }
  3292. inline std::shared_ptr<Response> Client::Get(const char *path,
  3293. ContentReceiver content_receiver,
  3294. Progress progress) {
  3295. return Get(path, Headers(), nullptr, std::move(content_receiver),
  3296. std::move(progress));
  3297. }
  3298. inline std::shared_ptr<Response> Client::Get(const char *path,
  3299. const Headers &headers,
  3300. ContentReceiver content_receiver) {
  3301. return Get(path, headers, nullptr, std::move(content_receiver), Progress());
  3302. }
  3303. inline std::shared_ptr<Response> Client::Get(const char *path,
  3304. const Headers &headers,
  3305. ContentReceiver content_receiver,
  3306. Progress progress) {
  3307. return Get(path, headers, nullptr, std::move(content_receiver),
  3308. std::move(progress));
  3309. }
  3310. inline std::shared_ptr<Response> Client::Get(const char *path,
  3311. const Headers &headers,
  3312. ResponseHandler response_handler,
  3313. ContentReceiver content_receiver) {
  3314. return Get(path, headers, std::move(response_handler), content_receiver,
  3315. Progress());
  3316. }
  3317. inline std::shared_ptr<Response> Client::Get(const char *path,
  3318. const Headers &headers,
  3319. ResponseHandler response_handler,
  3320. ContentReceiver content_receiver,
  3321. Progress progress) {
  3322. Request req;
  3323. req.method = "GET";
  3324. req.path = path;
  3325. req.headers = headers;
  3326. req.response_handler = std::move(response_handler);
  3327. req.content_receiver = std::move(content_receiver);
  3328. req.progress = std::move(progress);
  3329. auto res = std::make_shared<Response>();
  3330. return send(req, *res) ? res : nullptr;
  3331. }
  3332. inline std::shared_ptr<Response> Client::Head(const char *path) {
  3333. return Head(path, Headers());
  3334. }
  3335. inline std::shared_ptr<Response> Client::Head(const char *path,
  3336. const Headers &headers) {
  3337. Request req;
  3338. req.method = "HEAD";
  3339. req.headers = headers;
  3340. req.path = path;
  3341. auto res = std::make_shared<Response>();
  3342. return send(req, *res) ? res : nullptr;
  3343. }
  3344. inline std::shared_ptr<Response> Client::Post(const char *path,
  3345. const std::string &body,
  3346. const char *content_type) {
  3347. return Post(path, Headers(), body, content_type);
  3348. }
  3349. inline std::shared_ptr<Response> Client::Post(const char *path,
  3350. const Headers &headers,
  3351. const std::string &body,
  3352. const char *content_type) {
  3353. return send_with_content_provider("POST", path, headers, body, 0, nullptr,
  3354. content_type);
  3355. }
  3356. inline std::shared_ptr<Response> Client::Post(const char *path,
  3357. const Params &params) {
  3358. return Post(path, Headers(), params);
  3359. }
  3360. inline std::shared_ptr<Response> Client::Post(const char *path,
  3361. size_t content_length,
  3362. ContentProvider content_provider,
  3363. const char *content_type) {
  3364. return Post(path, Headers(), content_length, content_provider, content_type);
  3365. }
  3366. inline std::shared_ptr<Response>
  3367. Client::Post(const char *path, const Headers &headers, size_t content_length,
  3368. ContentProvider content_provider, const char *content_type) {
  3369. return send_with_content_provider("POST", path, headers, std::string(),
  3370. content_length, content_provider,
  3371. content_type);
  3372. }
  3373. inline std::shared_ptr<Response>
  3374. Client::Post(const char *path, const Headers &headers, const Params &params) {
  3375. std::string query;
  3376. for (auto it = params.begin(); it != params.end(); ++it) {
  3377. if (it != params.begin()) { query += "&"; }
  3378. query += it->first;
  3379. query += "=";
  3380. query += detail::encode_url(it->second);
  3381. }
  3382. return Post(path, headers, query, "application/x-www-form-urlencoded");
  3383. }
  3384. inline std::shared_ptr<Response>
  3385. Client::Post(const char *path, const MultipartFormDataItems &items) {
  3386. return Post(path, Headers(), items);
  3387. }
  3388. inline std::shared_ptr<Response>
  3389. Client::Post(const char *path, const Headers &headers,
  3390. const MultipartFormDataItems &items) {
  3391. auto boundary = detail::make_multipart_data_boundary();
  3392. std::string body;
  3393. for (const auto &item : items) {
  3394. body += "--" + boundary + "\r\n";
  3395. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3396. if (!item.filename.empty()) {
  3397. body += "; filename=\"" + item.filename + "\"";
  3398. }
  3399. body += "\r\n";
  3400. if (!item.content_type.empty()) {
  3401. body += "Content-Type: " + item.content_type + "\r\n";
  3402. }
  3403. body += "\r\n";
  3404. body += item.content + "\r\n";
  3405. }
  3406. body += "--" + boundary + "--\r\n";
  3407. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3408. return Post(path, headers, body, content_type.c_str());
  3409. }
  3410. inline std::shared_ptr<Response> Client::Put(const char *path,
  3411. const std::string &body,
  3412. const char *content_type) {
  3413. return Put(path, Headers(), body, content_type);
  3414. }
  3415. inline std::shared_ptr<Response> Client::Put(const char *path,
  3416. const Headers &headers,
  3417. const std::string &body,
  3418. const char *content_type) {
  3419. return send_with_content_provider("PUT", path, headers, body, 0, nullptr,
  3420. content_type);
  3421. }
  3422. inline std::shared_ptr<Response> Client::Put(const char *path,
  3423. size_t content_length,
  3424. ContentProvider content_provider,
  3425. const char *content_type) {
  3426. return Put(path, Headers(), content_length, content_provider, content_type);
  3427. }
  3428. inline std::shared_ptr<Response>
  3429. Client::Put(const char *path, const Headers &headers, size_t content_length,
  3430. ContentProvider content_provider, const char *content_type) {
  3431. return send_with_content_provider("PUT", path, headers, std::string(),
  3432. content_length, content_provider,
  3433. content_type);
  3434. }
  3435. inline std::shared_ptr<Response> Client::Put(const char *path,
  3436. const Params &params) {
  3437. return Put(path, Headers(), params);
  3438. }
  3439. inline std::shared_ptr<Response>
  3440. Client::Put(const char *path, const Headers &headers, const Params &params) {
  3441. std::string query;
  3442. for (auto it = params.begin(); it != params.end(); ++it) {
  3443. if (it != params.begin()) { query += "&"; }
  3444. query += it->first;
  3445. query += "=";
  3446. query += detail::encode_url(it->second);
  3447. }
  3448. return Put(path, headers, query, "application/x-www-form-urlencoded");
  3449. }
  3450. inline std::shared_ptr<Response> Client::Patch(const char *path,
  3451. const std::string &body,
  3452. const char *content_type) {
  3453. return Patch(path, Headers(), body, content_type);
  3454. }
  3455. inline std::shared_ptr<Response> Client::Patch(const char *path,
  3456. const Headers &headers,
  3457. const std::string &body,
  3458. const char *content_type) {
  3459. return send_with_content_provider("PATCH", path, headers, body, 0, nullptr,
  3460. content_type);
  3461. }
  3462. inline std::shared_ptr<Response> Client::Patch(const char *path,
  3463. size_t content_length,
  3464. ContentProvider content_provider,
  3465. const char *content_type) {
  3466. return Patch(path, Headers(), content_length, content_provider, content_type);
  3467. }
  3468. inline std::shared_ptr<Response>
  3469. Client::Patch(const char *path, const Headers &headers, size_t content_length,
  3470. ContentProvider content_provider, const char *content_type) {
  3471. return send_with_content_provider("PATCH", path, headers, std::string(),
  3472. content_length, content_provider,
  3473. content_type);
  3474. }
  3475. inline std::shared_ptr<Response> Client::Delete(const char *path) {
  3476. return Delete(path, Headers(), std::string(), nullptr);
  3477. }
  3478. inline std::shared_ptr<Response> Client::Delete(const char *path,
  3479. const std::string &body,
  3480. const char *content_type) {
  3481. return Delete(path, Headers(), body, content_type);
  3482. }
  3483. inline std::shared_ptr<Response> Client::Delete(const char *path,
  3484. const Headers &headers) {
  3485. return Delete(path, headers, std::string(), nullptr);
  3486. }
  3487. inline std::shared_ptr<Response> Client::Delete(const char *path,
  3488. const Headers &headers,
  3489. const std::string &body,
  3490. const char *content_type) {
  3491. Request req;
  3492. req.method = "DELETE";
  3493. req.headers = headers;
  3494. req.path = path;
  3495. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  3496. req.body = body;
  3497. auto res = std::make_shared<Response>();
  3498. return send(req, *res) ? res : nullptr;
  3499. }
  3500. inline std::shared_ptr<Response> Client::Options(const char *path) {
  3501. return Options(path, Headers());
  3502. }
  3503. inline std::shared_ptr<Response> Client::Options(const char *path,
  3504. const Headers &headers) {
  3505. Request req;
  3506. req.method = "OPTIONS";
  3507. req.path = path;
  3508. req.headers = headers;
  3509. auto res = std::make_shared<Response>();
  3510. return send(req, *res) ? res : nullptr;
  3511. }
  3512. inline void Client::set_timeout_sec(time_t timeout_sec) {
  3513. timeout_sec_ = timeout_sec;
  3514. }
  3515. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  3516. read_timeout_sec_ = sec;
  3517. read_timeout_usec_ = usec;
  3518. }
  3519. inline void Client::set_keep_alive_max_count(size_t count) {
  3520. keep_alive_max_count_ = count;
  3521. }
  3522. inline void Client::set_basic_auth(const char *username, const char *password) {
  3523. basic_auth_username_ = username;
  3524. basic_auth_password_ = password;
  3525. }
  3526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3527. inline void Client::set_digest_auth(const char *username,
  3528. const char *password) {
  3529. digest_auth_username_ = username;
  3530. digest_auth_password_ = password;
  3531. }
  3532. #endif
  3533. inline void Client::set_follow_location(bool on) { follow_location_ = on; }
  3534. inline void Client::set_compress(bool on) { compress_ = on; }
  3535. inline void Client::set_interface(const char *intf) { interface_ = intf; }
  3536. inline void Client::set_proxy(const char *host, int port) {
  3537. proxy_host_ = host;
  3538. proxy_port_ = port;
  3539. }
  3540. inline void Client::set_proxy_basic_auth(const char *username,
  3541. const char *password) {
  3542. proxy_basic_auth_username_ = username;
  3543. proxy_basic_auth_password_ = password;
  3544. }
  3545. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3546. inline void Client::set_proxy_digest_auth(const char *username,
  3547. const char *password) {
  3548. proxy_digest_auth_username_ = username;
  3549. proxy_digest_auth_password_ = password;
  3550. }
  3551. #endif
  3552. inline void Client::set_logger(Logger logger) { logger_ = std::move(logger); }
  3553. /*
  3554. * SSL Implementation
  3555. */
  3556. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3557. namespace detail {
  3558. template <typename U, typename V, typename T>
  3559. inline bool process_and_close_socket_ssl(
  3560. bool is_client_request, socket_t sock, size_t keep_alive_max_count,
  3561. time_t read_timeout_sec, time_t read_timeout_usec, SSL_CTX *ctx,
  3562. std::mutex &ctx_mutex, U SSL_connect_or_accept, V setup, T callback) {
  3563. assert(keep_alive_max_count > 0);
  3564. SSL *ssl = nullptr;
  3565. {
  3566. std::lock_guard<std::mutex> guard(ctx_mutex);
  3567. ssl = SSL_new(ctx);
  3568. }
  3569. if (!ssl) {
  3570. close_socket(sock);
  3571. return false;
  3572. }
  3573. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  3574. SSL_set_bio(ssl, bio, bio);
  3575. if (!setup(ssl)) {
  3576. SSL_shutdown(ssl);
  3577. {
  3578. std::lock_guard<std::mutex> guard(ctx_mutex);
  3579. SSL_free(ssl);
  3580. }
  3581. close_socket(sock);
  3582. return false;
  3583. }
  3584. auto ret = false;
  3585. if (SSL_connect_or_accept(ssl) == 1) {
  3586. if (keep_alive_max_count > 1) {
  3587. auto count = keep_alive_max_count;
  3588. while (count > 0 &&
  3589. (is_client_request ||
  3590. detail::select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  3591. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
  3592. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec);
  3593. auto last_connection = count == 1;
  3594. auto connection_close = false;
  3595. ret = callback(ssl, strm, last_connection, connection_close);
  3596. if (!ret || connection_close) { break; }
  3597. count--;
  3598. }
  3599. } else {
  3600. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec);
  3601. auto dummy_connection_close = false;
  3602. ret = callback(ssl, strm, true, dummy_connection_close);
  3603. }
  3604. }
  3605. SSL_shutdown(ssl);
  3606. {
  3607. std::lock_guard<std::mutex> guard(ctx_mutex);
  3608. SSL_free(ssl);
  3609. }
  3610. close_socket(sock);
  3611. return ret;
  3612. }
  3613. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  3614. static std::shared_ptr<std::vector<std::mutex>> openSSL_locks_;
  3615. class SSLThreadLocks {
  3616. public:
  3617. SSLThreadLocks() {
  3618. openSSL_locks_ =
  3619. std::make_shared<std::vector<std::mutex>>(CRYPTO_num_locks());
  3620. CRYPTO_set_locking_callback(locking_callback);
  3621. }
  3622. ~SSLThreadLocks() { CRYPTO_set_locking_callback(nullptr); }
  3623. private:
  3624. static void locking_callback(int mode, int type, const char * /*file*/,
  3625. int /*line*/) {
  3626. auto &locks = *openSSL_locks_;
  3627. if (mode & CRYPTO_LOCK) {
  3628. locks[type].lock();
  3629. } else {
  3630. locks[type].unlock();
  3631. }
  3632. }
  3633. };
  3634. #endif
  3635. class SSLInit {
  3636. public:
  3637. SSLInit() {
  3638. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  3639. SSL_load_error_strings();
  3640. SSL_library_init();
  3641. #else
  3642. OPENSSL_init_ssl(
  3643. OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
  3644. #endif
  3645. }
  3646. ~SSLInit() {
  3647. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  3648. ERR_free_strings();
  3649. #endif
  3650. }
  3651. private:
  3652. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  3653. SSLThreadLocks thread_init_;
  3654. #endif
  3655. };
  3656. // SSL socket stream implementation
  3657. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
  3658. time_t read_timeout_sec,
  3659. time_t read_timeout_usec)
  3660. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  3661. read_timeout_usec_(read_timeout_usec) {}
  3662. inline SSLSocketStream::~SSLSocketStream() {}
  3663. inline bool SSLSocketStream::is_readable() const {
  3664. return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  3665. }
  3666. inline bool SSLSocketStream::is_writable() const {
  3667. return detail::select_write(sock_, 0, 0) > 0;
  3668. }
  3669. inline int SSLSocketStream::read(char *ptr, size_t size) {
  3670. if (SSL_pending(ssl_) > 0 ||
  3671. select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0) {
  3672. return SSL_read(ssl_, ptr, static_cast<int>(size));
  3673. }
  3674. return -1;
  3675. }
  3676. inline int SSLSocketStream::write(const char *ptr, size_t size) {
  3677. if (is_writable()) { return SSL_write(ssl_, ptr, static_cast<int>(size)); }
  3678. return -1;
  3679. }
  3680. inline std::string SSLSocketStream::get_remote_addr() const {
  3681. return detail::get_remote_addr(sock_);
  3682. }
  3683. static SSLInit sslinit_;
  3684. } // namespace detail
  3685. // SSL HTTP server implementation
  3686. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  3687. const char *client_ca_cert_file_path,
  3688. const char *client_ca_cert_dir_path) {
  3689. ctx_ = SSL_CTX_new(SSLv23_server_method());
  3690. if (ctx_) {
  3691. SSL_CTX_set_options(ctx_,
  3692. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  3693. SSL_OP_NO_COMPRESSION |
  3694. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  3695. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  3696. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  3697. // EC_KEY_free(ecdh);
  3698. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  3699. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  3700. 1) {
  3701. SSL_CTX_free(ctx_);
  3702. ctx_ = nullptr;
  3703. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  3704. // if (client_ca_cert_file_path) {
  3705. // auto list = SSL_load_client_CA_file(client_ca_cert_file_path);
  3706. // SSL_CTX_set_client_CA_list(ctx_, list);
  3707. // }
  3708. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  3709. client_ca_cert_dir_path);
  3710. SSL_CTX_set_verify(
  3711. ctx_,
  3712. SSL_VERIFY_PEER |
  3713. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  3714. nullptr);
  3715. }
  3716. }
  3717. }
  3718. inline SSLServer::~SSLServer() {
  3719. if (ctx_) { SSL_CTX_free(ctx_); }
  3720. }
  3721. inline bool SSLServer::is_valid() const { return ctx_; }
  3722. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  3723. return detail::process_and_close_socket_ssl(
  3724. false, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
  3725. ctx_, ctx_mutex_, SSL_accept, [](SSL * /*ssl*/) { return true; },
  3726. [this](SSL *ssl, Stream &strm, bool last_connection,
  3727. bool &connection_close) {
  3728. return process_request(strm, last_connection, connection_close,
  3729. [&](Request &req) { req.ssl = ssl; });
  3730. });
  3731. }
  3732. // SSL HTTP client implementation
  3733. inline SSLClient::SSLClient(const std::string &host, int port,
  3734. const std::string &client_cert_path,
  3735. const std::string &client_key_path)
  3736. : Client(host, port, client_cert_path, client_key_path) {
  3737. ctx_ = SSL_CTX_new(SSLv23_client_method());
  3738. detail::split(&host_[0], &host_[host_.size()], '.',
  3739. [&](const char *b, const char *e) {
  3740. host_components_.emplace_back(std::string(b, e));
  3741. });
  3742. if (!client_cert_path.empty() && !client_key_path.empty()) {
  3743. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  3744. SSL_FILETYPE_PEM) != 1 ||
  3745. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  3746. SSL_FILETYPE_PEM) != 1) {
  3747. SSL_CTX_free(ctx_);
  3748. ctx_ = nullptr;
  3749. }
  3750. }
  3751. }
  3752. inline SSLClient::~SSLClient() {
  3753. if (ctx_) { SSL_CTX_free(ctx_); }
  3754. }
  3755. inline bool SSLClient::is_valid() const { return ctx_; }
  3756. inline void SSLClient::set_ca_cert_path(const char *ca_cert_file_path,
  3757. const char *ca_cert_dir_path) {
  3758. if (ca_cert_file_path) { ca_cert_file_path_ = ca_cert_file_path; }
  3759. if (ca_cert_dir_path) { ca_cert_dir_path_ = ca_cert_dir_path; }
  3760. }
  3761. inline void SSLClient::enable_server_certificate_verification(bool enabled) {
  3762. server_certificate_verification_ = enabled;
  3763. }
  3764. inline long SSLClient::get_openssl_verify_result() const {
  3765. return verify_result_;
  3766. }
  3767. inline SSL_CTX *SSLClient::ssl_context() const noexcept { return ctx_; }
  3768. inline bool SSLClient::process_and_close_socket(
  3769. socket_t sock, size_t request_count,
  3770. std::function<bool(Stream &strm, bool last_connection,
  3771. bool &connection_close)>
  3772. callback) {
  3773. request_count = std::min(request_count, keep_alive_max_count_);
  3774. return is_valid() &&
  3775. detail::process_and_close_socket_ssl(
  3776. true, sock, request_count, read_timeout_sec_, read_timeout_usec_,
  3777. ctx_, ctx_mutex_,
  3778. [&](SSL *ssl) {
  3779. if (ca_cert_file_path_.empty()) {
  3780. SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, nullptr);
  3781. } else {
  3782. if (!SSL_CTX_load_verify_locations(
  3783. ctx_, ca_cert_file_path_.c_str(), nullptr)) {
  3784. return false;
  3785. }
  3786. SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER, nullptr);
  3787. }
  3788. if (SSL_connect(ssl) != 1) { return false; }
  3789. if (server_certificate_verification_) {
  3790. verify_result_ = SSL_get_verify_result(ssl);
  3791. if (verify_result_ != X509_V_OK) { return false; }
  3792. auto server_cert = SSL_get_peer_certificate(ssl);
  3793. if (server_cert == nullptr) { return false; }
  3794. if (!verify_host(server_cert)) {
  3795. X509_free(server_cert);
  3796. return false;
  3797. }
  3798. X509_free(server_cert);
  3799. }
  3800. return true;
  3801. },
  3802. [&](SSL *ssl) {
  3803. SSL_set_tlsext_host_name(ssl, host_.c_str());
  3804. return true;
  3805. },
  3806. [&](SSL * /*ssl*/, Stream &strm, bool last_connection,
  3807. bool &connection_close) {
  3808. return callback(strm, last_connection, connection_close);
  3809. });
  3810. }
  3811. inline bool SSLClient::is_ssl() const { return true; }
  3812. inline bool SSLClient::verify_host(X509 *server_cert) const {
  3813. /* Quote from RFC2818 section 3.1 "Server Identity"
  3814. If a subjectAltName extension of type dNSName is present, that MUST
  3815. be used as the identity. Otherwise, the (most specific) Common Name
  3816. field in the Subject field of the certificate MUST be used. Although
  3817. the use of the Common Name is existing practice, it is deprecated and
  3818. Certification Authorities are encouraged to use the dNSName instead.
  3819. Matching is performed using the matching rules specified by
  3820. [RFC2459]. If more than one identity of a given type is present in
  3821. the certificate (e.g., more than one dNSName name, a match in any one
  3822. of the set is considered acceptable.) Names may contain the wildcard
  3823. character * which is considered to match any single domain name
  3824. component or component fragment. E.g., *.a.com matches foo.a.com but
  3825. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  3826. In some cases, the URI is specified as an IP address rather than a
  3827. hostname. In this case, the iPAddress subjectAltName must be present
  3828. in the certificate and must exactly match the IP in the URI.
  3829. */
  3830. return verify_host_with_subject_alt_name(server_cert) ||
  3831. verify_host_with_common_name(server_cert);
  3832. }
  3833. inline bool
  3834. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  3835. auto ret = false;
  3836. auto type = GEN_DNS;
  3837. struct in6_addr addr6;
  3838. struct in_addr addr;
  3839. size_t addr_len = 0;
  3840. #ifndef __MINGW32__
  3841. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  3842. type = GEN_IPADD;
  3843. addr_len = sizeof(struct in6_addr);
  3844. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  3845. type = GEN_IPADD;
  3846. addr_len = sizeof(struct in_addr);
  3847. }
  3848. #endif
  3849. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  3850. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  3851. if (alt_names) {
  3852. auto dsn_matched = false;
  3853. auto ip_mached = false;
  3854. auto count = sk_GENERAL_NAME_num(alt_names);
  3855. for (auto i = 0; i < count && !dsn_matched; i++) {
  3856. auto val = sk_GENERAL_NAME_value(alt_names, i);
  3857. if (val->type == type) {
  3858. auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);
  3859. auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);
  3860. if (strlen(name) == name_len) {
  3861. switch (type) {
  3862. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  3863. case GEN_IPADD:
  3864. if (!memcmp(&addr6, name, addr_len) ||
  3865. !memcmp(&addr, name, addr_len)) {
  3866. ip_mached = true;
  3867. }
  3868. break;
  3869. }
  3870. }
  3871. }
  3872. }
  3873. if (dsn_matched || ip_mached) { ret = true; }
  3874. }
  3875. GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);
  3876. return ret;
  3877. }
  3878. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  3879. const auto subject_name = X509_get_subject_name(server_cert);
  3880. if (subject_name != nullptr) {
  3881. char name[BUFSIZ];
  3882. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3883. name, sizeof(name));
  3884. if (name_len != -1) { return check_host_name(name, name_len); }
  3885. }
  3886. return false;
  3887. }
  3888. inline bool SSLClient::check_host_name(const char *pattern,
  3889. size_t pattern_len) const {
  3890. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  3891. // Wildcard match
  3892. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  3893. std::vector<std::string> pattern_components;
  3894. detail::split(&pattern[0], &pattern[pattern_len], '.',
  3895. [&](const char *b, const char *e) {
  3896. pattern_components.emplace_back(std::string(b, e));
  3897. });
  3898. if (host_components_.size() != pattern_components.size()) { return false; }
  3899. auto itr = pattern_components.begin();
  3900. for (const auto &h : host_components_) {
  3901. auto &p = *itr;
  3902. if (p != h && p != "*") {
  3903. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  3904. !p.compare(0, p.size() - 1, h));
  3905. if (!partial_match) { return false; }
  3906. }
  3907. ++itr;
  3908. }
  3909. return true;
  3910. }
  3911. #endif
  3912. // ----------------------------------------------------------------------------
  3913. } // namespace httplib
  3914. #endif // CPPHTTPLIB_HTTPLIB_H