httplib.h 128 KB

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