httplib.h 153 KB

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