httplib.h 384 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2025 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.23.0"
  10. /*
  11. * Platform compatibility check
  12. */
  13. #if defined(_WIN32) && !defined(_WIN64)
  14. #error \
  15. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler."
  16. #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8
  17. #error \
  18. "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler."
  19. #elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8
  20. #error \
  21. "cpp-httplib doesn't support platforms where size_t is less than 64 bits."
  22. #endif
  23. #ifdef _WIN32
  24. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0602
  25. #error \
  26. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  27. #endif
  28. #endif
  29. /*
  30. * Configuration
  31. */
  32. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  33. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  34. #endif
  35. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  36. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  37. #endif
  38. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  39. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  40. #endif
  41. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  43. #endif
  44. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  49. #endif
  50. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  60. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  61. #endif
  62. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  63. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  64. #endif
  65. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  66. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  67. #endif
  68. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  69. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  70. #endif
  71. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  73. #endif
  74. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  75. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  78. #ifdef _WIN64
  79. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  80. #else
  81. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  82. #endif
  83. #endif
  84. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  85. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  86. #endif
  87. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  88. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  89. #endif
  90. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  91. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  92. #endif
  93. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  94. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  95. #endif
  96. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  97. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  98. #endif
  99. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  100. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  101. #endif
  102. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  103. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  104. #endif
  105. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  106. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  107. #endif
  108. #ifndef CPPHTTPLIB_TCP_NODELAY
  109. #define CPPHTTPLIB_TCP_NODELAY false
  110. #endif
  111. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  112. #define CPPHTTPLIB_IPV6_V6ONLY false
  113. #endif
  114. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  115. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  116. #endif
  117. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  118. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  119. #endif
  120. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  121. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  124. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  125. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  126. ? std::thread::hardware_concurrency() - 1 \
  127. : 0))
  128. #endif
  129. #ifndef CPPHTTPLIB_RECV_FLAGS
  130. #define CPPHTTPLIB_RECV_FLAGS 0
  131. #endif
  132. #ifndef CPPHTTPLIB_SEND_FLAGS
  133. #define CPPHTTPLIB_SEND_FLAGS 0
  134. #endif
  135. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  136. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  137. #endif
  138. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  139. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  140. #endif
  141. /*
  142. * Headers
  143. */
  144. #ifdef _WIN64
  145. #ifndef _CRT_SECURE_NO_WARNINGS
  146. #define _CRT_SECURE_NO_WARNINGS
  147. #endif //_CRT_SECURE_NO_WARNINGS
  148. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  149. #define _CRT_NONSTDC_NO_DEPRECATE
  150. #endif //_CRT_NONSTDC_NO_DEPRECATE
  151. #if defined(_MSC_VER)
  152. #if _MSC_VER < 1900
  153. #error Sorry, Visual Studio versions prior to 2015 are not supported
  154. #endif
  155. #pragma comment(lib, "ws2_32.lib")
  156. using ssize_t = __int64;
  157. #endif // _MSC_VER
  158. #ifndef S_ISREG
  159. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  160. #endif // S_ISREG
  161. #ifndef S_ISDIR
  162. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  163. #endif // S_ISDIR
  164. #ifndef NOMINMAX
  165. #define NOMINMAX
  166. #endif // NOMINMAX
  167. #include <io.h>
  168. #include <winsock2.h>
  169. #include <ws2tcpip.h>
  170. #if defined(__has_include)
  171. #if __has_include(<afunix.h>)
  172. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  173. #include <afunix.h>
  174. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  175. #endif
  176. #endif
  177. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  178. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  179. #endif
  180. using nfds_t = unsigned long;
  181. using socket_t = SOCKET;
  182. using socklen_t = int;
  183. #else // not _WIN64
  184. #include <arpa/inet.h>
  185. #if !defined(_AIX) && !defined(__MVS__)
  186. #include <ifaddrs.h>
  187. #endif
  188. #ifdef __MVS__
  189. #include <strings.h>
  190. #ifndef NI_MAXHOST
  191. #define NI_MAXHOST 1025
  192. #endif
  193. #endif
  194. #include <net/if.h>
  195. #include <netdb.h>
  196. #include <netinet/in.h>
  197. #ifdef __linux__
  198. #include <resolv.h>
  199. #endif
  200. #include <csignal>
  201. #include <netinet/tcp.h>
  202. #include <poll.h>
  203. #include <pthread.h>
  204. #include <sys/mman.h>
  205. #include <sys/socket.h>
  206. #include <sys/un.h>
  207. #include <unistd.h>
  208. using socket_t = int;
  209. #ifndef INVALID_SOCKET
  210. #define INVALID_SOCKET (-1)
  211. #endif
  212. #endif //_WIN64
  213. #if defined(__APPLE__)
  214. #include <TargetConditionals.h>
  215. #endif
  216. #include <algorithm>
  217. #include <array>
  218. #include <atomic>
  219. #include <cassert>
  220. #include <cctype>
  221. #include <climits>
  222. #include <condition_variable>
  223. #include <cstring>
  224. #include <errno.h>
  225. #include <exception>
  226. #include <fcntl.h>
  227. #include <functional>
  228. #include <iomanip>
  229. #include <iostream>
  230. #include <list>
  231. #include <map>
  232. #include <memory>
  233. #include <mutex>
  234. #include <random>
  235. #include <regex>
  236. #include <set>
  237. #include <sstream>
  238. #include <string>
  239. #include <sys/stat.h>
  240. #include <thread>
  241. #include <unordered_map>
  242. #include <unordered_set>
  243. #include <utility>
  244. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  245. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  246. #if TARGET_OS_OSX
  247. #include <CFNetwork/CFHost.h>
  248. #include <CoreFoundation/CoreFoundation.h>
  249. #endif
  250. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or
  251. // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  252. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  253. #ifdef _WIN64
  254. #include <wincrypt.h>
  255. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  256. // used
  257. #undef X509_NAME
  258. #undef X509_CERT_PAIR
  259. #undef X509_EXTENSIONS
  260. #undef PKCS7_SIGNER_INFO
  261. #ifdef _MSC_VER
  262. #pragma comment(lib, "crypt32.lib")
  263. #endif
  264. #endif // _WIN64
  265. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  266. #if TARGET_OS_OSX
  267. #include <Security/Security.h>
  268. #endif
  269. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  270. #include <openssl/err.h>
  271. #include <openssl/evp.h>
  272. #include <openssl/ssl.h>
  273. #include <openssl/x509v3.h>
  274. #if defined(_WIN64) && defined(OPENSSL_USE_APPLINK)
  275. #include <openssl/applink.c>
  276. #endif
  277. #include <iostream>
  278. #include <sstream>
  279. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  280. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  281. #error Please use OpenSSL or a current version of BoringSSL
  282. #endif
  283. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  284. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  285. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  286. #endif
  287. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  288. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  289. #include <zlib.h>
  290. #endif
  291. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  292. #include <brotli/decode.h>
  293. #include <brotli/encode.h>
  294. #endif
  295. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  296. #include <zstd.h>
  297. #endif
  298. /*
  299. * Declaration
  300. */
  301. namespace httplib {
  302. namespace detail {
  303. /*
  304. * Backport std::make_unique from C++14.
  305. *
  306. * NOTE: This code came up with the following stackoverflow post:
  307. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  308. *
  309. */
  310. template <class T, class... Args>
  311. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  312. make_unique(Args &&...args) {
  313. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  314. }
  315. template <class T>
  316. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  317. make_unique(std::size_t n) {
  318. typedef typename std::remove_extent<T>::type RT;
  319. return std::unique_ptr<T>(new RT[n]);
  320. }
  321. namespace case_ignore {
  322. inline unsigned char to_lower(int c) {
  323. const static unsigned char table[256] = {
  324. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  325. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  326. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  327. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  328. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  329. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  330. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  331. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  332. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  333. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  334. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  335. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  336. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  337. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  338. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  339. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  340. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  341. 255,
  342. };
  343. return table[(unsigned char)(char)c];
  344. }
  345. inline bool equal(const std::string &a, const std::string &b) {
  346. return a.size() == b.size() &&
  347. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  348. return to_lower(ca) == to_lower(cb);
  349. });
  350. }
  351. struct equal_to {
  352. bool operator()(const std::string &a, const std::string &b) const {
  353. return equal(a, b);
  354. }
  355. };
  356. struct hash {
  357. size_t operator()(const std::string &key) const {
  358. return hash_core(key.data(), key.size(), 0);
  359. }
  360. size_t hash_core(const char *s, size_t l, size_t h) const {
  361. return (l == 0) ? h
  362. : hash_core(s + 1, l - 1,
  363. // Unsets the 6 high bits of h, therefore no
  364. // overflow happens
  365. (((std::numeric_limits<size_t>::max)() >> 6) &
  366. h * 33) ^
  367. static_cast<unsigned char>(to_lower(*s)));
  368. }
  369. };
  370. template <typename T>
  371. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  372. detail::case_ignore::equal_to>;
  373. } // namespace case_ignore
  374. // This is based on
  375. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  376. struct scope_exit {
  377. explicit scope_exit(std::function<void(void)> &&f)
  378. : exit_function(std::move(f)), execute_on_destruction{true} {}
  379. scope_exit(scope_exit &&rhs) noexcept
  380. : exit_function(std::move(rhs.exit_function)),
  381. execute_on_destruction{rhs.execute_on_destruction} {
  382. rhs.release();
  383. }
  384. ~scope_exit() {
  385. if (execute_on_destruction) { this->exit_function(); }
  386. }
  387. void release() { this->execute_on_destruction = false; }
  388. private:
  389. scope_exit(const scope_exit &) = delete;
  390. void operator=(const scope_exit &) = delete;
  391. scope_exit &operator=(scope_exit &&) = delete;
  392. std::function<void(void)> exit_function;
  393. bool execute_on_destruction;
  394. };
  395. } // namespace detail
  396. enum SSLVerifierResponse {
  397. // no decision has been made, use the built-in certificate verifier
  398. NoDecisionMade,
  399. // connection certificate is verified and accepted
  400. CertificateAccepted,
  401. // connection certificate was processed but is rejected
  402. CertificateRejected
  403. };
  404. enum StatusCode {
  405. // Information responses
  406. Continue_100 = 100,
  407. SwitchingProtocol_101 = 101,
  408. Processing_102 = 102,
  409. EarlyHints_103 = 103,
  410. // Successful responses
  411. OK_200 = 200,
  412. Created_201 = 201,
  413. Accepted_202 = 202,
  414. NonAuthoritativeInformation_203 = 203,
  415. NoContent_204 = 204,
  416. ResetContent_205 = 205,
  417. PartialContent_206 = 206,
  418. MultiStatus_207 = 207,
  419. AlreadyReported_208 = 208,
  420. IMUsed_226 = 226,
  421. // Redirection messages
  422. MultipleChoices_300 = 300,
  423. MovedPermanently_301 = 301,
  424. Found_302 = 302,
  425. SeeOther_303 = 303,
  426. NotModified_304 = 304,
  427. UseProxy_305 = 305,
  428. unused_306 = 306,
  429. TemporaryRedirect_307 = 307,
  430. PermanentRedirect_308 = 308,
  431. // Client error responses
  432. BadRequest_400 = 400,
  433. Unauthorized_401 = 401,
  434. PaymentRequired_402 = 402,
  435. Forbidden_403 = 403,
  436. NotFound_404 = 404,
  437. MethodNotAllowed_405 = 405,
  438. NotAcceptable_406 = 406,
  439. ProxyAuthenticationRequired_407 = 407,
  440. RequestTimeout_408 = 408,
  441. Conflict_409 = 409,
  442. Gone_410 = 410,
  443. LengthRequired_411 = 411,
  444. PreconditionFailed_412 = 412,
  445. PayloadTooLarge_413 = 413,
  446. UriTooLong_414 = 414,
  447. UnsupportedMediaType_415 = 415,
  448. RangeNotSatisfiable_416 = 416,
  449. ExpectationFailed_417 = 417,
  450. ImATeapot_418 = 418,
  451. MisdirectedRequest_421 = 421,
  452. UnprocessableContent_422 = 422,
  453. Locked_423 = 423,
  454. FailedDependency_424 = 424,
  455. TooEarly_425 = 425,
  456. UpgradeRequired_426 = 426,
  457. PreconditionRequired_428 = 428,
  458. TooManyRequests_429 = 429,
  459. RequestHeaderFieldsTooLarge_431 = 431,
  460. UnavailableForLegalReasons_451 = 451,
  461. // Server error responses
  462. InternalServerError_500 = 500,
  463. NotImplemented_501 = 501,
  464. BadGateway_502 = 502,
  465. ServiceUnavailable_503 = 503,
  466. GatewayTimeout_504 = 504,
  467. HttpVersionNotSupported_505 = 505,
  468. VariantAlsoNegotiates_506 = 506,
  469. InsufficientStorage_507 = 507,
  470. LoopDetected_508 = 508,
  471. NotExtended_510 = 510,
  472. NetworkAuthenticationRequired_511 = 511,
  473. };
  474. using Headers =
  475. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  476. detail::case_ignore::equal_to>;
  477. using Params = std::multimap<std::string, std::string>;
  478. using Match = std::smatch;
  479. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  480. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  481. struct Response;
  482. using ResponseHandler = std::function<bool(const Response &response)>;
  483. struct FormData {
  484. std::string name;
  485. std::string content;
  486. std::string filename;
  487. std::string content_type;
  488. Headers headers;
  489. };
  490. struct FormField {
  491. std::string name;
  492. std::string content;
  493. Headers headers;
  494. };
  495. using FormFields = std::multimap<std::string, FormField>;
  496. using FormFiles = std::multimap<std::string, FormData>;
  497. struct MultipartFormData {
  498. FormFields fields; // Text fields from multipart
  499. FormFiles files; // Files from multipart
  500. // Text field access
  501. std::string get_field(const std::string &key, size_t id = 0) const;
  502. std::vector<std::string> get_fields(const std::string &key) const;
  503. bool has_field(const std::string &key) const;
  504. size_t get_field_count(const std::string &key) const;
  505. // File access
  506. FormData get_file(const std::string &key, size_t id = 0) const;
  507. std::vector<FormData> get_files(const std::string &key) const;
  508. bool has_file(const std::string &key) const;
  509. size_t get_file_count(const std::string &key) const;
  510. };
  511. struct UploadFormData {
  512. std::string name;
  513. std::string content;
  514. std::string filename;
  515. std::string content_type;
  516. };
  517. using UploadFormDataItems = std::vector<UploadFormData>;
  518. class DataSink {
  519. public:
  520. DataSink() : os(&sb_), sb_(*this) {}
  521. DataSink(const DataSink &) = delete;
  522. DataSink &operator=(const DataSink &) = delete;
  523. DataSink(DataSink &&) = delete;
  524. DataSink &operator=(DataSink &&) = delete;
  525. std::function<bool(const char *data, size_t data_len)> write;
  526. std::function<bool()> is_writable;
  527. std::function<void()> done;
  528. std::function<void(const Headers &trailer)> done_with_trailer;
  529. std::ostream os;
  530. private:
  531. class data_sink_streambuf final : public std::streambuf {
  532. public:
  533. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  534. protected:
  535. std::streamsize xsputn(const char *s, std::streamsize n) override {
  536. sink_.write(s, static_cast<size_t>(n));
  537. return n;
  538. }
  539. private:
  540. DataSink &sink_;
  541. };
  542. data_sink_streambuf sb_;
  543. };
  544. using ContentProvider =
  545. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  546. using ContentProviderWithoutLength =
  547. std::function<bool(size_t offset, DataSink &sink)>;
  548. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  549. struct FormDataProvider {
  550. std::string name;
  551. ContentProviderWithoutLength provider;
  552. std::string filename;
  553. std::string content_type;
  554. };
  555. using FormDataProviderItems = std::vector<FormDataProvider>;
  556. using ContentReceiverWithProgress = std::function<bool(
  557. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  558. using ContentReceiver =
  559. std::function<bool(const char *data, size_t data_length)>;
  560. using FormDataHeader = std::function<bool(const FormData &file)>;
  561. class ContentReader {
  562. public:
  563. using Reader = std::function<bool(ContentReceiver receiver)>;
  564. using FormDataReader =
  565. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  566. ContentReader(Reader reader, FormDataReader multipart_reader)
  567. : reader_(std::move(reader)),
  568. formdata_reader_(std::move(multipart_reader)) {}
  569. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  570. return formdata_reader_(std::move(header), std::move(receiver));
  571. }
  572. bool operator()(ContentReceiver receiver) const {
  573. return reader_(std::move(receiver));
  574. }
  575. Reader reader_;
  576. FormDataReader formdata_reader_;
  577. };
  578. using Range = std::pair<ssize_t, ssize_t>;
  579. using Ranges = std::vector<Range>;
  580. struct Request {
  581. std::string method;
  582. std::string path;
  583. std::string matched_route;
  584. Params params;
  585. Headers headers;
  586. Headers trailers;
  587. std::string body;
  588. std::string remote_addr;
  589. int remote_port = -1;
  590. std::string local_addr;
  591. int local_port = -1;
  592. // for server
  593. std::string version;
  594. std::string target;
  595. MultipartFormData form;
  596. Ranges ranges;
  597. Match matches;
  598. std::unordered_map<std::string, std::string> path_params;
  599. std::function<bool()> is_connection_closed = []() { return true; };
  600. // for client
  601. std::vector<std::string> accept_content_types;
  602. ResponseHandler response_handler;
  603. ContentReceiverWithProgress content_receiver;
  604. DownloadProgress download_progress;
  605. UploadProgress upload_progress;
  606. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  607. const SSL *ssl = nullptr;
  608. #endif
  609. bool has_header(const std::string &key) const;
  610. std::string get_header_value(const std::string &key, const char *def = "",
  611. size_t id = 0) const;
  612. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  613. size_t id = 0) const;
  614. size_t get_header_value_count(const std::string &key) const;
  615. void set_header(const std::string &key, const std::string &val);
  616. bool has_trailer(const std::string &key) const;
  617. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  618. size_t get_trailer_value_count(const std::string &key) const;
  619. bool has_param(const std::string &key) const;
  620. std::string get_param_value(const std::string &key, size_t id = 0) const;
  621. size_t get_param_value_count(const std::string &key) const;
  622. bool is_multipart_form_data() const;
  623. // private members...
  624. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  625. size_t content_length_ = 0;
  626. ContentProvider content_provider_;
  627. bool is_chunked_content_provider_ = false;
  628. size_t authorization_count_ = 0;
  629. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  630. (std::chrono::steady_clock::time_point::min)();
  631. };
  632. struct Response {
  633. std::string version;
  634. int status = -1;
  635. std::string reason;
  636. Headers headers;
  637. Headers trailers;
  638. std::string body;
  639. std::string location; // Redirect location
  640. bool has_header(const std::string &key) const;
  641. std::string get_header_value(const std::string &key, const char *def = "",
  642. size_t id = 0) const;
  643. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  644. size_t id = 0) const;
  645. size_t get_header_value_count(const std::string &key) const;
  646. void set_header(const std::string &key, const std::string &val);
  647. bool has_trailer(const std::string &key) const;
  648. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  649. size_t get_trailer_value_count(const std::string &key) const;
  650. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  651. void set_content(const char *s, size_t n, const std::string &content_type);
  652. void set_content(const std::string &s, const std::string &content_type);
  653. void set_content(std::string &&s, const std::string &content_type);
  654. void set_content_provider(
  655. size_t length, const std::string &content_type, ContentProvider provider,
  656. ContentProviderResourceReleaser resource_releaser = nullptr);
  657. void set_content_provider(
  658. const std::string &content_type, ContentProviderWithoutLength provider,
  659. ContentProviderResourceReleaser resource_releaser = nullptr);
  660. void set_chunked_content_provider(
  661. const std::string &content_type, ContentProviderWithoutLength provider,
  662. ContentProviderResourceReleaser resource_releaser = nullptr);
  663. void set_file_content(const std::string &path,
  664. const std::string &content_type);
  665. void set_file_content(const std::string &path);
  666. Response() = default;
  667. Response(const Response &) = default;
  668. Response &operator=(const Response &) = default;
  669. Response(Response &&) = default;
  670. Response &operator=(Response &&) = default;
  671. ~Response() {
  672. if (content_provider_resource_releaser_) {
  673. content_provider_resource_releaser_(content_provider_success_);
  674. }
  675. }
  676. // private members...
  677. size_t content_length_ = 0;
  678. ContentProvider content_provider_;
  679. ContentProviderResourceReleaser content_provider_resource_releaser_;
  680. bool is_chunked_content_provider_ = false;
  681. bool content_provider_success_ = false;
  682. std::string file_content_path_;
  683. std::string file_content_content_type_;
  684. };
  685. class Stream {
  686. public:
  687. virtual ~Stream() = default;
  688. virtual bool is_readable() const = 0;
  689. virtual bool wait_readable() const = 0;
  690. virtual bool wait_writable() const = 0;
  691. virtual ssize_t read(char *ptr, size_t size) = 0;
  692. virtual ssize_t write(const char *ptr, size_t size) = 0;
  693. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  694. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  695. virtual socket_t socket() const = 0;
  696. virtual time_t duration() const = 0;
  697. ssize_t write(const char *ptr);
  698. ssize_t write(const std::string &s);
  699. };
  700. class TaskQueue {
  701. public:
  702. TaskQueue() = default;
  703. virtual ~TaskQueue() = default;
  704. virtual bool enqueue(std::function<void()> fn) = 0;
  705. virtual void shutdown() = 0;
  706. virtual void on_idle() {}
  707. };
  708. class ThreadPool final : public TaskQueue {
  709. public:
  710. explicit ThreadPool(size_t n, size_t mqr = 0)
  711. : shutdown_(false), max_queued_requests_(mqr) {
  712. while (n) {
  713. threads_.emplace_back(worker(*this));
  714. n--;
  715. }
  716. }
  717. ThreadPool(const ThreadPool &) = delete;
  718. ~ThreadPool() override = default;
  719. bool enqueue(std::function<void()> fn) override {
  720. {
  721. std::unique_lock<std::mutex> lock(mutex_);
  722. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  723. return false;
  724. }
  725. jobs_.push_back(std::move(fn));
  726. }
  727. cond_.notify_one();
  728. return true;
  729. }
  730. void shutdown() override {
  731. // Stop all worker threads...
  732. {
  733. std::unique_lock<std::mutex> lock(mutex_);
  734. shutdown_ = true;
  735. }
  736. cond_.notify_all();
  737. // Join...
  738. for (auto &t : threads_) {
  739. t.join();
  740. }
  741. }
  742. private:
  743. struct worker {
  744. explicit worker(ThreadPool &pool) : pool_(pool) {}
  745. void operator()() {
  746. for (;;) {
  747. std::function<void()> fn;
  748. {
  749. std::unique_lock<std::mutex> lock(pool_.mutex_);
  750. pool_.cond_.wait(
  751. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  752. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  753. fn = pool_.jobs_.front();
  754. pool_.jobs_.pop_front();
  755. }
  756. assert(true == static_cast<bool>(fn));
  757. fn();
  758. }
  759. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  760. !defined(LIBRESSL_VERSION_NUMBER)
  761. OPENSSL_thread_stop();
  762. #endif
  763. }
  764. ThreadPool &pool_;
  765. };
  766. friend struct worker;
  767. std::vector<std::thread> threads_;
  768. std::list<std::function<void()>> jobs_;
  769. bool shutdown_;
  770. size_t max_queued_requests_ = 0;
  771. std::condition_variable cond_;
  772. std::mutex mutex_;
  773. };
  774. using Logger = std::function<void(const Request &, const Response &)>;
  775. using SocketOptions = std::function<void(socket_t sock)>;
  776. namespace detail {
  777. bool set_socket_opt_impl(socket_t sock, int level, int optname,
  778. const void *optval, socklen_t optlen);
  779. bool set_socket_opt(socket_t sock, int level, int optname, int opt);
  780. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  781. time_t usec);
  782. } // namespace detail
  783. void default_socket_options(socket_t sock);
  784. const char *status_message(int status);
  785. std::string get_bearer_token_auth(const Request &req);
  786. namespace detail {
  787. class MatcherBase {
  788. public:
  789. MatcherBase(std::string pattern) : pattern_(pattern) {}
  790. virtual ~MatcherBase() = default;
  791. const std::string &pattern() const { return pattern_; }
  792. // Match request path and populate its matches and
  793. virtual bool match(Request &request) const = 0;
  794. private:
  795. std::string pattern_;
  796. };
  797. /**
  798. * Captures parameters in request path and stores them in Request::path_params
  799. *
  800. * Capture name is a substring of a pattern from : to /.
  801. * The rest of the pattern is matched against the request path directly
  802. * Parameters are captured starting from the next character after
  803. * the end of the last matched static pattern fragment until the next /.
  804. *
  805. * Example pattern:
  806. * "/path/fragments/:capture/more/fragments/:second_capture"
  807. * Static fragments:
  808. * "/path/fragments/", "more/fragments/"
  809. *
  810. * Given the following request path:
  811. * "/path/fragments/:1/more/fragments/:2"
  812. * the resulting capture will be
  813. * {{"capture", "1"}, {"second_capture", "2"}}
  814. */
  815. class PathParamsMatcher final : public MatcherBase {
  816. public:
  817. PathParamsMatcher(const std::string &pattern);
  818. bool match(Request &request) const override;
  819. private:
  820. // Treat segment separators as the end of path parameter capture
  821. // Does not need to handle query parameters as they are parsed before path
  822. // matching
  823. static constexpr char separator = '/';
  824. // Contains static path fragments to match against, excluding the '/' after
  825. // path params
  826. // Fragments are separated by path params
  827. std::vector<std::string> static_fragments_;
  828. // Stores the names of the path parameters to be used as keys in the
  829. // Request::path_params map
  830. std::vector<std::string> param_names_;
  831. };
  832. /**
  833. * Performs std::regex_match on request path
  834. * and stores the result in Request::matches
  835. *
  836. * Note that regex match is performed directly on the whole request.
  837. * This means that wildcard patterns may match multiple path segments with /:
  838. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  839. */
  840. class RegexMatcher final : public MatcherBase {
  841. public:
  842. RegexMatcher(const std::string &pattern)
  843. : MatcherBase(pattern), regex_(pattern) {}
  844. bool match(Request &request) const override;
  845. private:
  846. std::regex regex_;
  847. };
  848. ssize_t write_headers(Stream &strm, const Headers &headers);
  849. } // namespace detail
  850. class Server {
  851. public:
  852. using Handler = std::function<void(const Request &, Response &)>;
  853. using ExceptionHandler =
  854. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  855. enum class HandlerResponse {
  856. Handled,
  857. Unhandled,
  858. };
  859. using HandlerWithResponse =
  860. std::function<HandlerResponse(const Request &, Response &)>;
  861. using HandlerWithContentReader = std::function<void(
  862. const Request &, Response &, const ContentReader &content_reader)>;
  863. using Expect100ContinueHandler =
  864. std::function<int(const Request &, Response &)>;
  865. Server();
  866. virtual ~Server();
  867. virtual bool is_valid() const;
  868. Server &Get(const std::string &pattern, Handler handler);
  869. Server &Post(const std::string &pattern, Handler handler);
  870. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  871. Server &Put(const std::string &pattern, Handler handler);
  872. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  873. Server &Patch(const std::string &pattern, Handler handler);
  874. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  875. Server &Delete(const std::string &pattern, Handler handler);
  876. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  877. Server &Options(const std::string &pattern, Handler handler);
  878. bool set_base_dir(const std::string &dir,
  879. const std::string &mount_point = std::string());
  880. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  881. Headers headers = Headers());
  882. bool remove_mount_point(const std::string &mount_point);
  883. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  884. const std::string &mime);
  885. Server &set_default_file_mimetype(const std::string &mime);
  886. Server &set_file_request_handler(Handler handler);
  887. template <class ErrorHandlerFunc>
  888. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  889. return set_error_handler_core(
  890. std::forward<ErrorHandlerFunc>(handler),
  891. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  892. }
  893. Server &set_exception_handler(ExceptionHandler handler);
  894. Server &set_pre_routing_handler(HandlerWithResponse handler);
  895. Server &set_post_routing_handler(Handler handler);
  896. Server &set_pre_request_handler(HandlerWithResponse handler);
  897. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  898. Server &set_logger(Logger logger);
  899. Server &set_pre_compression_logger(Logger logger);
  900. Server &set_address_family(int family);
  901. Server &set_tcp_nodelay(bool on);
  902. Server &set_ipv6_v6only(bool on);
  903. Server &set_socket_options(SocketOptions socket_options);
  904. Server &set_default_headers(Headers headers);
  905. Server &
  906. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  907. Server &set_keep_alive_max_count(size_t count);
  908. Server &set_keep_alive_timeout(time_t sec);
  909. Server &set_read_timeout(time_t sec, time_t usec = 0);
  910. template <class Rep, class Period>
  911. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  912. Server &set_write_timeout(time_t sec, time_t usec = 0);
  913. template <class Rep, class Period>
  914. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  915. Server &set_idle_interval(time_t sec, time_t usec = 0);
  916. template <class Rep, class Period>
  917. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  918. Server &set_payload_max_length(size_t length);
  919. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  920. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  921. bool listen_after_bind();
  922. bool listen(const std::string &host, int port, int socket_flags = 0);
  923. bool is_running() const;
  924. void wait_until_ready() const;
  925. void stop();
  926. void decommission();
  927. std::function<TaskQueue *(void)> new_task_queue;
  928. protected:
  929. bool process_request(Stream &strm, const std::string &remote_addr,
  930. int remote_port, const std::string &local_addr,
  931. int local_port, bool close_connection,
  932. bool &connection_closed,
  933. const std::function<void(Request &)> &setup_request);
  934. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  935. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  936. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  937. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  938. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  939. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  940. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  941. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  942. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  943. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  944. private:
  945. using Handlers =
  946. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  947. using HandlersForContentReader =
  948. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  949. HandlerWithContentReader>>;
  950. static std::unique_ptr<detail::MatcherBase>
  951. make_matcher(const std::string &pattern);
  952. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  953. Server &set_error_handler_core(Handler handler, std::false_type);
  954. socket_t create_server_socket(const std::string &host, int port,
  955. int socket_flags,
  956. SocketOptions socket_options) const;
  957. int bind_internal(const std::string &host, int port, int socket_flags);
  958. bool listen_internal();
  959. bool routing(Request &req, Response &res, Stream &strm);
  960. bool handle_file_request(const Request &req, Response &res);
  961. bool dispatch_request(Request &req, Response &res,
  962. const Handlers &handlers) const;
  963. bool dispatch_request_for_content_reader(
  964. Request &req, Response &res, ContentReader content_reader,
  965. const HandlersForContentReader &handlers) const;
  966. bool parse_request_line(const char *s, Request &req) const;
  967. void apply_ranges(const Request &req, Response &res,
  968. std::string &content_type, std::string &boundary) const;
  969. bool write_response(Stream &strm, bool close_connection, Request &req,
  970. Response &res);
  971. bool write_response_with_content(Stream &strm, bool close_connection,
  972. const Request &req, Response &res);
  973. bool write_response_core(Stream &strm, bool close_connection,
  974. const Request &req, Response &res,
  975. bool need_apply_ranges);
  976. bool write_content_with_provider(Stream &strm, const Request &req,
  977. Response &res, const std::string &boundary,
  978. const std::string &content_type);
  979. bool read_content(Stream &strm, Request &req, Response &res);
  980. bool read_content_with_content_receiver(Stream &strm, Request &req,
  981. Response &res,
  982. ContentReceiver receiver,
  983. FormDataHeader multipart_header,
  984. ContentReceiver multipart_receiver);
  985. bool read_content_core(Stream &strm, Request &req, Response &res,
  986. ContentReceiver receiver,
  987. FormDataHeader multipart_header,
  988. ContentReceiver multipart_receiver) const;
  989. virtual bool process_and_close_socket(socket_t sock);
  990. std::atomic<bool> is_running_{false};
  991. std::atomic<bool> is_decommissioned{false};
  992. struct MountPointEntry {
  993. std::string mount_point;
  994. std::string base_dir;
  995. Headers headers;
  996. };
  997. std::vector<MountPointEntry> base_dirs_;
  998. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  999. std::string default_file_mimetype_ = "application/octet-stream";
  1000. Handler file_request_handler_;
  1001. Handlers get_handlers_;
  1002. Handlers post_handlers_;
  1003. HandlersForContentReader post_handlers_for_content_reader_;
  1004. Handlers put_handlers_;
  1005. HandlersForContentReader put_handlers_for_content_reader_;
  1006. Handlers patch_handlers_;
  1007. HandlersForContentReader patch_handlers_for_content_reader_;
  1008. Handlers delete_handlers_;
  1009. HandlersForContentReader delete_handlers_for_content_reader_;
  1010. Handlers options_handlers_;
  1011. HandlerWithResponse error_handler_;
  1012. ExceptionHandler exception_handler_;
  1013. HandlerWithResponse pre_routing_handler_;
  1014. Handler post_routing_handler_;
  1015. HandlerWithResponse pre_request_handler_;
  1016. Expect100ContinueHandler expect_100_continue_handler_;
  1017. Logger logger_;
  1018. Logger pre_compression_logger_;
  1019. int address_family_ = AF_UNSPEC;
  1020. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1021. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1022. SocketOptions socket_options_ = default_socket_options;
  1023. Headers default_headers_;
  1024. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1025. detail::write_headers;
  1026. };
  1027. enum class Error {
  1028. Success = 0,
  1029. Unknown,
  1030. Connection,
  1031. BindIPAddress,
  1032. Read,
  1033. Write,
  1034. ExceedRedirectCount,
  1035. Canceled,
  1036. SSLConnection,
  1037. SSLLoadingCerts,
  1038. SSLServerVerification,
  1039. SSLServerHostnameVerification,
  1040. UnsupportedMultipartBoundaryChars,
  1041. Compression,
  1042. ConnectionTimeout,
  1043. ProxyConnection,
  1044. // For internal use only
  1045. SSLPeerCouldBeClosed_,
  1046. };
  1047. std::string to_string(Error error);
  1048. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1049. class Result {
  1050. public:
  1051. Result() = default;
  1052. Result(std::unique_ptr<Response> &&res, Error err,
  1053. Headers &&request_headers = Headers{})
  1054. : res_(std::move(res)), err_(err),
  1055. request_headers_(std::move(request_headers)) {}
  1056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1057. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1058. int ssl_error)
  1059. : res_(std::move(res)), err_(err),
  1060. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1061. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1062. int ssl_error, unsigned long ssl_openssl_error)
  1063. : res_(std::move(res)), err_(err),
  1064. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1065. ssl_openssl_error_(ssl_openssl_error) {}
  1066. #endif
  1067. // Response
  1068. operator bool() const { return res_ != nullptr; }
  1069. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1070. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1071. const Response &value() const { return *res_; }
  1072. Response &value() { return *res_; }
  1073. const Response &operator*() const { return *res_; }
  1074. Response &operator*() { return *res_; }
  1075. const Response *operator->() const { return res_.get(); }
  1076. Response *operator->() { return res_.get(); }
  1077. // Error
  1078. Error error() const { return err_; }
  1079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1080. // SSL Error
  1081. int ssl_error() const { return ssl_error_; }
  1082. // OpenSSL Error
  1083. unsigned long ssl_openssl_error() const { return ssl_openssl_error_; }
  1084. #endif
  1085. // Request Headers
  1086. bool has_request_header(const std::string &key) const;
  1087. std::string get_request_header_value(const std::string &key,
  1088. const char *def = "",
  1089. size_t id = 0) const;
  1090. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1091. size_t id = 0) const;
  1092. size_t get_request_header_value_count(const std::string &key) const;
  1093. private:
  1094. std::unique_ptr<Response> res_;
  1095. Error err_ = Error::Unknown;
  1096. Headers request_headers_;
  1097. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1098. int ssl_error_ = 0;
  1099. unsigned long ssl_openssl_error_ = 0;
  1100. #endif
  1101. };
  1102. class ClientImpl {
  1103. public:
  1104. explicit ClientImpl(const std::string &host);
  1105. explicit ClientImpl(const std::string &host, int port);
  1106. explicit ClientImpl(const std::string &host, int port,
  1107. const std::string &client_cert_path,
  1108. const std::string &client_key_path);
  1109. virtual ~ClientImpl();
  1110. virtual bool is_valid() const;
  1111. // clang-format off
  1112. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1113. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1114. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1115. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1116. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1117. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1118. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1119. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1120. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1121. Result Head(const std::string &path);
  1122. Result Head(const std::string &path, const Headers &headers);
  1123. Result Post(const std::string &path);
  1124. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1125. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1126. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1127. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1128. Result Post(const std::string &path, const Params &params);
  1129. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1130. Result Post(const std::string &path, const Headers &headers);
  1131. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1132. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1133. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1134. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1135. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1136. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1137. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1138. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1139. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1140. Result Put(const std::string &path);
  1141. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1142. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1143. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1144. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1145. Result Put(const std::string &path, const Params &params);
  1146. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1147. Result Put(const std::string &path, const Headers &headers);
  1148. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1149. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1150. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1151. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1152. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1153. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1154. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1155. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1156. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1157. Result Patch(const std::string &path);
  1158. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1159. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1160. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1161. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1162. Result Patch(const std::string &path, const Params &params);
  1163. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1164. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1165. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1166. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1167. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1168. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1169. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1170. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1171. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1172. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1173. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1174. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1175. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1176. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1177. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1178. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1179. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1180. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1181. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1182. Result Options(const std::string &path);
  1183. Result Options(const std::string &path, const Headers &headers);
  1184. // clang-format on
  1185. bool send(Request &req, Response &res, Error &error);
  1186. Result send(const Request &req);
  1187. void stop();
  1188. std::string host() const;
  1189. int port() const;
  1190. size_t is_socket_open() const;
  1191. socket_t socket() const;
  1192. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1193. void set_default_headers(Headers headers);
  1194. void
  1195. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1196. void set_address_family(int family);
  1197. void set_tcp_nodelay(bool on);
  1198. void set_ipv6_v6only(bool on);
  1199. void set_socket_options(SocketOptions socket_options);
  1200. void set_connection_timeout(time_t sec, time_t usec = 0);
  1201. template <class Rep, class Period>
  1202. void
  1203. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1204. void set_read_timeout(time_t sec, time_t usec = 0);
  1205. template <class Rep, class Period>
  1206. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1207. void set_write_timeout(time_t sec, time_t usec = 0);
  1208. template <class Rep, class Period>
  1209. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1210. void set_max_timeout(time_t msec);
  1211. template <class Rep, class Period>
  1212. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1213. void set_basic_auth(const std::string &username, const std::string &password);
  1214. void set_bearer_token_auth(const std::string &token);
  1215. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1216. void set_digest_auth(const std::string &username,
  1217. const std::string &password);
  1218. #endif
  1219. void set_keep_alive(bool on);
  1220. void set_follow_location(bool on);
  1221. void set_path_encode(bool on);
  1222. void set_compress(bool on);
  1223. void set_decompress(bool on);
  1224. void set_interface(const std::string &intf);
  1225. void set_proxy(const std::string &host, int port);
  1226. void set_proxy_basic_auth(const std::string &username,
  1227. const std::string &password);
  1228. void set_proxy_bearer_token_auth(const std::string &token);
  1229. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1230. void set_proxy_digest_auth(const std::string &username,
  1231. const std::string &password);
  1232. #endif
  1233. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1234. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1235. const std::string &ca_cert_dir_path = std::string());
  1236. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1237. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1238. #endif
  1239. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1240. void enable_server_certificate_verification(bool enabled);
  1241. void enable_server_hostname_verification(bool enabled);
  1242. void set_server_certificate_verifier(
  1243. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1244. #endif
  1245. void set_logger(Logger logger);
  1246. protected:
  1247. struct Socket {
  1248. socket_t sock = INVALID_SOCKET;
  1249. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1250. SSL *ssl = nullptr;
  1251. #endif
  1252. bool is_open() const { return sock != INVALID_SOCKET; }
  1253. };
  1254. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1255. // All of:
  1256. // shutdown_ssl
  1257. // shutdown_socket
  1258. // close_socket
  1259. // should ONLY be called when socket_mutex_ is locked.
  1260. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1261. // with a DIFFERENT thread sending requests using that socket.
  1262. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1263. void shutdown_socket(Socket &socket) const;
  1264. void close_socket(Socket &socket);
  1265. bool process_request(Stream &strm, Request &req, Response &res,
  1266. bool close_connection, Error &error);
  1267. bool write_content_with_provider(Stream &strm, const Request &req,
  1268. Error &error) const;
  1269. void copy_settings(const ClientImpl &rhs);
  1270. // Socket endpoint information
  1271. const std::string host_;
  1272. const int port_;
  1273. const std::string host_and_port_;
  1274. // Current open socket
  1275. Socket socket_;
  1276. mutable std::mutex socket_mutex_;
  1277. std::recursive_mutex request_mutex_;
  1278. // These are all protected under socket_mutex
  1279. size_t socket_requests_in_flight_ = 0;
  1280. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1281. bool socket_should_be_closed_when_request_is_done_ = false;
  1282. // Hostname-IP map
  1283. std::map<std::string, std::string> addr_map_;
  1284. // Default headers
  1285. Headers default_headers_;
  1286. // Header writer
  1287. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1288. detail::write_headers;
  1289. // Settings
  1290. std::string client_cert_path_;
  1291. std::string client_key_path_;
  1292. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1293. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1294. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1295. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1296. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1297. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1298. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1299. std::string basic_auth_username_;
  1300. std::string basic_auth_password_;
  1301. std::string bearer_token_auth_token_;
  1302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1303. std::string digest_auth_username_;
  1304. std::string digest_auth_password_;
  1305. #endif
  1306. bool keep_alive_ = false;
  1307. bool follow_location_ = false;
  1308. bool path_encode_ = true;
  1309. int address_family_ = AF_UNSPEC;
  1310. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1311. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1312. SocketOptions socket_options_ = nullptr;
  1313. bool compress_ = false;
  1314. bool decompress_ = true;
  1315. std::string interface_;
  1316. std::string proxy_host_;
  1317. int proxy_port_ = -1;
  1318. std::string proxy_basic_auth_username_;
  1319. std::string proxy_basic_auth_password_;
  1320. std::string proxy_bearer_token_auth_token_;
  1321. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1322. std::string proxy_digest_auth_username_;
  1323. std::string proxy_digest_auth_password_;
  1324. #endif
  1325. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1326. std::string ca_cert_file_path_;
  1327. std::string ca_cert_dir_path_;
  1328. X509_STORE *ca_cert_store_ = nullptr;
  1329. #endif
  1330. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1331. bool server_certificate_verification_ = true;
  1332. bool server_hostname_verification_ = true;
  1333. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1334. #endif
  1335. Logger logger_;
  1336. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1337. int last_ssl_error_ = 0;
  1338. unsigned long last_openssl_error_ = 0;
  1339. #endif
  1340. private:
  1341. bool send_(Request &req, Response &res, Error &error);
  1342. Result send_(Request &&req);
  1343. socket_t create_client_socket(Error &error) const;
  1344. bool read_response_line(Stream &strm, const Request &req,
  1345. Response &res) const;
  1346. bool write_request(Stream &strm, Request &req, bool close_connection,
  1347. Error &error);
  1348. bool redirect(Request &req, Response &res, Error &error);
  1349. bool create_redirect_client(const std::string &scheme,
  1350. const std::string &host, int port, Request &req,
  1351. Response &res, const std::string &path,
  1352. const std::string &location, Error &error);
  1353. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1354. bool handle_request(Stream &strm, Request &req, Response &res,
  1355. bool close_connection, Error &error);
  1356. std::unique_ptr<Response> send_with_content_provider(
  1357. Request &req, const char *body, size_t content_length,
  1358. ContentProvider content_provider,
  1359. ContentProviderWithoutLength content_provider_without_length,
  1360. const std::string &content_type, Error &error);
  1361. Result send_with_content_provider(
  1362. const std::string &method, const std::string &path,
  1363. const Headers &headers, const char *body, size_t content_length,
  1364. ContentProvider content_provider,
  1365. ContentProviderWithoutLength content_provider_without_length,
  1366. const std::string &content_type, UploadProgress progress);
  1367. ContentProviderWithoutLength get_multipart_content_provider(
  1368. const std::string &boundary, const UploadFormDataItems &items,
  1369. const FormDataProviderItems &provider_items) const;
  1370. std::string adjust_host_string(const std::string &host) const;
  1371. virtual bool
  1372. process_socket(const Socket &socket,
  1373. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1374. std::function<bool(Stream &strm)> callback);
  1375. virtual bool is_ssl() const;
  1376. };
  1377. class Client {
  1378. public:
  1379. // Universal interface
  1380. explicit Client(const std::string &scheme_host_port);
  1381. explicit Client(const std::string &scheme_host_port,
  1382. const std::string &client_cert_path,
  1383. const std::string &client_key_path);
  1384. // HTTP only interface
  1385. explicit Client(const std::string &host, int port);
  1386. explicit Client(const std::string &host, int port,
  1387. const std::string &client_cert_path,
  1388. const std::string &client_key_path);
  1389. Client(Client &&) = default;
  1390. Client &operator=(Client &&) = default;
  1391. ~Client();
  1392. bool is_valid() const;
  1393. // clang-format off
  1394. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1395. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1396. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1397. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1398. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1399. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1400. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1401. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1402. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1403. Result Head(const std::string &path);
  1404. Result Head(const std::string &path, const Headers &headers);
  1405. Result Post(const std::string &path);
  1406. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1407. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1408. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1409. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1410. Result Post(const std::string &path, const Params &params);
  1411. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1412. Result Post(const std::string &path, const Headers &headers);
  1413. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1414. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1415. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1416. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1417. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1418. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1419. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1420. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1421. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1422. Result Put(const std::string &path);
  1423. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1424. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1425. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1426. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1427. Result Put(const std::string &path, const Params &params);
  1428. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1429. Result Put(const std::string &path, const Headers &headers);
  1430. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1431. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1432. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1433. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1434. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1435. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1436. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1437. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1438. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1439. Result Patch(const std::string &path);
  1440. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1441. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1442. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1443. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1444. Result Patch(const std::string &path, const Params &params);
  1445. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1446. Result Patch(const std::string &path, const Headers &headers);
  1447. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1448. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1449. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1450. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1451. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1452. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1453. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1454. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1455. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1456. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1457. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1458. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1459. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1460. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1461. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1462. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1463. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1464. Result Options(const std::string &path);
  1465. Result Options(const std::string &path, const Headers &headers);
  1466. // clang-format on
  1467. bool send(Request &req, Response &res, Error &error);
  1468. Result send(const Request &req);
  1469. void stop();
  1470. std::string host() const;
  1471. int port() const;
  1472. size_t is_socket_open() const;
  1473. socket_t socket() const;
  1474. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1475. void set_default_headers(Headers headers);
  1476. void
  1477. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1478. void set_address_family(int family);
  1479. void set_tcp_nodelay(bool on);
  1480. void set_socket_options(SocketOptions socket_options);
  1481. void set_connection_timeout(time_t sec, time_t usec = 0);
  1482. template <class Rep, class Period>
  1483. void
  1484. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1485. void set_read_timeout(time_t sec, time_t usec = 0);
  1486. template <class Rep, class Period>
  1487. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1488. void set_write_timeout(time_t sec, time_t usec = 0);
  1489. template <class Rep, class Period>
  1490. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1491. void set_max_timeout(time_t msec);
  1492. template <class Rep, class Period>
  1493. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1494. void set_basic_auth(const std::string &username, const std::string &password);
  1495. void set_bearer_token_auth(const std::string &token);
  1496. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1497. void set_digest_auth(const std::string &username,
  1498. const std::string &password);
  1499. #endif
  1500. void set_keep_alive(bool on);
  1501. void set_follow_location(bool on);
  1502. void set_path_encode(bool on);
  1503. void set_url_encode(bool on);
  1504. void set_compress(bool on);
  1505. void set_decompress(bool on);
  1506. void set_interface(const std::string &intf);
  1507. void set_proxy(const std::string &host, int port);
  1508. void set_proxy_basic_auth(const std::string &username,
  1509. const std::string &password);
  1510. void set_proxy_bearer_token_auth(const std::string &token);
  1511. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1512. void set_proxy_digest_auth(const std::string &username,
  1513. const std::string &password);
  1514. #endif
  1515. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1516. void enable_server_certificate_verification(bool enabled);
  1517. void enable_server_hostname_verification(bool enabled);
  1518. void set_server_certificate_verifier(
  1519. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1520. #endif
  1521. void set_logger(Logger logger);
  1522. // SSL
  1523. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1524. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1525. const std::string &ca_cert_dir_path = std::string());
  1526. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1527. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1528. long get_openssl_verify_result() const;
  1529. SSL_CTX *ssl_context() const;
  1530. #endif
  1531. private:
  1532. std::unique_ptr<ClientImpl> cli_;
  1533. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1534. bool is_ssl_ = false;
  1535. #endif
  1536. };
  1537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1538. class SSLServer : public Server {
  1539. public:
  1540. SSLServer(const char *cert_path, const char *private_key_path,
  1541. const char *client_ca_cert_file_path = nullptr,
  1542. const char *client_ca_cert_dir_path = nullptr,
  1543. const char *private_key_password = nullptr);
  1544. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1545. X509_STORE *client_ca_cert_store = nullptr);
  1546. SSLServer(
  1547. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1548. ~SSLServer() override;
  1549. bool is_valid() const override;
  1550. SSL_CTX *ssl_context() const;
  1551. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1552. X509_STORE *client_ca_cert_store = nullptr);
  1553. private:
  1554. bool process_and_close_socket(socket_t sock) override;
  1555. SSL_CTX *ctx_;
  1556. std::mutex ctx_mutex_;
  1557. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1558. int last_ssl_error_ = 0;
  1559. #endif
  1560. };
  1561. class SSLClient final : public ClientImpl {
  1562. public:
  1563. explicit SSLClient(const std::string &host);
  1564. explicit SSLClient(const std::string &host, int port);
  1565. explicit SSLClient(const std::string &host, int port,
  1566. const std::string &client_cert_path,
  1567. const std::string &client_key_path,
  1568. const std::string &private_key_password = std::string());
  1569. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1570. EVP_PKEY *client_key,
  1571. const std::string &private_key_password = std::string());
  1572. ~SSLClient() override;
  1573. bool is_valid() const override;
  1574. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1575. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1576. long get_openssl_verify_result() const;
  1577. SSL_CTX *ssl_context() const;
  1578. private:
  1579. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1580. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1581. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1582. bool
  1583. process_socket(const Socket &socket,
  1584. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1585. std::function<bool(Stream &strm)> callback) override;
  1586. bool is_ssl() const override;
  1587. bool connect_with_proxy(
  1588. Socket &sock,
  1589. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1590. Response &res, bool &success, Error &error);
  1591. bool initialize_ssl(Socket &socket, Error &error);
  1592. bool load_certs();
  1593. bool verify_host(X509 *server_cert) const;
  1594. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1595. bool verify_host_with_common_name(X509 *server_cert) const;
  1596. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1597. SSL_CTX *ctx_;
  1598. std::mutex ctx_mutex_;
  1599. std::once_flag initialize_cert_;
  1600. std::vector<std::string> host_components_;
  1601. long verify_result_ = 0;
  1602. friend class ClientImpl;
  1603. };
  1604. #endif
  1605. /*
  1606. * Implementation of template methods.
  1607. */
  1608. namespace detail {
  1609. template <typename T, typename U>
  1610. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1611. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1612. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1613. duration - std::chrono::seconds(sec))
  1614. .count();
  1615. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1616. }
  1617. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1618. return N - 1;
  1619. }
  1620. inline bool is_numeric(const std::string &str) {
  1621. return !str.empty() &&
  1622. std::all_of(str.cbegin(), str.cend(),
  1623. [](unsigned char c) { return std::isdigit(c); });
  1624. }
  1625. inline size_t get_header_value_u64(const Headers &headers,
  1626. const std::string &key, size_t def,
  1627. size_t id, bool &is_invalid_value) {
  1628. is_invalid_value = false;
  1629. auto rng = headers.equal_range(key);
  1630. auto it = rng.first;
  1631. std::advance(it, static_cast<ssize_t>(id));
  1632. if (it != rng.second) {
  1633. if (is_numeric(it->second)) {
  1634. return std::strtoull(it->second.data(), nullptr, 10);
  1635. } else {
  1636. is_invalid_value = true;
  1637. }
  1638. }
  1639. return def;
  1640. }
  1641. inline size_t get_header_value_u64(const Headers &headers,
  1642. const std::string &key, size_t def,
  1643. size_t id) {
  1644. bool dummy = false;
  1645. return get_header_value_u64(headers, key, def, id, dummy);
  1646. }
  1647. } // namespace detail
  1648. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  1649. size_t id) const {
  1650. return detail::get_header_value_u64(headers, key, def, id);
  1651. }
  1652. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  1653. size_t id) const {
  1654. return detail::get_header_value_u64(headers, key, def, id);
  1655. }
  1656. namespace detail {
  1657. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1658. const void *optval, socklen_t optlen) {
  1659. return setsockopt(sock, level, optname,
  1660. #ifdef _WIN64
  1661. reinterpret_cast<const char *>(optval),
  1662. #else
  1663. optval,
  1664. #endif
  1665. optlen) == 0;
  1666. }
  1667. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1668. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1669. }
  1670. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1671. time_t sec, time_t usec) {
  1672. #ifdef _WIN64
  1673. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1674. #else
  1675. timeval timeout;
  1676. timeout.tv_sec = static_cast<long>(sec);
  1677. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1678. #endif
  1679. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1680. }
  1681. } // namespace detail
  1682. inline void default_socket_options(socket_t sock) {
  1683. detail::set_socket_opt(sock, SOL_SOCKET,
  1684. #ifdef SO_REUSEPORT
  1685. SO_REUSEPORT,
  1686. #else
  1687. SO_REUSEADDR,
  1688. #endif
  1689. 1);
  1690. }
  1691. inline const char *status_message(int status) {
  1692. switch (status) {
  1693. case StatusCode::Continue_100: return "Continue";
  1694. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  1695. case StatusCode::Processing_102: return "Processing";
  1696. case StatusCode::EarlyHints_103: return "Early Hints";
  1697. case StatusCode::OK_200: return "OK";
  1698. case StatusCode::Created_201: return "Created";
  1699. case StatusCode::Accepted_202: return "Accepted";
  1700. case StatusCode::NonAuthoritativeInformation_203:
  1701. return "Non-Authoritative Information";
  1702. case StatusCode::NoContent_204: return "No Content";
  1703. case StatusCode::ResetContent_205: return "Reset Content";
  1704. case StatusCode::PartialContent_206: return "Partial Content";
  1705. case StatusCode::MultiStatus_207: return "Multi-Status";
  1706. case StatusCode::AlreadyReported_208: return "Already Reported";
  1707. case StatusCode::IMUsed_226: return "IM Used";
  1708. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  1709. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  1710. case StatusCode::Found_302: return "Found";
  1711. case StatusCode::SeeOther_303: return "See Other";
  1712. case StatusCode::NotModified_304: return "Not Modified";
  1713. case StatusCode::UseProxy_305: return "Use Proxy";
  1714. case StatusCode::unused_306: return "unused";
  1715. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  1716. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  1717. case StatusCode::BadRequest_400: return "Bad Request";
  1718. case StatusCode::Unauthorized_401: return "Unauthorized";
  1719. case StatusCode::PaymentRequired_402: return "Payment Required";
  1720. case StatusCode::Forbidden_403: return "Forbidden";
  1721. case StatusCode::NotFound_404: return "Not Found";
  1722. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  1723. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  1724. case StatusCode::ProxyAuthenticationRequired_407:
  1725. return "Proxy Authentication Required";
  1726. case StatusCode::RequestTimeout_408: return "Request Timeout";
  1727. case StatusCode::Conflict_409: return "Conflict";
  1728. case StatusCode::Gone_410: return "Gone";
  1729. case StatusCode::LengthRequired_411: return "Length Required";
  1730. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  1731. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  1732. case StatusCode::UriTooLong_414: return "URI Too Long";
  1733. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  1734. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  1735. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  1736. case StatusCode::ImATeapot_418: return "I'm a teapot";
  1737. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  1738. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  1739. case StatusCode::Locked_423: return "Locked";
  1740. case StatusCode::FailedDependency_424: return "Failed Dependency";
  1741. case StatusCode::TooEarly_425: return "Too Early";
  1742. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  1743. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  1744. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  1745. case StatusCode::RequestHeaderFieldsTooLarge_431:
  1746. return "Request Header Fields Too Large";
  1747. case StatusCode::UnavailableForLegalReasons_451:
  1748. return "Unavailable For Legal Reasons";
  1749. case StatusCode::NotImplemented_501: return "Not Implemented";
  1750. case StatusCode::BadGateway_502: return "Bad Gateway";
  1751. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  1752. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  1753. case StatusCode::HttpVersionNotSupported_505:
  1754. return "HTTP Version Not Supported";
  1755. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  1756. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  1757. case StatusCode::LoopDetected_508: return "Loop Detected";
  1758. case StatusCode::NotExtended_510: return "Not Extended";
  1759. case StatusCode::NetworkAuthenticationRequired_511:
  1760. return "Network Authentication Required";
  1761. default:
  1762. case StatusCode::InternalServerError_500: return "Internal Server Error";
  1763. }
  1764. }
  1765. inline std::string get_bearer_token_auth(const Request &req) {
  1766. if (req.has_header("Authorization")) {
  1767. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1768. return req.get_header_value("Authorization")
  1769. .substr(bearer_header_prefix_len);
  1770. }
  1771. return "";
  1772. }
  1773. template <class Rep, class Period>
  1774. inline Server &
  1775. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1776. detail::duration_to_sec_and_usec(
  1777. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1778. return *this;
  1779. }
  1780. template <class Rep, class Period>
  1781. inline Server &
  1782. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1783. detail::duration_to_sec_and_usec(
  1784. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1785. return *this;
  1786. }
  1787. template <class Rep, class Period>
  1788. inline Server &
  1789. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1790. detail::duration_to_sec_and_usec(
  1791. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1792. return *this;
  1793. }
  1794. inline std::string to_string(const Error error) {
  1795. switch (error) {
  1796. case Error::Success: return "Success (no error)";
  1797. case Error::Connection: return "Could not establish connection";
  1798. case Error::BindIPAddress: return "Failed to bind IP address";
  1799. case Error::Read: return "Failed to read connection";
  1800. case Error::Write: return "Failed to write connection";
  1801. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  1802. case Error::Canceled: return "Connection handling canceled";
  1803. case Error::SSLConnection: return "SSL connection failed";
  1804. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  1805. case Error::SSLServerVerification: return "SSL server verification failed";
  1806. case Error::SSLServerHostnameVerification:
  1807. return "SSL server hostname verification failed";
  1808. case Error::UnsupportedMultipartBoundaryChars:
  1809. return "Unsupported HTTP multipart boundary characters";
  1810. case Error::Compression: return "Compression failed";
  1811. case Error::ConnectionTimeout: return "Connection timed out";
  1812. case Error::ProxyConnection: return "Proxy connection failed";
  1813. case Error::Unknown: return "Unknown";
  1814. default: break;
  1815. }
  1816. return "Invalid";
  1817. }
  1818. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  1819. os << to_string(obj);
  1820. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  1821. return os;
  1822. }
  1823. inline size_t Result::get_request_header_value_u64(const std::string &key,
  1824. size_t def,
  1825. size_t id) const {
  1826. return detail::get_header_value_u64(request_headers_, key, def, id);
  1827. }
  1828. template <class Rep, class Period>
  1829. inline void ClientImpl::set_connection_timeout(
  1830. const std::chrono::duration<Rep, Period> &duration) {
  1831. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1832. set_connection_timeout(sec, usec);
  1833. });
  1834. }
  1835. template <class Rep, class Period>
  1836. inline void ClientImpl::set_read_timeout(
  1837. const std::chrono::duration<Rep, Period> &duration) {
  1838. detail::duration_to_sec_and_usec(
  1839. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1840. }
  1841. template <class Rep, class Period>
  1842. inline void ClientImpl::set_write_timeout(
  1843. const std::chrono::duration<Rep, Period> &duration) {
  1844. detail::duration_to_sec_and_usec(
  1845. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1846. }
  1847. template <class Rep, class Period>
  1848. inline void ClientImpl::set_max_timeout(
  1849. const std::chrono::duration<Rep, Period> &duration) {
  1850. auto msec =
  1851. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  1852. set_max_timeout(msec);
  1853. }
  1854. template <class Rep, class Period>
  1855. inline void Client::set_connection_timeout(
  1856. const std::chrono::duration<Rep, Period> &duration) {
  1857. cli_->set_connection_timeout(duration);
  1858. }
  1859. template <class Rep, class Period>
  1860. inline void
  1861. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1862. cli_->set_read_timeout(duration);
  1863. }
  1864. template <class Rep, class Period>
  1865. inline void
  1866. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1867. cli_->set_write_timeout(duration);
  1868. }
  1869. template <class Rep, class Period>
  1870. inline void
  1871. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1872. cli_->set_max_timeout(duration);
  1873. }
  1874. /*
  1875. * Forward declarations and types that will be part of the .h file if split into
  1876. * .h + .cc.
  1877. */
  1878. std::string hosted_at(const std::string &hostname);
  1879. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  1880. std::string encode_uri_component(const std::string &value);
  1881. std::string encode_uri(const std::string &value);
  1882. std::string decode_uri_component(const std::string &value);
  1883. std::string decode_uri(const std::string &value);
  1884. std::string encode_query_param(const std::string &value);
  1885. std::string append_query_params(const std::string &path, const Params &params);
  1886. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  1887. std::pair<std::string, std::string>
  1888. make_basic_authentication_header(const std::string &username,
  1889. const std::string &password,
  1890. bool is_proxy = false);
  1891. namespace detail {
  1892. #if defined(_WIN64)
  1893. inline std::wstring u8string_to_wstring(const char *s) {
  1894. std::wstring ws;
  1895. auto len = static_cast<int>(strlen(s));
  1896. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  1897. if (wlen > 0) {
  1898. ws.resize(wlen);
  1899. wlen = ::MultiByteToWideChar(
  1900. CP_UTF8, 0, s, len,
  1901. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  1902. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  1903. }
  1904. return ws;
  1905. }
  1906. #endif
  1907. struct FileStat {
  1908. FileStat(const std::string &path);
  1909. bool is_file() const;
  1910. bool is_dir() const;
  1911. private:
  1912. #if defined(_WIN64)
  1913. struct _stat st_;
  1914. #else
  1915. struct stat st_;
  1916. #endif
  1917. int ret_ = -1;
  1918. };
  1919. std::string decode_path(const std::string &s, bool convert_plus_to_space);
  1920. std::string trim_copy(const std::string &s);
  1921. void divide(
  1922. const char *data, std::size_t size, char d,
  1923. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1924. fn);
  1925. void divide(
  1926. const std::string &str, char d,
  1927. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1928. fn);
  1929. void split(const char *b, const char *e, char d,
  1930. std::function<void(const char *, const char *)> fn);
  1931. void split(const char *b, const char *e, char d, size_t m,
  1932. std::function<void(const char *, const char *)> fn);
  1933. bool process_client_socket(
  1934. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  1935. time_t write_timeout_sec, time_t write_timeout_usec,
  1936. time_t max_timeout_msec,
  1937. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1938. std::function<bool(Stream &)> callback);
  1939. socket_t create_client_socket(const std::string &host, const std::string &ip,
  1940. int port, int address_family, bool tcp_nodelay,
  1941. bool ipv6_v6only, SocketOptions socket_options,
  1942. time_t connection_timeout_sec,
  1943. time_t connection_timeout_usec,
  1944. time_t read_timeout_sec, time_t read_timeout_usec,
  1945. time_t write_timeout_sec,
  1946. time_t write_timeout_usec,
  1947. const std::string &intf, Error &error);
  1948. const char *get_header_value(const Headers &headers, const std::string &key,
  1949. const char *def, size_t id);
  1950. std::string params_to_query_str(const Params &params);
  1951. void parse_query_text(const char *data, std::size_t size, Params &params);
  1952. void parse_query_text(const std::string &s, Params &params);
  1953. bool parse_multipart_boundary(const std::string &content_type,
  1954. std::string &boundary);
  1955. bool parse_range_header(const std::string &s, Ranges &ranges);
  1956. bool parse_accept_header(const std::string &s,
  1957. std::vector<std::string> &content_types);
  1958. int close_socket(socket_t sock);
  1959. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  1960. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  1961. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  1962. EncodingType encoding_type(const Request &req, const Response &res);
  1963. class BufferStream final : public Stream {
  1964. public:
  1965. BufferStream() = default;
  1966. ~BufferStream() override = default;
  1967. bool is_readable() const override;
  1968. bool wait_readable() const override;
  1969. bool wait_writable() const override;
  1970. ssize_t read(char *ptr, size_t size) override;
  1971. ssize_t write(const char *ptr, size_t size) override;
  1972. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1973. void get_local_ip_and_port(std::string &ip, int &port) const override;
  1974. socket_t socket() const override;
  1975. time_t duration() const override;
  1976. const std::string &get_buffer() const;
  1977. private:
  1978. std::string buffer;
  1979. size_t position = 0;
  1980. };
  1981. class compressor {
  1982. public:
  1983. virtual ~compressor() = default;
  1984. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1985. virtual bool compress(const char *data, size_t data_length, bool last,
  1986. Callback callback) = 0;
  1987. };
  1988. class decompressor {
  1989. public:
  1990. virtual ~decompressor() = default;
  1991. virtual bool is_valid() const = 0;
  1992. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1993. virtual bool decompress(const char *data, size_t data_length,
  1994. Callback callback) = 0;
  1995. };
  1996. class nocompressor final : public compressor {
  1997. public:
  1998. ~nocompressor() override = default;
  1999. bool compress(const char *data, size_t data_length, bool /*last*/,
  2000. Callback callback) override;
  2001. };
  2002. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2003. class gzip_compressor final : public compressor {
  2004. public:
  2005. gzip_compressor();
  2006. ~gzip_compressor() override;
  2007. bool compress(const char *data, size_t data_length, bool last,
  2008. Callback callback) override;
  2009. private:
  2010. bool is_valid_ = false;
  2011. z_stream strm_;
  2012. };
  2013. class gzip_decompressor final : public decompressor {
  2014. public:
  2015. gzip_decompressor();
  2016. ~gzip_decompressor() override;
  2017. bool is_valid() const override;
  2018. bool decompress(const char *data, size_t data_length,
  2019. Callback callback) override;
  2020. private:
  2021. bool is_valid_ = false;
  2022. z_stream strm_;
  2023. };
  2024. #endif
  2025. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2026. class brotli_compressor final : public compressor {
  2027. public:
  2028. brotli_compressor();
  2029. ~brotli_compressor();
  2030. bool compress(const char *data, size_t data_length, bool last,
  2031. Callback callback) override;
  2032. private:
  2033. BrotliEncoderState *state_ = nullptr;
  2034. };
  2035. class brotli_decompressor final : public decompressor {
  2036. public:
  2037. brotli_decompressor();
  2038. ~brotli_decompressor();
  2039. bool is_valid() const override;
  2040. bool decompress(const char *data, size_t data_length,
  2041. Callback callback) override;
  2042. private:
  2043. BrotliDecoderResult decoder_r;
  2044. BrotliDecoderState *decoder_s = nullptr;
  2045. };
  2046. #endif
  2047. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2048. class zstd_compressor : public compressor {
  2049. public:
  2050. zstd_compressor();
  2051. ~zstd_compressor();
  2052. bool compress(const char *data, size_t data_length, bool last,
  2053. Callback callback) override;
  2054. private:
  2055. ZSTD_CCtx *ctx_ = nullptr;
  2056. };
  2057. class zstd_decompressor : public decompressor {
  2058. public:
  2059. zstd_decompressor();
  2060. ~zstd_decompressor();
  2061. bool is_valid() const override;
  2062. bool decompress(const char *data, size_t data_length,
  2063. Callback callback) override;
  2064. private:
  2065. ZSTD_DCtx *ctx_ = nullptr;
  2066. };
  2067. #endif
  2068. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2069. // to store data. The call can set memory on stack for performance.
  2070. class stream_line_reader {
  2071. public:
  2072. stream_line_reader(Stream &strm, char *fixed_buffer,
  2073. size_t fixed_buffer_size);
  2074. const char *ptr() const;
  2075. size_t size() const;
  2076. bool end_with_crlf() const;
  2077. bool getline();
  2078. private:
  2079. void append(char c);
  2080. Stream &strm_;
  2081. char *fixed_buffer_;
  2082. const size_t fixed_buffer_size_;
  2083. size_t fixed_buffer_used_size_ = 0;
  2084. std::string growable_buffer_;
  2085. };
  2086. class mmap {
  2087. public:
  2088. mmap(const char *path);
  2089. ~mmap();
  2090. bool open(const char *path);
  2091. void close();
  2092. bool is_open() const;
  2093. size_t size() const;
  2094. const char *data() const;
  2095. private:
  2096. #if defined(_WIN64)
  2097. HANDLE hFile_ = NULL;
  2098. HANDLE hMapping_ = NULL;
  2099. #else
  2100. int fd_ = -1;
  2101. #endif
  2102. size_t size_ = 0;
  2103. void *addr_ = nullptr;
  2104. bool is_open_empty_file = false;
  2105. };
  2106. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2107. namespace fields {
  2108. inline bool is_token_char(char c) {
  2109. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  2110. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  2111. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  2112. }
  2113. inline bool is_token(const std::string &s) {
  2114. if (s.empty()) { return false; }
  2115. for (auto c : s) {
  2116. if (!is_token_char(c)) { return false; }
  2117. }
  2118. return true;
  2119. }
  2120. inline bool is_field_name(const std::string &s) { return is_token(s); }
  2121. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  2122. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  2123. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  2124. inline bool is_field_content(const std::string &s) {
  2125. if (s.empty()) { return true; }
  2126. if (s.size() == 1) {
  2127. return is_field_vchar(s[0]);
  2128. } else if (s.size() == 2) {
  2129. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  2130. } else {
  2131. size_t i = 0;
  2132. if (!is_field_vchar(s[i])) { return false; }
  2133. i++;
  2134. while (i < s.size() - 1) {
  2135. auto c = s[i++];
  2136. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  2137. } else {
  2138. return false;
  2139. }
  2140. }
  2141. return is_field_vchar(s[i]);
  2142. }
  2143. }
  2144. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  2145. } // namespace fields
  2146. } // namespace detail
  2147. // ----------------------------------------------------------------------------
  2148. /*
  2149. * Implementation that will be part of the .cc file if split into .h + .cc.
  2150. */
  2151. namespace detail {
  2152. inline bool is_hex(char c, int &v) {
  2153. if (0x20 <= c && isdigit(c)) {
  2154. v = c - '0';
  2155. return true;
  2156. } else if ('A' <= c && c <= 'F') {
  2157. v = c - 'A' + 10;
  2158. return true;
  2159. } else if ('a' <= c && c <= 'f') {
  2160. v = c - 'a' + 10;
  2161. return true;
  2162. }
  2163. return false;
  2164. }
  2165. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  2166. int &val) {
  2167. if (i >= s.size()) { return false; }
  2168. val = 0;
  2169. for (; cnt; i++, cnt--) {
  2170. if (!s[i]) { return false; }
  2171. auto v = 0;
  2172. if (is_hex(s[i], v)) {
  2173. val = val * 16 + v;
  2174. } else {
  2175. return false;
  2176. }
  2177. }
  2178. return true;
  2179. }
  2180. inline std::string from_i_to_hex(size_t n) {
  2181. static const auto charset = "0123456789abcdef";
  2182. std::string ret;
  2183. do {
  2184. ret = charset[n & 15] + ret;
  2185. n >>= 4;
  2186. } while (n > 0);
  2187. return ret;
  2188. }
  2189. inline size_t to_utf8(int code, char *buff) {
  2190. if (code < 0x0080) {
  2191. buff[0] = static_cast<char>(code & 0x7F);
  2192. return 1;
  2193. } else if (code < 0x0800) {
  2194. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  2195. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  2196. return 2;
  2197. } else if (code < 0xD800) {
  2198. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2199. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2200. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2201. return 3;
  2202. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  2203. return 0;
  2204. } else if (code < 0x10000) {
  2205. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2206. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2207. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2208. return 3;
  2209. } else if (code < 0x110000) {
  2210. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  2211. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  2212. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2213. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  2214. return 4;
  2215. }
  2216. // NOTREACHED
  2217. return 0;
  2218. }
  2219. // NOTE: This code came up with the following stackoverflow post:
  2220. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  2221. inline std::string base64_encode(const std::string &in) {
  2222. static const auto lookup =
  2223. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2224. std::string out;
  2225. out.reserve(in.size());
  2226. auto val = 0;
  2227. auto valb = -6;
  2228. for (auto c : in) {
  2229. val = (val << 8) + static_cast<uint8_t>(c);
  2230. valb += 8;
  2231. while (valb >= 0) {
  2232. out.push_back(lookup[(val >> valb) & 0x3F]);
  2233. valb -= 6;
  2234. }
  2235. }
  2236. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  2237. while (out.size() % 4) {
  2238. out.push_back('=');
  2239. }
  2240. return out;
  2241. }
  2242. inline bool is_valid_path(const std::string &path) {
  2243. size_t level = 0;
  2244. size_t i = 0;
  2245. // Skip slash
  2246. while (i < path.size() && path[i] == '/') {
  2247. i++;
  2248. }
  2249. while (i < path.size()) {
  2250. // Read component
  2251. auto beg = i;
  2252. while (i < path.size() && path[i] != '/') {
  2253. if (path[i] == '\0') {
  2254. return false;
  2255. } else if (path[i] == '\\') {
  2256. return false;
  2257. }
  2258. i++;
  2259. }
  2260. auto len = i - beg;
  2261. assert(len > 0);
  2262. if (!path.compare(beg, len, ".")) {
  2263. ;
  2264. } else if (!path.compare(beg, len, "..")) {
  2265. if (level == 0) { return false; }
  2266. level--;
  2267. } else {
  2268. level++;
  2269. }
  2270. // Skip slash
  2271. while (i < path.size() && path[i] == '/') {
  2272. i++;
  2273. }
  2274. }
  2275. return true;
  2276. }
  2277. inline FileStat::FileStat(const std::string &path) {
  2278. #if defined(_WIN64)
  2279. auto wpath = u8string_to_wstring(path.c_str());
  2280. ret_ = _wstat(wpath.c_str(), &st_);
  2281. #else
  2282. ret_ = stat(path.c_str(), &st_);
  2283. #endif
  2284. }
  2285. inline bool FileStat::is_file() const {
  2286. return ret_ >= 0 && S_ISREG(st_.st_mode);
  2287. }
  2288. inline bool FileStat::is_dir() const {
  2289. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  2290. }
  2291. inline std::string encode_path(const std::string &s) {
  2292. std::string result;
  2293. result.reserve(s.size());
  2294. for (size_t i = 0; s[i]; i++) {
  2295. switch (s[i]) {
  2296. case ' ': result += "%20"; break;
  2297. case '+': result += "%2B"; break;
  2298. case '\r': result += "%0D"; break;
  2299. case '\n': result += "%0A"; break;
  2300. case '\'': result += "%27"; break;
  2301. case ',': result += "%2C"; break;
  2302. // case ':': result += "%3A"; break; // ok? probably...
  2303. case ';': result += "%3B"; break;
  2304. default:
  2305. auto c = static_cast<uint8_t>(s[i]);
  2306. if (c >= 0x80) {
  2307. result += '%';
  2308. char hex[4];
  2309. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  2310. assert(len == 2);
  2311. result.append(hex, static_cast<size_t>(len));
  2312. } else {
  2313. result += s[i];
  2314. }
  2315. break;
  2316. }
  2317. }
  2318. return result;
  2319. }
  2320. inline std::string decode_path(const std::string &s,
  2321. bool convert_plus_to_space) {
  2322. std::string result;
  2323. for (size_t i = 0; i < s.size(); i++) {
  2324. if (s[i] == '%' && i + 1 < s.size()) {
  2325. if (s[i + 1] == 'u') {
  2326. auto val = 0;
  2327. if (from_hex_to_i(s, i + 2, 4, val)) {
  2328. // 4 digits Unicode codes
  2329. char buff[4];
  2330. size_t len = to_utf8(val, buff);
  2331. if (len > 0) { result.append(buff, len); }
  2332. i += 5; // 'u0000'
  2333. } else {
  2334. result += s[i];
  2335. }
  2336. } else {
  2337. auto val = 0;
  2338. if (from_hex_to_i(s, i + 1, 2, val)) {
  2339. // 2 digits hex codes
  2340. result += static_cast<char>(val);
  2341. i += 2; // '00'
  2342. } else {
  2343. result += s[i];
  2344. }
  2345. }
  2346. } else if (convert_plus_to_space && s[i] == '+') {
  2347. result += ' ';
  2348. } else {
  2349. result += s[i];
  2350. }
  2351. }
  2352. return result;
  2353. }
  2354. inline std::string file_extension(const std::string &path) {
  2355. std::smatch m;
  2356. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  2357. if (std::regex_search(path, m, re)) { return m[1].str(); }
  2358. return std::string();
  2359. }
  2360. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  2361. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  2362. size_t right) {
  2363. while (b + left < e && is_space_or_tab(b[left])) {
  2364. left++;
  2365. }
  2366. while (right > 0 && is_space_or_tab(b[right - 1])) {
  2367. right--;
  2368. }
  2369. return std::make_pair(left, right);
  2370. }
  2371. inline std::string trim_copy(const std::string &s) {
  2372. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  2373. return s.substr(r.first, r.second - r.first);
  2374. }
  2375. inline std::string trim_double_quotes_copy(const std::string &s) {
  2376. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  2377. return s.substr(1, s.size() - 2);
  2378. }
  2379. return s;
  2380. }
  2381. inline void
  2382. divide(const char *data, std::size_t size, char d,
  2383. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2384. fn) {
  2385. const auto it = std::find(data, data + size, d);
  2386. const auto found = static_cast<std::size_t>(it != data + size);
  2387. const auto lhs_data = data;
  2388. const auto lhs_size = static_cast<std::size_t>(it - data);
  2389. const auto rhs_data = it + found;
  2390. const auto rhs_size = size - lhs_size - found;
  2391. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  2392. }
  2393. inline void
  2394. divide(const std::string &str, char d,
  2395. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2396. fn) {
  2397. divide(str.data(), str.size(), d, std::move(fn));
  2398. }
  2399. inline void split(const char *b, const char *e, char d,
  2400. std::function<void(const char *, const char *)> fn) {
  2401. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  2402. }
  2403. inline void split(const char *b, const char *e, char d, size_t m,
  2404. std::function<void(const char *, const char *)> fn) {
  2405. size_t i = 0;
  2406. size_t beg = 0;
  2407. size_t count = 1;
  2408. while (e ? (b + i < e) : (b[i] != '\0')) {
  2409. if (b[i] == d && count < m) {
  2410. auto r = trim(b, e, beg, i);
  2411. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2412. beg = i + 1;
  2413. count++;
  2414. }
  2415. i++;
  2416. }
  2417. if (i) {
  2418. auto r = trim(b, e, beg, i);
  2419. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2420. }
  2421. }
  2422. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  2423. size_t fixed_buffer_size)
  2424. : strm_(strm), fixed_buffer_(fixed_buffer),
  2425. fixed_buffer_size_(fixed_buffer_size) {}
  2426. inline const char *stream_line_reader::ptr() const {
  2427. if (growable_buffer_.empty()) {
  2428. return fixed_buffer_;
  2429. } else {
  2430. return growable_buffer_.data();
  2431. }
  2432. }
  2433. inline size_t stream_line_reader::size() const {
  2434. if (growable_buffer_.empty()) {
  2435. return fixed_buffer_used_size_;
  2436. } else {
  2437. return growable_buffer_.size();
  2438. }
  2439. }
  2440. inline bool stream_line_reader::end_with_crlf() const {
  2441. auto end = ptr() + size();
  2442. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  2443. }
  2444. inline bool stream_line_reader::getline() {
  2445. fixed_buffer_used_size_ = 0;
  2446. growable_buffer_.clear();
  2447. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2448. char prev_byte = 0;
  2449. #endif
  2450. for (size_t i = 0;; i++) {
  2451. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  2452. // Treat exceptionally long lines as an error to
  2453. // prevent infinite loops/memory exhaustion
  2454. return false;
  2455. }
  2456. char byte;
  2457. auto n = strm_.read(&byte, 1);
  2458. if (n < 0) {
  2459. return false;
  2460. } else if (n == 0) {
  2461. if (i == 0) {
  2462. return false;
  2463. } else {
  2464. break;
  2465. }
  2466. }
  2467. append(byte);
  2468. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2469. if (byte == '\n') { break; }
  2470. #else
  2471. if (prev_byte == '\r' && byte == '\n') { break; }
  2472. prev_byte = byte;
  2473. #endif
  2474. }
  2475. return true;
  2476. }
  2477. inline void stream_line_reader::append(char c) {
  2478. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  2479. fixed_buffer_[fixed_buffer_used_size_++] = c;
  2480. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  2481. } else {
  2482. if (growable_buffer_.empty()) {
  2483. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  2484. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  2485. }
  2486. growable_buffer_ += c;
  2487. }
  2488. }
  2489. inline mmap::mmap(const char *path) { open(path); }
  2490. inline mmap::~mmap() { close(); }
  2491. inline bool mmap::open(const char *path) {
  2492. close();
  2493. #if defined(_WIN64)
  2494. auto wpath = u8string_to_wstring(path);
  2495. if (wpath.empty()) { return false; }
  2496. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  2497. OPEN_EXISTING, NULL);
  2498. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  2499. LARGE_INTEGER size{};
  2500. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  2501. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  2502. // See:
  2503. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  2504. if (static_cast<ULONGLONG>(size.QuadPart) >
  2505. (std::numeric_limits<decltype(size_)>::max)()) {
  2506. // `size_t` might be 32-bits, on 32-bits Windows.
  2507. return false;
  2508. }
  2509. size_ = static_cast<size_t>(size.QuadPart);
  2510. hMapping_ =
  2511. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  2512. // Special treatment for an empty file...
  2513. if (hMapping_ == NULL && size_ == 0) {
  2514. close();
  2515. is_open_empty_file = true;
  2516. return true;
  2517. }
  2518. if (hMapping_ == NULL) {
  2519. close();
  2520. return false;
  2521. }
  2522. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  2523. if (addr_ == nullptr) {
  2524. close();
  2525. return false;
  2526. }
  2527. #else
  2528. fd_ = ::open(path, O_RDONLY);
  2529. if (fd_ == -1) { return false; }
  2530. struct stat sb;
  2531. if (fstat(fd_, &sb) == -1) {
  2532. close();
  2533. return false;
  2534. }
  2535. size_ = static_cast<size_t>(sb.st_size);
  2536. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  2537. // Special treatment for an empty file...
  2538. if (addr_ == MAP_FAILED && size_ == 0) {
  2539. close();
  2540. is_open_empty_file = true;
  2541. return false;
  2542. }
  2543. #endif
  2544. return true;
  2545. }
  2546. inline bool mmap::is_open() const {
  2547. return is_open_empty_file ? true : addr_ != nullptr;
  2548. }
  2549. inline size_t mmap::size() const { return size_; }
  2550. inline const char *mmap::data() const {
  2551. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  2552. }
  2553. inline void mmap::close() {
  2554. #if defined(_WIN64)
  2555. if (addr_) {
  2556. ::UnmapViewOfFile(addr_);
  2557. addr_ = nullptr;
  2558. }
  2559. if (hMapping_) {
  2560. ::CloseHandle(hMapping_);
  2561. hMapping_ = NULL;
  2562. }
  2563. if (hFile_ != INVALID_HANDLE_VALUE) {
  2564. ::CloseHandle(hFile_);
  2565. hFile_ = INVALID_HANDLE_VALUE;
  2566. }
  2567. is_open_empty_file = false;
  2568. #else
  2569. if (addr_ != nullptr) {
  2570. munmap(addr_, size_);
  2571. addr_ = nullptr;
  2572. }
  2573. if (fd_ != -1) {
  2574. ::close(fd_);
  2575. fd_ = -1;
  2576. }
  2577. #endif
  2578. size_ = 0;
  2579. }
  2580. inline int close_socket(socket_t sock) {
  2581. #ifdef _WIN64
  2582. return closesocket(sock);
  2583. #else
  2584. return close(sock);
  2585. #endif
  2586. }
  2587. template <typename T> inline ssize_t handle_EINTR(T fn) {
  2588. ssize_t res = 0;
  2589. while (true) {
  2590. res = fn();
  2591. if (res < 0 && errno == EINTR) {
  2592. std::this_thread::sleep_for(std::chrono::microseconds{1});
  2593. continue;
  2594. }
  2595. break;
  2596. }
  2597. return res;
  2598. }
  2599. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  2600. return handle_EINTR([&]() {
  2601. return recv(sock,
  2602. #ifdef _WIN64
  2603. static_cast<char *>(ptr), static_cast<int>(size),
  2604. #else
  2605. ptr, size,
  2606. #endif
  2607. flags);
  2608. });
  2609. }
  2610. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  2611. int flags) {
  2612. return handle_EINTR([&]() {
  2613. return send(sock,
  2614. #ifdef _WIN64
  2615. static_cast<const char *>(ptr), static_cast<int>(size),
  2616. #else
  2617. ptr, size,
  2618. #endif
  2619. flags);
  2620. });
  2621. }
  2622. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  2623. #ifdef _WIN64
  2624. return ::WSAPoll(fds, nfds, timeout);
  2625. #else
  2626. return ::poll(fds, nfds, timeout);
  2627. #endif
  2628. }
  2629. template <bool Read>
  2630. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  2631. #ifdef __APPLE__
  2632. if (sock >= FD_SETSIZE) { return -1; }
  2633. fd_set fds, *rfds, *wfds;
  2634. FD_ZERO(&fds);
  2635. FD_SET(sock, &fds);
  2636. rfds = (Read ? &fds : nullptr);
  2637. wfds = (Read ? nullptr : &fds);
  2638. timeval tv;
  2639. tv.tv_sec = static_cast<long>(sec);
  2640. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  2641. return handle_EINTR([&]() {
  2642. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  2643. });
  2644. #else
  2645. struct pollfd pfd;
  2646. pfd.fd = sock;
  2647. pfd.events = (Read ? POLLIN : POLLOUT);
  2648. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2649. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  2650. #endif
  2651. }
  2652. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  2653. return select_impl<true>(sock, sec, usec);
  2654. }
  2655. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  2656. return select_impl<false>(sock, sec, usec);
  2657. }
  2658. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  2659. time_t usec) {
  2660. #ifdef __APPLE__
  2661. if (sock >= FD_SETSIZE) { return Error::Connection; }
  2662. fd_set fdsr, fdsw;
  2663. FD_ZERO(&fdsr);
  2664. FD_ZERO(&fdsw);
  2665. FD_SET(sock, &fdsr);
  2666. FD_SET(sock, &fdsw);
  2667. timeval tv;
  2668. tv.tv_sec = static_cast<long>(sec);
  2669. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  2670. auto ret = handle_EINTR([&]() {
  2671. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  2672. });
  2673. if (ret == 0) { return Error::ConnectionTimeout; }
  2674. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  2675. auto error = 0;
  2676. socklen_t len = sizeof(error);
  2677. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2678. reinterpret_cast<char *>(&error), &len);
  2679. auto successful = res >= 0 && !error;
  2680. return successful ? Error::Success : Error::Connection;
  2681. }
  2682. return Error::Connection;
  2683. #else
  2684. struct pollfd pfd_read;
  2685. pfd_read.fd = sock;
  2686. pfd_read.events = POLLIN | POLLOUT;
  2687. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2688. auto poll_res =
  2689. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  2690. if (poll_res == 0) { return Error::ConnectionTimeout; }
  2691. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  2692. auto error = 0;
  2693. socklen_t len = sizeof(error);
  2694. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2695. reinterpret_cast<char *>(&error), &len);
  2696. auto successful = res >= 0 && !error;
  2697. return successful ? Error::Success : Error::Connection;
  2698. }
  2699. return Error::Connection;
  2700. #endif
  2701. }
  2702. inline bool is_socket_alive(socket_t sock) {
  2703. const auto val = detail::select_read(sock, 0, 0);
  2704. if (val == 0) {
  2705. return true;
  2706. } else if (val < 0 && errno == EBADF) {
  2707. return false;
  2708. }
  2709. char buf[1];
  2710. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  2711. }
  2712. class SocketStream final : public Stream {
  2713. public:
  2714. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2715. time_t write_timeout_sec, time_t write_timeout_usec,
  2716. time_t max_timeout_msec = 0,
  2717. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2718. (std::chrono::steady_clock::time_point::min)());
  2719. ~SocketStream() override;
  2720. bool is_readable() const override;
  2721. bool wait_readable() const override;
  2722. bool wait_writable() const override;
  2723. ssize_t read(char *ptr, size_t size) override;
  2724. ssize_t write(const char *ptr, size_t size) override;
  2725. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2726. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2727. socket_t socket() const override;
  2728. time_t duration() const override;
  2729. private:
  2730. socket_t sock_;
  2731. time_t read_timeout_sec_;
  2732. time_t read_timeout_usec_;
  2733. time_t write_timeout_sec_;
  2734. time_t write_timeout_usec_;
  2735. time_t max_timeout_msec_;
  2736. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2737. std::vector<char> read_buff_;
  2738. size_t read_buff_off_ = 0;
  2739. size_t read_buff_content_size_ = 0;
  2740. static const size_t read_buff_size_ = 1024l * 4;
  2741. };
  2742. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2743. class SSLSocketStream final : public Stream {
  2744. public:
  2745. SSLSocketStream(
  2746. socket_t sock, SSL *ssl, time_t read_timeout_sec,
  2747. time_t read_timeout_usec, time_t write_timeout_sec,
  2748. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  2749. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2750. (std::chrono::steady_clock::time_point::min)());
  2751. ~SSLSocketStream() override;
  2752. bool is_readable() const override;
  2753. bool wait_readable() const override;
  2754. bool wait_writable() const override;
  2755. ssize_t read(char *ptr, size_t size) override;
  2756. ssize_t write(const char *ptr, size_t size) override;
  2757. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2758. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2759. socket_t socket() const override;
  2760. time_t duration() const override;
  2761. private:
  2762. socket_t sock_;
  2763. SSL *ssl_;
  2764. time_t read_timeout_sec_;
  2765. time_t read_timeout_usec_;
  2766. time_t write_timeout_sec_;
  2767. time_t write_timeout_usec_;
  2768. time_t max_timeout_msec_;
  2769. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2770. };
  2771. #endif
  2772. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2773. time_t keep_alive_timeout_sec) {
  2774. using namespace std::chrono;
  2775. const auto interval_usec =
  2776. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  2777. // Avoid expensive `steady_clock::now()` call for the first time
  2778. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  2779. const auto start = steady_clock::now() - microseconds{interval_usec};
  2780. const auto timeout = seconds{keep_alive_timeout_sec};
  2781. while (true) {
  2782. if (svr_sock == INVALID_SOCKET) {
  2783. break; // Server socket is closed
  2784. }
  2785. auto val = select_read(sock, 0, interval_usec);
  2786. if (val < 0) {
  2787. break; // Ssocket error
  2788. } else if (val == 0) {
  2789. if (steady_clock::now() - start > timeout) {
  2790. break; // Timeout
  2791. }
  2792. } else {
  2793. return true; // Ready for read
  2794. }
  2795. }
  2796. return false;
  2797. }
  2798. template <typename T>
  2799. inline bool
  2800. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2801. size_t keep_alive_max_count,
  2802. time_t keep_alive_timeout_sec, T callback) {
  2803. assert(keep_alive_max_count > 0);
  2804. auto ret = false;
  2805. auto count = keep_alive_max_count;
  2806. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  2807. auto close_connection = count == 1;
  2808. auto connection_closed = false;
  2809. ret = callback(close_connection, connection_closed);
  2810. if (!ret || connection_closed) { break; }
  2811. count--;
  2812. }
  2813. return ret;
  2814. }
  2815. template <typename T>
  2816. inline bool
  2817. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2818. size_t keep_alive_max_count,
  2819. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  2820. time_t read_timeout_usec, time_t write_timeout_sec,
  2821. time_t write_timeout_usec, T callback) {
  2822. return process_server_socket_core(
  2823. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  2824. [&](bool close_connection, bool &connection_closed) {
  2825. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2826. write_timeout_sec, write_timeout_usec);
  2827. return callback(strm, close_connection, connection_closed);
  2828. });
  2829. }
  2830. inline bool process_client_socket(
  2831. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2832. time_t write_timeout_sec, time_t write_timeout_usec,
  2833. time_t max_timeout_msec,
  2834. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2835. std::function<bool(Stream &)> callback) {
  2836. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2837. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  2838. start_time);
  2839. return callback(strm);
  2840. }
  2841. inline int shutdown_socket(socket_t sock) {
  2842. #ifdef _WIN64
  2843. return shutdown(sock, SD_BOTH);
  2844. #else
  2845. return shutdown(sock, SHUT_RDWR);
  2846. #endif
  2847. }
  2848. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  2849. if (s.size() > 1 && s[0] == '\0') {
  2850. auto ret = s;
  2851. ret[0] = '@';
  2852. return ret;
  2853. }
  2854. return s;
  2855. }
  2856. inline std::string
  2857. unescape_abstract_namespace_unix_domain(const std::string &s) {
  2858. if (s.size() > 1 && s[0] == '@') {
  2859. auto ret = s;
  2860. ret[0] = '\0';
  2861. return ret;
  2862. }
  2863. return s;
  2864. }
  2865. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  2866. const struct addrinfo *hints,
  2867. struct addrinfo **res, time_t timeout_sec) {
  2868. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2869. if (timeout_sec <= 0) {
  2870. // No timeout specified, use standard getaddrinfo
  2871. return getaddrinfo(node, service, hints, res);
  2872. }
  2873. #ifdef _WIN64
  2874. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  2875. OVERLAPPED overlapped = {0};
  2876. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  2877. if (!event) { return EAI_FAIL; }
  2878. overlapped.hEvent = event;
  2879. PADDRINFOEXW result_addrinfo = nullptr;
  2880. HANDLE cancel_handle = nullptr;
  2881. ADDRINFOEXW hints_ex = {0};
  2882. if (hints) {
  2883. hints_ex.ai_flags = hints->ai_flags;
  2884. hints_ex.ai_family = hints->ai_family;
  2885. hints_ex.ai_socktype = hints->ai_socktype;
  2886. hints_ex.ai_protocol = hints->ai_protocol;
  2887. }
  2888. auto wnode = u8string_to_wstring(node);
  2889. auto wservice = u8string_to_wstring(service);
  2890. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  2891. hints ? &hints_ex : nullptr, &result_addrinfo,
  2892. nullptr, &overlapped, nullptr, &cancel_handle);
  2893. if (ret == WSA_IO_PENDING) {
  2894. auto wait_result =
  2895. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  2896. if (wait_result == WAIT_TIMEOUT) {
  2897. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  2898. ::CloseHandle(event);
  2899. return EAI_AGAIN;
  2900. }
  2901. DWORD bytes_returned;
  2902. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  2903. &bytes_returned, FALSE)) {
  2904. ::CloseHandle(event);
  2905. return ::WSAGetLastError();
  2906. }
  2907. }
  2908. ::CloseHandle(event);
  2909. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  2910. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  2911. return 0;
  2912. }
  2913. return ret;
  2914. #elif defined(TARGET_OS_OSX)
  2915. // macOS implementation using CFHost API for asynchronous DNS resolution
  2916. CFStringRef hostname_ref = CFStringCreateWithCString(
  2917. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  2918. if (!hostname_ref) { return EAI_MEMORY; }
  2919. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  2920. CFRelease(hostname_ref);
  2921. if (!host_ref) { return EAI_MEMORY; }
  2922. // Set up context for callback
  2923. struct CFHostContext {
  2924. bool completed = false;
  2925. bool success = false;
  2926. CFArrayRef addresses = nullptr;
  2927. std::mutex mutex;
  2928. std::condition_variable cv;
  2929. } context;
  2930. CFHostClientContext client_context;
  2931. memset(&client_context, 0, sizeof(client_context));
  2932. client_context.info = &context;
  2933. // Set callback
  2934. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  2935. const CFStreamError *error, void *info) {
  2936. auto ctx = static_cast<CFHostContext *>(info);
  2937. std::lock_guard<std::mutex> lock(ctx->mutex);
  2938. if (error && error->error != 0) {
  2939. ctx->success = false;
  2940. } else {
  2941. Boolean hasBeenResolved;
  2942. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  2943. if (ctx->addresses && hasBeenResolved) {
  2944. CFRetain(ctx->addresses);
  2945. ctx->success = true;
  2946. } else {
  2947. ctx->success = false;
  2948. }
  2949. }
  2950. ctx->completed = true;
  2951. ctx->cv.notify_one();
  2952. };
  2953. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  2954. CFRelease(host_ref);
  2955. return EAI_SYSTEM;
  2956. }
  2957. // Schedule on run loop
  2958. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  2959. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2960. // Start resolution
  2961. CFStreamError stream_error;
  2962. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  2963. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2964. CFRelease(host_ref);
  2965. return EAI_FAIL;
  2966. }
  2967. // Wait for completion with timeout
  2968. auto timeout_time =
  2969. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  2970. bool timed_out = false;
  2971. {
  2972. std::unique_lock<std::mutex> lock(context.mutex);
  2973. while (!context.completed) {
  2974. auto now = std::chrono::steady_clock::now();
  2975. if (now >= timeout_time) {
  2976. timed_out = true;
  2977. break;
  2978. }
  2979. // Run the runloop for a short time
  2980. lock.unlock();
  2981. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  2982. lock.lock();
  2983. }
  2984. }
  2985. // Clean up
  2986. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2987. CFHostSetClient(host_ref, nullptr, nullptr);
  2988. if (timed_out || !context.completed) {
  2989. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  2990. CFRelease(host_ref);
  2991. return EAI_AGAIN;
  2992. }
  2993. if (!context.success || !context.addresses) {
  2994. CFRelease(host_ref);
  2995. return EAI_NODATA;
  2996. }
  2997. // Convert CFArray to addrinfo
  2998. CFIndex count = CFArrayGetCount(context.addresses);
  2999. if (count == 0) {
  3000. CFRelease(context.addresses);
  3001. CFRelease(host_ref);
  3002. return EAI_NODATA;
  3003. }
  3004. struct addrinfo *result_addrinfo = nullptr;
  3005. struct addrinfo **current = &result_addrinfo;
  3006. for (CFIndex i = 0; i < count; i++) {
  3007. CFDataRef addr_data =
  3008. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  3009. if (!addr_data) continue;
  3010. const struct sockaddr *sockaddr_ptr =
  3011. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  3012. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  3013. // Allocate addrinfo structure
  3014. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  3015. if (!*current) {
  3016. freeaddrinfo(result_addrinfo);
  3017. CFRelease(context.addresses);
  3018. CFRelease(host_ref);
  3019. return EAI_MEMORY;
  3020. }
  3021. memset(*current, 0, sizeof(struct addrinfo));
  3022. // Set up addrinfo fields
  3023. (*current)->ai_family = sockaddr_ptr->sa_family;
  3024. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  3025. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  3026. (*current)->ai_addrlen = sockaddr_len;
  3027. // Copy sockaddr
  3028. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  3029. if (!(*current)->ai_addr) {
  3030. freeaddrinfo(result_addrinfo);
  3031. CFRelease(context.addresses);
  3032. CFRelease(host_ref);
  3033. return EAI_MEMORY;
  3034. }
  3035. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  3036. // Set port if service is specified
  3037. if (service && strlen(service) > 0) {
  3038. int port = atoi(service);
  3039. if (port > 0) {
  3040. if (sockaddr_ptr->sa_family == AF_INET) {
  3041. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  3042. ->sin_port = htons(static_cast<uint16_t>(port));
  3043. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  3044. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  3045. ->sin6_port = htons(static_cast<uint16_t>(port));
  3046. }
  3047. }
  3048. }
  3049. current = &((*current)->ai_next);
  3050. }
  3051. CFRelease(context.addresses);
  3052. CFRelease(host_ref);
  3053. *res = result_addrinfo;
  3054. return 0;
  3055. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  3056. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  3057. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  3058. struct gaicb request;
  3059. struct gaicb *requests[1] = {&request};
  3060. struct sigevent sevp;
  3061. struct timespec timeout;
  3062. // Initialize the request structure
  3063. memset(&request, 0, sizeof(request));
  3064. request.ar_name = node;
  3065. request.ar_service = service;
  3066. request.ar_request = hints;
  3067. // Set up timeout
  3068. timeout.tv_sec = timeout_sec;
  3069. timeout.tv_nsec = 0;
  3070. // Initialize sigevent structure (not used, but required)
  3071. memset(&sevp, 0, sizeof(sevp));
  3072. sevp.sigev_notify = SIGEV_NONE;
  3073. // Start asynchronous resolution
  3074. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  3075. if (start_result != 0) { return start_result; }
  3076. // Wait for completion with timeout
  3077. int wait_result =
  3078. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  3079. if (wait_result == 0) {
  3080. // Completed successfully, get the result
  3081. int gai_result = gai_error(&request);
  3082. if (gai_result == 0) {
  3083. *res = request.ar_result;
  3084. return 0;
  3085. } else {
  3086. // Clean up on error
  3087. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  3088. return gai_result;
  3089. }
  3090. } else if (wait_result == EAI_AGAIN) {
  3091. // Timeout occurred, cancel the request
  3092. gai_cancel(&request);
  3093. return EAI_AGAIN;
  3094. } else {
  3095. // Other error occurred
  3096. gai_cancel(&request);
  3097. return wait_result;
  3098. }
  3099. #else
  3100. // Fallback implementation using thread-based timeout for other Unix systems
  3101. std::mutex result_mutex;
  3102. std::condition_variable result_cv;
  3103. auto completed = false;
  3104. auto result = EAI_SYSTEM;
  3105. struct addrinfo *result_addrinfo = nullptr;
  3106. std::thread resolve_thread([&]() {
  3107. auto thread_result = getaddrinfo(node, service, hints, &result_addrinfo);
  3108. std::lock_guard<std::mutex> lock(result_mutex);
  3109. result = thread_result;
  3110. completed = true;
  3111. result_cv.notify_one();
  3112. });
  3113. // Wait for completion or timeout
  3114. std::unique_lock<std::mutex> lock(result_mutex);
  3115. auto finished = result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  3116. [&] { return completed; });
  3117. if (finished) {
  3118. // Operation completed within timeout
  3119. resolve_thread.join();
  3120. *res = result_addrinfo;
  3121. return result;
  3122. } else {
  3123. // Timeout occurred
  3124. resolve_thread.detach(); // Let the thread finish in background
  3125. return EAI_AGAIN; // Return timeout error
  3126. }
  3127. #endif
  3128. #else
  3129. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  3130. return getaddrinfo(node, service, hints, res);
  3131. #endif
  3132. }
  3133. template <typename BindOrConnect>
  3134. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  3135. int address_family, int socket_flags, bool tcp_nodelay,
  3136. bool ipv6_v6only, SocketOptions socket_options,
  3137. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  3138. // Get address info
  3139. const char *node = nullptr;
  3140. struct addrinfo hints;
  3141. struct addrinfo *result;
  3142. memset(&hints, 0, sizeof(struct addrinfo));
  3143. hints.ai_socktype = SOCK_STREAM;
  3144. hints.ai_protocol = IPPROTO_IP;
  3145. if (!ip.empty()) {
  3146. node = ip.c_str();
  3147. // Ask getaddrinfo to convert IP in c-string to address
  3148. hints.ai_family = AF_UNSPEC;
  3149. hints.ai_flags = AI_NUMERICHOST;
  3150. } else {
  3151. if (!host.empty()) { node = host.c_str(); }
  3152. hints.ai_family = address_family;
  3153. hints.ai_flags = socket_flags;
  3154. }
  3155. #if !defined(_WIN64) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  3156. if (hints.ai_family == AF_UNIX) {
  3157. const auto addrlen = host.length();
  3158. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  3159. #ifdef SOCK_CLOEXEC
  3160. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  3161. hints.ai_protocol);
  3162. #else
  3163. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  3164. #endif
  3165. if (sock != INVALID_SOCKET) {
  3166. sockaddr_un addr{};
  3167. addr.sun_family = AF_UNIX;
  3168. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  3169. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  3170. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  3171. hints.ai_addrlen = static_cast<socklen_t>(
  3172. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  3173. #ifndef SOCK_CLOEXEC
  3174. #ifndef _WIN64
  3175. fcntl(sock, F_SETFD, FD_CLOEXEC);
  3176. #endif
  3177. #endif
  3178. if (socket_options) { socket_options(sock); }
  3179. #ifdef _WIN64
  3180. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  3181. // remove the option.
  3182. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  3183. #endif
  3184. bool dummy;
  3185. if (!bind_or_connect(sock, hints, dummy)) {
  3186. close_socket(sock);
  3187. sock = INVALID_SOCKET;
  3188. }
  3189. }
  3190. return sock;
  3191. }
  3192. #endif
  3193. auto service = std::to_string(port);
  3194. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  3195. timeout_sec)) {
  3196. #if defined __linux__ && !defined __ANDROID__
  3197. res_init();
  3198. #endif
  3199. return INVALID_SOCKET;
  3200. }
  3201. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  3202. for (auto rp = result; rp; rp = rp->ai_next) {
  3203. // Create a socket
  3204. #ifdef _WIN64
  3205. auto sock =
  3206. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  3207. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  3208. /**
  3209. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  3210. * and above the socket creation fails on older Windows Systems.
  3211. *
  3212. * Let's try to create a socket the old way in this case.
  3213. *
  3214. * Reference:
  3215. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  3216. *
  3217. * WSA_FLAG_NO_HANDLE_INHERIT:
  3218. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  3219. * SP1, and later
  3220. *
  3221. */
  3222. if (sock == INVALID_SOCKET) {
  3223. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  3224. }
  3225. #else
  3226. #ifdef SOCK_CLOEXEC
  3227. auto sock =
  3228. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  3229. #else
  3230. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  3231. #endif
  3232. #endif
  3233. if (sock == INVALID_SOCKET) { continue; }
  3234. #if !defined _WIN64 && !defined SOCK_CLOEXEC
  3235. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  3236. close_socket(sock);
  3237. continue;
  3238. }
  3239. #endif
  3240. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  3241. if (rp->ai_family == AF_INET6) {
  3242. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  3243. }
  3244. if (socket_options) { socket_options(sock); }
  3245. // bind or connect
  3246. auto quit = false;
  3247. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  3248. close_socket(sock);
  3249. if (quit) { break; }
  3250. }
  3251. return INVALID_SOCKET;
  3252. }
  3253. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  3254. #ifdef _WIN64
  3255. auto flags = nonblocking ? 1UL : 0UL;
  3256. ioctlsocket(sock, FIONBIO, &flags);
  3257. #else
  3258. auto flags = fcntl(sock, F_GETFL, 0);
  3259. fcntl(sock, F_SETFL,
  3260. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  3261. #endif
  3262. }
  3263. inline bool is_connection_error() {
  3264. #ifdef _WIN64
  3265. return WSAGetLastError() != WSAEWOULDBLOCK;
  3266. #else
  3267. return errno != EINPROGRESS;
  3268. #endif
  3269. }
  3270. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  3271. struct addrinfo hints;
  3272. struct addrinfo *result;
  3273. memset(&hints, 0, sizeof(struct addrinfo));
  3274. hints.ai_family = AF_UNSPEC;
  3275. hints.ai_socktype = SOCK_STREAM;
  3276. hints.ai_protocol = 0;
  3277. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  3278. return false;
  3279. }
  3280. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  3281. auto ret = false;
  3282. for (auto rp = result; rp; rp = rp->ai_next) {
  3283. const auto &ai = *rp;
  3284. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  3285. ret = true;
  3286. break;
  3287. }
  3288. }
  3289. return ret;
  3290. }
  3291. #if !defined _WIN64 && !defined ANDROID && !defined _AIX && !defined __MVS__
  3292. #define USE_IF2IP
  3293. #endif
  3294. #ifdef USE_IF2IP
  3295. inline std::string if2ip(int address_family, const std::string &ifn) {
  3296. struct ifaddrs *ifap;
  3297. getifaddrs(&ifap);
  3298. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  3299. std::string addr_candidate;
  3300. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  3301. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  3302. (AF_UNSPEC == address_family ||
  3303. ifa->ifa_addr->sa_family == address_family)) {
  3304. if (ifa->ifa_addr->sa_family == AF_INET) {
  3305. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  3306. char buf[INET_ADDRSTRLEN];
  3307. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  3308. return std::string(buf, INET_ADDRSTRLEN);
  3309. }
  3310. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  3311. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  3312. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  3313. char buf[INET6_ADDRSTRLEN] = {};
  3314. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  3315. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  3316. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  3317. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  3318. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  3319. } else {
  3320. return std::string(buf, INET6_ADDRSTRLEN);
  3321. }
  3322. }
  3323. }
  3324. }
  3325. }
  3326. }
  3327. return addr_candidate;
  3328. }
  3329. #endif
  3330. inline socket_t create_client_socket(
  3331. const std::string &host, const std::string &ip, int port,
  3332. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  3333. SocketOptions socket_options, time_t connection_timeout_sec,
  3334. time_t connection_timeout_usec, time_t read_timeout_sec,
  3335. time_t read_timeout_usec, time_t write_timeout_sec,
  3336. time_t write_timeout_usec, const std::string &intf, Error &error) {
  3337. auto sock = create_socket(
  3338. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  3339. std::move(socket_options),
  3340. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  3341. if (!intf.empty()) {
  3342. #ifdef USE_IF2IP
  3343. auto ip_from_if = if2ip(address_family, intf);
  3344. if (ip_from_if.empty()) { ip_from_if = intf; }
  3345. if (!bind_ip_address(sock2, ip_from_if)) {
  3346. error = Error::BindIPAddress;
  3347. return false;
  3348. }
  3349. #endif
  3350. }
  3351. set_nonblocking(sock2, true);
  3352. auto ret =
  3353. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  3354. if (ret < 0) {
  3355. if (is_connection_error()) {
  3356. error = Error::Connection;
  3357. return false;
  3358. }
  3359. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  3360. connection_timeout_usec);
  3361. if (error != Error::Success) {
  3362. if (error == Error::ConnectionTimeout) { quit = true; }
  3363. return false;
  3364. }
  3365. }
  3366. set_nonblocking(sock2, false);
  3367. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  3368. read_timeout_usec);
  3369. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  3370. write_timeout_usec);
  3371. error = Error::Success;
  3372. return true;
  3373. },
  3374. connection_timeout_sec); // Pass DNS timeout
  3375. if (sock != INVALID_SOCKET) {
  3376. error = Error::Success;
  3377. } else {
  3378. if (error == Error::Success) { error = Error::Connection; }
  3379. }
  3380. return sock;
  3381. }
  3382. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  3383. socklen_t addr_len, std::string &ip, int &port) {
  3384. if (addr.ss_family == AF_INET) {
  3385. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  3386. } else if (addr.ss_family == AF_INET6) {
  3387. port =
  3388. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  3389. } else {
  3390. return false;
  3391. }
  3392. std::array<char, NI_MAXHOST> ipstr{};
  3393. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  3394. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  3395. 0, NI_NUMERICHOST)) {
  3396. return false;
  3397. }
  3398. ip = ipstr.data();
  3399. return true;
  3400. }
  3401. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3402. struct sockaddr_storage addr;
  3403. socklen_t addr_len = sizeof(addr);
  3404. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3405. &addr_len)) {
  3406. get_ip_and_port(addr, addr_len, ip, port);
  3407. }
  3408. }
  3409. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3410. struct sockaddr_storage addr;
  3411. socklen_t addr_len = sizeof(addr);
  3412. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3413. &addr_len)) {
  3414. #ifndef _WIN64
  3415. if (addr.ss_family == AF_UNIX) {
  3416. #if defined(__linux__)
  3417. struct ucred ucred;
  3418. socklen_t len = sizeof(ucred);
  3419. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  3420. port = ucred.pid;
  3421. }
  3422. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  3423. pid_t pid;
  3424. socklen_t len = sizeof(pid);
  3425. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  3426. port = pid;
  3427. }
  3428. #endif
  3429. return;
  3430. }
  3431. #endif
  3432. get_ip_and_port(addr, addr_len, ip, port);
  3433. }
  3434. }
  3435. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  3436. unsigned int h) {
  3437. return (l == 0)
  3438. ? h
  3439. : str2tag_core(
  3440. s + 1, l - 1,
  3441. // Unsets the 6 high bits of h, therefore no overflow happens
  3442. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  3443. h * 33) ^
  3444. static_cast<unsigned char>(*s));
  3445. }
  3446. inline unsigned int str2tag(const std::string &s) {
  3447. return str2tag_core(s.data(), s.size(), 0);
  3448. }
  3449. namespace udl {
  3450. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  3451. return str2tag_core(s, l, 0);
  3452. }
  3453. } // namespace udl
  3454. inline std::string
  3455. find_content_type(const std::string &path,
  3456. const std::map<std::string, std::string> &user_data,
  3457. const std::string &default_content_type) {
  3458. auto ext = file_extension(path);
  3459. auto it = user_data.find(ext);
  3460. if (it != user_data.end()) { return it->second; }
  3461. using udl::operator""_t;
  3462. switch (str2tag(ext)) {
  3463. default: return default_content_type;
  3464. case "css"_t: return "text/css";
  3465. case "csv"_t: return "text/csv";
  3466. case "htm"_t:
  3467. case "html"_t: return "text/html";
  3468. case "js"_t:
  3469. case "mjs"_t: return "text/javascript";
  3470. case "txt"_t: return "text/plain";
  3471. case "vtt"_t: return "text/vtt";
  3472. case "apng"_t: return "image/apng";
  3473. case "avif"_t: return "image/avif";
  3474. case "bmp"_t: return "image/bmp";
  3475. case "gif"_t: return "image/gif";
  3476. case "png"_t: return "image/png";
  3477. case "svg"_t: return "image/svg+xml";
  3478. case "webp"_t: return "image/webp";
  3479. case "ico"_t: return "image/x-icon";
  3480. case "tif"_t: return "image/tiff";
  3481. case "tiff"_t: return "image/tiff";
  3482. case "jpg"_t:
  3483. case "jpeg"_t: return "image/jpeg";
  3484. case "mp4"_t: return "video/mp4";
  3485. case "mpeg"_t: return "video/mpeg";
  3486. case "webm"_t: return "video/webm";
  3487. case "mp3"_t: return "audio/mp3";
  3488. case "mpga"_t: return "audio/mpeg";
  3489. case "weba"_t: return "audio/webm";
  3490. case "wav"_t: return "audio/wave";
  3491. case "otf"_t: return "font/otf";
  3492. case "ttf"_t: return "font/ttf";
  3493. case "woff"_t: return "font/woff";
  3494. case "woff2"_t: return "font/woff2";
  3495. case "7z"_t: return "application/x-7z-compressed";
  3496. case "atom"_t: return "application/atom+xml";
  3497. case "pdf"_t: return "application/pdf";
  3498. case "json"_t: return "application/json";
  3499. case "rss"_t: return "application/rss+xml";
  3500. case "tar"_t: return "application/x-tar";
  3501. case "xht"_t:
  3502. case "xhtml"_t: return "application/xhtml+xml";
  3503. case "xslt"_t: return "application/xslt+xml";
  3504. case "xml"_t: return "application/xml";
  3505. case "gz"_t: return "application/gzip";
  3506. case "zip"_t: return "application/zip";
  3507. case "wasm"_t: return "application/wasm";
  3508. }
  3509. }
  3510. inline bool can_compress_content_type(const std::string &content_type) {
  3511. using udl::operator""_t;
  3512. auto tag = str2tag(content_type);
  3513. switch (tag) {
  3514. case "image/svg+xml"_t:
  3515. case "application/javascript"_t:
  3516. case "application/json"_t:
  3517. case "application/xml"_t:
  3518. case "application/protobuf"_t:
  3519. case "application/xhtml+xml"_t: return true;
  3520. case "text/event-stream"_t: return false;
  3521. default: return !content_type.rfind("text/", 0);
  3522. }
  3523. }
  3524. inline EncodingType encoding_type(const Request &req, const Response &res) {
  3525. auto ret =
  3526. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  3527. if (!ret) { return EncodingType::None; }
  3528. const auto &s = req.get_header_value("Accept-Encoding");
  3529. (void)(s);
  3530. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3531. // TODO: 'Accept-Encoding' has br, not br;q=0
  3532. ret = s.find("br") != std::string::npos;
  3533. if (ret) { return EncodingType::Brotli; }
  3534. #endif
  3535. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3536. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  3537. ret = s.find("gzip") != std::string::npos;
  3538. if (ret) { return EncodingType::Gzip; }
  3539. #endif
  3540. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3541. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  3542. ret = s.find("zstd") != std::string::npos;
  3543. if (ret) { return EncodingType::Zstd; }
  3544. #endif
  3545. return EncodingType::None;
  3546. }
  3547. inline bool nocompressor::compress(const char *data, size_t data_length,
  3548. bool /*last*/, Callback callback) {
  3549. if (!data_length) { return true; }
  3550. return callback(data, data_length);
  3551. }
  3552. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3553. inline gzip_compressor::gzip_compressor() {
  3554. std::memset(&strm_, 0, sizeof(strm_));
  3555. strm_.zalloc = Z_NULL;
  3556. strm_.zfree = Z_NULL;
  3557. strm_.opaque = Z_NULL;
  3558. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  3559. Z_DEFAULT_STRATEGY) == Z_OK;
  3560. }
  3561. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  3562. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  3563. bool last, Callback callback) {
  3564. assert(is_valid_);
  3565. do {
  3566. constexpr size_t max_avail_in =
  3567. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3568. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3569. (std::min)(data_length, max_avail_in));
  3570. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3571. data_length -= strm_.avail_in;
  3572. data += strm_.avail_in;
  3573. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  3574. auto ret = Z_OK;
  3575. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3576. do {
  3577. strm_.avail_out = static_cast<uInt>(buff.size());
  3578. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3579. ret = deflate(&strm_, flush);
  3580. if (ret == Z_STREAM_ERROR) { return false; }
  3581. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3582. return false;
  3583. }
  3584. } while (strm_.avail_out == 0);
  3585. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  3586. (flush == Z_NO_FLUSH && ret == Z_OK));
  3587. assert(strm_.avail_in == 0);
  3588. } while (data_length > 0);
  3589. return true;
  3590. }
  3591. inline gzip_decompressor::gzip_decompressor() {
  3592. std::memset(&strm_, 0, sizeof(strm_));
  3593. strm_.zalloc = Z_NULL;
  3594. strm_.zfree = Z_NULL;
  3595. strm_.opaque = Z_NULL;
  3596. // 15 is the value of wbits, which should be at the maximum possible value
  3597. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  3598. // that the stream type should be automatically detected either gzip or
  3599. // deflate.
  3600. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  3601. }
  3602. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  3603. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  3604. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  3605. Callback callback) {
  3606. assert(is_valid_);
  3607. auto ret = Z_OK;
  3608. do {
  3609. constexpr size_t max_avail_in =
  3610. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3611. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3612. (std::min)(data_length, max_avail_in));
  3613. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3614. data_length -= strm_.avail_in;
  3615. data += strm_.avail_in;
  3616. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3617. while (strm_.avail_in > 0 && ret == Z_OK) {
  3618. strm_.avail_out = static_cast<uInt>(buff.size());
  3619. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3620. ret = inflate(&strm_, Z_NO_FLUSH);
  3621. assert(ret != Z_STREAM_ERROR);
  3622. switch (ret) {
  3623. case Z_NEED_DICT:
  3624. case Z_DATA_ERROR:
  3625. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  3626. }
  3627. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3628. return false;
  3629. }
  3630. }
  3631. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  3632. } while (data_length > 0);
  3633. return true;
  3634. }
  3635. #endif
  3636. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3637. inline brotli_compressor::brotli_compressor() {
  3638. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  3639. }
  3640. inline brotli_compressor::~brotli_compressor() {
  3641. BrotliEncoderDestroyInstance(state_);
  3642. }
  3643. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  3644. bool last, Callback callback) {
  3645. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3646. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  3647. auto available_in = data_length;
  3648. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3649. for (;;) {
  3650. if (last) {
  3651. if (BrotliEncoderIsFinished(state_)) { break; }
  3652. } else {
  3653. if (!available_in) { break; }
  3654. }
  3655. auto available_out = buff.size();
  3656. auto next_out = buff.data();
  3657. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  3658. &available_out, &next_out, nullptr)) {
  3659. return false;
  3660. }
  3661. auto output_bytes = buff.size() - available_out;
  3662. if (output_bytes) {
  3663. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  3664. }
  3665. }
  3666. return true;
  3667. }
  3668. inline brotli_decompressor::brotli_decompressor() {
  3669. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  3670. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  3671. : BROTLI_DECODER_RESULT_ERROR;
  3672. }
  3673. inline brotli_decompressor::~brotli_decompressor() {
  3674. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  3675. }
  3676. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  3677. inline bool brotli_decompressor::decompress(const char *data,
  3678. size_t data_length,
  3679. Callback callback) {
  3680. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3681. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  3682. return 0;
  3683. }
  3684. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3685. size_t avail_in = data_length;
  3686. size_t total_out;
  3687. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  3688. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3689. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  3690. char *next_out = buff.data();
  3691. size_t avail_out = buff.size();
  3692. decoder_r = BrotliDecoderDecompressStream(
  3693. decoder_s, &avail_in, &next_in, &avail_out,
  3694. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  3695. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  3696. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  3697. }
  3698. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3699. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  3700. }
  3701. #endif
  3702. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3703. inline zstd_compressor::zstd_compressor() {
  3704. ctx_ = ZSTD_createCCtx();
  3705. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  3706. }
  3707. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  3708. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  3709. bool last, Callback callback) {
  3710. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3711. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  3712. ZSTD_inBuffer input = {data, data_length, 0};
  3713. bool finished;
  3714. do {
  3715. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3716. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  3717. if (ZSTD_isError(remaining)) { return false; }
  3718. if (!callback(buff.data(), output.pos)) { return false; }
  3719. finished = last ? (remaining == 0) : (input.pos == input.size);
  3720. } while (!finished);
  3721. return true;
  3722. }
  3723. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  3724. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  3725. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  3726. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  3727. Callback callback) {
  3728. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3729. ZSTD_inBuffer input = {data, data_length, 0};
  3730. while (input.pos < input.size) {
  3731. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3732. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  3733. if (ZSTD_isError(remaining)) { return false; }
  3734. if (!callback(buff.data(), output.pos)) { return false; }
  3735. }
  3736. return true;
  3737. }
  3738. #endif
  3739. inline bool has_header(const Headers &headers, const std::string &key) {
  3740. return headers.find(key) != headers.end();
  3741. }
  3742. inline const char *get_header_value(const Headers &headers,
  3743. const std::string &key, const char *def,
  3744. size_t id) {
  3745. auto rng = headers.equal_range(key);
  3746. auto it = rng.first;
  3747. std::advance(it, static_cast<ssize_t>(id));
  3748. if (it != rng.second) { return it->second.c_str(); }
  3749. return def;
  3750. }
  3751. template <typename T>
  3752. inline bool parse_header(const char *beg, const char *end, T fn) {
  3753. // Skip trailing spaces and tabs.
  3754. while (beg < end && is_space_or_tab(end[-1])) {
  3755. end--;
  3756. }
  3757. auto p = beg;
  3758. while (p < end && *p != ':') {
  3759. p++;
  3760. }
  3761. auto name = std::string(beg, p);
  3762. if (!detail::fields::is_field_name(name)) { return false; }
  3763. if (p == end) { return false; }
  3764. auto key_end = p;
  3765. if (*p++ != ':') { return false; }
  3766. while (p < end && is_space_or_tab(*p)) {
  3767. p++;
  3768. }
  3769. if (p <= end) {
  3770. auto key_len = key_end - beg;
  3771. if (!key_len) { return false; }
  3772. auto key = std::string(beg, key_end);
  3773. auto val = std::string(p, end);
  3774. if (!detail::fields::is_field_value(val)) { return false; }
  3775. if (case_ignore::equal(key, "Location") ||
  3776. case_ignore::equal(key, "Referer")) {
  3777. fn(key, val);
  3778. } else {
  3779. fn(key, decode_path(val, false));
  3780. }
  3781. return true;
  3782. }
  3783. return false;
  3784. }
  3785. inline bool read_headers(Stream &strm, Headers &headers) {
  3786. const auto bufsiz = 2048;
  3787. char buf[bufsiz];
  3788. stream_line_reader line_reader(strm, buf, bufsiz);
  3789. size_t header_count = 0;
  3790. for (;;) {
  3791. if (!line_reader.getline()) { return false; }
  3792. // Check if the line ends with CRLF.
  3793. auto line_terminator_len = 2;
  3794. if (line_reader.end_with_crlf()) {
  3795. // Blank line indicates end of headers.
  3796. if (line_reader.size() == 2) { break; }
  3797. } else {
  3798. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3799. // Blank line indicates end of headers.
  3800. if (line_reader.size() == 1) { break; }
  3801. line_terminator_len = 1;
  3802. #else
  3803. continue; // Skip invalid line.
  3804. #endif
  3805. }
  3806. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3807. // Check header count limit
  3808. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3809. // Exclude line terminator
  3810. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3811. if (!parse_header(line_reader.ptr(), end,
  3812. [&](const std::string &key, const std::string &val) {
  3813. headers.emplace(key, val);
  3814. })) {
  3815. return false;
  3816. }
  3817. header_count++;
  3818. }
  3819. return true;
  3820. }
  3821. inline bool read_content_with_length(Stream &strm, size_t len,
  3822. DownloadProgress progress,
  3823. ContentReceiverWithProgress out) {
  3824. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3825. size_t r = 0;
  3826. while (r < len) {
  3827. auto read_len = static_cast<size_t>(len - r);
  3828. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3829. if (n <= 0) { return false; }
  3830. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  3831. r += static_cast<size_t>(n);
  3832. if (progress) {
  3833. if (!progress(r, len)) { return false; }
  3834. }
  3835. }
  3836. return true;
  3837. }
  3838. inline void skip_content_with_length(Stream &strm, size_t len) {
  3839. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3840. size_t r = 0;
  3841. while (r < len) {
  3842. auto read_len = static_cast<size_t>(len - r);
  3843. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3844. if (n <= 0) { return; }
  3845. r += static_cast<size_t>(n);
  3846. }
  3847. }
  3848. enum class ReadContentResult {
  3849. Success, // Successfully read the content
  3850. PayloadTooLarge, // The content exceeds the specified payload limit
  3851. Error // An error occurred while reading the content
  3852. };
  3853. inline ReadContentResult
  3854. read_content_without_length(Stream &strm, size_t payload_max_length,
  3855. ContentReceiverWithProgress out) {
  3856. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3857. size_t r = 0;
  3858. for (;;) {
  3859. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  3860. if (n == 0) { return ReadContentResult::Success; }
  3861. if (n < 0) { return ReadContentResult::Error; }
  3862. // Check if adding this data would exceed the payload limit
  3863. if (r > payload_max_length ||
  3864. payload_max_length - r < static_cast<size_t>(n)) {
  3865. return ReadContentResult::PayloadTooLarge;
  3866. }
  3867. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  3868. return ReadContentResult::Error;
  3869. }
  3870. r += static_cast<size_t>(n);
  3871. }
  3872. return ReadContentResult::Success;
  3873. }
  3874. template <typename T>
  3875. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  3876. size_t payload_max_length,
  3877. ContentReceiverWithProgress out) {
  3878. const auto bufsiz = 16;
  3879. char buf[bufsiz];
  3880. stream_line_reader line_reader(strm, buf, bufsiz);
  3881. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3882. unsigned long chunk_len;
  3883. size_t total_len = 0;
  3884. while (true) {
  3885. char *end_ptr;
  3886. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  3887. if (end_ptr == line_reader.ptr()) { return ReadContentResult::Error; }
  3888. if (chunk_len == ULONG_MAX) { return ReadContentResult::Error; }
  3889. if (chunk_len == 0) { break; }
  3890. // Check if adding this chunk would exceed the payload limit
  3891. if (total_len > payload_max_length ||
  3892. payload_max_length - total_len < chunk_len) {
  3893. return ReadContentResult::PayloadTooLarge;
  3894. }
  3895. total_len += chunk_len;
  3896. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  3897. return ReadContentResult::Error;
  3898. }
  3899. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3900. if (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3901. return ReadContentResult::Error;
  3902. }
  3903. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3904. }
  3905. assert(chunk_len == 0);
  3906. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3907. // transfer coding is complete when a chunk with a chunk-size of zero is
  3908. // received, possibly followed by a trailer section, and finally terminated by
  3909. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3910. //
  3911. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3912. // does't care for the existence of the final CRLF. In other words, it seems
  3913. // to be ok whether the final CRLF exists or not in the chunked data.
  3914. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3915. //
  3916. // According to the reference code in RFC 9112, cpp-httplib now allows
  3917. // chunked transfer coding data without the final CRLF.
  3918. if (!line_reader.getline()) { return ReadContentResult::Success; }
  3919. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3920. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3921. // Message framing
  3922. "transfer-encoding", "content-length",
  3923. // Routing
  3924. "host",
  3925. // Authentication
  3926. "authorization", "www-authenticate", "proxy-authenticate",
  3927. "proxy-authorization", "cookie", "set-cookie",
  3928. // Request modifiers
  3929. "cache-control", "expect", "max-forwards", "pragma", "range", "te",
  3930. // Response control
  3931. "age", "expires", "date", "location", "retry-after", "vary", "warning",
  3932. // Payload processing
  3933. "content-encoding", "content-type", "content-range", "trailer"};
  3934. // Parse declared trailer headers once for performance
  3935. case_ignore::unordered_set<std::string> declared_trailers;
  3936. if (has_header(x.headers, "Trailer")) {
  3937. auto trailer_header = get_header_value(x.headers, "Trailer", "", 0);
  3938. auto len = std::strlen(trailer_header);
  3939. split(trailer_header, trailer_header + len, ',',
  3940. [&](const char *b, const char *e) {
  3941. std::string key(b, e);
  3942. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3943. declared_trailers.insert(key);
  3944. }
  3945. });
  3946. }
  3947. size_t trailer_header_count = 0;
  3948. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3949. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) {
  3950. return ReadContentResult::Error;
  3951. }
  3952. // Check trailer header count limit
  3953. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  3954. return ReadContentResult::Error;
  3955. }
  3956. // Exclude line terminator
  3957. constexpr auto line_terminator_len = 2;
  3958. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3959. parse_header(line_reader.ptr(), end,
  3960. [&](const std::string &key, const std::string &val) {
  3961. if (declared_trailers.find(key) != declared_trailers.end()) {
  3962. x.trailers.emplace(key, val);
  3963. trailer_header_count++;
  3964. }
  3965. });
  3966. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3967. }
  3968. return ReadContentResult::Success;
  3969. }
  3970. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  3971. return case_ignore::equal(
  3972. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  3973. }
  3974. template <typename T, typename U>
  3975. bool prepare_content_receiver(T &x, int &status,
  3976. ContentReceiverWithProgress receiver,
  3977. bool decompress, U callback) {
  3978. if (decompress) {
  3979. std::string encoding = x.get_header_value("Content-Encoding");
  3980. std::unique_ptr<decompressor> decompressor;
  3981. if (encoding == "gzip" || encoding == "deflate") {
  3982. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3983. decompressor = detail::make_unique<gzip_decompressor>();
  3984. #else
  3985. status = StatusCode::UnsupportedMediaType_415;
  3986. return false;
  3987. #endif
  3988. } else if (encoding.find("br") != std::string::npos) {
  3989. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3990. decompressor = detail::make_unique<brotli_decompressor>();
  3991. #else
  3992. status = StatusCode::UnsupportedMediaType_415;
  3993. return false;
  3994. #endif
  3995. } else if (encoding == "zstd") {
  3996. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3997. decompressor = detail::make_unique<zstd_decompressor>();
  3998. #else
  3999. status = StatusCode::UnsupportedMediaType_415;
  4000. return false;
  4001. #endif
  4002. }
  4003. if (decompressor) {
  4004. if (decompressor->is_valid()) {
  4005. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  4006. size_t off, size_t len) {
  4007. return decompressor->decompress(buf, n,
  4008. [&](const char *buf2, size_t n2) {
  4009. return receiver(buf2, n2, off, len);
  4010. });
  4011. };
  4012. return callback(std::move(out));
  4013. } else {
  4014. status = StatusCode::InternalServerError_500;
  4015. return false;
  4016. }
  4017. }
  4018. }
  4019. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  4020. size_t len) {
  4021. return receiver(buf, n, off, len);
  4022. };
  4023. return callback(std::move(out));
  4024. }
  4025. template <typename T>
  4026. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  4027. DownloadProgress progress,
  4028. ContentReceiverWithProgress receiver, bool decompress) {
  4029. return prepare_content_receiver(
  4030. x, status, std::move(receiver), decompress,
  4031. [&](const ContentReceiverWithProgress &out) {
  4032. auto ret = true;
  4033. auto exceed_payload_max_length = false;
  4034. if (is_chunked_transfer_encoding(x.headers)) {
  4035. auto result = read_content_chunked(strm, x, payload_max_length, out);
  4036. if (result == ReadContentResult::Success) {
  4037. ret = true;
  4038. } else if (result == ReadContentResult::PayloadTooLarge) {
  4039. exceed_payload_max_length = true;
  4040. ret = false;
  4041. } else {
  4042. ret = false;
  4043. }
  4044. } else if (!has_header(x.headers, "Content-Length")) {
  4045. auto result =
  4046. read_content_without_length(strm, payload_max_length, out);
  4047. if (result == ReadContentResult::Success) {
  4048. ret = true;
  4049. } else if (result == ReadContentResult::PayloadTooLarge) {
  4050. exceed_payload_max_length = true;
  4051. ret = false;
  4052. } else {
  4053. ret = false;
  4054. }
  4055. } else {
  4056. auto is_invalid_value = false;
  4057. auto len = get_header_value_u64(x.headers, "Content-Length",
  4058. (std::numeric_limits<size_t>::max)(),
  4059. 0, is_invalid_value);
  4060. if (is_invalid_value) {
  4061. ret = false;
  4062. } else if (len > payload_max_length) {
  4063. exceed_payload_max_length = true;
  4064. skip_content_with_length(strm, len);
  4065. ret = false;
  4066. } else if (len > 0) {
  4067. ret = read_content_with_length(strm, len, std::move(progress), out);
  4068. }
  4069. }
  4070. if (!ret) {
  4071. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  4072. : StatusCode::BadRequest_400;
  4073. }
  4074. return ret;
  4075. });
  4076. }
  4077. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  4078. const std::string &path) {
  4079. std::string s = method;
  4080. s += " ";
  4081. s += path;
  4082. s += " HTTP/1.1\r\n";
  4083. return strm.write(s.data(), s.size());
  4084. }
  4085. inline ssize_t write_response_line(Stream &strm, int status) {
  4086. std::string s = "HTTP/1.1 ";
  4087. s += std::to_string(status);
  4088. s += " ";
  4089. s += httplib::status_message(status);
  4090. s += "\r\n";
  4091. return strm.write(s.data(), s.size());
  4092. }
  4093. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  4094. ssize_t write_len = 0;
  4095. for (const auto &x : headers) {
  4096. std::string s;
  4097. s = x.first;
  4098. s += ": ";
  4099. s += x.second;
  4100. s += "\r\n";
  4101. auto len = strm.write(s.data(), s.size());
  4102. if (len < 0) { return len; }
  4103. write_len += len;
  4104. }
  4105. auto len = strm.write("\r\n");
  4106. if (len < 0) { return len; }
  4107. write_len += len;
  4108. return write_len;
  4109. }
  4110. inline bool write_data(Stream &strm, const char *d, size_t l) {
  4111. size_t offset = 0;
  4112. while (offset < l) {
  4113. auto length = strm.write(d + offset, l - offset);
  4114. if (length < 0) { return false; }
  4115. offset += static_cast<size_t>(length);
  4116. }
  4117. return true;
  4118. }
  4119. template <typename T>
  4120. inline bool write_content_with_progress(Stream &strm,
  4121. const ContentProvider &content_provider,
  4122. size_t offset, size_t length,
  4123. T is_shutting_down,
  4124. const UploadProgress &upload_progress,
  4125. Error &error) {
  4126. size_t end_offset = offset + length;
  4127. size_t start_offset = offset;
  4128. auto ok = true;
  4129. DataSink data_sink;
  4130. data_sink.write = [&](const char *d, size_t l) -> bool {
  4131. if (ok) {
  4132. if (write_data(strm, d, l)) {
  4133. offset += l;
  4134. if (upload_progress && length > 0) {
  4135. size_t current_written = offset - start_offset;
  4136. if (!upload_progress(current_written, length)) {
  4137. ok = false;
  4138. return false;
  4139. }
  4140. }
  4141. } else {
  4142. ok = false;
  4143. }
  4144. }
  4145. return ok;
  4146. };
  4147. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4148. while (offset < end_offset && !is_shutting_down()) {
  4149. if (!strm.wait_writable()) {
  4150. error = Error::Write;
  4151. return false;
  4152. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  4153. error = Error::Canceled;
  4154. return false;
  4155. } else if (!ok) {
  4156. error = Error::Write;
  4157. return false;
  4158. }
  4159. }
  4160. error = Error::Success;
  4161. return true;
  4162. }
  4163. template <typename T>
  4164. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4165. size_t offset, size_t length, T is_shutting_down,
  4166. Error &error) {
  4167. return write_content_with_progress<T>(strm, content_provider, offset, length,
  4168. is_shutting_down, nullptr, error);
  4169. }
  4170. template <typename T>
  4171. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4172. size_t offset, size_t length,
  4173. const T &is_shutting_down) {
  4174. auto error = Error::Success;
  4175. return write_content(strm, content_provider, offset, length, is_shutting_down,
  4176. error);
  4177. }
  4178. template <typename T>
  4179. inline bool
  4180. write_content_without_length(Stream &strm,
  4181. const ContentProvider &content_provider,
  4182. const T &is_shutting_down) {
  4183. size_t offset = 0;
  4184. auto data_available = true;
  4185. auto ok = true;
  4186. DataSink data_sink;
  4187. data_sink.write = [&](const char *d, size_t l) -> bool {
  4188. if (ok) {
  4189. offset += l;
  4190. if (!write_data(strm, d, l)) { ok = false; }
  4191. }
  4192. return ok;
  4193. };
  4194. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4195. data_sink.done = [&](void) { data_available = false; };
  4196. while (data_available && !is_shutting_down()) {
  4197. if (!strm.wait_writable()) {
  4198. return false;
  4199. } else if (!content_provider(offset, 0, data_sink)) {
  4200. return false;
  4201. } else if (!ok) {
  4202. return false;
  4203. }
  4204. }
  4205. return true;
  4206. }
  4207. template <typename T, typename U>
  4208. inline bool
  4209. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  4210. const T &is_shutting_down, U &compressor, Error &error) {
  4211. size_t offset = 0;
  4212. auto data_available = true;
  4213. auto ok = true;
  4214. DataSink data_sink;
  4215. data_sink.write = [&](const char *d, size_t l) -> bool {
  4216. if (ok) {
  4217. data_available = l > 0;
  4218. offset += l;
  4219. std::string payload;
  4220. if (compressor.compress(d, l, false,
  4221. [&](const char *data, size_t data_len) {
  4222. payload.append(data, data_len);
  4223. return true;
  4224. })) {
  4225. if (!payload.empty()) {
  4226. // Emit chunked response header and footer for each chunk
  4227. auto chunk =
  4228. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  4229. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  4230. }
  4231. } else {
  4232. ok = false;
  4233. }
  4234. }
  4235. return ok;
  4236. };
  4237. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4238. auto done_with_trailer = [&](const Headers *trailer) {
  4239. if (!ok) { return; }
  4240. data_available = false;
  4241. std::string payload;
  4242. if (!compressor.compress(nullptr, 0, true,
  4243. [&](const char *data, size_t data_len) {
  4244. payload.append(data, data_len);
  4245. return true;
  4246. })) {
  4247. ok = false;
  4248. return;
  4249. }
  4250. if (!payload.empty()) {
  4251. // Emit chunked response header and footer for each chunk
  4252. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  4253. if (!write_data(strm, chunk.data(), chunk.size())) {
  4254. ok = false;
  4255. return;
  4256. }
  4257. }
  4258. constexpr const char done_marker[] = "0\r\n";
  4259. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  4260. // Trailer
  4261. if (trailer) {
  4262. for (const auto &kv : *trailer) {
  4263. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  4264. if (!write_data(strm, field_line.data(), field_line.size())) {
  4265. ok = false;
  4266. }
  4267. }
  4268. }
  4269. constexpr const char crlf[] = "\r\n";
  4270. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  4271. };
  4272. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  4273. data_sink.done_with_trailer = [&](const Headers &trailer) {
  4274. done_with_trailer(&trailer);
  4275. };
  4276. while (data_available && !is_shutting_down()) {
  4277. if (!strm.wait_writable()) {
  4278. error = Error::Write;
  4279. return false;
  4280. } else if (!content_provider(offset, 0, data_sink)) {
  4281. error = Error::Canceled;
  4282. return false;
  4283. } else if (!ok) {
  4284. error = Error::Write;
  4285. return false;
  4286. }
  4287. }
  4288. error = Error::Success;
  4289. return true;
  4290. }
  4291. template <typename T, typename U>
  4292. inline bool write_content_chunked(Stream &strm,
  4293. const ContentProvider &content_provider,
  4294. const T &is_shutting_down, U &compressor) {
  4295. auto error = Error::Success;
  4296. return write_content_chunked(strm, content_provider, is_shutting_down,
  4297. compressor, error);
  4298. }
  4299. template <typename T>
  4300. inline bool redirect(T &cli, Request &req, Response &res,
  4301. const std::string &path, const std::string &location,
  4302. Error &error) {
  4303. Request new_req = req;
  4304. new_req.path = path;
  4305. new_req.redirect_count_ -= 1;
  4306. if (res.status == StatusCode::SeeOther_303 &&
  4307. (req.method != "GET" && req.method != "HEAD")) {
  4308. new_req.method = "GET";
  4309. new_req.body.clear();
  4310. new_req.headers.clear();
  4311. }
  4312. Response new_res;
  4313. auto ret = cli.send(new_req, new_res, error);
  4314. if (ret) {
  4315. req = new_req;
  4316. res = new_res;
  4317. if (res.location.empty()) { res.location = location; }
  4318. }
  4319. return ret;
  4320. }
  4321. inline std::string params_to_query_str(const Params &params) {
  4322. std::string query;
  4323. for (auto it = params.begin(); it != params.end(); ++it) {
  4324. if (it != params.begin()) { query += "&"; }
  4325. query += it->first;
  4326. query += "=";
  4327. query += httplib::encode_uri_component(it->second);
  4328. }
  4329. return query;
  4330. }
  4331. inline void parse_query_text(const char *data, std::size_t size,
  4332. Params &params) {
  4333. std::set<std::string> cache;
  4334. split(data, data + size, '&', [&](const char *b, const char *e) {
  4335. std::string kv(b, e);
  4336. if (cache.find(kv) != cache.end()) { return; }
  4337. cache.insert(std::move(kv));
  4338. std::string key;
  4339. std::string val;
  4340. divide(b, static_cast<std::size_t>(e - b), '=',
  4341. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  4342. std::size_t rhs_size) {
  4343. key.assign(lhs_data, lhs_size);
  4344. val.assign(rhs_data, rhs_size);
  4345. });
  4346. if (!key.empty()) {
  4347. params.emplace(decode_path(key, true), decode_path(val, true));
  4348. }
  4349. });
  4350. }
  4351. inline void parse_query_text(const std::string &s, Params &params) {
  4352. parse_query_text(s.data(), s.size(), params);
  4353. }
  4354. inline bool parse_multipart_boundary(const std::string &content_type,
  4355. std::string &boundary) {
  4356. auto boundary_keyword = "boundary=";
  4357. auto pos = content_type.find(boundary_keyword);
  4358. if (pos == std::string::npos) { return false; }
  4359. auto end = content_type.find(';', pos);
  4360. auto beg = pos + strlen(boundary_keyword);
  4361. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  4362. return !boundary.empty();
  4363. }
  4364. inline void parse_disposition_params(const std::string &s, Params &params) {
  4365. std::set<std::string> cache;
  4366. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  4367. std::string kv(b, e);
  4368. if (cache.find(kv) != cache.end()) { return; }
  4369. cache.insert(kv);
  4370. std::string key;
  4371. std::string val;
  4372. split(b, e, '=', [&](const char *b2, const char *e2) {
  4373. if (key.empty()) {
  4374. key.assign(b2, e2);
  4375. } else {
  4376. val.assign(b2, e2);
  4377. }
  4378. });
  4379. if (!key.empty()) {
  4380. params.emplace(trim_double_quotes_copy((key)),
  4381. trim_double_quotes_copy((val)));
  4382. }
  4383. });
  4384. }
  4385. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4386. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  4387. #else
  4388. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  4389. #endif
  4390. auto is_valid = [](const std::string &str) {
  4391. return std::all_of(str.cbegin(), str.cend(),
  4392. [](unsigned char c) { return std::isdigit(c); });
  4393. };
  4394. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  4395. const auto pos = static_cast<size_t>(6);
  4396. const auto len = static_cast<size_t>(s.size() - 6);
  4397. auto all_valid_ranges = true;
  4398. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  4399. if (!all_valid_ranges) { return; }
  4400. const auto it = std::find(b, e, '-');
  4401. if (it == e) {
  4402. all_valid_ranges = false;
  4403. return;
  4404. }
  4405. const auto lhs = std::string(b, it);
  4406. const auto rhs = std::string(it + 1, e);
  4407. if (!is_valid(lhs) || !is_valid(rhs)) {
  4408. all_valid_ranges = false;
  4409. return;
  4410. }
  4411. const auto first =
  4412. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  4413. const auto last =
  4414. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  4415. if ((first == -1 && last == -1) ||
  4416. (first != -1 && last != -1 && first > last)) {
  4417. all_valid_ranges = false;
  4418. return;
  4419. }
  4420. ranges.emplace_back(first, last);
  4421. });
  4422. return all_valid_ranges && !ranges.empty();
  4423. }
  4424. return false;
  4425. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4426. }
  4427. #else
  4428. } catch (...) { return false; }
  4429. #endif
  4430. inline bool parse_accept_header(const std::string &s,
  4431. std::vector<std::string> &content_types) {
  4432. content_types.clear();
  4433. // Empty string is considered valid (no preference)
  4434. if (s.empty()) { return true; }
  4435. // Check for invalid patterns: leading/trailing commas or consecutive commas
  4436. if (s.front() == ',' || s.back() == ',' ||
  4437. s.find(",,") != std::string::npos) {
  4438. return false;
  4439. }
  4440. struct AcceptEntry {
  4441. std::string media_type;
  4442. double quality;
  4443. int order; // Original order in header
  4444. };
  4445. std::vector<AcceptEntry> entries;
  4446. int order = 0;
  4447. bool has_invalid_entry = false;
  4448. // Split by comma and parse each entry
  4449. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  4450. std::string entry(b, e);
  4451. entry = trim_copy(entry);
  4452. if (entry.empty()) {
  4453. has_invalid_entry = true;
  4454. return;
  4455. }
  4456. AcceptEntry accept_entry;
  4457. accept_entry.quality = 1.0; // Default quality
  4458. accept_entry.order = order++;
  4459. // Find q= parameter
  4460. auto q_pos = entry.find(";q=");
  4461. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  4462. if (q_pos != std::string::npos) {
  4463. // Extract media type (before q parameter)
  4464. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  4465. // Extract quality value
  4466. auto q_start = entry.find('=', q_pos) + 1;
  4467. auto q_end = entry.find(';', q_start);
  4468. if (q_end == std::string::npos) { q_end = entry.length(); }
  4469. std::string quality_str =
  4470. trim_copy(entry.substr(q_start, q_end - q_start));
  4471. if (quality_str.empty()) {
  4472. has_invalid_entry = true;
  4473. return;
  4474. }
  4475. try {
  4476. accept_entry.quality = std::stod(quality_str);
  4477. // Check if quality is in valid range [0.0, 1.0]
  4478. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  4479. has_invalid_entry = true;
  4480. return;
  4481. }
  4482. } catch (...) {
  4483. has_invalid_entry = true;
  4484. return;
  4485. }
  4486. } else {
  4487. // No quality parameter, use entire entry as media type
  4488. accept_entry.media_type = entry;
  4489. }
  4490. // Remove additional parameters from media type
  4491. auto param_pos = accept_entry.media_type.find(';');
  4492. if (param_pos != std::string::npos) {
  4493. accept_entry.media_type =
  4494. trim_copy(accept_entry.media_type.substr(0, param_pos));
  4495. }
  4496. // Basic validation of media type format
  4497. if (accept_entry.media_type.empty()) {
  4498. has_invalid_entry = true;
  4499. return;
  4500. }
  4501. // Check for basic media type format (should contain '/' or be '*')
  4502. if (accept_entry.media_type != "*" &&
  4503. accept_entry.media_type.find('/') == std::string::npos) {
  4504. has_invalid_entry = true;
  4505. return;
  4506. }
  4507. entries.push_back(accept_entry);
  4508. });
  4509. // Return false if any invalid entry was found
  4510. if (has_invalid_entry) { return false; }
  4511. // Sort by quality (descending), then by original order (ascending)
  4512. std::sort(entries.begin(), entries.end(),
  4513. [](const AcceptEntry &a, const AcceptEntry &b) {
  4514. if (a.quality != b.quality) {
  4515. return a.quality > b.quality; // Higher quality first
  4516. }
  4517. return a.order < b.order; // Earlier order first for same quality
  4518. });
  4519. // Extract sorted media types
  4520. content_types.reserve(entries.size());
  4521. for (const auto &entry : entries) {
  4522. content_types.push_back(entry.media_type);
  4523. }
  4524. return true;
  4525. }
  4526. class FormDataParser {
  4527. public:
  4528. FormDataParser() = default;
  4529. void set_boundary(std::string &&boundary) {
  4530. boundary_ = boundary;
  4531. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  4532. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  4533. }
  4534. bool is_valid() const { return is_valid_; }
  4535. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  4536. const ContentReceiver &content_callback) {
  4537. buf_append(buf, n);
  4538. while (buf_size() > 0) {
  4539. switch (state_) {
  4540. case 0: { // Initial boundary
  4541. auto pos = buf_find(dash_boundary_crlf_);
  4542. if (pos == buf_size()) { return true; }
  4543. buf_erase(pos + dash_boundary_crlf_.size());
  4544. state_ = 1;
  4545. break;
  4546. }
  4547. case 1: { // New entry
  4548. clear_file_info();
  4549. state_ = 2;
  4550. break;
  4551. }
  4552. case 2: { // Headers
  4553. auto pos = buf_find(crlf_);
  4554. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4555. while (pos < buf_size()) {
  4556. // Empty line
  4557. if (pos == 0) {
  4558. if (!header_callback(file_)) {
  4559. is_valid_ = false;
  4560. return false;
  4561. }
  4562. buf_erase(crlf_.size());
  4563. state_ = 3;
  4564. break;
  4565. }
  4566. const auto header = buf_head(pos);
  4567. if (!parse_header(header.data(), header.data() + header.size(),
  4568. [&](const std::string &, const std::string &) {})) {
  4569. is_valid_ = false;
  4570. return false;
  4571. }
  4572. // Parse and emplace space trimmed headers into a map
  4573. if (!parse_header(
  4574. header.data(), header.data() + header.size(),
  4575. [&](const std::string &key, const std::string &val) {
  4576. file_.headers.emplace(key, val);
  4577. })) {
  4578. is_valid_ = false;
  4579. return false;
  4580. }
  4581. constexpr const char header_content_type[] = "Content-Type:";
  4582. if (start_with_case_ignore(header, header_content_type)) {
  4583. file_.content_type =
  4584. trim_copy(header.substr(str_len(header_content_type)));
  4585. } else {
  4586. thread_local const std::regex re_content_disposition(
  4587. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  4588. std::regex_constants::icase);
  4589. std::smatch m;
  4590. if (std::regex_match(header, m, re_content_disposition)) {
  4591. Params params;
  4592. parse_disposition_params(m[1], params);
  4593. auto it = params.find("name");
  4594. if (it != params.end()) {
  4595. file_.name = it->second;
  4596. } else {
  4597. is_valid_ = false;
  4598. return false;
  4599. }
  4600. it = params.find("filename");
  4601. if (it != params.end()) { file_.filename = it->second; }
  4602. it = params.find("filename*");
  4603. if (it != params.end()) {
  4604. // Only allow UTF-8 encoding...
  4605. thread_local const std::regex re_rfc5987_encoding(
  4606. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  4607. std::smatch m2;
  4608. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  4609. file_.filename = decode_path(m2[1], false); // override...
  4610. } else {
  4611. is_valid_ = false;
  4612. return false;
  4613. }
  4614. }
  4615. }
  4616. }
  4617. buf_erase(pos + crlf_.size());
  4618. pos = buf_find(crlf_);
  4619. }
  4620. if (state_ != 3) { return true; }
  4621. break;
  4622. }
  4623. case 3: { // Body
  4624. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  4625. auto pos = buf_find(crlf_dash_boundary_);
  4626. if (pos < buf_size()) {
  4627. if (!content_callback(buf_data(), pos)) {
  4628. is_valid_ = false;
  4629. return false;
  4630. }
  4631. buf_erase(pos + crlf_dash_boundary_.size());
  4632. state_ = 4;
  4633. } else {
  4634. auto len = buf_size() - crlf_dash_boundary_.size();
  4635. if (len > 0) {
  4636. if (!content_callback(buf_data(), len)) {
  4637. is_valid_ = false;
  4638. return false;
  4639. }
  4640. buf_erase(len);
  4641. }
  4642. return true;
  4643. }
  4644. break;
  4645. }
  4646. case 4: { // Boundary
  4647. if (crlf_.size() > buf_size()) { return true; }
  4648. if (buf_start_with(crlf_)) {
  4649. buf_erase(crlf_.size());
  4650. state_ = 1;
  4651. } else {
  4652. if (dash_.size() > buf_size()) { return true; }
  4653. if (buf_start_with(dash_)) {
  4654. buf_erase(dash_.size());
  4655. is_valid_ = true;
  4656. buf_erase(buf_size()); // Remove epilogue
  4657. } else {
  4658. return true;
  4659. }
  4660. }
  4661. break;
  4662. }
  4663. }
  4664. }
  4665. return true;
  4666. }
  4667. private:
  4668. void clear_file_info() {
  4669. file_.name.clear();
  4670. file_.filename.clear();
  4671. file_.content_type.clear();
  4672. file_.headers.clear();
  4673. }
  4674. bool start_with_case_ignore(const std::string &a, const char *b) const {
  4675. const auto b_len = strlen(b);
  4676. if (a.size() < b_len) { return false; }
  4677. for (size_t i = 0; i < b_len; i++) {
  4678. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  4679. return false;
  4680. }
  4681. }
  4682. return true;
  4683. }
  4684. const std::string dash_ = "--";
  4685. const std::string crlf_ = "\r\n";
  4686. std::string boundary_;
  4687. std::string dash_boundary_crlf_;
  4688. std::string crlf_dash_boundary_;
  4689. size_t state_ = 0;
  4690. bool is_valid_ = false;
  4691. FormData file_;
  4692. // Buffer
  4693. bool start_with(const std::string &a, size_t spos, size_t epos,
  4694. const std::string &b) const {
  4695. if (epos - spos < b.size()) { return false; }
  4696. for (size_t i = 0; i < b.size(); i++) {
  4697. if (a[i + spos] != b[i]) { return false; }
  4698. }
  4699. return true;
  4700. }
  4701. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  4702. const char *buf_data() const { return &buf_[buf_spos_]; }
  4703. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  4704. bool buf_start_with(const std::string &s) const {
  4705. return start_with(buf_, buf_spos_, buf_epos_, s);
  4706. }
  4707. size_t buf_find(const std::string &s) const {
  4708. auto c = s.front();
  4709. size_t off = buf_spos_;
  4710. while (off < buf_epos_) {
  4711. auto pos = off;
  4712. while (true) {
  4713. if (pos == buf_epos_) { return buf_size(); }
  4714. if (buf_[pos] == c) { break; }
  4715. pos++;
  4716. }
  4717. auto remaining_size = buf_epos_ - pos;
  4718. if (s.size() > remaining_size) { return buf_size(); }
  4719. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  4720. off = pos + 1;
  4721. }
  4722. return buf_size();
  4723. }
  4724. void buf_append(const char *data, size_t n) {
  4725. auto remaining_size = buf_size();
  4726. if (remaining_size > 0 && buf_spos_ > 0) {
  4727. for (size_t i = 0; i < remaining_size; i++) {
  4728. buf_[i] = buf_[buf_spos_ + i];
  4729. }
  4730. }
  4731. buf_spos_ = 0;
  4732. buf_epos_ = remaining_size;
  4733. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  4734. for (size_t i = 0; i < n; i++) {
  4735. buf_[buf_epos_ + i] = data[i];
  4736. }
  4737. buf_epos_ += n;
  4738. }
  4739. void buf_erase(size_t size) { buf_spos_ += size; }
  4740. std::string buf_;
  4741. size_t buf_spos_ = 0;
  4742. size_t buf_epos_ = 0;
  4743. };
  4744. inline std::string random_string(size_t length) {
  4745. constexpr const char data[] =
  4746. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  4747. thread_local auto engine([]() {
  4748. // std::random_device might actually be deterministic on some
  4749. // platforms, but due to lack of support in the c++ standard library,
  4750. // doing better requires either some ugly hacks or breaking portability.
  4751. std::random_device seed_gen;
  4752. // Request 128 bits of entropy for initialization
  4753. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  4754. return std::mt19937(seed_sequence);
  4755. }());
  4756. std::string result;
  4757. for (size_t i = 0; i < length; i++) {
  4758. result += data[engine() % (sizeof(data) - 1)];
  4759. }
  4760. return result;
  4761. }
  4762. inline std::string make_multipart_data_boundary() {
  4763. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  4764. }
  4765. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  4766. auto valid = true;
  4767. for (size_t i = 0; i < boundary.size(); i++) {
  4768. auto c = boundary[i];
  4769. if (!std::isalnum(c) && c != '-' && c != '_') {
  4770. valid = false;
  4771. break;
  4772. }
  4773. }
  4774. return valid;
  4775. }
  4776. template <typename T>
  4777. inline std::string
  4778. serialize_multipart_formdata_item_begin(const T &item,
  4779. const std::string &boundary) {
  4780. std::string body = "--" + boundary + "\r\n";
  4781. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4782. if (!item.filename.empty()) {
  4783. body += "; filename=\"" + item.filename + "\"";
  4784. }
  4785. body += "\r\n";
  4786. if (!item.content_type.empty()) {
  4787. body += "Content-Type: " + item.content_type + "\r\n";
  4788. }
  4789. body += "\r\n";
  4790. return body;
  4791. }
  4792. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  4793. inline std::string
  4794. serialize_multipart_formdata_finish(const std::string &boundary) {
  4795. return "--" + boundary + "--\r\n";
  4796. }
  4797. inline std::string
  4798. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  4799. return "multipart/form-data; boundary=" + boundary;
  4800. }
  4801. inline std::string
  4802. serialize_multipart_formdata(const UploadFormDataItems &items,
  4803. const std::string &boundary, bool finish = true) {
  4804. std::string body;
  4805. for (const auto &item : items) {
  4806. body += serialize_multipart_formdata_item_begin(item, boundary);
  4807. body += item.content + serialize_multipart_formdata_item_end();
  4808. }
  4809. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  4810. return body;
  4811. }
  4812. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  4813. if (ranges.size() <= 1) return;
  4814. // Sort ranges by start position
  4815. std::sort(ranges.begin(), ranges.end(),
  4816. [](const Range &a, const Range &b) { return a.first < b.first; });
  4817. Ranges coalesced;
  4818. coalesced.reserve(ranges.size());
  4819. for (auto &r : ranges) {
  4820. auto first_pos = r.first;
  4821. auto last_pos = r.second;
  4822. // Handle special cases like in range_error
  4823. if (first_pos == -1 && last_pos == -1) {
  4824. first_pos = 0;
  4825. last_pos = static_cast<ssize_t>(content_length);
  4826. }
  4827. if (first_pos == -1) {
  4828. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  4829. last_pos = static_cast<ssize_t>(content_length) - 1;
  4830. }
  4831. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  4832. last_pos = static_cast<ssize_t>(content_length) - 1;
  4833. }
  4834. // Skip invalid ranges
  4835. if (!(0 <= first_pos && first_pos <= last_pos &&
  4836. last_pos < static_cast<ssize_t>(content_length))) {
  4837. continue;
  4838. }
  4839. // Coalesce with previous range if overlapping or adjacent (but not
  4840. // identical)
  4841. if (!coalesced.empty()) {
  4842. auto &prev = coalesced.back();
  4843. // Check if current range overlaps or is adjacent to previous range
  4844. // but don't coalesce identical ranges (allow duplicates)
  4845. if (first_pos <= prev.second + 1 &&
  4846. !(first_pos == prev.first && last_pos == prev.second)) {
  4847. // Extend the previous range
  4848. prev.second = (std::max)(prev.second, last_pos);
  4849. continue;
  4850. }
  4851. }
  4852. // Add new range
  4853. coalesced.emplace_back(first_pos, last_pos);
  4854. }
  4855. ranges = std::move(coalesced);
  4856. }
  4857. inline bool range_error(Request &req, Response &res) {
  4858. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  4859. ssize_t content_len = static_cast<ssize_t>(
  4860. res.content_length_ ? res.content_length_ : res.body.size());
  4861. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  4862. size_t overwrapping_count = 0;
  4863. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  4864. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  4865. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  4866. // Too many ranges
  4867. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  4868. for (auto &r : req.ranges) {
  4869. auto &first_pos = r.first;
  4870. auto &last_pos = r.second;
  4871. if (first_pos == -1 && last_pos == -1) {
  4872. first_pos = 0;
  4873. last_pos = content_len;
  4874. }
  4875. if (first_pos == -1) {
  4876. first_pos = content_len - last_pos;
  4877. last_pos = content_len - 1;
  4878. }
  4879. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  4880. // A client can limit the number of bytes requested without knowing the
  4881. // size of the selected representation. If the last-pos value is absent,
  4882. // or if the value is greater than or equal to the current length of the
  4883. // representation data, the byte range is interpreted as the remainder of
  4884. // the representation (i.e., the server replaces the value of last-pos
  4885. // with a value that is one less than the current length of the selected
  4886. // representation).
  4887. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  4888. if (last_pos == -1 || last_pos >= content_len) {
  4889. last_pos = content_len - 1;
  4890. }
  4891. // Range must be within content length
  4892. if (!(0 <= first_pos && first_pos <= last_pos &&
  4893. last_pos <= content_len - 1)) {
  4894. return true;
  4895. }
  4896. // Request must not have more than two overlapping ranges
  4897. for (const auto &processed_range : processed_ranges) {
  4898. if (!(last_pos < processed_range.first ||
  4899. first_pos > processed_range.second)) {
  4900. overwrapping_count++;
  4901. if (overwrapping_count > 2) { return true; }
  4902. break; // Only count once per range
  4903. }
  4904. }
  4905. processed_ranges.emplace_back(first_pos, last_pos);
  4906. }
  4907. // After validation, coalesce overlapping ranges as per RFC 9110
  4908. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  4909. }
  4910. return false;
  4911. }
  4912. inline std::pair<size_t, size_t>
  4913. get_range_offset_and_length(Range r, size_t content_length) {
  4914. assert(r.first != -1 && r.second != -1);
  4915. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  4916. assert(r.first <= r.second &&
  4917. r.second < static_cast<ssize_t>(content_length));
  4918. (void)(content_length);
  4919. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  4920. }
  4921. inline std::string make_content_range_header_field(
  4922. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  4923. auto st = offset_and_length.first;
  4924. auto ed = st + offset_and_length.second - 1;
  4925. std::string field = "bytes ";
  4926. field += std::to_string(st);
  4927. field += "-";
  4928. field += std::to_string(ed);
  4929. field += "/";
  4930. field += std::to_string(content_length);
  4931. return field;
  4932. }
  4933. template <typename SToken, typename CToken, typename Content>
  4934. bool process_multipart_ranges_data(const Request &req,
  4935. const std::string &boundary,
  4936. const std::string &content_type,
  4937. size_t content_length, SToken stoken,
  4938. CToken ctoken, Content content) {
  4939. for (size_t i = 0; i < req.ranges.size(); i++) {
  4940. ctoken("--");
  4941. stoken(boundary);
  4942. ctoken("\r\n");
  4943. if (!content_type.empty()) {
  4944. ctoken("Content-Type: ");
  4945. stoken(content_type);
  4946. ctoken("\r\n");
  4947. }
  4948. auto offset_and_length =
  4949. get_range_offset_and_length(req.ranges[i], content_length);
  4950. ctoken("Content-Range: ");
  4951. stoken(make_content_range_header_field(offset_and_length, content_length));
  4952. ctoken("\r\n");
  4953. ctoken("\r\n");
  4954. if (!content(offset_and_length.first, offset_and_length.second)) {
  4955. return false;
  4956. }
  4957. ctoken("\r\n");
  4958. }
  4959. ctoken("--");
  4960. stoken(boundary);
  4961. ctoken("--");
  4962. return true;
  4963. }
  4964. inline void make_multipart_ranges_data(const Request &req, Response &res,
  4965. const std::string &boundary,
  4966. const std::string &content_type,
  4967. size_t content_length,
  4968. std::string &data) {
  4969. process_multipart_ranges_data(
  4970. req, boundary, content_type, content_length,
  4971. [&](const std::string &token) { data += token; },
  4972. [&](const std::string &token) { data += token; },
  4973. [&](size_t offset, size_t length) {
  4974. assert(offset + length <= content_length);
  4975. data += res.body.substr(offset, length);
  4976. return true;
  4977. });
  4978. }
  4979. inline size_t get_multipart_ranges_data_length(const Request &req,
  4980. const std::string &boundary,
  4981. const std::string &content_type,
  4982. size_t content_length) {
  4983. size_t data_length = 0;
  4984. process_multipart_ranges_data(
  4985. req, boundary, content_type, content_length,
  4986. [&](const std::string &token) { data_length += token.size(); },
  4987. [&](const std::string &token) { data_length += token.size(); },
  4988. [&](size_t /*offset*/, size_t length) {
  4989. data_length += length;
  4990. return true;
  4991. });
  4992. return data_length;
  4993. }
  4994. template <typename T>
  4995. inline bool
  4996. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  4997. const std::string &boundary,
  4998. const std::string &content_type,
  4999. size_t content_length, const T &is_shutting_down) {
  5000. return process_multipart_ranges_data(
  5001. req, boundary, content_type, content_length,
  5002. [&](const std::string &token) { strm.write(token); },
  5003. [&](const std::string &token) { strm.write(token); },
  5004. [&](size_t offset, size_t length) {
  5005. return write_content(strm, res.content_provider_, offset, length,
  5006. is_shutting_down);
  5007. });
  5008. }
  5009. inline bool expect_content(const Request &req) {
  5010. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  5011. req.method == "DELETE") {
  5012. return true;
  5013. }
  5014. if (req.has_header("Content-Length") &&
  5015. req.get_header_value_u64("Content-Length") > 0) {
  5016. return true;
  5017. }
  5018. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  5019. return false;
  5020. }
  5021. inline bool has_crlf(const std::string &s) {
  5022. auto p = s.c_str();
  5023. while (*p) {
  5024. if (*p == '\r' || *p == '\n') { return true; }
  5025. p++;
  5026. }
  5027. return false;
  5028. }
  5029. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5030. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  5031. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  5032. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  5033. unsigned int hash_length = 0;
  5034. unsigned char hash[EVP_MAX_MD_SIZE];
  5035. EVP_DigestInit_ex(context.get(), algo, nullptr);
  5036. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  5037. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  5038. std::stringstream ss;
  5039. for (auto i = 0u; i < hash_length; ++i) {
  5040. ss << std::hex << std::setw(2) << std::setfill('0')
  5041. << static_cast<unsigned int>(hash[i]);
  5042. }
  5043. return ss.str();
  5044. }
  5045. inline std::string MD5(const std::string &s) {
  5046. return message_digest(s, EVP_md5());
  5047. }
  5048. inline std::string SHA_256(const std::string &s) {
  5049. return message_digest(s, EVP_sha256());
  5050. }
  5051. inline std::string SHA_512(const std::string &s) {
  5052. return message_digest(s, EVP_sha512());
  5053. }
  5054. inline std::pair<std::string, std::string> make_digest_authentication_header(
  5055. const Request &req, const std::map<std::string, std::string> &auth,
  5056. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  5057. const std::string &password, bool is_proxy = false) {
  5058. std::string nc;
  5059. {
  5060. std::stringstream ss;
  5061. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  5062. nc = ss.str();
  5063. }
  5064. std::string qop;
  5065. if (auth.find("qop") != auth.end()) {
  5066. qop = auth.at("qop");
  5067. if (qop.find("auth-int") != std::string::npos) {
  5068. qop = "auth-int";
  5069. } else if (qop.find("auth") != std::string::npos) {
  5070. qop = "auth";
  5071. } else {
  5072. qop.clear();
  5073. }
  5074. }
  5075. std::string algo = "MD5";
  5076. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  5077. std::string response;
  5078. {
  5079. auto H = algo == "SHA-256" ? detail::SHA_256
  5080. : algo == "SHA-512" ? detail::SHA_512
  5081. : detail::MD5;
  5082. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  5083. auto A2 = req.method + ":" + req.path;
  5084. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  5085. if (qop.empty()) {
  5086. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  5087. } else {
  5088. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  5089. ":" + qop + ":" + H(A2));
  5090. }
  5091. }
  5092. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  5093. auto field = "Digest username=\"" + username + "\", realm=\"" +
  5094. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  5095. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  5096. (qop.empty() ? ", response=\""
  5097. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  5098. cnonce + "\", response=\"") +
  5099. response + "\"" +
  5100. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  5101. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5102. return std::make_pair(key, field);
  5103. }
  5104. inline bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) {
  5105. detail::set_nonblocking(sock, true);
  5106. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  5107. char buf[1];
  5108. return !SSL_peek(ssl, buf, 1) &&
  5109. SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
  5110. }
  5111. #ifdef _WIN64
  5112. // NOTE: This code came up with the following stackoverflow post:
  5113. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  5114. inline bool load_system_certs_on_windows(X509_STORE *store) {
  5115. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  5116. if (!hStore) { return false; }
  5117. auto result = false;
  5118. PCCERT_CONTEXT pContext = NULL;
  5119. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  5120. nullptr) {
  5121. auto encoded_cert =
  5122. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  5123. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  5124. if (x509) {
  5125. X509_STORE_add_cert(store, x509);
  5126. X509_free(x509);
  5127. result = true;
  5128. }
  5129. }
  5130. CertFreeCertificateContext(pContext);
  5131. CertCloseStore(hStore, 0);
  5132. return result;
  5133. }
  5134. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  5135. defined(TARGET_OS_OSX)
  5136. template <typename T>
  5137. using CFObjectPtr =
  5138. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  5139. inline void cf_object_ptr_deleter(CFTypeRef obj) {
  5140. if (obj) { CFRelease(obj); }
  5141. }
  5142. inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5143. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  5144. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  5145. kCFBooleanTrue};
  5146. CFObjectPtr<CFDictionaryRef> query(
  5147. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  5148. sizeof(keys) / sizeof(keys[0]),
  5149. &kCFTypeDictionaryKeyCallBacks,
  5150. &kCFTypeDictionaryValueCallBacks),
  5151. cf_object_ptr_deleter);
  5152. if (!query) { return false; }
  5153. CFTypeRef security_items = nullptr;
  5154. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  5155. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  5156. return false;
  5157. }
  5158. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  5159. return true;
  5160. }
  5161. inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5162. CFArrayRef root_security_items = nullptr;
  5163. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  5164. return false;
  5165. }
  5166. certs.reset(root_security_items);
  5167. return true;
  5168. }
  5169. inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  5170. auto result = false;
  5171. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  5172. const auto cert = reinterpret_cast<const __SecCertificate *>(
  5173. CFArrayGetValueAtIndex(certs, i));
  5174. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  5175. CFDataRef cert_data = nullptr;
  5176. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  5177. errSecSuccess) {
  5178. continue;
  5179. }
  5180. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  5181. auto encoded_cert = static_cast<const unsigned char *>(
  5182. CFDataGetBytePtr(cert_data_ptr.get()));
  5183. auto x509 =
  5184. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  5185. if (x509) {
  5186. X509_STORE_add_cert(store, x509);
  5187. X509_free(x509);
  5188. result = true;
  5189. }
  5190. }
  5191. return result;
  5192. }
  5193. inline bool load_system_certs_on_macos(X509_STORE *store) {
  5194. auto result = false;
  5195. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  5196. if (retrieve_certs_from_keychain(certs) && certs) {
  5197. result = add_certs_to_x509_store(certs.get(), store);
  5198. }
  5199. if (retrieve_root_certs_from_keychain(certs) && certs) {
  5200. result = add_certs_to_x509_store(certs.get(), store) || result;
  5201. }
  5202. return result;
  5203. }
  5204. #endif // _WIN64
  5205. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  5206. #ifdef _WIN64
  5207. class WSInit {
  5208. public:
  5209. WSInit() {
  5210. WSADATA wsaData;
  5211. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  5212. }
  5213. ~WSInit() {
  5214. if (is_valid_) WSACleanup();
  5215. }
  5216. bool is_valid_ = false;
  5217. };
  5218. static WSInit wsinit_;
  5219. #endif
  5220. inline bool parse_www_authenticate(const Response &res,
  5221. std::map<std::string, std::string> &auth,
  5222. bool is_proxy) {
  5223. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  5224. if (res.has_header(auth_key)) {
  5225. thread_local auto re =
  5226. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  5227. auto s = res.get_header_value(auth_key);
  5228. auto pos = s.find(' ');
  5229. if (pos != std::string::npos) {
  5230. auto type = s.substr(0, pos);
  5231. if (type == "Basic") {
  5232. return false;
  5233. } else if (type == "Digest") {
  5234. s = s.substr(pos + 1);
  5235. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  5236. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  5237. const auto &m = *i;
  5238. auto key = s.substr(static_cast<size_t>(m.position(1)),
  5239. static_cast<size_t>(m.length(1)));
  5240. auto val = m.length(2) > 0
  5241. ? s.substr(static_cast<size_t>(m.position(2)),
  5242. static_cast<size_t>(m.length(2)))
  5243. : s.substr(static_cast<size_t>(m.position(3)),
  5244. static_cast<size_t>(m.length(3)));
  5245. auth[key] = val;
  5246. }
  5247. return true;
  5248. }
  5249. }
  5250. }
  5251. return false;
  5252. }
  5253. class ContentProviderAdapter {
  5254. public:
  5255. explicit ContentProviderAdapter(
  5256. ContentProviderWithoutLength &&content_provider)
  5257. : content_provider_(content_provider) {}
  5258. bool operator()(size_t offset, size_t, DataSink &sink) {
  5259. return content_provider_(offset, sink);
  5260. }
  5261. private:
  5262. ContentProviderWithoutLength content_provider_;
  5263. };
  5264. } // namespace detail
  5265. inline std::string hosted_at(const std::string &hostname) {
  5266. std::vector<std::string> addrs;
  5267. hosted_at(hostname, addrs);
  5268. if (addrs.empty()) { return std::string(); }
  5269. return addrs[0];
  5270. }
  5271. inline void hosted_at(const std::string &hostname,
  5272. std::vector<std::string> &addrs) {
  5273. struct addrinfo hints;
  5274. struct addrinfo *result;
  5275. memset(&hints, 0, sizeof(struct addrinfo));
  5276. hints.ai_family = AF_UNSPEC;
  5277. hints.ai_socktype = SOCK_STREAM;
  5278. hints.ai_protocol = 0;
  5279. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  5280. &result, 0)) {
  5281. #if defined __linux__ && !defined __ANDROID__
  5282. res_init();
  5283. #endif
  5284. return;
  5285. }
  5286. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5287. for (auto rp = result; rp; rp = rp->ai_next) {
  5288. const auto &addr =
  5289. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  5290. std::string ip;
  5291. auto dummy = -1;
  5292. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  5293. dummy)) {
  5294. addrs.push_back(ip);
  5295. }
  5296. }
  5297. }
  5298. inline std::string encode_uri_component(const std::string &value) {
  5299. std::ostringstream escaped;
  5300. escaped.fill('0');
  5301. escaped << std::hex;
  5302. for (auto c : value) {
  5303. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  5304. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  5305. c == ')') {
  5306. escaped << c;
  5307. } else {
  5308. escaped << std::uppercase;
  5309. escaped << '%' << std::setw(2)
  5310. << static_cast<int>(static_cast<unsigned char>(c));
  5311. escaped << std::nouppercase;
  5312. }
  5313. }
  5314. return escaped.str();
  5315. }
  5316. inline std::string encode_uri(const std::string &value) {
  5317. std::ostringstream escaped;
  5318. escaped.fill('0');
  5319. escaped << std::hex;
  5320. for (auto c : value) {
  5321. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  5322. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  5323. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  5324. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  5325. escaped << c;
  5326. } else {
  5327. escaped << std::uppercase;
  5328. escaped << '%' << std::setw(2)
  5329. << static_cast<int>(static_cast<unsigned char>(c));
  5330. escaped << std::nouppercase;
  5331. }
  5332. }
  5333. return escaped.str();
  5334. }
  5335. inline std::string decode_uri_component(const std::string &value) {
  5336. std::string result;
  5337. for (size_t i = 0; i < value.size(); i++) {
  5338. if (value[i] == '%' && i + 2 < value.size()) {
  5339. auto val = 0;
  5340. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  5341. result += static_cast<char>(val);
  5342. i += 2;
  5343. } else {
  5344. result += value[i];
  5345. }
  5346. } else {
  5347. result += value[i];
  5348. }
  5349. }
  5350. return result;
  5351. }
  5352. inline std::string decode_uri(const std::string &value) {
  5353. std::string result;
  5354. for (size_t i = 0; i < value.size(); i++) {
  5355. if (value[i] == '%' && i + 2 < value.size()) {
  5356. auto val = 0;
  5357. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  5358. result += static_cast<char>(val);
  5359. i += 2;
  5360. } else {
  5361. result += value[i];
  5362. }
  5363. } else {
  5364. result += value[i];
  5365. }
  5366. }
  5367. return result;
  5368. }
  5369. [[deprecated("Use encode_uri_component instead")]]
  5370. inline std::string encode_query_param(const std::string &value) {
  5371. return encode_uri_component(value);
  5372. }
  5373. inline std::string append_query_params(const std::string &path,
  5374. const Params &params) {
  5375. std::string path_with_query = path;
  5376. thread_local const std::regex re("[^?]+\\?.*");
  5377. auto delm = std::regex_match(path, re) ? '&' : '?';
  5378. path_with_query += delm + detail::params_to_query_str(params);
  5379. return path_with_query;
  5380. }
  5381. // Header utilities
  5382. inline std::pair<std::string, std::string>
  5383. make_range_header(const Ranges &ranges) {
  5384. std::string field = "bytes=";
  5385. auto i = 0;
  5386. for (const auto &r : ranges) {
  5387. if (i != 0) { field += ", "; }
  5388. if (r.first != -1) { field += std::to_string(r.first); }
  5389. field += '-';
  5390. if (r.second != -1) { field += std::to_string(r.second); }
  5391. i++;
  5392. }
  5393. return std::make_pair("Range", std::move(field));
  5394. }
  5395. inline std::pair<std::string, std::string>
  5396. make_basic_authentication_header(const std::string &username,
  5397. const std::string &password, bool is_proxy) {
  5398. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  5399. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5400. return std::make_pair(key, std::move(field));
  5401. }
  5402. inline std::pair<std::string, std::string>
  5403. make_bearer_token_authentication_header(const std::string &token,
  5404. bool is_proxy = false) {
  5405. auto field = "Bearer " + token;
  5406. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5407. return std::make_pair(key, std::move(field));
  5408. }
  5409. // Request implementation
  5410. inline bool Request::has_header(const std::string &key) const {
  5411. return detail::has_header(headers, key);
  5412. }
  5413. inline std::string Request::get_header_value(const std::string &key,
  5414. const char *def, size_t id) const {
  5415. return detail::get_header_value(headers, key, def, id);
  5416. }
  5417. inline size_t Request::get_header_value_count(const std::string &key) const {
  5418. auto r = headers.equal_range(key);
  5419. return static_cast<size_t>(std::distance(r.first, r.second));
  5420. }
  5421. inline void Request::set_header(const std::string &key,
  5422. const std::string &val) {
  5423. if (detail::fields::is_field_name(key) &&
  5424. detail::fields::is_field_value(val)) {
  5425. headers.emplace(key, val);
  5426. }
  5427. }
  5428. inline bool Request::has_trailer(const std::string &key) const {
  5429. return trailers.find(key) != trailers.end();
  5430. }
  5431. inline std::string Request::get_trailer_value(const std::string &key,
  5432. size_t id) const {
  5433. auto rng = trailers.equal_range(key);
  5434. auto it = rng.first;
  5435. std::advance(it, static_cast<ssize_t>(id));
  5436. if (it != rng.second) { return it->second; }
  5437. return std::string();
  5438. }
  5439. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  5440. auto r = trailers.equal_range(key);
  5441. return static_cast<size_t>(std::distance(r.first, r.second));
  5442. }
  5443. inline bool Request::has_param(const std::string &key) const {
  5444. return params.find(key) != params.end();
  5445. }
  5446. inline std::string Request::get_param_value(const std::string &key,
  5447. size_t id) const {
  5448. auto rng = params.equal_range(key);
  5449. auto it = rng.first;
  5450. std::advance(it, static_cast<ssize_t>(id));
  5451. if (it != rng.second) { return it->second; }
  5452. return std::string();
  5453. }
  5454. inline size_t Request::get_param_value_count(const std::string &key) const {
  5455. auto r = params.equal_range(key);
  5456. return static_cast<size_t>(std::distance(r.first, r.second));
  5457. }
  5458. inline bool Request::is_multipart_form_data() const {
  5459. const auto &content_type = get_header_value("Content-Type");
  5460. return !content_type.rfind("multipart/form-data", 0);
  5461. }
  5462. // Multipart FormData implementation
  5463. inline std::string MultipartFormData::get_field(const std::string &key,
  5464. size_t id) const {
  5465. auto rng = fields.equal_range(key);
  5466. auto it = rng.first;
  5467. std::advance(it, static_cast<ssize_t>(id));
  5468. if (it != rng.second) { return it->second.content; }
  5469. return std::string();
  5470. }
  5471. inline std::vector<std::string>
  5472. MultipartFormData::get_fields(const std::string &key) const {
  5473. std::vector<std::string> values;
  5474. auto rng = fields.equal_range(key);
  5475. for (auto it = rng.first; it != rng.second; it++) {
  5476. values.push_back(it->second.content);
  5477. }
  5478. return values;
  5479. }
  5480. inline bool MultipartFormData::has_field(const std::string &key) const {
  5481. return fields.find(key) != fields.end();
  5482. }
  5483. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  5484. auto r = fields.equal_range(key);
  5485. return static_cast<size_t>(std::distance(r.first, r.second));
  5486. }
  5487. inline FormData MultipartFormData::get_file(const std::string &key,
  5488. size_t id) const {
  5489. auto rng = files.equal_range(key);
  5490. auto it = rng.first;
  5491. std::advance(it, static_cast<ssize_t>(id));
  5492. if (it != rng.second) { return it->second; }
  5493. return FormData();
  5494. }
  5495. inline std::vector<FormData>
  5496. MultipartFormData::get_files(const std::string &key) const {
  5497. std::vector<FormData> values;
  5498. auto rng = files.equal_range(key);
  5499. for (auto it = rng.first; it != rng.second; it++) {
  5500. values.push_back(it->second);
  5501. }
  5502. return values;
  5503. }
  5504. inline bool MultipartFormData::has_file(const std::string &key) const {
  5505. return files.find(key) != files.end();
  5506. }
  5507. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  5508. auto r = files.equal_range(key);
  5509. return static_cast<size_t>(std::distance(r.first, r.second));
  5510. }
  5511. // Response implementation
  5512. inline bool Response::has_header(const std::string &key) const {
  5513. return headers.find(key) != headers.end();
  5514. }
  5515. inline std::string Response::get_header_value(const std::string &key,
  5516. const char *def,
  5517. size_t id) const {
  5518. return detail::get_header_value(headers, key, def, id);
  5519. }
  5520. inline size_t Response::get_header_value_count(const std::string &key) const {
  5521. auto r = headers.equal_range(key);
  5522. return static_cast<size_t>(std::distance(r.first, r.second));
  5523. }
  5524. inline void Response::set_header(const std::string &key,
  5525. const std::string &val) {
  5526. if (detail::fields::is_field_name(key) &&
  5527. detail::fields::is_field_value(val)) {
  5528. headers.emplace(key, val);
  5529. }
  5530. }
  5531. inline bool Response::has_trailer(const std::string &key) const {
  5532. return trailers.find(key) != trailers.end();
  5533. }
  5534. inline std::string Response::get_trailer_value(const std::string &key,
  5535. size_t id) const {
  5536. auto rng = trailers.equal_range(key);
  5537. auto it = rng.first;
  5538. std::advance(it, static_cast<ssize_t>(id));
  5539. if (it != rng.second) { return it->second; }
  5540. return std::string();
  5541. }
  5542. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  5543. auto r = trailers.equal_range(key);
  5544. return static_cast<size_t>(std::distance(r.first, r.second));
  5545. }
  5546. inline void Response::set_redirect(const std::string &url, int stat) {
  5547. if (detail::fields::is_field_value(url)) {
  5548. set_header("Location", url);
  5549. if (300 <= stat && stat < 400) {
  5550. this->status = stat;
  5551. } else {
  5552. this->status = StatusCode::Found_302;
  5553. }
  5554. }
  5555. }
  5556. inline void Response::set_content(const char *s, size_t n,
  5557. const std::string &content_type) {
  5558. body.assign(s, n);
  5559. auto rng = headers.equal_range("Content-Type");
  5560. headers.erase(rng.first, rng.second);
  5561. set_header("Content-Type", content_type);
  5562. }
  5563. inline void Response::set_content(const std::string &s,
  5564. const std::string &content_type) {
  5565. set_content(s.data(), s.size(), content_type);
  5566. }
  5567. inline void Response::set_content(std::string &&s,
  5568. const std::string &content_type) {
  5569. body = std::move(s);
  5570. auto rng = headers.equal_range("Content-Type");
  5571. headers.erase(rng.first, rng.second);
  5572. set_header("Content-Type", content_type);
  5573. }
  5574. inline void Response::set_content_provider(
  5575. size_t in_length, const std::string &content_type, ContentProvider provider,
  5576. ContentProviderResourceReleaser resource_releaser) {
  5577. set_header("Content-Type", content_type);
  5578. content_length_ = in_length;
  5579. if (in_length > 0) { content_provider_ = std::move(provider); }
  5580. content_provider_resource_releaser_ = std::move(resource_releaser);
  5581. is_chunked_content_provider_ = false;
  5582. }
  5583. inline void Response::set_content_provider(
  5584. const std::string &content_type, ContentProviderWithoutLength provider,
  5585. ContentProviderResourceReleaser resource_releaser) {
  5586. set_header("Content-Type", content_type);
  5587. content_length_ = 0;
  5588. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5589. content_provider_resource_releaser_ = std::move(resource_releaser);
  5590. is_chunked_content_provider_ = false;
  5591. }
  5592. inline void Response::set_chunked_content_provider(
  5593. const std::string &content_type, ContentProviderWithoutLength provider,
  5594. ContentProviderResourceReleaser resource_releaser) {
  5595. set_header("Content-Type", content_type);
  5596. content_length_ = 0;
  5597. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5598. content_provider_resource_releaser_ = std::move(resource_releaser);
  5599. is_chunked_content_provider_ = true;
  5600. }
  5601. inline void Response::set_file_content(const std::string &path,
  5602. const std::string &content_type) {
  5603. file_content_path_ = path;
  5604. file_content_content_type_ = content_type;
  5605. }
  5606. inline void Response::set_file_content(const std::string &path) {
  5607. file_content_path_ = path;
  5608. }
  5609. // Result implementation
  5610. inline bool Result::has_request_header(const std::string &key) const {
  5611. return request_headers_.find(key) != request_headers_.end();
  5612. }
  5613. inline std::string Result::get_request_header_value(const std::string &key,
  5614. const char *def,
  5615. size_t id) const {
  5616. return detail::get_header_value(request_headers_, key, def, id);
  5617. }
  5618. inline size_t
  5619. Result::get_request_header_value_count(const std::string &key) const {
  5620. auto r = request_headers_.equal_range(key);
  5621. return static_cast<size_t>(std::distance(r.first, r.second));
  5622. }
  5623. // Stream implementation
  5624. inline ssize_t Stream::write(const char *ptr) {
  5625. return write(ptr, strlen(ptr));
  5626. }
  5627. inline ssize_t Stream::write(const std::string &s) {
  5628. return write(s.data(), s.size());
  5629. }
  5630. namespace detail {
  5631. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  5632. time_t timeout_sec, time_t timeout_usec,
  5633. time_t &actual_timeout_sec,
  5634. time_t &actual_timeout_usec) {
  5635. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  5636. auto actual_timeout_msec =
  5637. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  5638. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  5639. actual_timeout_sec = actual_timeout_msec / 1000;
  5640. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  5641. }
  5642. // Socket stream implementation
  5643. inline SocketStream::SocketStream(
  5644. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5645. time_t write_timeout_sec, time_t write_timeout_usec,
  5646. time_t max_timeout_msec,
  5647. std::chrono::time_point<std::chrono::steady_clock> start_time)
  5648. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  5649. read_timeout_usec_(read_timeout_usec),
  5650. write_timeout_sec_(write_timeout_sec),
  5651. write_timeout_usec_(write_timeout_usec),
  5652. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  5653. read_buff_(read_buff_size_, 0) {}
  5654. inline SocketStream::~SocketStream() = default;
  5655. inline bool SocketStream::is_readable() const {
  5656. return read_buff_off_ < read_buff_content_size_;
  5657. }
  5658. inline bool SocketStream::wait_readable() const {
  5659. if (max_timeout_msec_ <= 0) {
  5660. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  5661. }
  5662. time_t read_timeout_sec;
  5663. time_t read_timeout_usec;
  5664. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  5665. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  5666. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  5667. }
  5668. inline bool SocketStream::wait_writable() const {
  5669. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  5670. is_socket_alive(sock_);
  5671. }
  5672. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  5673. #ifdef _WIN64
  5674. size =
  5675. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5676. #else
  5677. size = (std::min)(size,
  5678. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  5679. #endif
  5680. if (read_buff_off_ < read_buff_content_size_) {
  5681. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  5682. if (size <= remaining_size) {
  5683. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  5684. read_buff_off_ += size;
  5685. return static_cast<ssize_t>(size);
  5686. } else {
  5687. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  5688. read_buff_off_ += remaining_size;
  5689. return static_cast<ssize_t>(remaining_size);
  5690. }
  5691. }
  5692. if (!wait_readable()) { return -1; }
  5693. read_buff_off_ = 0;
  5694. read_buff_content_size_ = 0;
  5695. if (size < read_buff_size_) {
  5696. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  5697. CPPHTTPLIB_RECV_FLAGS);
  5698. if (n <= 0) {
  5699. return n;
  5700. } else if (n <= static_cast<ssize_t>(size)) {
  5701. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  5702. return n;
  5703. } else {
  5704. memcpy(ptr, read_buff_.data(), size);
  5705. read_buff_off_ = size;
  5706. read_buff_content_size_ = static_cast<size_t>(n);
  5707. return static_cast<ssize_t>(size);
  5708. }
  5709. } else {
  5710. return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  5711. }
  5712. }
  5713. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  5714. if (!wait_writable()) { return -1; }
  5715. #if defined(_WIN64) && !defined(_WIN64)
  5716. size =
  5717. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5718. #endif
  5719. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  5720. }
  5721. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  5722. int &port) const {
  5723. return detail::get_remote_ip_and_port(sock_, ip, port);
  5724. }
  5725. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  5726. int &port) const {
  5727. return detail::get_local_ip_and_port(sock_, ip, port);
  5728. }
  5729. inline socket_t SocketStream::socket() const { return sock_; }
  5730. inline time_t SocketStream::duration() const {
  5731. return std::chrono::duration_cast<std::chrono::milliseconds>(
  5732. std::chrono::steady_clock::now() - start_time_)
  5733. .count();
  5734. }
  5735. // Buffer stream implementation
  5736. inline bool BufferStream::is_readable() const { return true; }
  5737. inline bool BufferStream::wait_readable() const { return true; }
  5738. inline bool BufferStream::wait_writable() const { return true; }
  5739. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  5740. #if defined(_MSC_VER) && _MSC_VER < 1910
  5741. auto len_read = buffer._Copy_s(ptr, size, size, position);
  5742. #else
  5743. auto len_read = buffer.copy(ptr, size, position);
  5744. #endif
  5745. position += static_cast<size_t>(len_read);
  5746. return static_cast<ssize_t>(len_read);
  5747. }
  5748. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  5749. buffer.append(ptr, size);
  5750. return static_cast<ssize_t>(size);
  5751. }
  5752. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  5753. int & /*port*/) const {}
  5754. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  5755. int & /*port*/) const {}
  5756. inline socket_t BufferStream::socket() const { return 0; }
  5757. inline time_t BufferStream::duration() const { return 0; }
  5758. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  5759. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  5760. : MatcherBase(pattern) {
  5761. constexpr const char marker[] = "/:";
  5762. // One past the last ending position of a path param substring
  5763. std::size_t last_param_end = 0;
  5764. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5765. // Needed to ensure that parameter names are unique during matcher
  5766. // construction
  5767. // If exceptions are disabled, only last duplicate path
  5768. // parameter will be set
  5769. std::unordered_set<std::string> param_name_set;
  5770. #endif
  5771. while (true) {
  5772. const auto marker_pos = pattern.find(
  5773. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  5774. if (marker_pos == std::string::npos) { break; }
  5775. static_fragments_.push_back(
  5776. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  5777. const auto param_name_start = marker_pos + str_len(marker);
  5778. auto sep_pos = pattern.find(separator, param_name_start);
  5779. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  5780. auto param_name =
  5781. pattern.substr(param_name_start, sep_pos - param_name_start);
  5782. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5783. if (param_name_set.find(param_name) != param_name_set.cend()) {
  5784. std::string msg = "Encountered path parameter '" + param_name +
  5785. "' multiple times in route pattern '" + pattern + "'.";
  5786. throw std::invalid_argument(msg);
  5787. }
  5788. #endif
  5789. param_names_.push_back(std::move(param_name));
  5790. last_param_end = sep_pos + 1;
  5791. }
  5792. if (last_param_end < pattern.length()) {
  5793. static_fragments_.push_back(pattern.substr(last_param_end));
  5794. }
  5795. }
  5796. inline bool PathParamsMatcher::match(Request &request) const {
  5797. request.matches = std::smatch();
  5798. request.path_params.clear();
  5799. request.path_params.reserve(param_names_.size());
  5800. // One past the position at which the path matched the pattern last time
  5801. std::size_t starting_pos = 0;
  5802. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  5803. const auto &fragment = static_fragments_[i];
  5804. if (starting_pos + fragment.length() > request.path.length()) {
  5805. return false;
  5806. }
  5807. // Avoid unnecessary allocation by using strncmp instead of substr +
  5808. // comparison
  5809. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  5810. fragment.length()) != 0) {
  5811. return false;
  5812. }
  5813. starting_pos += fragment.length();
  5814. // Should only happen when we have a static fragment after a param
  5815. // Example: '/users/:id/subscriptions'
  5816. // The 'subscriptions' fragment here does not have a corresponding param
  5817. if (i >= param_names_.size()) { continue; }
  5818. auto sep_pos = request.path.find(separator, starting_pos);
  5819. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  5820. const auto &param_name = param_names_[i];
  5821. request.path_params.emplace(
  5822. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  5823. // Mark everything up to '/' as matched
  5824. starting_pos = sep_pos + 1;
  5825. }
  5826. // Returns false if the path is longer than the pattern
  5827. return starting_pos >= request.path.length();
  5828. }
  5829. inline bool RegexMatcher::match(Request &request) const {
  5830. request.path_params.clear();
  5831. return std::regex_match(request.path, request.matches, regex_);
  5832. }
  5833. } // namespace detail
  5834. // HTTP server implementation
  5835. inline Server::Server()
  5836. : new_task_queue(
  5837. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  5838. #ifndef _WIN64
  5839. signal(SIGPIPE, SIG_IGN);
  5840. #endif
  5841. }
  5842. inline Server::~Server() = default;
  5843. inline std::unique_ptr<detail::MatcherBase>
  5844. Server::make_matcher(const std::string &pattern) {
  5845. if (pattern.find("/:") != std::string::npos) {
  5846. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  5847. } else {
  5848. return detail::make_unique<detail::RegexMatcher>(pattern);
  5849. }
  5850. }
  5851. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  5852. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5853. return *this;
  5854. }
  5855. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  5856. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5857. return *this;
  5858. }
  5859. inline Server &Server::Post(const std::string &pattern,
  5860. HandlerWithContentReader handler) {
  5861. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5862. std::move(handler));
  5863. return *this;
  5864. }
  5865. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  5866. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5867. return *this;
  5868. }
  5869. inline Server &Server::Put(const std::string &pattern,
  5870. HandlerWithContentReader handler) {
  5871. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5872. std::move(handler));
  5873. return *this;
  5874. }
  5875. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  5876. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5877. return *this;
  5878. }
  5879. inline Server &Server::Patch(const std::string &pattern,
  5880. HandlerWithContentReader handler) {
  5881. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5882. std::move(handler));
  5883. return *this;
  5884. }
  5885. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  5886. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5887. return *this;
  5888. }
  5889. inline Server &Server::Delete(const std::string &pattern,
  5890. HandlerWithContentReader handler) {
  5891. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5892. std::move(handler));
  5893. return *this;
  5894. }
  5895. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  5896. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5897. return *this;
  5898. }
  5899. inline bool Server::set_base_dir(const std::string &dir,
  5900. const std::string &mount_point) {
  5901. return set_mount_point(mount_point, dir);
  5902. }
  5903. inline bool Server::set_mount_point(const std::string &mount_point,
  5904. const std::string &dir, Headers headers) {
  5905. detail::FileStat stat(dir);
  5906. if (stat.is_dir()) {
  5907. std::string mnt = !mount_point.empty() ? mount_point : "/";
  5908. if (!mnt.empty() && mnt[0] == '/') {
  5909. base_dirs_.push_back({mnt, dir, std::move(headers)});
  5910. return true;
  5911. }
  5912. }
  5913. return false;
  5914. }
  5915. inline bool Server::remove_mount_point(const std::string &mount_point) {
  5916. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  5917. if (it->mount_point == mount_point) {
  5918. base_dirs_.erase(it);
  5919. return true;
  5920. }
  5921. }
  5922. return false;
  5923. }
  5924. inline Server &
  5925. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  5926. const std::string &mime) {
  5927. file_extension_and_mimetype_map_[ext] = mime;
  5928. return *this;
  5929. }
  5930. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  5931. default_file_mimetype_ = mime;
  5932. return *this;
  5933. }
  5934. inline Server &Server::set_file_request_handler(Handler handler) {
  5935. file_request_handler_ = std::move(handler);
  5936. return *this;
  5937. }
  5938. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  5939. std::true_type) {
  5940. error_handler_ = std::move(handler);
  5941. return *this;
  5942. }
  5943. inline Server &Server::set_error_handler_core(Handler handler,
  5944. std::false_type) {
  5945. error_handler_ = [handler](const Request &req, Response &res) {
  5946. handler(req, res);
  5947. return HandlerResponse::Handled;
  5948. };
  5949. return *this;
  5950. }
  5951. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  5952. exception_handler_ = std::move(handler);
  5953. return *this;
  5954. }
  5955. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  5956. pre_routing_handler_ = std::move(handler);
  5957. return *this;
  5958. }
  5959. inline Server &Server::set_post_routing_handler(Handler handler) {
  5960. post_routing_handler_ = std::move(handler);
  5961. return *this;
  5962. }
  5963. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  5964. pre_request_handler_ = std::move(handler);
  5965. return *this;
  5966. }
  5967. inline Server &Server::set_logger(Logger logger) {
  5968. logger_ = std::move(logger);
  5969. return *this;
  5970. }
  5971. inline Server &Server::set_pre_compression_logger(Logger logger) {
  5972. pre_compression_logger_ = std::move(logger);
  5973. return *this;
  5974. }
  5975. inline Server &
  5976. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  5977. expect_100_continue_handler_ = std::move(handler);
  5978. return *this;
  5979. }
  5980. inline Server &Server::set_address_family(int family) {
  5981. address_family_ = family;
  5982. return *this;
  5983. }
  5984. inline Server &Server::set_tcp_nodelay(bool on) {
  5985. tcp_nodelay_ = on;
  5986. return *this;
  5987. }
  5988. inline Server &Server::set_ipv6_v6only(bool on) {
  5989. ipv6_v6only_ = on;
  5990. return *this;
  5991. }
  5992. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  5993. socket_options_ = std::move(socket_options);
  5994. return *this;
  5995. }
  5996. inline Server &Server::set_default_headers(Headers headers) {
  5997. default_headers_ = std::move(headers);
  5998. return *this;
  5999. }
  6000. inline Server &Server::set_header_writer(
  6001. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  6002. header_writer_ = writer;
  6003. return *this;
  6004. }
  6005. inline Server &Server::set_keep_alive_max_count(size_t count) {
  6006. keep_alive_max_count_ = count;
  6007. return *this;
  6008. }
  6009. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  6010. keep_alive_timeout_sec_ = sec;
  6011. return *this;
  6012. }
  6013. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  6014. read_timeout_sec_ = sec;
  6015. read_timeout_usec_ = usec;
  6016. return *this;
  6017. }
  6018. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  6019. write_timeout_sec_ = sec;
  6020. write_timeout_usec_ = usec;
  6021. return *this;
  6022. }
  6023. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  6024. idle_interval_sec_ = sec;
  6025. idle_interval_usec_ = usec;
  6026. return *this;
  6027. }
  6028. inline Server &Server::set_payload_max_length(size_t length) {
  6029. payload_max_length_ = length;
  6030. return *this;
  6031. }
  6032. inline bool Server::bind_to_port(const std::string &host, int port,
  6033. int socket_flags) {
  6034. auto ret = bind_internal(host, port, socket_flags);
  6035. if (ret == -1) { is_decommissioned = true; }
  6036. return ret >= 0;
  6037. }
  6038. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  6039. auto ret = bind_internal(host, 0, socket_flags);
  6040. if (ret == -1) { is_decommissioned = true; }
  6041. return ret;
  6042. }
  6043. inline bool Server::listen_after_bind() { return listen_internal(); }
  6044. inline bool Server::listen(const std::string &host, int port,
  6045. int socket_flags) {
  6046. return bind_to_port(host, port, socket_flags) && listen_internal();
  6047. }
  6048. inline bool Server::is_running() const { return is_running_; }
  6049. inline void Server::wait_until_ready() const {
  6050. while (!is_running_ && !is_decommissioned) {
  6051. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  6052. }
  6053. }
  6054. inline void Server::stop() {
  6055. if (is_running_) {
  6056. assert(svr_sock_ != INVALID_SOCKET);
  6057. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  6058. detail::shutdown_socket(sock);
  6059. detail::close_socket(sock);
  6060. }
  6061. is_decommissioned = false;
  6062. }
  6063. inline void Server::decommission() { is_decommissioned = true; }
  6064. inline bool Server::parse_request_line(const char *s, Request &req) const {
  6065. auto len = strlen(s);
  6066. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  6067. len -= 2;
  6068. {
  6069. size_t count = 0;
  6070. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  6071. switch (count) {
  6072. case 0: req.method = std::string(b, e); break;
  6073. case 1: req.target = std::string(b, e); break;
  6074. case 2: req.version = std::string(b, e); break;
  6075. default: break;
  6076. }
  6077. count++;
  6078. });
  6079. if (count != 3) { return false; }
  6080. }
  6081. thread_local const std::set<std::string> methods{
  6082. "GET", "HEAD", "POST", "PUT", "DELETE",
  6083. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  6084. if (methods.find(req.method) == methods.end()) { return false; }
  6085. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; }
  6086. {
  6087. // Skip URL fragment
  6088. for (size_t i = 0; i < req.target.size(); i++) {
  6089. if (req.target[i] == '#') {
  6090. req.target.erase(i);
  6091. break;
  6092. }
  6093. }
  6094. detail::divide(req.target, '?',
  6095. [&](const char *lhs_data, std::size_t lhs_size,
  6096. const char *rhs_data, std::size_t rhs_size) {
  6097. req.path = detail::decode_path(
  6098. std::string(lhs_data, lhs_size), false);
  6099. detail::parse_query_text(rhs_data, rhs_size, req.params);
  6100. });
  6101. }
  6102. return true;
  6103. }
  6104. inline bool Server::write_response(Stream &strm, bool close_connection,
  6105. Request &req, Response &res) {
  6106. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  6107. // incorrectly to the error content.
  6108. req.ranges.clear();
  6109. return write_response_core(strm, close_connection, req, res, false);
  6110. }
  6111. inline bool Server::write_response_with_content(Stream &strm,
  6112. bool close_connection,
  6113. const Request &req,
  6114. Response &res) {
  6115. return write_response_core(strm, close_connection, req, res, true);
  6116. }
  6117. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  6118. const Request &req, Response &res,
  6119. bool need_apply_ranges) {
  6120. assert(res.status != -1);
  6121. if (400 <= res.status && error_handler_ &&
  6122. error_handler_(req, res) == HandlerResponse::Handled) {
  6123. need_apply_ranges = true;
  6124. }
  6125. std::string content_type;
  6126. std::string boundary;
  6127. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  6128. // Prepare additional headers
  6129. if (close_connection || req.get_header_value("Connection") == "close") {
  6130. res.set_header("Connection", "close");
  6131. } else {
  6132. std::string s = "timeout=";
  6133. s += std::to_string(keep_alive_timeout_sec_);
  6134. s += ", max=";
  6135. s += std::to_string(keep_alive_max_count_);
  6136. res.set_header("Keep-Alive", s);
  6137. }
  6138. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  6139. !res.has_header("Content-Type")) {
  6140. res.set_header("Content-Type", "text/plain");
  6141. }
  6142. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  6143. !res.has_header("Content-Length")) {
  6144. res.set_header("Content-Length", "0");
  6145. }
  6146. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  6147. res.set_header("Accept-Ranges", "bytes");
  6148. }
  6149. if (post_routing_handler_) { post_routing_handler_(req, res); }
  6150. // Response line and headers
  6151. {
  6152. detail::BufferStream bstrm;
  6153. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  6154. if (!header_writer_(bstrm, res.headers)) { return false; }
  6155. // Flush buffer
  6156. auto &data = bstrm.get_buffer();
  6157. detail::write_data(strm, data.data(), data.size());
  6158. }
  6159. // Body
  6160. auto ret = true;
  6161. if (req.method != "HEAD") {
  6162. if (!res.body.empty()) {
  6163. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  6164. ret = false;
  6165. }
  6166. } else if (res.content_provider_) {
  6167. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  6168. res.content_provider_success_ = true;
  6169. } else {
  6170. ret = false;
  6171. }
  6172. }
  6173. }
  6174. // Log
  6175. if (logger_) { logger_(req, res); }
  6176. return ret;
  6177. }
  6178. inline bool
  6179. Server::write_content_with_provider(Stream &strm, const Request &req,
  6180. Response &res, const std::string &boundary,
  6181. const std::string &content_type) {
  6182. auto is_shutting_down = [this]() {
  6183. return this->svr_sock_ == INVALID_SOCKET;
  6184. };
  6185. if (res.content_length_ > 0) {
  6186. if (req.ranges.empty()) {
  6187. return detail::write_content(strm, res.content_provider_, 0,
  6188. res.content_length_, is_shutting_down);
  6189. } else if (req.ranges.size() == 1) {
  6190. auto offset_and_length = detail::get_range_offset_and_length(
  6191. req.ranges[0], res.content_length_);
  6192. return detail::write_content(strm, res.content_provider_,
  6193. offset_and_length.first,
  6194. offset_and_length.second, is_shutting_down);
  6195. } else {
  6196. return detail::write_multipart_ranges_data(
  6197. strm, req, res, boundary, content_type, res.content_length_,
  6198. is_shutting_down);
  6199. }
  6200. } else {
  6201. if (res.is_chunked_content_provider_) {
  6202. auto type = detail::encoding_type(req, res);
  6203. std::unique_ptr<detail::compressor> compressor;
  6204. if (type == detail::EncodingType::Gzip) {
  6205. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6206. compressor = detail::make_unique<detail::gzip_compressor>();
  6207. #endif
  6208. } else if (type == detail::EncodingType::Brotli) {
  6209. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6210. compressor = detail::make_unique<detail::brotli_compressor>();
  6211. #endif
  6212. } else if (type == detail::EncodingType::Zstd) {
  6213. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6214. compressor = detail::make_unique<detail::zstd_compressor>();
  6215. #endif
  6216. } else {
  6217. compressor = detail::make_unique<detail::nocompressor>();
  6218. }
  6219. assert(compressor != nullptr);
  6220. return detail::write_content_chunked(strm, res.content_provider_,
  6221. is_shutting_down, *compressor);
  6222. } else {
  6223. return detail::write_content_without_length(strm, res.content_provider_,
  6224. is_shutting_down);
  6225. }
  6226. }
  6227. }
  6228. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  6229. FormFields::iterator cur_field;
  6230. FormFiles::iterator cur_file;
  6231. auto is_text_field = false;
  6232. size_t count = 0;
  6233. if (read_content_core(
  6234. strm, req, res,
  6235. // Regular
  6236. [&](const char *buf, size_t n) {
  6237. if (req.body.size() + n > req.body.max_size()) { return false; }
  6238. req.body.append(buf, n);
  6239. return true;
  6240. },
  6241. // Multipart FormData
  6242. [&](const FormData &file) {
  6243. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  6244. return false;
  6245. }
  6246. if (file.filename.empty()) {
  6247. cur_field = req.form.fields.emplace(
  6248. file.name, FormField{file.name, file.content, file.headers});
  6249. is_text_field = true;
  6250. } else {
  6251. cur_file = req.form.files.emplace(file.name, file);
  6252. is_text_field = false;
  6253. }
  6254. return true;
  6255. },
  6256. [&](const char *buf, size_t n) {
  6257. if (is_text_field) {
  6258. auto &content = cur_field->second.content;
  6259. if (content.size() + n > content.max_size()) { return false; }
  6260. content.append(buf, n);
  6261. } else {
  6262. auto &content = cur_file->second.content;
  6263. if (content.size() + n > content.max_size()) { return false; }
  6264. content.append(buf, n);
  6265. }
  6266. return true;
  6267. })) {
  6268. const auto &content_type = req.get_header_value("Content-Type");
  6269. if (!content_type.find("application/x-www-form-urlencoded")) {
  6270. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  6271. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  6272. return false;
  6273. }
  6274. detail::parse_query_text(req.body, req.params);
  6275. }
  6276. return true;
  6277. }
  6278. return false;
  6279. }
  6280. inline bool Server::read_content_with_content_receiver(
  6281. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  6282. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  6283. return read_content_core(strm, req, res, std::move(receiver),
  6284. std::move(multipart_header),
  6285. std::move(multipart_receiver));
  6286. }
  6287. inline bool Server::read_content_core(
  6288. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  6289. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  6290. detail::FormDataParser multipart_form_data_parser;
  6291. ContentReceiverWithProgress out;
  6292. if (req.is_multipart_form_data()) {
  6293. const auto &content_type = req.get_header_value("Content-Type");
  6294. std::string boundary;
  6295. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  6296. res.status = StatusCode::BadRequest_400;
  6297. return false;
  6298. }
  6299. multipart_form_data_parser.set_boundary(std::move(boundary));
  6300. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  6301. return multipart_form_data_parser.parse(buf, n, multipart_header,
  6302. multipart_receiver);
  6303. };
  6304. } else {
  6305. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  6306. size_t /*len*/) { return receiver(buf, n); };
  6307. }
  6308. if (req.method == "DELETE" && !req.has_header("Content-Length")) {
  6309. return true;
  6310. }
  6311. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  6312. out, true)) {
  6313. return false;
  6314. }
  6315. if (req.is_multipart_form_data()) {
  6316. if (!multipart_form_data_parser.is_valid()) {
  6317. res.status = StatusCode::BadRequest_400;
  6318. return false;
  6319. }
  6320. }
  6321. return true;
  6322. }
  6323. inline bool Server::handle_file_request(const Request &req, Response &res) {
  6324. for (const auto &entry : base_dirs_) {
  6325. // Prefix match
  6326. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  6327. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  6328. if (detail::is_valid_path(sub_path)) {
  6329. auto path = entry.base_dir + sub_path;
  6330. if (path.back() == '/') { path += "index.html"; }
  6331. detail::FileStat stat(path);
  6332. if (stat.is_dir()) {
  6333. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  6334. return true;
  6335. }
  6336. if (stat.is_file()) {
  6337. for (const auto &kv : entry.headers) {
  6338. res.set_header(kv.first, kv.second);
  6339. }
  6340. auto mm = std::make_shared<detail::mmap>(path.c_str());
  6341. if (!mm->is_open()) { return false; }
  6342. res.set_content_provider(
  6343. mm->size(),
  6344. detail::find_content_type(path, file_extension_and_mimetype_map_,
  6345. default_file_mimetype_),
  6346. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  6347. sink.write(mm->data() + offset, length);
  6348. return true;
  6349. });
  6350. if (req.method != "HEAD" && file_request_handler_) {
  6351. file_request_handler_(req, res);
  6352. }
  6353. return true;
  6354. }
  6355. }
  6356. }
  6357. }
  6358. return false;
  6359. }
  6360. inline socket_t
  6361. Server::create_server_socket(const std::string &host, int port,
  6362. int socket_flags,
  6363. SocketOptions socket_options) const {
  6364. return detail::create_socket(
  6365. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  6366. ipv6_v6only_, std::move(socket_options),
  6367. [](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  6368. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  6369. return false;
  6370. }
  6371. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; }
  6372. return true;
  6373. });
  6374. }
  6375. inline int Server::bind_internal(const std::string &host, int port,
  6376. int socket_flags) {
  6377. if (is_decommissioned) { return -1; }
  6378. if (!is_valid()) { return -1; }
  6379. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  6380. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  6381. if (port == 0) {
  6382. struct sockaddr_storage addr;
  6383. socklen_t addr_len = sizeof(addr);
  6384. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  6385. &addr_len) == -1) {
  6386. return -1;
  6387. }
  6388. if (addr.ss_family == AF_INET) {
  6389. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  6390. } else if (addr.ss_family == AF_INET6) {
  6391. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  6392. } else {
  6393. return -1;
  6394. }
  6395. } else {
  6396. return port;
  6397. }
  6398. }
  6399. inline bool Server::listen_internal() {
  6400. if (is_decommissioned) { return false; }
  6401. auto ret = true;
  6402. is_running_ = true;
  6403. auto se = detail::scope_exit([&]() { is_running_ = false; });
  6404. {
  6405. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  6406. while (svr_sock_ != INVALID_SOCKET) {
  6407. #ifndef _WIN64
  6408. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  6409. #endif
  6410. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  6411. idle_interval_usec_);
  6412. if (val == 0) { // Timeout
  6413. task_queue->on_idle();
  6414. continue;
  6415. }
  6416. #ifndef _WIN64
  6417. }
  6418. #endif
  6419. #if defined _WIN64
  6420. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  6421. // OVERLAPPED
  6422. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  6423. #elif defined SOCK_CLOEXEC
  6424. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  6425. #else
  6426. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  6427. #endif
  6428. if (sock == INVALID_SOCKET) {
  6429. if (errno == EMFILE) {
  6430. // The per-process limit of open file descriptors has been reached.
  6431. // Try to accept new connections after a short sleep.
  6432. std::this_thread::sleep_for(std::chrono::microseconds{1});
  6433. continue;
  6434. } else if (errno == EINTR || errno == EAGAIN) {
  6435. continue;
  6436. }
  6437. if (svr_sock_ != INVALID_SOCKET) {
  6438. detail::close_socket(svr_sock_);
  6439. ret = false;
  6440. } else {
  6441. ; // The server socket was closed by user.
  6442. }
  6443. break;
  6444. }
  6445. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  6446. read_timeout_sec_, read_timeout_usec_);
  6447. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  6448. write_timeout_sec_, write_timeout_usec_);
  6449. if (!task_queue->enqueue(
  6450. [this, sock]() { process_and_close_socket(sock); })) {
  6451. detail::shutdown_socket(sock);
  6452. detail::close_socket(sock);
  6453. }
  6454. }
  6455. task_queue->shutdown();
  6456. }
  6457. is_decommissioned = !ret;
  6458. return ret;
  6459. }
  6460. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  6461. if (pre_routing_handler_ &&
  6462. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  6463. return true;
  6464. }
  6465. // File handler
  6466. if ((req.method == "GET" || req.method == "HEAD") &&
  6467. handle_file_request(req, res)) {
  6468. return true;
  6469. }
  6470. if (detail::expect_content(req)) {
  6471. // Content reader handler
  6472. {
  6473. ContentReader reader(
  6474. [&](ContentReceiver receiver) {
  6475. return read_content_with_content_receiver(
  6476. strm, req, res, std::move(receiver), nullptr, nullptr);
  6477. },
  6478. [&](FormDataHeader header, ContentReceiver receiver) {
  6479. return read_content_with_content_receiver(strm, req, res, nullptr,
  6480. std::move(header),
  6481. std::move(receiver));
  6482. });
  6483. if (req.method == "POST") {
  6484. if (dispatch_request_for_content_reader(
  6485. req, res, std::move(reader),
  6486. post_handlers_for_content_reader_)) {
  6487. return true;
  6488. }
  6489. } else if (req.method == "PUT") {
  6490. if (dispatch_request_for_content_reader(
  6491. req, res, std::move(reader),
  6492. put_handlers_for_content_reader_)) {
  6493. return true;
  6494. }
  6495. } else if (req.method == "PATCH") {
  6496. if (dispatch_request_for_content_reader(
  6497. req, res, std::move(reader),
  6498. patch_handlers_for_content_reader_)) {
  6499. return true;
  6500. }
  6501. } else if (req.method == "DELETE") {
  6502. if (dispatch_request_for_content_reader(
  6503. req, res, std::move(reader),
  6504. delete_handlers_for_content_reader_)) {
  6505. return true;
  6506. }
  6507. }
  6508. }
  6509. // Read content into `req.body`
  6510. if (!read_content(strm, req, res)) { return false; }
  6511. }
  6512. // Regular handler
  6513. if (req.method == "GET" || req.method == "HEAD") {
  6514. return dispatch_request(req, res, get_handlers_);
  6515. } else if (req.method == "POST") {
  6516. return dispatch_request(req, res, post_handlers_);
  6517. } else if (req.method == "PUT") {
  6518. return dispatch_request(req, res, put_handlers_);
  6519. } else if (req.method == "DELETE") {
  6520. return dispatch_request(req, res, delete_handlers_);
  6521. } else if (req.method == "OPTIONS") {
  6522. return dispatch_request(req, res, options_handlers_);
  6523. } else if (req.method == "PATCH") {
  6524. return dispatch_request(req, res, patch_handlers_);
  6525. }
  6526. res.status = StatusCode::BadRequest_400;
  6527. return false;
  6528. }
  6529. inline bool Server::dispatch_request(Request &req, Response &res,
  6530. const Handlers &handlers) const {
  6531. for (const auto &x : handlers) {
  6532. const auto &matcher = x.first;
  6533. const auto &handler = x.second;
  6534. if (matcher->match(req)) {
  6535. req.matched_route = matcher->pattern();
  6536. if (!pre_request_handler_ ||
  6537. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  6538. handler(req, res);
  6539. }
  6540. return true;
  6541. }
  6542. }
  6543. return false;
  6544. }
  6545. inline void Server::apply_ranges(const Request &req, Response &res,
  6546. std::string &content_type,
  6547. std::string &boundary) const {
  6548. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  6549. auto it = res.headers.find("Content-Type");
  6550. if (it != res.headers.end()) {
  6551. content_type = it->second;
  6552. res.headers.erase(it);
  6553. }
  6554. boundary = detail::make_multipart_data_boundary();
  6555. res.set_header("Content-Type",
  6556. "multipart/byteranges; boundary=" + boundary);
  6557. }
  6558. auto type = detail::encoding_type(req, res);
  6559. if (res.body.empty()) {
  6560. if (res.content_length_ > 0) {
  6561. size_t length = 0;
  6562. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  6563. length = res.content_length_;
  6564. } else if (req.ranges.size() == 1) {
  6565. auto offset_and_length = detail::get_range_offset_and_length(
  6566. req.ranges[0], res.content_length_);
  6567. length = offset_and_length.second;
  6568. auto content_range = detail::make_content_range_header_field(
  6569. offset_and_length, res.content_length_);
  6570. res.set_header("Content-Range", content_range);
  6571. } else {
  6572. length = detail::get_multipart_ranges_data_length(
  6573. req, boundary, content_type, res.content_length_);
  6574. }
  6575. res.set_header("Content-Length", std::to_string(length));
  6576. } else {
  6577. if (res.content_provider_) {
  6578. if (res.is_chunked_content_provider_) {
  6579. res.set_header("Transfer-Encoding", "chunked");
  6580. if (type == detail::EncodingType::Gzip) {
  6581. res.set_header("Content-Encoding", "gzip");
  6582. } else if (type == detail::EncodingType::Brotli) {
  6583. res.set_header("Content-Encoding", "br");
  6584. } else if (type == detail::EncodingType::Zstd) {
  6585. res.set_header("Content-Encoding", "zstd");
  6586. }
  6587. }
  6588. }
  6589. }
  6590. } else {
  6591. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  6592. ;
  6593. } else if (req.ranges.size() == 1) {
  6594. auto offset_and_length =
  6595. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  6596. auto offset = offset_and_length.first;
  6597. auto length = offset_and_length.second;
  6598. auto content_range = detail::make_content_range_header_field(
  6599. offset_and_length, res.body.size());
  6600. res.set_header("Content-Range", content_range);
  6601. assert(offset + length <= res.body.size());
  6602. res.body = res.body.substr(offset, length);
  6603. } else {
  6604. std::string data;
  6605. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  6606. res.body.size(), data);
  6607. res.body.swap(data);
  6608. }
  6609. if (type != detail::EncodingType::None) {
  6610. if (pre_compression_logger_) { pre_compression_logger_(req, res); }
  6611. std::unique_ptr<detail::compressor> compressor;
  6612. std::string content_encoding;
  6613. if (type == detail::EncodingType::Gzip) {
  6614. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6615. compressor = detail::make_unique<detail::gzip_compressor>();
  6616. content_encoding = "gzip";
  6617. #endif
  6618. } else if (type == detail::EncodingType::Brotli) {
  6619. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6620. compressor = detail::make_unique<detail::brotli_compressor>();
  6621. content_encoding = "br";
  6622. #endif
  6623. } else if (type == detail::EncodingType::Zstd) {
  6624. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6625. compressor = detail::make_unique<detail::zstd_compressor>();
  6626. content_encoding = "zstd";
  6627. #endif
  6628. }
  6629. if (compressor) {
  6630. std::string compressed;
  6631. if (compressor->compress(res.body.data(), res.body.size(), true,
  6632. [&](const char *data, size_t data_len) {
  6633. compressed.append(data, data_len);
  6634. return true;
  6635. })) {
  6636. res.body.swap(compressed);
  6637. res.set_header("Content-Encoding", content_encoding);
  6638. }
  6639. }
  6640. }
  6641. auto length = std::to_string(res.body.size());
  6642. res.set_header("Content-Length", length);
  6643. }
  6644. }
  6645. inline bool Server::dispatch_request_for_content_reader(
  6646. Request &req, Response &res, ContentReader content_reader,
  6647. const HandlersForContentReader &handlers) const {
  6648. for (const auto &x : handlers) {
  6649. const auto &matcher = x.first;
  6650. const auto &handler = x.second;
  6651. if (matcher->match(req)) {
  6652. req.matched_route = matcher->pattern();
  6653. if (!pre_request_handler_ ||
  6654. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  6655. handler(req, res, content_reader);
  6656. }
  6657. return true;
  6658. }
  6659. }
  6660. return false;
  6661. }
  6662. inline bool
  6663. Server::process_request(Stream &strm, const std::string &remote_addr,
  6664. int remote_port, const std::string &local_addr,
  6665. int local_port, bool close_connection,
  6666. bool &connection_closed,
  6667. const std::function<void(Request &)> &setup_request) {
  6668. std::array<char, 2048> buf{};
  6669. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  6670. // Connection has been closed on client
  6671. if (!line_reader.getline()) { return false; }
  6672. Request req;
  6673. Response res;
  6674. res.version = "HTTP/1.1";
  6675. res.headers = default_headers_;
  6676. #ifdef __APPLE__
  6677. // Socket file descriptor exceeded FD_SETSIZE...
  6678. if (strm.socket() >= FD_SETSIZE) {
  6679. Headers dummy;
  6680. detail::read_headers(strm, dummy);
  6681. res.status = StatusCode::InternalServerError_500;
  6682. return write_response(strm, close_connection, req, res);
  6683. }
  6684. #endif
  6685. // Request line and headers
  6686. if (!parse_request_line(line_reader.ptr(), req) ||
  6687. !detail::read_headers(strm, req.headers)) {
  6688. res.status = StatusCode::BadRequest_400;
  6689. return write_response(strm, close_connection, req, res);
  6690. }
  6691. // Check if the request URI doesn't exceed the limit
  6692. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  6693. Headers dummy;
  6694. detail::read_headers(strm, dummy);
  6695. res.status = StatusCode::UriTooLong_414;
  6696. return write_response(strm, close_connection, req, res);
  6697. }
  6698. if (req.get_header_value("Connection") == "close") {
  6699. connection_closed = true;
  6700. }
  6701. if (req.version == "HTTP/1.0" &&
  6702. req.get_header_value("Connection") != "Keep-Alive") {
  6703. connection_closed = true;
  6704. }
  6705. req.remote_addr = remote_addr;
  6706. req.remote_port = remote_port;
  6707. req.set_header("REMOTE_ADDR", req.remote_addr);
  6708. req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
  6709. req.local_addr = local_addr;
  6710. req.local_port = local_port;
  6711. req.set_header("LOCAL_ADDR", req.local_addr);
  6712. req.set_header("LOCAL_PORT", std::to_string(req.local_port));
  6713. if (req.has_header("Accept")) {
  6714. const auto &accept_header = req.get_header_value("Accept");
  6715. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  6716. res.status = StatusCode::BadRequest_400;
  6717. return write_response(strm, close_connection, req, res);
  6718. }
  6719. }
  6720. if (req.has_header("Range")) {
  6721. const auto &range_header_value = req.get_header_value("Range");
  6722. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  6723. res.status = StatusCode::RangeNotSatisfiable_416;
  6724. return write_response(strm, close_connection, req, res);
  6725. }
  6726. }
  6727. if (setup_request) { setup_request(req); }
  6728. if (req.get_header_value("Expect") == "100-continue") {
  6729. int status = StatusCode::Continue_100;
  6730. if (expect_100_continue_handler_) {
  6731. status = expect_100_continue_handler_(req, res);
  6732. }
  6733. switch (status) {
  6734. case StatusCode::Continue_100:
  6735. case StatusCode::ExpectationFailed_417:
  6736. detail::write_response_line(strm, status);
  6737. strm.write("\r\n");
  6738. break;
  6739. default:
  6740. connection_closed = true;
  6741. return write_response(strm, true, req, res);
  6742. }
  6743. }
  6744. // Setup `is_connection_closed` method
  6745. auto sock = strm.socket();
  6746. req.is_connection_closed = [sock]() {
  6747. return !detail::is_socket_alive(sock);
  6748. };
  6749. // Routing
  6750. auto routed = false;
  6751. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6752. routed = routing(req, res, strm);
  6753. #else
  6754. try {
  6755. routed = routing(req, res, strm);
  6756. } catch (std::exception &e) {
  6757. if (exception_handler_) {
  6758. auto ep = std::current_exception();
  6759. exception_handler_(req, res, ep);
  6760. routed = true;
  6761. } else {
  6762. res.status = StatusCode::InternalServerError_500;
  6763. std::string val;
  6764. auto s = e.what();
  6765. for (size_t i = 0; s[i]; i++) {
  6766. switch (s[i]) {
  6767. case '\r': val += "\\r"; break;
  6768. case '\n': val += "\\n"; break;
  6769. default: val += s[i]; break;
  6770. }
  6771. }
  6772. res.set_header("EXCEPTION_WHAT", val);
  6773. }
  6774. } catch (...) {
  6775. if (exception_handler_) {
  6776. auto ep = std::current_exception();
  6777. exception_handler_(req, res, ep);
  6778. routed = true;
  6779. } else {
  6780. res.status = StatusCode::InternalServerError_500;
  6781. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  6782. }
  6783. }
  6784. #endif
  6785. if (routed) {
  6786. if (res.status == -1) {
  6787. res.status = req.ranges.empty() ? StatusCode::OK_200
  6788. : StatusCode::PartialContent_206;
  6789. }
  6790. // Serve file content by using a content provider
  6791. if (!res.file_content_path_.empty()) {
  6792. const auto &path = res.file_content_path_;
  6793. auto mm = std::make_shared<detail::mmap>(path.c_str());
  6794. if (!mm->is_open()) {
  6795. res.body.clear();
  6796. res.content_length_ = 0;
  6797. res.content_provider_ = nullptr;
  6798. res.status = StatusCode::NotFound_404;
  6799. return write_response(strm, close_connection, req, res);
  6800. }
  6801. auto content_type = res.file_content_content_type_;
  6802. if (content_type.empty()) {
  6803. content_type = detail::find_content_type(
  6804. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  6805. }
  6806. res.set_content_provider(
  6807. mm->size(), content_type,
  6808. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  6809. sink.write(mm->data() + offset, length);
  6810. return true;
  6811. });
  6812. }
  6813. if (detail::range_error(req, res)) {
  6814. res.body.clear();
  6815. res.content_length_ = 0;
  6816. res.content_provider_ = nullptr;
  6817. res.status = StatusCode::RangeNotSatisfiable_416;
  6818. return write_response(strm, close_connection, req, res);
  6819. }
  6820. return write_response_with_content(strm, close_connection, req, res);
  6821. } else {
  6822. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  6823. return write_response(strm, close_connection, req, res);
  6824. }
  6825. }
  6826. inline bool Server::is_valid() const { return true; }
  6827. inline bool Server::process_and_close_socket(socket_t sock) {
  6828. std::string remote_addr;
  6829. int remote_port = 0;
  6830. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  6831. std::string local_addr;
  6832. int local_port = 0;
  6833. detail::get_local_ip_and_port(sock, local_addr, local_port);
  6834. auto ret = detail::process_server_socket(
  6835. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  6836. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  6837. write_timeout_usec_,
  6838. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  6839. return process_request(strm, remote_addr, remote_port, local_addr,
  6840. local_port, close_connection, connection_closed,
  6841. nullptr);
  6842. });
  6843. detail::shutdown_socket(sock);
  6844. detail::close_socket(sock);
  6845. return ret;
  6846. }
  6847. // HTTP client implementation
  6848. inline ClientImpl::ClientImpl(const std::string &host)
  6849. : ClientImpl(host, 80, std::string(), std::string()) {}
  6850. inline ClientImpl::ClientImpl(const std::string &host, int port)
  6851. : ClientImpl(host, port, std::string(), std::string()) {}
  6852. inline ClientImpl::ClientImpl(const std::string &host, int port,
  6853. const std::string &client_cert_path,
  6854. const std::string &client_key_path)
  6855. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  6856. host_and_port_(adjust_host_string(host_) + ":" + std::to_string(port)),
  6857. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  6858. inline ClientImpl::~ClientImpl() {
  6859. // Wait until all the requests in flight are handled.
  6860. size_t retry_count = 10;
  6861. while (retry_count-- > 0) {
  6862. {
  6863. std::lock_guard<std::mutex> guard(socket_mutex_);
  6864. if (socket_requests_in_flight_ == 0) { break; }
  6865. }
  6866. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  6867. }
  6868. std::lock_guard<std::mutex> guard(socket_mutex_);
  6869. shutdown_socket(socket_);
  6870. close_socket(socket_);
  6871. }
  6872. inline bool ClientImpl::is_valid() const { return true; }
  6873. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  6874. client_cert_path_ = rhs.client_cert_path_;
  6875. client_key_path_ = rhs.client_key_path_;
  6876. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  6877. read_timeout_sec_ = rhs.read_timeout_sec_;
  6878. read_timeout_usec_ = rhs.read_timeout_usec_;
  6879. write_timeout_sec_ = rhs.write_timeout_sec_;
  6880. write_timeout_usec_ = rhs.write_timeout_usec_;
  6881. max_timeout_msec_ = rhs.max_timeout_msec_;
  6882. basic_auth_username_ = rhs.basic_auth_username_;
  6883. basic_auth_password_ = rhs.basic_auth_password_;
  6884. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  6885. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6886. digest_auth_username_ = rhs.digest_auth_username_;
  6887. digest_auth_password_ = rhs.digest_auth_password_;
  6888. #endif
  6889. keep_alive_ = rhs.keep_alive_;
  6890. follow_location_ = rhs.follow_location_;
  6891. path_encode_ = rhs.path_encode_;
  6892. address_family_ = rhs.address_family_;
  6893. tcp_nodelay_ = rhs.tcp_nodelay_;
  6894. ipv6_v6only_ = rhs.ipv6_v6only_;
  6895. socket_options_ = rhs.socket_options_;
  6896. compress_ = rhs.compress_;
  6897. decompress_ = rhs.decompress_;
  6898. interface_ = rhs.interface_;
  6899. proxy_host_ = rhs.proxy_host_;
  6900. proxy_port_ = rhs.proxy_port_;
  6901. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  6902. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  6903. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  6904. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6905. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  6906. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  6907. #endif
  6908. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6909. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  6910. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  6911. ca_cert_store_ = rhs.ca_cert_store_;
  6912. #endif
  6913. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6914. server_certificate_verification_ = rhs.server_certificate_verification_;
  6915. server_hostname_verification_ = rhs.server_hostname_verification_;
  6916. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  6917. #endif
  6918. logger_ = rhs.logger_;
  6919. }
  6920. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  6921. if (!proxy_host_.empty() && proxy_port_ != -1) {
  6922. return detail::create_client_socket(
  6923. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  6924. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  6925. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  6926. write_timeout_sec_, write_timeout_usec_, interface_, error);
  6927. }
  6928. // Check is custom IP specified for host_
  6929. std::string ip;
  6930. auto it = addr_map_.find(host_);
  6931. if (it != addr_map_.end()) { ip = it->second; }
  6932. return detail::create_client_socket(
  6933. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  6934. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  6935. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  6936. write_timeout_usec_, interface_, error);
  6937. }
  6938. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  6939. Error &error) {
  6940. auto sock = create_client_socket(error);
  6941. if (sock == INVALID_SOCKET) { return false; }
  6942. socket.sock = sock;
  6943. return true;
  6944. }
  6945. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  6946. bool /*shutdown_gracefully*/) {
  6947. // If there are any requests in flight from threads other than us, then it's
  6948. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  6949. assert(socket_requests_in_flight_ == 0 ||
  6950. socket_requests_are_from_thread_ == std::this_thread::get_id());
  6951. }
  6952. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  6953. if (socket.sock == INVALID_SOCKET) { return; }
  6954. detail::shutdown_socket(socket.sock);
  6955. }
  6956. inline void ClientImpl::close_socket(Socket &socket) {
  6957. // If there are requests in flight in another thread, usually closing
  6958. // the socket will be fine and they will simply receive an error when
  6959. // using the closed socket, but it is still a bug since rarely the OS
  6960. // may reassign the socket id to be used for a new socket, and then
  6961. // suddenly they will be operating on a live socket that is different
  6962. // than the one they intended!
  6963. assert(socket_requests_in_flight_ == 0 ||
  6964. socket_requests_are_from_thread_ == std::this_thread::get_id());
  6965. // It is also a bug if this happens while SSL is still active
  6966. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6967. assert(socket.ssl == nullptr);
  6968. #endif
  6969. if (socket.sock == INVALID_SOCKET) { return; }
  6970. detail::close_socket(socket.sock);
  6971. socket.sock = INVALID_SOCKET;
  6972. }
  6973. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  6974. Response &res) const {
  6975. std::array<char, 2048> buf{};
  6976. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  6977. if (!line_reader.getline()) { return false; }
  6978. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6979. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  6980. #else
  6981. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  6982. #endif
  6983. std::cmatch m;
  6984. if (!std::regex_match(line_reader.ptr(), m, re)) {
  6985. return req.method == "CONNECT";
  6986. }
  6987. res.version = std::string(m[1]);
  6988. res.status = std::stoi(std::string(m[2]));
  6989. res.reason = std::string(m[3]);
  6990. // Ignore '100 Continue'
  6991. while (res.status == StatusCode::Continue_100) {
  6992. if (!line_reader.getline()) { return false; } // CRLF
  6993. if (!line_reader.getline()) { return false; } // next response line
  6994. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  6995. res.version = std::string(m[1]);
  6996. res.status = std::stoi(std::string(m[2]));
  6997. res.reason = std::string(m[3]);
  6998. }
  6999. return true;
  7000. }
  7001. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  7002. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  7003. auto ret = send_(req, res, error);
  7004. if (error == Error::SSLPeerCouldBeClosed_) {
  7005. assert(!ret);
  7006. ret = send_(req, res, error);
  7007. }
  7008. return ret;
  7009. }
  7010. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  7011. {
  7012. std::lock_guard<std::mutex> guard(socket_mutex_);
  7013. // Set this to false immediately - if it ever gets set to true by the end of
  7014. // the request, we know another thread instructed us to close the socket.
  7015. socket_should_be_closed_when_request_is_done_ = false;
  7016. auto is_alive = false;
  7017. if (socket_.is_open()) {
  7018. is_alive = detail::is_socket_alive(socket_.sock);
  7019. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7020. if (is_alive && is_ssl()) {
  7021. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  7022. is_alive = false;
  7023. }
  7024. }
  7025. #endif
  7026. if (!is_alive) {
  7027. // Attempt to avoid sigpipe by shutting down non-gracefully if it seems
  7028. // like the other side has already closed the connection Also, there
  7029. // cannot be any requests in flight from other threads since we locked
  7030. // request_mutex_, so safe to close everything immediately
  7031. const bool shutdown_gracefully = false;
  7032. shutdown_ssl(socket_, shutdown_gracefully);
  7033. shutdown_socket(socket_);
  7034. close_socket(socket_);
  7035. }
  7036. }
  7037. if (!is_alive) {
  7038. if (!create_and_connect_socket(socket_, error)) { return false; }
  7039. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7040. // TODO: refactoring
  7041. if (is_ssl()) {
  7042. auto &scli = static_cast<SSLClient &>(*this);
  7043. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7044. auto success = false;
  7045. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  7046. error)) {
  7047. return success;
  7048. }
  7049. }
  7050. if (!scli.initialize_ssl(socket_, error)) { return false; }
  7051. }
  7052. #endif
  7053. }
  7054. // Mark the current socket as being in use so that it cannot be closed by
  7055. // anyone else while this request is ongoing, even though we will be
  7056. // releasing the mutex.
  7057. if (socket_requests_in_flight_ > 1) {
  7058. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  7059. }
  7060. socket_requests_in_flight_ += 1;
  7061. socket_requests_are_from_thread_ = std::this_thread::get_id();
  7062. }
  7063. for (const auto &header : default_headers_) {
  7064. if (req.headers.find(header.first) == req.headers.end()) {
  7065. req.headers.insert(header);
  7066. }
  7067. }
  7068. auto ret = false;
  7069. auto close_connection = !keep_alive_;
  7070. auto se = detail::scope_exit([&]() {
  7071. // Briefly lock mutex in order to mark that a request is no longer ongoing
  7072. std::lock_guard<std::mutex> guard(socket_mutex_);
  7073. socket_requests_in_flight_ -= 1;
  7074. if (socket_requests_in_flight_ <= 0) {
  7075. assert(socket_requests_in_flight_ == 0);
  7076. socket_requests_are_from_thread_ = std::thread::id();
  7077. }
  7078. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  7079. !ret) {
  7080. shutdown_ssl(socket_, true);
  7081. shutdown_socket(socket_);
  7082. close_socket(socket_);
  7083. }
  7084. });
  7085. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  7086. return handle_request(strm, req, res, close_connection, error);
  7087. });
  7088. if (!ret) {
  7089. if (error == Error::Success) { error = Error::Unknown; }
  7090. }
  7091. return ret;
  7092. }
  7093. inline Result ClientImpl::send(const Request &req) {
  7094. auto req2 = req;
  7095. return send_(std::move(req2));
  7096. }
  7097. inline Result ClientImpl::send_(Request &&req) {
  7098. auto res = detail::make_unique<Response>();
  7099. auto error = Error::Success;
  7100. auto ret = send(req, *res, error);
  7101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7102. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  7103. last_ssl_error_, last_openssl_error_};
  7104. #else
  7105. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  7106. #endif
  7107. }
  7108. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  7109. Response &res, bool close_connection,
  7110. Error &error) {
  7111. if (req.path.empty()) {
  7112. error = Error::Connection;
  7113. return false;
  7114. }
  7115. auto req_save = req;
  7116. bool ret;
  7117. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  7118. auto req2 = req;
  7119. req2.path = "http://" + host_and_port_ + req.path;
  7120. ret = process_request(strm, req2, res, close_connection, error);
  7121. req = req2;
  7122. req.path = req_save.path;
  7123. } else {
  7124. ret = process_request(strm, req, res, close_connection, error);
  7125. }
  7126. if (!ret) { return false; }
  7127. if (res.get_header_value("Connection") == "close" ||
  7128. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  7129. // TODO this requires a not-entirely-obvious chain of calls to be correct
  7130. // for this to be safe.
  7131. // This is safe to call because handle_request is only called by send_
  7132. // which locks the request mutex during the process. It would be a bug
  7133. // to call it from a different thread since it's a thread-safety issue
  7134. // to do these things to the socket if another thread is using the socket.
  7135. std::lock_guard<std::mutex> guard(socket_mutex_);
  7136. shutdown_ssl(socket_, true);
  7137. shutdown_socket(socket_);
  7138. close_socket(socket_);
  7139. }
  7140. if (300 < res.status && res.status < 400 && follow_location_) {
  7141. req = req_save;
  7142. ret = redirect(req, res, error);
  7143. }
  7144. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7145. if ((res.status == StatusCode::Unauthorized_401 ||
  7146. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  7147. req.authorization_count_ < 5) {
  7148. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  7149. const auto &username =
  7150. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  7151. const auto &password =
  7152. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  7153. if (!username.empty() && !password.empty()) {
  7154. std::map<std::string, std::string> auth;
  7155. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  7156. Request new_req = req;
  7157. new_req.authorization_count_ += 1;
  7158. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  7159. : "Authorization");
  7160. new_req.headers.insert(detail::make_digest_authentication_header(
  7161. req, auth, new_req.authorization_count_, detail::random_string(10),
  7162. username, password, is_proxy));
  7163. Response new_res;
  7164. ret = send(new_req, new_res, error);
  7165. if (ret) { res = new_res; }
  7166. }
  7167. }
  7168. }
  7169. #endif
  7170. return ret;
  7171. }
  7172. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  7173. if (req.redirect_count_ == 0) {
  7174. error = Error::ExceedRedirectCount;
  7175. return false;
  7176. }
  7177. auto location = res.get_header_value("location");
  7178. if (location.empty()) { return false; }
  7179. thread_local const std::regex re(
  7180. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  7181. std::smatch m;
  7182. if (!std::regex_match(location, m, re)) { return false; }
  7183. auto scheme = is_ssl() ? "https" : "http";
  7184. auto next_scheme = m[1].str();
  7185. auto next_host = m[2].str();
  7186. if (next_host.empty()) { next_host = m[3].str(); }
  7187. auto port_str = m[4].str();
  7188. auto next_path = m[5].str();
  7189. auto next_query = m[6].str();
  7190. auto next_port = port_;
  7191. if (!port_str.empty()) {
  7192. next_port = std::stoi(port_str);
  7193. } else if (!next_scheme.empty()) {
  7194. next_port = next_scheme == "https" ? 443 : 80;
  7195. }
  7196. if (next_scheme.empty()) { next_scheme = scheme; }
  7197. if (next_host.empty()) { next_host = host_; }
  7198. if (next_path.empty()) { next_path = "/"; }
  7199. auto path = detail::decode_path(next_path, true) + next_query;
  7200. // Same host redirect - use current client
  7201. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  7202. return detail::redirect(*this, req, res, path, location, error);
  7203. }
  7204. // Cross-host/scheme redirect - create new client with robust setup
  7205. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  7206. path, location, error);
  7207. }
  7208. // New method for robust redirect client creation
  7209. inline bool ClientImpl::create_redirect_client(
  7210. const std::string &scheme, const std::string &host, int port, Request &req,
  7211. Response &res, const std::string &path, const std::string &location,
  7212. Error &error) {
  7213. // Determine if we need SSL
  7214. auto need_ssl = (scheme == "https");
  7215. // Clean up request headers that are host/client specific
  7216. // Remove headers that should not be carried over to new host
  7217. auto headers_to_remove =
  7218. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  7219. for (const auto &header_name : headers_to_remove) {
  7220. auto it = req.headers.find(header_name);
  7221. while (it != req.headers.end()) {
  7222. it = req.headers.erase(it);
  7223. it = req.headers.find(header_name);
  7224. }
  7225. }
  7226. // Create appropriate client type and handle redirect
  7227. if (need_ssl) {
  7228. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7229. // Create SSL client for HTTPS redirect
  7230. SSLClient redirect_client(host, port);
  7231. // Setup basic client configuration first
  7232. setup_redirect_client(redirect_client);
  7233. // SSL-specific configuration for proxy environments
  7234. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7235. // Critical: Disable SSL verification for proxy environments
  7236. redirect_client.enable_server_certificate_verification(false);
  7237. redirect_client.enable_server_hostname_verification(false);
  7238. } else {
  7239. // For direct SSL connections, copy SSL verification settings
  7240. redirect_client.enable_server_certificate_verification(
  7241. server_certificate_verification_);
  7242. redirect_client.enable_server_hostname_verification(
  7243. server_hostname_verification_);
  7244. }
  7245. // Handle CA certificate store and paths if available
  7246. if (ca_cert_store_) { redirect_client.set_ca_cert_store(ca_cert_store_); }
  7247. if (!ca_cert_file_path_.empty()) {
  7248. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  7249. }
  7250. // Client certificates are set through constructor for SSLClient
  7251. // NOTE: SSLClient constructor already takes client_cert_path and
  7252. // client_key_path so we need to create it properly if client certs are
  7253. // needed
  7254. // Execute the redirect
  7255. return detail::redirect(redirect_client, req, res, path, location, error);
  7256. #else
  7257. // SSL not supported - set appropriate error
  7258. error = Error::SSLConnection;
  7259. return false;
  7260. #endif
  7261. } else {
  7262. // HTTP redirect
  7263. ClientImpl redirect_client(host, port);
  7264. // Setup client with robust configuration
  7265. setup_redirect_client(redirect_client);
  7266. // Execute the redirect
  7267. return detail::redirect(redirect_client, req, res, path, location, error);
  7268. }
  7269. }
  7270. // New method for robust client setup (based on basic_manual_redirect.cpp logic)
  7271. template <typename ClientType>
  7272. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  7273. // Copy basic settings first
  7274. client.set_connection_timeout(connection_timeout_sec_);
  7275. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  7276. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  7277. client.set_keep_alive(keep_alive_);
  7278. client.set_follow_location(
  7279. true); // Enable redirects to handle multi-step redirects
  7280. client.set_path_encode(path_encode_);
  7281. client.set_compress(compress_);
  7282. client.set_decompress(decompress_);
  7283. // Copy authentication settings BEFORE proxy setup
  7284. if (!basic_auth_username_.empty()) {
  7285. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  7286. }
  7287. if (!bearer_token_auth_token_.empty()) {
  7288. client.set_bearer_token_auth(bearer_token_auth_token_);
  7289. }
  7290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7291. if (!digest_auth_username_.empty()) {
  7292. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  7293. }
  7294. #endif
  7295. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  7296. // before proxy auth)
  7297. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7298. // First set proxy host and port
  7299. client.set_proxy(proxy_host_, proxy_port_);
  7300. // Then set proxy authentication (order matters!)
  7301. if (!proxy_basic_auth_username_.empty()) {
  7302. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  7303. proxy_basic_auth_password_);
  7304. }
  7305. if (!proxy_bearer_token_auth_token_.empty()) {
  7306. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  7307. }
  7308. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7309. if (!proxy_digest_auth_username_.empty()) {
  7310. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  7311. proxy_digest_auth_password_);
  7312. }
  7313. #endif
  7314. }
  7315. // Copy network and socket settings
  7316. client.set_address_family(address_family_);
  7317. client.set_tcp_nodelay(tcp_nodelay_);
  7318. client.set_ipv6_v6only(ipv6_v6only_);
  7319. if (socket_options_) { client.set_socket_options(socket_options_); }
  7320. if (!interface_.empty()) { client.set_interface(interface_); }
  7321. // Copy logging and headers
  7322. if (logger_) { client.set_logger(logger_); }
  7323. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  7324. // Each new client should generate its own headers based on its target host
  7325. }
  7326. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  7327. const Request &req,
  7328. Error &error) const {
  7329. auto is_shutting_down = []() { return false; };
  7330. if (req.is_chunked_content_provider_) {
  7331. // TODO: Brotli support
  7332. std::unique_ptr<detail::compressor> compressor;
  7333. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7334. if (compress_) {
  7335. compressor = detail::make_unique<detail::gzip_compressor>();
  7336. } else
  7337. #endif
  7338. {
  7339. compressor = detail::make_unique<detail::nocompressor>();
  7340. }
  7341. return detail::write_content_chunked(strm, req.content_provider_,
  7342. is_shutting_down, *compressor, error);
  7343. } else {
  7344. return detail::write_content_with_progress(
  7345. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  7346. req.upload_progress, error);
  7347. }
  7348. }
  7349. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  7350. bool close_connection, Error &error) {
  7351. // Prepare additional headers
  7352. if (close_connection) {
  7353. if (!req.has_header("Connection")) {
  7354. req.set_header("Connection", "close");
  7355. }
  7356. }
  7357. if (!req.has_header("Host")) {
  7358. if (is_ssl()) {
  7359. if (port_ == 443) {
  7360. req.set_header("Host", host_);
  7361. } else {
  7362. req.set_header("Host", host_and_port_);
  7363. }
  7364. } else {
  7365. if (port_ == 80) {
  7366. req.set_header("Host", host_);
  7367. } else {
  7368. req.set_header("Host", host_and_port_);
  7369. }
  7370. }
  7371. }
  7372. if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); }
  7373. if (!req.content_receiver) {
  7374. if (!req.has_header("Accept-Encoding")) {
  7375. std::string accept_encoding;
  7376. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7377. accept_encoding = "br";
  7378. #endif
  7379. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7380. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  7381. accept_encoding += "gzip, deflate";
  7382. #endif
  7383. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7384. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  7385. accept_encoding += "zstd";
  7386. #endif
  7387. req.set_header("Accept-Encoding", accept_encoding);
  7388. }
  7389. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  7390. if (!req.has_header("User-Agent")) {
  7391. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  7392. req.set_header("User-Agent", agent);
  7393. }
  7394. #endif
  7395. };
  7396. if (req.body.empty()) {
  7397. if (req.content_provider_) {
  7398. if (!req.is_chunked_content_provider_) {
  7399. if (!req.has_header("Content-Length")) {
  7400. auto length = std::to_string(req.content_length_);
  7401. req.set_header("Content-Length", length);
  7402. }
  7403. }
  7404. } else {
  7405. if (req.method == "POST" || req.method == "PUT" ||
  7406. req.method == "PATCH") {
  7407. req.set_header("Content-Length", "0");
  7408. }
  7409. }
  7410. } else {
  7411. if (!req.has_header("Content-Type")) {
  7412. req.set_header("Content-Type", "text/plain");
  7413. }
  7414. if (!req.has_header("Content-Length")) {
  7415. auto length = std::to_string(req.body.size());
  7416. req.set_header("Content-Length", length);
  7417. }
  7418. }
  7419. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  7420. if (!req.has_header("Authorization")) {
  7421. req.headers.insert(make_basic_authentication_header(
  7422. basic_auth_username_, basic_auth_password_, false));
  7423. }
  7424. }
  7425. if (!proxy_basic_auth_username_.empty() &&
  7426. !proxy_basic_auth_password_.empty()) {
  7427. if (!req.has_header("Proxy-Authorization")) {
  7428. req.headers.insert(make_basic_authentication_header(
  7429. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  7430. }
  7431. }
  7432. if (!bearer_token_auth_token_.empty()) {
  7433. if (!req.has_header("Authorization")) {
  7434. req.headers.insert(make_bearer_token_authentication_header(
  7435. bearer_token_auth_token_, false));
  7436. }
  7437. }
  7438. if (!proxy_bearer_token_auth_token_.empty()) {
  7439. if (!req.has_header("Proxy-Authorization")) {
  7440. req.headers.insert(make_bearer_token_authentication_header(
  7441. proxy_bearer_token_auth_token_, true));
  7442. }
  7443. }
  7444. // Request line and headers
  7445. {
  7446. detail::BufferStream bstrm;
  7447. const auto &path_with_query =
  7448. req.params.empty() ? req.path
  7449. : append_query_params(req.path, req.params);
  7450. const auto &path =
  7451. path_encode_ ? detail::encode_path(path_with_query) : path_with_query;
  7452. detail::write_request_line(bstrm, req.method, path);
  7453. header_writer_(bstrm, req.headers);
  7454. // Flush buffer
  7455. auto &data = bstrm.get_buffer();
  7456. if (!detail::write_data(strm, data.data(), data.size())) {
  7457. error = Error::Write;
  7458. return false;
  7459. }
  7460. }
  7461. // Body
  7462. if (req.body.empty()) {
  7463. return write_content_with_provider(strm, req, error);
  7464. }
  7465. if (req.upload_progress) {
  7466. auto body_size = req.body.size();
  7467. size_t written = 0;
  7468. auto data = req.body.data();
  7469. while (written < body_size) {
  7470. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  7471. if (!detail::write_data(strm, data + written, to_write)) {
  7472. error = Error::Write;
  7473. return false;
  7474. }
  7475. written += to_write;
  7476. if (!req.upload_progress(written, body_size)) {
  7477. error = Error::Canceled;
  7478. return false;
  7479. }
  7480. }
  7481. } else {
  7482. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  7483. error = Error::Write;
  7484. return false;
  7485. }
  7486. }
  7487. return true;
  7488. }
  7489. inline std::unique_ptr<Response> ClientImpl::send_with_content_provider(
  7490. Request &req, const char *body, size_t content_length,
  7491. ContentProvider content_provider,
  7492. ContentProviderWithoutLength content_provider_without_length,
  7493. const std::string &content_type, Error &error) {
  7494. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7495. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7496. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  7497. #endif
  7498. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7499. if (compress_ && !content_provider_without_length) {
  7500. // TODO: Brotli support
  7501. detail::gzip_compressor compressor;
  7502. if (content_provider) {
  7503. auto ok = true;
  7504. size_t offset = 0;
  7505. DataSink data_sink;
  7506. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  7507. if (ok) {
  7508. auto last = offset + data_len == content_length;
  7509. auto ret = compressor.compress(
  7510. data, data_len, last,
  7511. [&](const char *compressed_data, size_t compressed_data_len) {
  7512. req.body.append(compressed_data, compressed_data_len);
  7513. return true;
  7514. });
  7515. if (ret) {
  7516. offset += data_len;
  7517. } else {
  7518. ok = false;
  7519. }
  7520. }
  7521. return ok;
  7522. };
  7523. while (ok && offset < content_length) {
  7524. if (!content_provider(offset, content_length - offset, data_sink)) {
  7525. error = Error::Canceled;
  7526. return nullptr;
  7527. }
  7528. }
  7529. } else {
  7530. if (!compressor.compress(body, content_length, true,
  7531. [&](const char *data, size_t data_len) {
  7532. req.body.append(data, data_len);
  7533. return true;
  7534. })) {
  7535. error = Error::Compression;
  7536. return nullptr;
  7537. }
  7538. }
  7539. } else
  7540. #endif
  7541. {
  7542. if (content_provider) {
  7543. req.content_length_ = content_length;
  7544. req.content_provider_ = std::move(content_provider);
  7545. req.is_chunked_content_provider_ = false;
  7546. } else if (content_provider_without_length) {
  7547. req.content_length_ = 0;
  7548. req.content_provider_ = detail::ContentProviderAdapter(
  7549. std::move(content_provider_without_length));
  7550. req.is_chunked_content_provider_ = true;
  7551. req.set_header("Transfer-Encoding", "chunked");
  7552. } else {
  7553. req.body.assign(body, content_length);
  7554. }
  7555. }
  7556. auto res = detail::make_unique<Response>();
  7557. return send(req, *res, error) ? std::move(res) : nullptr;
  7558. }
  7559. inline Result ClientImpl::send_with_content_provider(
  7560. const std::string &method, const std::string &path, const Headers &headers,
  7561. const char *body, size_t content_length, ContentProvider content_provider,
  7562. ContentProviderWithoutLength content_provider_without_length,
  7563. const std::string &content_type, UploadProgress progress) {
  7564. Request req;
  7565. req.method = method;
  7566. req.headers = headers;
  7567. req.path = path;
  7568. req.upload_progress = std::move(progress);
  7569. if (max_timeout_msec_ > 0) {
  7570. req.start_time_ = std::chrono::steady_clock::now();
  7571. }
  7572. auto error = Error::Success;
  7573. auto res = send_with_content_provider(
  7574. req, body, content_length, std::move(content_provider),
  7575. std::move(content_provider_without_length), content_type, error);
  7576. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7577. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  7578. last_openssl_error_};
  7579. #else
  7580. return Result{std::move(res), error, std::move(req.headers)};
  7581. #endif
  7582. }
  7583. inline std::string
  7584. ClientImpl::adjust_host_string(const std::string &host) const {
  7585. if (host.find(':') != std::string::npos) { return "[" + host + "]"; }
  7586. return host;
  7587. }
  7588. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  7589. Response &res, bool close_connection,
  7590. Error &error) {
  7591. // Send request
  7592. if (!write_request(strm, req, close_connection, error)) { return false; }
  7593. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7594. if (is_ssl()) {
  7595. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  7596. if (!is_proxy_enabled) {
  7597. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  7598. error = Error::SSLPeerCouldBeClosed_;
  7599. return false;
  7600. }
  7601. }
  7602. }
  7603. #endif
  7604. // Receive response and headers
  7605. if (!read_response_line(strm, req, res) ||
  7606. !detail::read_headers(strm, res.headers)) {
  7607. error = Error::Read;
  7608. return false;
  7609. }
  7610. // Body
  7611. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  7612. req.method != "CONNECT") {
  7613. auto redirect = 300 < res.status && res.status < 400 &&
  7614. res.status != StatusCode::NotModified_304 &&
  7615. follow_location_;
  7616. if (req.response_handler && !redirect) {
  7617. if (!req.response_handler(res)) {
  7618. error = Error::Canceled;
  7619. return false;
  7620. }
  7621. }
  7622. auto out =
  7623. req.content_receiver
  7624. ? static_cast<ContentReceiverWithProgress>(
  7625. [&](const char *buf, size_t n, size_t off, size_t len) {
  7626. if (redirect) { return true; }
  7627. auto ret = req.content_receiver(buf, n, off, len);
  7628. if (!ret) { error = Error::Canceled; }
  7629. return ret;
  7630. })
  7631. : static_cast<ContentReceiverWithProgress>(
  7632. [&](const char *buf, size_t n, size_t /*off*/,
  7633. size_t /*len*/) {
  7634. assert(res.body.size() + n <= res.body.max_size());
  7635. res.body.append(buf, n);
  7636. return true;
  7637. });
  7638. auto progress = [&](size_t current, size_t total) {
  7639. if (!req.download_progress || redirect) { return true; }
  7640. auto ret = req.download_progress(current, total);
  7641. if (!ret) { error = Error::Canceled; }
  7642. return ret;
  7643. };
  7644. if (res.has_header("Content-Length")) {
  7645. if (!req.content_receiver) {
  7646. auto len = res.get_header_value_u64("Content-Length");
  7647. if (len > res.body.max_size()) {
  7648. error = Error::Read;
  7649. return false;
  7650. }
  7651. res.body.reserve(static_cast<size_t>(len));
  7652. }
  7653. }
  7654. if (res.status != StatusCode::NotModified_304) {
  7655. int dummy_status;
  7656. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  7657. dummy_status, std::move(progress),
  7658. std::move(out), decompress_)) {
  7659. if (error != Error::Canceled) { error = Error::Read; }
  7660. return false;
  7661. }
  7662. }
  7663. }
  7664. // Log
  7665. if (logger_) { logger_(req, res); }
  7666. return true;
  7667. }
  7668. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  7669. const std::string &boundary, const UploadFormDataItems &items,
  7670. const FormDataProviderItems &provider_items) const {
  7671. size_t cur_item = 0;
  7672. size_t cur_start = 0;
  7673. // cur_item and cur_start are copied to within the std::function and maintain
  7674. // state between successive calls
  7675. return [&, cur_item, cur_start](size_t offset,
  7676. DataSink &sink) mutable -> bool {
  7677. if (!offset && !items.empty()) {
  7678. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  7679. return true;
  7680. } else if (cur_item < provider_items.size()) {
  7681. if (!cur_start) {
  7682. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  7683. provider_items[cur_item], boundary);
  7684. offset += begin.size();
  7685. cur_start = offset;
  7686. sink.os << begin;
  7687. }
  7688. DataSink cur_sink;
  7689. auto has_data = true;
  7690. cur_sink.write = sink.write;
  7691. cur_sink.done = [&]() { has_data = false; };
  7692. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  7693. return false;
  7694. }
  7695. if (!has_data) {
  7696. sink.os << detail::serialize_multipart_formdata_item_end();
  7697. cur_item++;
  7698. cur_start = 0;
  7699. }
  7700. return true;
  7701. } else {
  7702. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  7703. sink.done();
  7704. return true;
  7705. }
  7706. };
  7707. }
  7708. inline bool ClientImpl::process_socket(
  7709. const Socket &socket,
  7710. std::chrono::time_point<std::chrono::steady_clock> start_time,
  7711. std::function<bool(Stream &strm)> callback) {
  7712. return detail::process_client_socket(
  7713. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  7714. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  7715. }
  7716. inline bool ClientImpl::is_ssl() const { return false; }
  7717. inline Result ClientImpl::Get(const std::string &path,
  7718. DownloadProgress progress) {
  7719. return Get(path, Headers(), std::move(progress));
  7720. }
  7721. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  7722. const Headers &headers,
  7723. DownloadProgress progress) {
  7724. if (params.empty()) { return Get(path, headers); }
  7725. std::string path_with_query = append_query_params(path, params);
  7726. return Get(path_with_query, headers, std::move(progress));
  7727. }
  7728. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  7729. DownloadProgress progress) {
  7730. Request req;
  7731. req.method = "GET";
  7732. req.path = path;
  7733. req.headers = headers;
  7734. req.download_progress = std::move(progress);
  7735. if (max_timeout_msec_ > 0) {
  7736. req.start_time_ = std::chrono::steady_clock::now();
  7737. }
  7738. return send_(std::move(req));
  7739. }
  7740. inline Result ClientImpl::Get(const std::string &path,
  7741. ContentReceiver content_receiver,
  7742. DownloadProgress progress) {
  7743. return Get(path, Headers(), nullptr, std::move(content_receiver),
  7744. std::move(progress));
  7745. }
  7746. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  7747. ContentReceiver content_receiver,
  7748. DownloadProgress progress) {
  7749. return Get(path, headers, nullptr, std::move(content_receiver),
  7750. std::move(progress));
  7751. }
  7752. inline Result ClientImpl::Get(const std::string &path,
  7753. ResponseHandler response_handler,
  7754. ContentReceiver content_receiver,
  7755. DownloadProgress progress) {
  7756. return Get(path, Headers(), std::move(response_handler),
  7757. std::move(content_receiver), std::move(progress));
  7758. }
  7759. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  7760. ResponseHandler response_handler,
  7761. ContentReceiver content_receiver,
  7762. DownloadProgress progress) {
  7763. Request req;
  7764. req.method = "GET";
  7765. req.path = path;
  7766. req.headers = headers;
  7767. req.response_handler = std::move(response_handler);
  7768. req.content_receiver =
  7769. [content_receiver](const char *data, size_t data_length,
  7770. size_t /*offset*/, size_t /*total_length*/) {
  7771. return content_receiver(data, data_length);
  7772. };
  7773. req.download_progress = std::move(progress);
  7774. if (max_timeout_msec_ > 0) {
  7775. req.start_time_ = std::chrono::steady_clock::now();
  7776. }
  7777. return send_(std::move(req));
  7778. }
  7779. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  7780. const Headers &headers,
  7781. ContentReceiver content_receiver,
  7782. DownloadProgress progress) {
  7783. return Get(path, params, headers, nullptr, std::move(content_receiver),
  7784. std::move(progress));
  7785. }
  7786. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  7787. const Headers &headers,
  7788. ResponseHandler response_handler,
  7789. ContentReceiver content_receiver,
  7790. DownloadProgress progress) {
  7791. if (params.empty()) {
  7792. return Get(path, headers, std::move(response_handler),
  7793. std::move(content_receiver), std::move(progress));
  7794. }
  7795. std::string path_with_query = append_query_params(path, params);
  7796. return Get(path_with_query, headers, std::move(response_handler),
  7797. std::move(content_receiver), std::move(progress));
  7798. }
  7799. inline Result ClientImpl::Head(const std::string &path) {
  7800. return Head(path, Headers());
  7801. }
  7802. inline Result ClientImpl::Head(const std::string &path,
  7803. const Headers &headers) {
  7804. Request req;
  7805. req.method = "HEAD";
  7806. req.headers = headers;
  7807. req.path = path;
  7808. if (max_timeout_msec_ > 0) {
  7809. req.start_time_ = std::chrono::steady_clock::now();
  7810. }
  7811. return send_(std::move(req));
  7812. }
  7813. inline Result ClientImpl::Post(const std::string &path) {
  7814. return Post(path, std::string(), std::string());
  7815. }
  7816. inline Result ClientImpl::Post(const std::string &path,
  7817. const Headers &headers) {
  7818. return Post(path, headers, nullptr, 0, std::string());
  7819. }
  7820. inline Result ClientImpl::Post(const std::string &path, const char *body,
  7821. size_t content_length,
  7822. const std::string &content_type,
  7823. UploadProgress progress) {
  7824. return Post(path, Headers(), body, content_length, content_type, progress);
  7825. }
  7826. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  7827. const std::string &content_type,
  7828. UploadProgress progress) {
  7829. return Post(path, Headers(), body, content_type, progress);
  7830. }
  7831. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  7832. return Post(path, Headers(), params);
  7833. }
  7834. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  7835. ContentProvider content_provider,
  7836. const std::string &content_type,
  7837. UploadProgress progress) {
  7838. return Post(path, Headers(), content_length, std::move(content_provider),
  7839. content_type, progress);
  7840. }
  7841. inline Result ClientImpl::Post(const std::string &path,
  7842. ContentProviderWithoutLength content_provider,
  7843. const std::string &content_type,
  7844. UploadProgress progress) {
  7845. return Post(path, Headers(), std::move(content_provider), content_type,
  7846. progress);
  7847. }
  7848. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7849. const Params &params) {
  7850. auto query = detail::params_to_query_str(params);
  7851. return Post(path, headers, query, "application/x-www-form-urlencoded");
  7852. }
  7853. inline Result ClientImpl::Post(const std::string &path,
  7854. const UploadFormDataItems &items,
  7855. UploadProgress progress) {
  7856. return Post(path, Headers(), items, progress);
  7857. }
  7858. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7859. const UploadFormDataItems &items,
  7860. UploadProgress progress) {
  7861. const auto &boundary = detail::make_multipart_data_boundary();
  7862. const auto &content_type =
  7863. detail::serialize_multipart_formdata_get_content_type(boundary);
  7864. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7865. return Post(path, headers, body, content_type, progress);
  7866. }
  7867. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7868. const UploadFormDataItems &items,
  7869. const std::string &boundary,
  7870. UploadProgress progress) {
  7871. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  7872. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  7873. }
  7874. const auto &content_type =
  7875. detail::serialize_multipart_formdata_get_content_type(boundary);
  7876. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7877. return Post(path, headers, body, content_type, progress);
  7878. }
  7879. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7880. const char *body, size_t content_length,
  7881. const std::string &content_type,
  7882. UploadProgress progress) {
  7883. return send_with_content_provider("POST", path, headers, body, content_length,
  7884. nullptr, nullptr, content_type, progress);
  7885. }
  7886. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7887. const std::string &body,
  7888. const std::string &content_type,
  7889. UploadProgress progress) {
  7890. return send_with_content_provider("POST", path, headers, body.data(),
  7891. body.size(), nullptr, nullptr, content_type,
  7892. progress);
  7893. }
  7894. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7895. size_t content_length,
  7896. ContentProvider content_provider,
  7897. const std::string &content_type,
  7898. UploadProgress progress) {
  7899. return send_with_content_provider("POST", path, headers, nullptr,
  7900. content_length, std::move(content_provider),
  7901. nullptr, content_type, progress);
  7902. }
  7903. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7904. ContentProviderWithoutLength content_provider,
  7905. const std::string &content_type,
  7906. UploadProgress progress) {
  7907. return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr,
  7908. std::move(content_provider), content_type,
  7909. progress);
  7910. }
  7911. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7912. const UploadFormDataItems &items,
  7913. const FormDataProviderItems &provider_items,
  7914. UploadProgress progress) {
  7915. const auto &boundary = detail::make_multipart_data_boundary();
  7916. const auto &content_type =
  7917. detail::serialize_multipart_formdata_get_content_type(boundary);
  7918. return send_with_content_provider(
  7919. "POST", path, headers, nullptr, 0, nullptr,
  7920. get_multipart_content_provider(boundary, items, provider_items),
  7921. content_type, progress);
  7922. }
  7923. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7924. const std::string &body,
  7925. const std::string &content_type,
  7926. ContentReceiver content_receiver,
  7927. DownloadProgress progress) {
  7928. Request req;
  7929. req.method = "POST";
  7930. req.path = path;
  7931. req.headers = headers;
  7932. req.body = body;
  7933. req.content_receiver =
  7934. [content_receiver](const char *data, size_t data_length,
  7935. size_t /*offset*/, size_t /*total_length*/) {
  7936. return content_receiver(data, data_length);
  7937. };
  7938. req.download_progress = std::move(progress);
  7939. if (max_timeout_msec_ > 0) {
  7940. req.start_time_ = std::chrono::steady_clock::now();
  7941. }
  7942. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7943. return send_(std::move(req));
  7944. }
  7945. inline Result ClientImpl::Put(const std::string &path) {
  7946. return Put(path, std::string(), std::string());
  7947. }
  7948. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  7949. return Put(path, headers, nullptr, 0, std::string());
  7950. }
  7951. inline Result ClientImpl::Put(const std::string &path, const char *body,
  7952. size_t content_length,
  7953. const std::string &content_type,
  7954. UploadProgress progress) {
  7955. return Put(path, Headers(), body, content_length, content_type, progress);
  7956. }
  7957. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  7958. const std::string &content_type,
  7959. UploadProgress progress) {
  7960. return Put(path, Headers(), body, content_type, progress);
  7961. }
  7962. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  7963. return Put(path, Headers(), params);
  7964. }
  7965. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  7966. ContentProvider content_provider,
  7967. const std::string &content_type,
  7968. UploadProgress progress) {
  7969. return Put(path, Headers(), content_length, std::move(content_provider),
  7970. content_type, progress);
  7971. }
  7972. inline Result ClientImpl::Put(const std::string &path,
  7973. ContentProviderWithoutLength content_provider,
  7974. const std::string &content_type,
  7975. UploadProgress progress) {
  7976. return Put(path, Headers(), std::move(content_provider), content_type,
  7977. progress);
  7978. }
  7979. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7980. const Params &params) {
  7981. auto query = detail::params_to_query_str(params);
  7982. return Put(path, headers, query, "application/x-www-form-urlencoded");
  7983. }
  7984. inline Result ClientImpl::Put(const std::string &path,
  7985. const UploadFormDataItems &items,
  7986. UploadProgress progress) {
  7987. return Put(path, Headers(), items, progress);
  7988. }
  7989. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7990. const UploadFormDataItems &items,
  7991. UploadProgress progress) {
  7992. const auto &boundary = detail::make_multipart_data_boundary();
  7993. const auto &content_type =
  7994. detail::serialize_multipart_formdata_get_content_type(boundary);
  7995. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7996. return Put(path, headers, body, content_type, progress);
  7997. }
  7998. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7999. const UploadFormDataItems &items,
  8000. const std::string &boundary,
  8001. UploadProgress progress) {
  8002. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  8003. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  8004. }
  8005. const auto &content_type =
  8006. detail::serialize_multipart_formdata_get_content_type(boundary);
  8007. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8008. return Put(path, headers, body, content_type, progress);
  8009. }
  8010. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8011. const char *body, size_t content_length,
  8012. const std::string &content_type,
  8013. UploadProgress progress) {
  8014. return send_with_content_provider("PUT", path, headers, body, content_length,
  8015. nullptr, nullptr, content_type, progress);
  8016. }
  8017. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8018. const std::string &body,
  8019. const std::string &content_type,
  8020. UploadProgress progress) {
  8021. return send_with_content_provider("PUT", path, headers, body.data(),
  8022. body.size(), nullptr, nullptr, content_type,
  8023. progress);
  8024. }
  8025. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8026. size_t content_length,
  8027. ContentProvider content_provider,
  8028. const std::string &content_type,
  8029. UploadProgress progress) {
  8030. return send_with_content_provider("PUT", path, headers, nullptr,
  8031. content_length, std::move(content_provider),
  8032. nullptr, content_type, progress);
  8033. }
  8034. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8035. ContentProviderWithoutLength content_provider,
  8036. const std::string &content_type,
  8037. UploadProgress progress) {
  8038. return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr,
  8039. std::move(content_provider), content_type,
  8040. progress);
  8041. }
  8042. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8043. const UploadFormDataItems &items,
  8044. const FormDataProviderItems &provider_items,
  8045. UploadProgress progress) {
  8046. const auto &boundary = detail::make_multipart_data_boundary();
  8047. const auto &content_type =
  8048. detail::serialize_multipart_formdata_get_content_type(boundary);
  8049. return send_with_content_provider(
  8050. "PUT", path, headers, nullptr, 0, nullptr,
  8051. get_multipart_content_provider(boundary, items, provider_items),
  8052. content_type, progress);
  8053. }
  8054. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8055. const std::string &body,
  8056. const std::string &content_type,
  8057. ContentReceiver content_receiver,
  8058. DownloadProgress progress) {
  8059. Request req;
  8060. req.method = "PUT";
  8061. req.path = path;
  8062. req.headers = headers;
  8063. req.body = body;
  8064. req.content_receiver =
  8065. [content_receiver](const char *data, size_t data_length,
  8066. size_t /*offset*/, size_t /*total_length*/) {
  8067. return content_receiver(data, data_length);
  8068. };
  8069. req.download_progress = std::move(progress);
  8070. if (max_timeout_msec_ > 0) {
  8071. req.start_time_ = std::chrono::steady_clock::now();
  8072. }
  8073. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8074. return send_(std::move(req));
  8075. }
  8076. inline Result ClientImpl::Patch(const std::string &path) {
  8077. return Patch(path, std::string(), std::string());
  8078. }
  8079. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8080. UploadProgress progress) {
  8081. return Patch(path, headers, nullptr, 0, std::string(), progress);
  8082. }
  8083. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  8084. size_t content_length,
  8085. const std::string &content_type,
  8086. UploadProgress progress) {
  8087. return Patch(path, Headers(), body, content_length, content_type, progress);
  8088. }
  8089. inline Result ClientImpl::Patch(const std::string &path,
  8090. const std::string &body,
  8091. const std::string &content_type,
  8092. UploadProgress progress) {
  8093. return Patch(path, Headers(), body, content_type, progress);
  8094. }
  8095. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  8096. return Patch(path, Headers(), params);
  8097. }
  8098. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  8099. ContentProvider content_provider,
  8100. const std::string &content_type,
  8101. UploadProgress progress) {
  8102. return Patch(path, Headers(), content_length, std::move(content_provider),
  8103. content_type, progress);
  8104. }
  8105. inline Result ClientImpl::Patch(const std::string &path,
  8106. ContentProviderWithoutLength content_provider,
  8107. const std::string &content_type,
  8108. UploadProgress progress) {
  8109. return Patch(path, Headers(), std::move(content_provider), content_type,
  8110. progress);
  8111. }
  8112. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8113. const Params &params) {
  8114. auto query = detail::params_to_query_str(params);
  8115. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  8116. }
  8117. inline Result ClientImpl::Patch(const std::string &path,
  8118. const UploadFormDataItems &items,
  8119. UploadProgress progress) {
  8120. return Patch(path, Headers(), items, progress);
  8121. }
  8122. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8123. const UploadFormDataItems &items,
  8124. UploadProgress progress) {
  8125. const auto &boundary = detail::make_multipart_data_boundary();
  8126. const auto &content_type =
  8127. detail::serialize_multipart_formdata_get_content_type(boundary);
  8128. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8129. return Patch(path, headers, body, content_type, progress);
  8130. }
  8131. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8132. const UploadFormDataItems &items,
  8133. const std::string &boundary,
  8134. UploadProgress progress) {
  8135. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  8136. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  8137. }
  8138. const auto &content_type =
  8139. detail::serialize_multipart_formdata_get_content_type(boundary);
  8140. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8141. return Patch(path, headers, body, content_type, progress);
  8142. }
  8143. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8144. const char *body, size_t content_length,
  8145. const std::string &content_type,
  8146. UploadProgress progress) {
  8147. return send_with_content_provider("PATCH", path, headers, body,
  8148. content_length, nullptr, nullptr,
  8149. content_type, progress);
  8150. }
  8151. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8152. const std::string &body,
  8153. const std::string &content_type,
  8154. UploadProgress progress) {
  8155. return send_with_content_provider("PATCH", path, headers, body.data(),
  8156. body.size(), nullptr, nullptr, content_type,
  8157. progress);
  8158. }
  8159. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8160. size_t content_length,
  8161. ContentProvider content_provider,
  8162. const std::string &content_type,
  8163. UploadProgress progress) {
  8164. return send_with_content_provider("PATCH", path, headers, nullptr,
  8165. content_length, std::move(content_provider),
  8166. nullptr, content_type, progress);
  8167. }
  8168. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8169. ContentProviderWithoutLength content_provider,
  8170. const std::string &content_type,
  8171. UploadProgress progress) {
  8172. return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr,
  8173. std::move(content_provider), content_type,
  8174. progress);
  8175. }
  8176. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8177. const UploadFormDataItems &items,
  8178. const FormDataProviderItems &provider_items,
  8179. UploadProgress progress) {
  8180. const auto &boundary = detail::make_multipart_data_boundary();
  8181. const auto &content_type =
  8182. detail::serialize_multipart_formdata_get_content_type(boundary);
  8183. return send_with_content_provider(
  8184. "PATCH", path, headers, nullptr, 0, nullptr,
  8185. get_multipart_content_provider(boundary, items, provider_items),
  8186. content_type, progress);
  8187. }
  8188. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8189. const std::string &body,
  8190. const std::string &content_type,
  8191. ContentReceiver content_receiver,
  8192. DownloadProgress progress) {
  8193. Request req;
  8194. req.method = "PATCH";
  8195. req.path = path;
  8196. req.headers = headers;
  8197. req.body = body;
  8198. req.content_receiver =
  8199. [content_receiver](const char *data, size_t data_length,
  8200. size_t /*offset*/, size_t /*total_length*/) {
  8201. return content_receiver(data, data_length);
  8202. };
  8203. req.download_progress = std::move(progress);
  8204. if (max_timeout_msec_ > 0) {
  8205. req.start_time_ = std::chrono::steady_clock::now();
  8206. }
  8207. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8208. return send_(std::move(req));
  8209. }
  8210. inline Result ClientImpl::Delete(const std::string &path,
  8211. DownloadProgress progress) {
  8212. return Delete(path, Headers(), std::string(), std::string(), progress);
  8213. }
  8214. inline Result ClientImpl::Delete(const std::string &path,
  8215. const Headers &headers,
  8216. DownloadProgress progress) {
  8217. return Delete(path, headers, std::string(), std::string(), progress);
  8218. }
  8219. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  8220. size_t content_length,
  8221. const std::string &content_type,
  8222. DownloadProgress progress) {
  8223. return Delete(path, Headers(), body, content_length, content_type, progress);
  8224. }
  8225. inline Result ClientImpl::Delete(const std::string &path,
  8226. const std::string &body,
  8227. const std::string &content_type,
  8228. DownloadProgress progress) {
  8229. return Delete(path, Headers(), body.data(), body.size(), content_type,
  8230. progress);
  8231. }
  8232. inline Result ClientImpl::Delete(const std::string &path,
  8233. const Headers &headers,
  8234. const std::string &body,
  8235. const std::string &content_type,
  8236. DownloadProgress progress) {
  8237. return Delete(path, headers, body.data(), body.size(), content_type,
  8238. progress);
  8239. }
  8240. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  8241. DownloadProgress progress) {
  8242. return Delete(path, Headers(), params, progress);
  8243. }
  8244. inline Result ClientImpl::Delete(const std::string &path,
  8245. const Headers &headers, const Params &params,
  8246. DownloadProgress progress) {
  8247. auto query = detail::params_to_query_str(params);
  8248. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  8249. progress);
  8250. }
  8251. inline Result ClientImpl::Delete(const std::string &path,
  8252. const Headers &headers, const char *body,
  8253. size_t content_length,
  8254. const std::string &content_type,
  8255. DownloadProgress progress) {
  8256. Request req;
  8257. req.method = "DELETE";
  8258. req.headers = headers;
  8259. req.path = path;
  8260. req.download_progress = std::move(progress);
  8261. if (max_timeout_msec_ > 0) {
  8262. req.start_time_ = std::chrono::steady_clock::now();
  8263. }
  8264. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8265. req.body.assign(body, content_length);
  8266. return send_(std::move(req));
  8267. }
  8268. inline Result ClientImpl::Options(const std::string &path) {
  8269. return Options(path, Headers());
  8270. }
  8271. inline Result ClientImpl::Options(const std::string &path,
  8272. const Headers &headers) {
  8273. Request req;
  8274. req.method = "OPTIONS";
  8275. req.headers = headers;
  8276. req.path = path;
  8277. if (max_timeout_msec_ > 0) {
  8278. req.start_time_ = std::chrono::steady_clock::now();
  8279. }
  8280. return send_(std::move(req));
  8281. }
  8282. inline void ClientImpl::stop() {
  8283. std::lock_guard<std::mutex> guard(socket_mutex_);
  8284. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  8285. // do is to shutdown_socket, so that threads using this socket suddenly
  8286. // discover they can't read/write any more and error out. Everything else
  8287. // (closing the socket, shutting ssl down) is unsafe because these actions are
  8288. // not thread-safe.
  8289. if (socket_requests_in_flight_ > 0) {
  8290. shutdown_socket(socket_);
  8291. // Aside from that, we set a flag for the socket to be closed when we're
  8292. // done.
  8293. socket_should_be_closed_when_request_is_done_ = true;
  8294. return;
  8295. }
  8296. // Otherwise, still holding the mutex, we can shut everything down ourselves
  8297. shutdown_ssl(socket_, true);
  8298. shutdown_socket(socket_);
  8299. close_socket(socket_);
  8300. }
  8301. inline std::string ClientImpl::host() const { return host_; }
  8302. inline int ClientImpl::port() const { return port_; }
  8303. inline size_t ClientImpl::is_socket_open() const {
  8304. std::lock_guard<std::mutex> guard(socket_mutex_);
  8305. return socket_.is_open();
  8306. }
  8307. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  8308. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  8309. connection_timeout_sec_ = sec;
  8310. connection_timeout_usec_ = usec;
  8311. }
  8312. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  8313. read_timeout_sec_ = sec;
  8314. read_timeout_usec_ = usec;
  8315. }
  8316. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  8317. write_timeout_sec_ = sec;
  8318. write_timeout_usec_ = usec;
  8319. }
  8320. inline void ClientImpl::set_max_timeout(time_t msec) {
  8321. max_timeout_msec_ = msec;
  8322. }
  8323. inline void ClientImpl::set_basic_auth(const std::string &username,
  8324. const std::string &password) {
  8325. basic_auth_username_ = username;
  8326. basic_auth_password_ = password;
  8327. }
  8328. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  8329. bearer_token_auth_token_ = token;
  8330. }
  8331. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8332. inline void ClientImpl::set_digest_auth(const std::string &username,
  8333. const std::string &password) {
  8334. digest_auth_username_ = username;
  8335. digest_auth_password_ = password;
  8336. }
  8337. #endif
  8338. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  8339. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  8340. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  8341. inline void
  8342. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  8343. addr_map_ = std::move(addr_map);
  8344. }
  8345. inline void ClientImpl::set_default_headers(Headers headers) {
  8346. default_headers_ = std::move(headers);
  8347. }
  8348. inline void ClientImpl::set_header_writer(
  8349. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  8350. header_writer_ = writer;
  8351. }
  8352. inline void ClientImpl::set_address_family(int family) {
  8353. address_family_ = family;
  8354. }
  8355. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  8356. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  8357. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  8358. socket_options_ = std::move(socket_options);
  8359. }
  8360. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  8361. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  8362. inline void ClientImpl::set_interface(const std::string &intf) {
  8363. interface_ = intf;
  8364. }
  8365. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  8366. proxy_host_ = host;
  8367. proxy_port_ = port;
  8368. }
  8369. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  8370. const std::string &password) {
  8371. proxy_basic_auth_username_ = username;
  8372. proxy_basic_auth_password_ = password;
  8373. }
  8374. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  8375. proxy_bearer_token_auth_token_ = token;
  8376. }
  8377. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8378. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  8379. const std::string &password) {
  8380. proxy_digest_auth_username_ = username;
  8381. proxy_digest_auth_password_ = password;
  8382. }
  8383. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  8384. const std::string &ca_cert_dir_path) {
  8385. ca_cert_file_path_ = ca_cert_file_path;
  8386. ca_cert_dir_path_ = ca_cert_dir_path;
  8387. }
  8388. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  8389. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  8390. ca_cert_store_ = ca_cert_store;
  8391. }
  8392. }
  8393. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  8394. std::size_t size) const {
  8395. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  8396. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  8397. if (!mem) { return nullptr; }
  8398. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  8399. if (!inf) { return nullptr; }
  8400. auto cts = X509_STORE_new();
  8401. if (cts) {
  8402. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  8403. auto itmp = sk_X509_INFO_value(inf, i);
  8404. if (!itmp) { continue; }
  8405. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  8406. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  8407. }
  8408. }
  8409. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  8410. return cts;
  8411. }
  8412. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  8413. server_certificate_verification_ = enabled;
  8414. }
  8415. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  8416. server_hostname_verification_ = enabled;
  8417. }
  8418. inline void ClientImpl::set_server_certificate_verifier(
  8419. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  8420. server_certificate_verifier_ = verifier;
  8421. }
  8422. #endif
  8423. inline void ClientImpl::set_logger(Logger logger) {
  8424. logger_ = std::move(logger);
  8425. }
  8426. /*
  8427. * SSL Implementation
  8428. */
  8429. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8430. namespace detail {
  8431. template <typename U, typename V>
  8432. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  8433. U SSL_connect_or_accept, V setup) {
  8434. SSL *ssl = nullptr;
  8435. {
  8436. std::lock_guard<std::mutex> guard(ctx_mutex);
  8437. ssl = SSL_new(ctx);
  8438. }
  8439. if (ssl) {
  8440. set_nonblocking(sock, true);
  8441. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  8442. BIO_set_nbio(bio, 1);
  8443. SSL_set_bio(ssl, bio, bio);
  8444. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  8445. SSL_shutdown(ssl);
  8446. {
  8447. std::lock_guard<std::mutex> guard(ctx_mutex);
  8448. SSL_free(ssl);
  8449. }
  8450. set_nonblocking(sock, false);
  8451. return nullptr;
  8452. }
  8453. BIO_set_nbio(bio, 0);
  8454. set_nonblocking(sock, false);
  8455. }
  8456. return ssl;
  8457. }
  8458. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock,
  8459. bool shutdown_gracefully) {
  8460. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  8461. // the remote has closed the network connection
  8462. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  8463. // best-efforts.
  8464. if (shutdown_gracefully) {
  8465. (void)(sock);
  8466. // SSL_shutdown() returns 0 on first call (indicating close_notify alert
  8467. // sent) and 1 on subsequent call (indicating close_notify alert received)
  8468. if (SSL_shutdown(ssl) == 0) {
  8469. // Expected to return 1, but even if it doesn't, we free ssl
  8470. SSL_shutdown(ssl);
  8471. }
  8472. }
  8473. std::lock_guard<std::mutex> guard(ctx_mutex);
  8474. SSL_free(ssl);
  8475. }
  8476. template <typename U>
  8477. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  8478. U ssl_connect_or_accept,
  8479. time_t timeout_sec, time_t timeout_usec,
  8480. int *ssl_error) {
  8481. auto res = 0;
  8482. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  8483. auto err = SSL_get_error(ssl, res);
  8484. switch (err) {
  8485. case SSL_ERROR_WANT_READ:
  8486. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  8487. break;
  8488. case SSL_ERROR_WANT_WRITE:
  8489. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  8490. break;
  8491. default: break;
  8492. }
  8493. if (ssl_error) { *ssl_error = err; }
  8494. return false;
  8495. }
  8496. return true;
  8497. }
  8498. template <typename T>
  8499. inline bool process_server_socket_ssl(
  8500. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  8501. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  8502. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  8503. time_t write_timeout_usec, T callback) {
  8504. return process_server_socket_core(
  8505. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  8506. [&](bool close_connection, bool &connection_closed) {
  8507. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  8508. write_timeout_sec, write_timeout_usec);
  8509. return callback(strm, close_connection, connection_closed);
  8510. });
  8511. }
  8512. template <typename T>
  8513. inline bool process_client_socket_ssl(
  8514. SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8515. time_t write_timeout_sec, time_t write_timeout_usec,
  8516. time_t max_timeout_msec,
  8517. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  8518. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  8519. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  8520. start_time);
  8521. return callback(strm);
  8522. }
  8523. // SSL socket stream implementation
  8524. inline SSLSocketStream::SSLSocketStream(
  8525. socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
  8526. time_t write_timeout_sec, time_t write_timeout_usec,
  8527. time_t max_timeout_msec,
  8528. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8529. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  8530. read_timeout_usec_(read_timeout_usec),
  8531. write_timeout_sec_(write_timeout_sec),
  8532. write_timeout_usec_(write_timeout_usec),
  8533. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  8534. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  8535. }
  8536. inline SSLSocketStream::~SSLSocketStream() = default;
  8537. inline bool SSLSocketStream::is_readable() const {
  8538. return SSL_pending(ssl_) > 0;
  8539. }
  8540. inline bool SSLSocketStream::wait_readable() const {
  8541. if (max_timeout_msec_ <= 0) {
  8542. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8543. }
  8544. time_t read_timeout_sec;
  8545. time_t read_timeout_usec;
  8546. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8547. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8548. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8549. }
  8550. inline bool SSLSocketStream::wait_writable() const {
  8551. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  8552. is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_);
  8553. }
  8554. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  8555. if (SSL_pending(ssl_) > 0) {
  8556. return SSL_read(ssl_, ptr, static_cast<int>(size));
  8557. } else if (wait_readable()) {
  8558. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  8559. if (ret < 0) {
  8560. auto err = SSL_get_error(ssl_, ret);
  8561. auto n = 1000;
  8562. #ifdef _WIN64
  8563. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  8564. (err == SSL_ERROR_SYSCALL &&
  8565. WSAGetLastError() == WSAETIMEDOUT))) {
  8566. #else
  8567. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  8568. #endif
  8569. if (SSL_pending(ssl_) > 0) {
  8570. return SSL_read(ssl_, ptr, static_cast<int>(size));
  8571. } else if (wait_readable()) {
  8572. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8573. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  8574. if (ret >= 0) { return ret; }
  8575. err = SSL_get_error(ssl_, ret);
  8576. } else {
  8577. break;
  8578. }
  8579. }
  8580. assert(ret < 0);
  8581. }
  8582. return ret;
  8583. } else {
  8584. return -1;
  8585. }
  8586. }
  8587. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  8588. if (wait_writable()) {
  8589. auto handle_size = static_cast<int>(
  8590. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  8591. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  8592. if (ret < 0) {
  8593. auto err = SSL_get_error(ssl_, ret);
  8594. auto n = 1000;
  8595. #ifdef _WIN64
  8596. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  8597. (err == SSL_ERROR_SYSCALL &&
  8598. WSAGetLastError() == WSAETIMEDOUT))) {
  8599. #else
  8600. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  8601. #endif
  8602. if (wait_writable()) {
  8603. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8604. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  8605. if (ret >= 0) { return ret; }
  8606. err = SSL_get_error(ssl_, ret);
  8607. } else {
  8608. break;
  8609. }
  8610. }
  8611. assert(ret < 0);
  8612. }
  8613. return ret;
  8614. }
  8615. return -1;
  8616. }
  8617. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  8618. int &port) const {
  8619. detail::get_remote_ip_and_port(sock_, ip, port);
  8620. }
  8621. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  8622. int &port) const {
  8623. detail::get_local_ip_and_port(sock_, ip, port);
  8624. }
  8625. inline socket_t SSLSocketStream::socket() const { return sock_; }
  8626. inline time_t SSLSocketStream::duration() const {
  8627. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8628. std::chrono::steady_clock::now() - start_time_)
  8629. .count();
  8630. }
  8631. } // namespace detail
  8632. // SSL HTTP server implementation
  8633. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  8634. const char *client_ca_cert_file_path,
  8635. const char *client_ca_cert_dir_path,
  8636. const char *private_key_password) {
  8637. ctx_ = SSL_CTX_new(TLS_server_method());
  8638. if (ctx_) {
  8639. SSL_CTX_set_options(ctx_,
  8640. SSL_OP_NO_COMPRESSION |
  8641. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  8642. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8643. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  8644. SSL_CTX_set_default_passwd_cb_userdata(
  8645. ctx_,
  8646. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  8647. }
  8648. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  8649. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  8650. 1 ||
  8651. SSL_CTX_check_private_key(ctx_) != 1) {
  8652. last_ssl_error_ = static_cast<int>(ERR_get_error());
  8653. SSL_CTX_free(ctx_);
  8654. ctx_ = nullptr;
  8655. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  8656. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  8657. client_ca_cert_dir_path);
  8658. SSL_CTX_set_verify(
  8659. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  8660. }
  8661. }
  8662. }
  8663. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  8664. X509_STORE *client_ca_cert_store) {
  8665. ctx_ = SSL_CTX_new(TLS_server_method());
  8666. if (ctx_) {
  8667. SSL_CTX_set_options(ctx_,
  8668. SSL_OP_NO_COMPRESSION |
  8669. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  8670. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8671. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  8672. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  8673. SSL_CTX_free(ctx_);
  8674. ctx_ = nullptr;
  8675. } else if (client_ca_cert_store) {
  8676. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  8677. SSL_CTX_set_verify(
  8678. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  8679. }
  8680. }
  8681. }
  8682. inline SSLServer::SSLServer(
  8683. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  8684. ctx_ = SSL_CTX_new(TLS_method());
  8685. if (ctx_) {
  8686. if (!setup_ssl_ctx_callback(*ctx_)) {
  8687. SSL_CTX_free(ctx_);
  8688. ctx_ = nullptr;
  8689. }
  8690. }
  8691. }
  8692. inline SSLServer::~SSLServer() {
  8693. if (ctx_) { SSL_CTX_free(ctx_); }
  8694. }
  8695. inline bool SSLServer::is_valid() const { return ctx_; }
  8696. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  8697. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  8698. X509_STORE *client_ca_cert_store) {
  8699. std::lock_guard<std::mutex> guard(ctx_mutex_);
  8700. SSL_CTX_use_certificate(ctx_, cert);
  8701. SSL_CTX_use_PrivateKey(ctx_, private_key);
  8702. if (client_ca_cert_store != nullptr) {
  8703. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  8704. }
  8705. }
  8706. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  8707. auto ssl = detail::ssl_new(
  8708. sock, ctx_, ctx_mutex_,
  8709. [&](SSL *ssl2) {
  8710. return detail::ssl_connect_or_accept_nonblocking(
  8711. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_,
  8712. &last_ssl_error_);
  8713. },
  8714. [](SSL * /*ssl2*/) { return true; });
  8715. auto ret = false;
  8716. if (ssl) {
  8717. std::string remote_addr;
  8718. int remote_port = 0;
  8719. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8720. std::string local_addr;
  8721. int local_port = 0;
  8722. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8723. ret = detail::process_server_socket_ssl(
  8724. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8725. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8726. write_timeout_usec_,
  8727. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8728. return process_request(strm, remote_addr, remote_port, local_addr,
  8729. local_port, close_connection,
  8730. connection_closed,
  8731. [&](Request &req) { req.ssl = ssl; });
  8732. });
  8733. // Shutdown gracefully if the result seemed successful, non-gracefully if
  8734. // the connection appeared to be closed.
  8735. const bool shutdown_gracefully = ret;
  8736. detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
  8737. }
  8738. detail::shutdown_socket(sock);
  8739. detail::close_socket(sock);
  8740. return ret;
  8741. }
  8742. // SSL HTTP client implementation
  8743. inline SSLClient::SSLClient(const std::string &host)
  8744. : SSLClient(host, 443, std::string(), std::string()) {}
  8745. inline SSLClient::SSLClient(const std::string &host, int port)
  8746. : SSLClient(host, port, std::string(), std::string()) {}
  8747. inline SSLClient::SSLClient(const std::string &host, int port,
  8748. const std::string &client_cert_path,
  8749. const std::string &client_key_path,
  8750. const std::string &private_key_password)
  8751. : ClientImpl(host, port, client_cert_path, client_key_path) {
  8752. ctx_ = SSL_CTX_new(TLS_client_method());
  8753. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8754. detail::split(&host_[0], &host_[host_.size()], '.',
  8755. [&](const char *b, const char *e) {
  8756. host_components_.emplace_back(b, e);
  8757. });
  8758. if (!client_cert_path.empty() && !client_key_path.empty()) {
  8759. if (!private_key_password.empty()) {
  8760. SSL_CTX_set_default_passwd_cb_userdata(
  8761. ctx_, reinterpret_cast<void *>(
  8762. const_cast<char *>(private_key_password.c_str())));
  8763. }
  8764. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  8765. SSL_FILETYPE_PEM) != 1 ||
  8766. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  8767. SSL_FILETYPE_PEM) != 1) {
  8768. last_openssl_error_ = ERR_get_error();
  8769. SSL_CTX_free(ctx_);
  8770. ctx_ = nullptr;
  8771. }
  8772. }
  8773. }
  8774. inline SSLClient::SSLClient(const std::string &host, int port,
  8775. X509 *client_cert, EVP_PKEY *client_key,
  8776. const std::string &private_key_password)
  8777. : ClientImpl(host, port) {
  8778. ctx_ = SSL_CTX_new(TLS_client_method());
  8779. detail::split(&host_[0], &host_[host_.size()], '.',
  8780. [&](const char *b, const char *e) {
  8781. host_components_.emplace_back(b, e);
  8782. });
  8783. if (client_cert != nullptr && client_key != nullptr) {
  8784. if (!private_key_password.empty()) {
  8785. SSL_CTX_set_default_passwd_cb_userdata(
  8786. ctx_, reinterpret_cast<void *>(
  8787. const_cast<char *>(private_key_password.c_str())));
  8788. }
  8789. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  8790. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  8791. last_openssl_error_ = ERR_get_error();
  8792. SSL_CTX_free(ctx_);
  8793. ctx_ = nullptr;
  8794. }
  8795. }
  8796. }
  8797. inline SSLClient::~SSLClient() {
  8798. if (ctx_) { SSL_CTX_free(ctx_); }
  8799. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  8800. // base function rather than the derived function once we get to the
  8801. // base class destructor, and won't free the SSL (causing a leak).
  8802. shutdown_ssl_impl(socket_, true);
  8803. }
  8804. inline bool SSLClient::is_valid() const { return ctx_; }
  8805. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  8806. if (ca_cert_store) {
  8807. if (ctx_) {
  8808. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  8809. // Free memory allocated for old cert and use new store `ca_cert_store`
  8810. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  8811. }
  8812. } else {
  8813. X509_STORE_free(ca_cert_store);
  8814. }
  8815. }
  8816. }
  8817. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  8818. std::size_t size) {
  8819. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  8820. }
  8821. inline long SSLClient::get_openssl_verify_result() const {
  8822. return verify_result_;
  8823. }
  8824. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  8825. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  8826. return is_valid() && ClientImpl::create_and_connect_socket(socket, error);
  8827. }
  8828. // Assumes that socket_mutex_ is locked and that there are no requests in flight
  8829. inline bool SSLClient::connect_with_proxy(
  8830. Socket &socket,
  8831. std::chrono::time_point<std::chrono::steady_clock> start_time,
  8832. Response &res, bool &success, Error &error) {
  8833. success = true;
  8834. Response proxy_res;
  8835. if (!detail::process_client_socket(
  8836. socket.sock, read_timeout_sec_, read_timeout_usec_,
  8837. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  8838. start_time, [&](Stream &strm) {
  8839. Request req2;
  8840. req2.method = "CONNECT";
  8841. req2.path = host_and_port_;
  8842. if (max_timeout_msec_ > 0) {
  8843. req2.start_time_ = std::chrono::steady_clock::now();
  8844. }
  8845. return process_request(strm, req2, proxy_res, false, error);
  8846. })) {
  8847. // Thread-safe to close everything because we are assuming there are no
  8848. // requests in flight
  8849. shutdown_ssl(socket, true);
  8850. shutdown_socket(socket);
  8851. close_socket(socket);
  8852. success = false;
  8853. return false;
  8854. }
  8855. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  8856. if (!proxy_digest_auth_username_.empty() &&
  8857. !proxy_digest_auth_password_.empty()) {
  8858. std::map<std::string, std::string> auth;
  8859. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  8860. // Close the current socket and create a new one for the authenticated
  8861. // request
  8862. shutdown_ssl(socket, true);
  8863. shutdown_socket(socket);
  8864. close_socket(socket);
  8865. // Create a new socket for the authenticated CONNECT request
  8866. if (!create_and_connect_socket(socket, error)) {
  8867. success = false;
  8868. return false;
  8869. }
  8870. proxy_res = Response();
  8871. if (!detail::process_client_socket(
  8872. socket.sock, read_timeout_sec_, read_timeout_usec_,
  8873. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  8874. start_time, [&](Stream &strm) {
  8875. Request req3;
  8876. req3.method = "CONNECT";
  8877. req3.path = host_and_port_;
  8878. req3.headers.insert(detail::make_digest_authentication_header(
  8879. req3, auth, 1, detail::random_string(10),
  8880. proxy_digest_auth_username_, proxy_digest_auth_password_,
  8881. true));
  8882. if (max_timeout_msec_ > 0) {
  8883. req3.start_time_ = std::chrono::steady_clock::now();
  8884. }
  8885. return process_request(strm, req3, proxy_res, false, error);
  8886. })) {
  8887. // Thread-safe to close everything because we are assuming there are
  8888. // no requests in flight
  8889. shutdown_ssl(socket, true);
  8890. shutdown_socket(socket);
  8891. close_socket(socket);
  8892. success = false;
  8893. return false;
  8894. }
  8895. }
  8896. }
  8897. }
  8898. // If status code is not 200, proxy request is failed.
  8899. // Set error to ProxyConnection and return proxy response
  8900. // as the response of the request
  8901. if (proxy_res.status != StatusCode::OK_200) {
  8902. error = Error::ProxyConnection;
  8903. res = std::move(proxy_res);
  8904. // Thread-safe to close everything because we are assuming there are
  8905. // no requests in flight
  8906. shutdown_ssl(socket, true);
  8907. shutdown_socket(socket);
  8908. close_socket(socket);
  8909. return false;
  8910. }
  8911. return true;
  8912. }
  8913. inline bool SSLClient::load_certs() {
  8914. auto ret = true;
  8915. std::call_once(initialize_cert_, [&]() {
  8916. std::lock_guard<std::mutex> guard(ctx_mutex_);
  8917. if (!ca_cert_file_path_.empty()) {
  8918. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  8919. nullptr)) {
  8920. last_openssl_error_ = ERR_get_error();
  8921. ret = false;
  8922. }
  8923. } else if (!ca_cert_dir_path_.empty()) {
  8924. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  8925. ca_cert_dir_path_.c_str())) {
  8926. last_openssl_error_ = ERR_get_error();
  8927. ret = false;
  8928. }
  8929. } else {
  8930. auto loaded = false;
  8931. #ifdef _WIN64
  8932. loaded =
  8933. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  8934. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  8935. defined(TARGET_OS_OSX)
  8936. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  8937. #endif // _WIN64
  8938. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  8939. }
  8940. });
  8941. return ret;
  8942. }
  8943. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  8944. auto ssl = detail::ssl_new(
  8945. socket.sock, ctx_, ctx_mutex_,
  8946. [&](SSL *ssl2) {
  8947. if (server_certificate_verification_) {
  8948. if (!load_certs()) {
  8949. error = Error::SSLLoadingCerts;
  8950. return false;
  8951. }
  8952. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  8953. }
  8954. if (!detail::ssl_connect_or_accept_nonblocking(
  8955. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  8956. connection_timeout_usec_, &last_ssl_error_)) {
  8957. error = Error::SSLConnection;
  8958. return false;
  8959. }
  8960. if (server_certificate_verification_) {
  8961. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  8962. if (server_certificate_verifier_) {
  8963. verification_status = server_certificate_verifier_(ssl2);
  8964. }
  8965. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  8966. last_openssl_error_ = ERR_get_error();
  8967. error = Error::SSLServerVerification;
  8968. return false;
  8969. }
  8970. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  8971. verify_result_ = SSL_get_verify_result(ssl2);
  8972. if (verify_result_ != X509_V_OK) {
  8973. last_openssl_error_ = static_cast<unsigned long>(verify_result_);
  8974. error = Error::SSLServerVerification;
  8975. return false;
  8976. }
  8977. auto server_cert = SSL_get1_peer_certificate(ssl2);
  8978. auto se = detail::scope_exit([&] { X509_free(server_cert); });
  8979. if (server_cert == nullptr) {
  8980. last_openssl_error_ = ERR_get_error();
  8981. error = Error::SSLServerVerification;
  8982. return false;
  8983. }
  8984. if (server_hostname_verification_) {
  8985. if (!verify_host(server_cert)) {
  8986. last_openssl_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  8987. error = Error::SSLServerHostnameVerification;
  8988. return false;
  8989. }
  8990. }
  8991. }
  8992. }
  8993. return true;
  8994. },
  8995. [&](SSL *ssl2) {
  8996. #if defined(OPENSSL_IS_BORINGSSL)
  8997. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  8998. #else
  8999. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  9000. // -Wold-style-cast warning
  9001. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  9002. static_cast<void *>(const_cast<char *>(host_.c_str())));
  9003. #endif
  9004. return true;
  9005. });
  9006. if (ssl) {
  9007. socket.ssl = ssl;
  9008. return true;
  9009. }
  9010. shutdown_socket(socket);
  9011. close_socket(socket);
  9012. return false;
  9013. }
  9014. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  9015. shutdown_ssl_impl(socket, shutdown_gracefully);
  9016. }
  9017. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  9018. bool shutdown_gracefully) {
  9019. if (socket.sock == INVALID_SOCKET) {
  9020. assert(socket.ssl == nullptr);
  9021. return;
  9022. }
  9023. if (socket.ssl) {
  9024. detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock,
  9025. shutdown_gracefully);
  9026. socket.ssl = nullptr;
  9027. }
  9028. assert(socket.ssl == nullptr);
  9029. }
  9030. inline bool SSLClient::process_socket(
  9031. const Socket &socket,
  9032. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9033. std::function<bool(Stream &strm)> callback) {
  9034. assert(socket.ssl);
  9035. return detail::process_client_socket_ssl(
  9036. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  9037. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  9038. std::move(callback));
  9039. }
  9040. inline bool SSLClient::is_ssl() const { return true; }
  9041. inline bool SSLClient::verify_host(X509 *server_cert) const {
  9042. /* Quote from RFC2818 section 3.1 "Server Identity"
  9043. If a subjectAltName extension of type dNSName is present, that MUST
  9044. be used as the identity. Otherwise, the (most specific) Common Name
  9045. field in the Subject field of the certificate MUST be used. Although
  9046. the use of the Common Name is existing practice, it is deprecated and
  9047. Certification Authorities are encouraged to use the dNSName instead.
  9048. Matching is performed using the matching rules specified by
  9049. [RFC2459]. If more than one identity of a given type is present in
  9050. the certificate (e.g., more than one dNSName name, a match in any one
  9051. of the set is considered acceptable.) Names may contain the wildcard
  9052. character * which is considered to match any single domain name
  9053. component or component fragment. E.g., *.a.com matches foo.a.com but
  9054. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  9055. In some cases, the URI is specified as an IP address rather than a
  9056. hostname. In this case, the iPAddress subjectAltName must be present
  9057. in the certificate and must exactly match the IP in the URI.
  9058. */
  9059. return verify_host_with_subject_alt_name(server_cert) ||
  9060. verify_host_with_common_name(server_cert);
  9061. }
  9062. inline bool
  9063. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  9064. auto ret = false;
  9065. auto type = GEN_DNS;
  9066. struct in6_addr addr6 = {};
  9067. struct in_addr addr = {};
  9068. size_t addr_len = 0;
  9069. #ifndef __MINGW32__
  9070. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  9071. type = GEN_IPADD;
  9072. addr_len = sizeof(struct in6_addr);
  9073. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  9074. type = GEN_IPADD;
  9075. addr_len = sizeof(struct in_addr);
  9076. }
  9077. #endif
  9078. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  9079. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  9080. if (alt_names) {
  9081. auto dsn_matched = false;
  9082. auto ip_matched = false;
  9083. auto count = sk_GENERAL_NAME_num(alt_names);
  9084. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  9085. auto val = sk_GENERAL_NAME_value(alt_names, i);
  9086. if (val->type == type) {
  9087. auto name =
  9088. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  9089. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  9090. switch (type) {
  9091. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  9092. case GEN_IPADD:
  9093. if (!memcmp(&addr6, name, addr_len) ||
  9094. !memcmp(&addr, name, addr_len)) {
  9095. ip_matched = true;
  9096. }
  9097. break;
  9098. }
  9099. }
  9100. }
  9101. if (dsn_matched || ip_matched) { ret = true; }
  9102. }
  9103. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  9104. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  9105. return ret;
  9106. }
  9107. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  9108. const auto subject_name = X509_get_subject_name(server_cert);
  9109. if (subject_name != nullptr) {
  9110. char name[BUFSIZ];
  9111. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  9112. name, sizeof(name));
  9113. if (name_len != -1) {
  9114. return check_host_name(name, static_cast<size_t>(name_len));
  9115. }
  9116. }
  9117. return false;
  9118. }
  9119. inline bool SSLClient::check_host_name(const char *pattern,
  9120. size_t pattern_len) const {
  9121. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  9122. // Wildcard match
  9123. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  9124. std::vector<std::string> pattern_components;
  9125. detail::split(&pattern[0], &pattern[pattern_len], '.',
  9126. [&](const char *b, const char *e) {
  9127. pattern_components.emplace_back(b, e);
  9128. });
  9129. if (host_components_.size() != pattern_components.size()) { return false; }
  9130. auto itr = pattern_components.begin();
  9131. for (const auto &h : host_components_) {
  9132. auto &p = *itr;
  9133. if (p != h && p != "*") {
  9134. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  9135. !p.compare(0, p.size() - 1, h));
  9136. if (!partial_match) { return false; }
  9137. }
  9138. ++itr;
  9139. }
  9140. return true;
  9141. }
  9142. #endif
  9143. // Universal client implementation
  9144. inline Client::Client(const std::string &scheme_host_port)
  9145. : Client(scheme_host_port, std::string(), std::string()) {}
  9146. inline Client::Client(const std::string &scheme_host_port,
  9147. const std::string &client_cert_path,
  9148. const std::string &client_key_path) {
  9149. const static std::regex re(
  9150. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  9151. std::smatch m;
  9152. if (std::regex_match(scheme_host_port, m, re)) {
  9153. auto scheme = m[1].str();
  9154. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9155. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  9156. #else
  9157. if (!scheme.empty() && scheme != "http") {
  9158. #endif
  9159. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9160. std::string msg = "'" + scheme + "' scheme is not supported.";
  9161. throw std::invalid_argument(msg);
  9162. #endif
  9163. return;
  9164. }
  9165. auto is_ssl = scheme == "https";
  9166. auto host = m[2].str();
  9167. if (host.empty()) { host = m[3].str(); }
  9168. auto port_str = m[4].str();
  9169. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  9170. if (is_ssl) {
  9171. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9172. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  9173. client_key_path);
  9174. is_ssl_ = is_ssl;
  9175. #endif
  9176. } else {
  9177. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  9178. client_key_path);
  9179. }
  9180. } else {
  9181. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  9182. // if port param below changes.
  9183. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  9184. client_cert_path, client_key_path);
  9185. }
  9186. } // namespace detail
  9187. inline Client::Client(const std::string &host, int port)
  9188. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  9189. inline Client::Client(const std::string &host, int port,
  9190. const std::string &client_cert_path,
  9191. const std::string &client_key_path)
  9192. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  9193. client_key_path)) {}
  9194. inline Client::~Client() = default;
  9195. inline bool Client::is_valid() const {
  9196. return cli_ != nullptr && cli_->is_valid();
  9197. }
  9198. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  9199. return cli_->Get(path, std::move(progress));
  9200. }
  9201. inline Result Client::Get(const std::string &path, const Headers &headers,
  9202. DownloadProgress progress) {
  9203. return cli_->Get(path, headers, std::move(progress));
  9204. }
  9205. inline Result Client::Get(const std::string &path,
  9206. ContentReceiver content_receiver,
  9207. DownloadProgress progress) {
  9208. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  9209. }
  9210. inline Result Client::Get(const std::string &path, const Headers &headers,
  9211. ContentReceiver content_receiver,
  9212. DownloadProgress progress) {
  9213. return cli_->Get(path, headers, std::move(content_receiver),
  9214. std::move(progress));
  9215. }
  9216. inline Result Client::Get(const std::string &path,
  9217. ResponseHandler response_handler,
  9218. ContentReceiver content_receiver,
  9219. DownloadProgress progress) {
  9220. return cli_->Get(path, std::move(response_handler),
  9221. std::move(content_receiver), std::move(progress));
  9222. }
  9223. inline Result Client::Get(const std::string &path, const Headers &headers,
  9224. ResponseHandler response_handler,
  9225. ContentReceiver content_receiver,
  9226. DownloadProgress progress) {
  9227. return cli_->Get(path, headers, std::move(response_handler),
  9228. std::move(content_receiver), std::move(progress));
  9229. }
  9230. inline Result Client::Get(const std::string &path, const Params &params,
  9231. const Headers &headers, DownloadProgress progress) {
  9232. return cli_->Get(path, params, headers, std::move(progress));
  9233. }
  9234. inline Result Client::Get(const std::string &path, const Params &params,
  9235. const Headers &headers,
  9236. ContentReceiver content_receiver,
  9237. DownloadProgress progress) {
  9238. return cli_->Get(path, params, headers, std::move(content_receiver),
  9239. std::move(progress));
  9240. }
  9241. inline Result Client::Get(const std::string &path, const Params &params,
  9242. const Headers &headers,
  9243. ResponseHandler response_handler,
  9244. ContentReceiver content_receiver,
  9245. DownloadProgress progress) {
  9246. return cli_->Get(path, params, headers, std::move(response_handler),
  9247. std::move(content_receiver), std::move(progress));
  9248. }
  9249. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  9250. inline Result Client::Head(const std::string &path, const Headers &headers) {
  9251. return cli_->Head(path, headers);
  9252. }
  9253. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  9254. inline Result Client::Post(const std::string &path, const Headers &headers) {
  9255. return cli_->Post(path, headers);
  9256. }
  9257. inline Result Client::Post(const std::string &path, const char *body,
  9258. size_t content_length,
  9259. const std::string &content_type,
  9260. UploadProgress progress) {
  9261. return cli_->Post(path, body, content_length, content_type, progress);
  9262. }
  9263. inline Result Client::Post(const std::string &path, const Headers &headers,
  9264. const char *body, size_t content_length,
  9265. const std::string &content_type,
  9266. UploadProgress progress) {
  9267. return cli_->Post(path, headers, body, content_length, content_type,
  9268. progress);
  9269. }
  9270. inline Result Client::Post(const std::string &path, const std::string &body,
  9271. const std::string &content_type,
  9272. UploadProgress progress) {
  9273. return cli_->Post(path, body, content_type, progress);
  9274. }
  9275. inline Result Client::Post(const std::string &path, const Headers &headers,
  9276. const std::string &body,
  9277. const std::string &content_type,
  9278. UploadProgress progress) {
  9279. return cli_->Post(path, headers, body, content_type, progress);
  9280. }
  9281. inline Result Client::Post(const std::string &path, size_t content_length,
  9282. ContentProvider content_provider,
  9283. const std::string &content_type,
  9284. UploadProgress progress) {
  9285. return cli_->Post(path, content_length, std::move(content_provider),
  9286. content_type, progress);
  9287. }
  9288. inline Result Client::Post(const std::string &path,
  9289. ContentProviderWithoutLength content_provider,
  9290. const std::string &content_type,
  9291. UploadProgress progress) {
  9292. return cli_->Post(path, std::move(content_provider), content_type, progress);
  9293. }
  9294. inline Result Client::Post(const std::string &path, const Headers &headers,
  9295. size_t content_length,
  9296. ContentProvider content_provider,
  9297. const std::string &content_type,
  9298. UploadProgress progress) {
  9299. return cli_->Post(path, headers, content_length, std::move(content_provider),
  9300. content_type, progress);
  9301. }
  9302. inline Result Client::Post(const std::string &path, const Headers &headers,
  9303. ContentProviderWithoutLength content_provider,
  9304. const std::string &content_type,
  9305. UploadProgress progress) {
  9306. return cli_->Post(path, headers, std::move(content_provider), content_type,
  9307. progress);
  9308. }
  9309. inline Result Client::Post(const std::string &path, const Params &params) {
  9310. return cli_->Post(path, params);
  9311. }
  9312. inline Result Client::Post(const std::string &path, const Headers &headers,
  9313. const Params &params) {
  9314. return cli_->Post(path, headers, params);
  9315. }
  9316. inline Result Client::Post(const std::string &path,
  9317. const UploadFormDataItems &items,
  9318. UploadProgress progress) {
  9319. return cli_->Post(path, items, progress);
  9320. }
  9321. inline Result Client::Post(const std::string &path, const Headers &headers,
  9322. const UploadFormDataItems &items,
  9323. UploadProgress progress) {
  9324. return cli_->Post(path, headers, items, progress);
  9325. }
  9326. inline Result Client::Post(const std::string &path, const Headers &headers,
  9327. const UploadFormDataItems &items,
  9328. const std::string &boundary,
  9329. UploadProgress progress) {
  9330. return cli_->Post(path, headers, items, boundary, progress);
  9331. }
  9332. inline Result Client::Post(const std::string &path, const Headers &headers,
  9333. const UploadFormDataItems &items,
  9334. const FormDataProviderItems &provider_items,
  9335. UploadProgress progress) {
  9336. return cli_->Post(path, headers, items, provider_items, progress);
  9337. }
  9338. inline Result Client::Post(const std::string &path, const Headers &headers,
  9339. const std::string &body,
  9340. const std::string &content_type,
  9341. ContentReceiver content_receiver,
  9342. DownloadProgress progress) {
  9343. return cli_->Post(path, headers, body, content_type, content_receiver,
  9344. progress);
  9345. }
  9346. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  9347. inline Result Client::Put(const std::string &path, const Headers &headers) {
  9348. return cli_->Put(path, headers);
  9349. }
  9350. inline Result Client::Put(const std::string &path, const char *body,
  9351. size_t content_length,
  9352. const std::string &content_type,
  9353. UploadProgress progress) {
  9354. return cli_->Put(path, body, content_length, content_type, progress);
  9355. }
  9356. inline Result Client::Put(const std::string &path, const Headers &headers,
  9357. const char *body, size_t content_length,
  9358. const std::string &content_type,
  9359. UploadProgress progress) {
  9360. return cli_->Put(path, headers, body, content_length, content_type, progress);
  9361. }
  9362. inline Result Client::Put(const std::string &path, const std::string &body,
  9363. const std::string &content_type,
  9364. UploadProgress progress) {
  9365. return cli_->Put(path, body, content_type, progress);
  9366. }
  9367. inline Result Client::Put(const std::string &path, const Headers &headers,
  9368. const std::string &body,
  9369. const std::string &content_type,
  9370. UploadProgress progress) {
  9371. return cli_->Put(path, headers, body, content_type, progress);
  9372. }
  9373. inline Result Client::Put(const std::string &path, size_t content_length,
  9374. ContentProvider content_provider,
  9375. const std::string &content_type,
  9376. UploadProgress progress) {
  9377. return cli_->Put(path, content_length, std::move(content_provider),
  9378. content_type, progress);
  9379. }
  9380. inline Result Client::Put(const std::string &path,
  9381. ContentProviderWithoutLength content_provider,
  9382. const std::string &content_type,
  9383. UploadProgress progress) {
  9384. return cli_->Put(path, std::move(content_provider), content_type, progress);
  9385. }
  9386. inline Result Client::Put(const std::string &path, const Headers &headers,
  9387. size_t content_length,
  9388. ContentProvider content_provider,
  9389. const std::string &content_type,
  9390. UploadProgress progress) {
  9391. return cli_->Put(path, headers, content_length, std::move(content_provider),
  9392. content_type, progress);
  9393. }
  9394. inline Result Client::Put(const std::string &path, const Headers &headers,
  9395. ContentProviderWithoutLength content_provider,
  9396. const std::string &content_type,
  9397. UploadProgress progress) {
  9398. return cli_->Put(path, headers, std::move(content_provider), content_type,
  9399. progress);
  9400. }
  9401. inline Result Client::Put(const std::string &path, const Params &params) {
  9402. return cli_->Put(path, params);
  9403. }
  9404. inline Result Client::Put(const std::string &path, const Headers &headers,
  9405. const Params &params) {
  9406. return cli_->Put(path, headers, params);
  9407. }
  9408. inline Result Client::Put(const std::string &path,
  9409. const UploadFormDataItems &items,
  9410. UploadProgress progress) {
  9411. return cli_->Put(path, items, progress);
  9412. }
  9413. inline Result Client::Put(const std::string &path, const Headers &headers,
  9414. const UploadFormDataItems &items,
  9415. UploadProgress progress) {
  9416. return cli_->Put(path, headers, items, progress);
  9417. }
  9418. inline Result Client::Put(const std::string &path, const Headers &headers,
  9419. const UploadFormDataItems &items,
  9420. const std::string &boundary,
  9421. UploadProgress progress) {
  9422. return cli_->Put(path, headers, items, boundary, progress);
  9423. }
  9424. inline Result Client::Put(const std::string &path, const Headers &headers,
  9425. const UploadFormDataItems &items,
  9426. const FormDataProviderItems &provider_items,
  9427. UploadProgress progress) {
  9428. return cli_->Put(path, headers, items, provider_items, progress);
  9429. }
  9430. inline Result Client::Put(const std::string &path, const Headers &headers,
  9431. const std::string &body,
  9432. const std::string &content_type,
  9433. ContentReceiver content_receiver,
  9434. DownloadProgress progress) {
  9435. return cli_->Put(path, headers, body, content_type, content_receiver,
  9436. progress);
  9437. }
  9438. inline Result Client::Patch(const std::string &path) {
  9439. return cli_->Patch(path);
  9440. }
  9441. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  9442. return cli_->Patch(path, headers);
  9443. }
  9444. inline Result Client::Patch(const std::string &path, const char *body,
  9445. size_t content_length,
  9446. const std::string &content_type,
  9447. UploadProgress progress) {
  9448. return cli_->Patch(path, body, content_length, content_type, progress);
  9449. }
  9450. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9451. const char *body, size_t content_length,
  9452. const std::string &content_type,
  9453. UploadProgress progress) {
  9454. return cli_->Patch(path, headers, body, content_length, content_type,
  9455. progress);
  9456. }
  9457. inline Result Client::Patch(const std::string &path, const std::string &body,
  9458. const std::string &content_type,
  9459. UploadProgress progress) {
  9460. return cli_->Patch(path, body, content_type, progress);
  9461. }
  9462. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9463. const std::string &body,
  9464. const std::string &content_type,
  9465. UploadProgress progress) {
  9466. return cli_->Patch(path, headers, body, content_type, progress);
  9467. }
  9468. inline Result Client::Patch(const std::string &path, size_t content_length,
  9469. ContentProvider content_provider,
  9470. const std::string &content_type,
  9471. UploadProgress progress) {
  9472. return cli_->Patch(path, content_length, std::move(content_provider),
  9473. content_type, progress);
  9474. }
  9475. inline Result Client::Patch(const std::string &path,
  9476. ContentProviderWithoutLength content_provider,
  9477. const std::string &content_type,
  9478. UploadProgress progress) {
  9479. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  9480. }
  9481. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9482. size_t content_length,
  9483. ContentProvider content_provider,
  9484. const std::string &content_type,
  9485. UploadProgress progress) {
  9486. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  9487. content_type, progress);
  9488. }
  9489. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9490. ContentProviderWithoutLength content_provider,
  9491. const std::string &content_type,
  9492. UploadProgress progress) {
  9493. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  9494. progress);
  9495. }
  9496. inline Result Client::Patch(const std::string &path, const Params &params) {
  9497. return cli_->Patch(path, params);
  9498. }
  9499. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9500. const Params &params) {
  9501. return cli_->Patch(path, headers, params);
  9502. }
  9503. inline Result Client::Patch(const std::string &path,
  9504. const UploadFormDataItems &items,
  9505. UploadProgress progress) {
  9506. return cli_->Patch(path, items, progress);
  9507. }
  9508. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9509. const UploadFormDataItems &items,
  9510. UploadProgress progress) {
  9511. return cli_->Patch(path, headers, items, progress);
  9512. }
  9513. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9514. const UploadFormDataItems &items,
  9515. const std::string &boundary,
  9516. UploadProgress progress) {
  9517. return cli_->Patch(path, headers, items, boundary, progress);
  9518. }
  9519. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9520. const UploadFormDataItems &items,
  9521. const FormDataProviderItems &provider_items,
  9522. UploadProgress progress) {
  9523. return cli_->Patch(path, headers, items, provider_items, progress);
  9524. }
  9525. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9526. const std::string &body,
  9527. const std::string &content_type,
  9528. ContentReceiver content_receiver,
  9529. DownloadProgress progress) {
  9530. return cli_->Patch(path, headers, body, content_type, content_receiver,
  9531. progress);
  9532. }
  9533. inline Result Client::Delete(const std::string &path,
  9534. DownloadProgress progress) {
  9535. return cli_->Delete(path, progress);
  9536. }
  9537. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9538. DownloadProgress progress) {
  9539. return cli_->Delete(path, headers, progress);
  9540. }
  9541. inline Result Client::Delete(const std::string &path, const char *body,
  9542. size_t content_length,
  9543. const std::string &content_type,
  9544. DownloadProgress progress) {
  9545. return cli_->Delete(path, body, content_length, content_type, progress);
  9546. }
  9547. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9548. const char *body, size_t content_length,
  9549. const std::string &content_type,
  9550. DownloadProgress progress) {
  9551. return cli_->Delete(path, headers, body, content_length, content_type,
  9552. progress);
  9553. }
  9554. inline Result Client::Delete(const std::string &path, const std::string &body,
  9555. const std::string &content_type,
  9556. DownloadProgress progress) {
  9557. return cli_->Delete(path, body, content_type, progress);
  9558. }
  9559. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9560. const std::string &body,
  9561. const std::string &content_type,
  9562. DownloadProgress progress) {
  9563. return cli_->Delete(path, headers, body, content_type, progress);
  9564. }
  9565. inline Result Client::Delete(const std::string &path, const Params &params,
  9566. DownloadProgress progress) {
  9567. return cli_->Delete(path, params, progress);
  9568. }
  9569. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9570. const Params &params, DownloadProgress progress) {
  9571. return cli_->Delete(path, headers, params, progress);
  9572. }
  9573. inline Result Client::Options(const std::string &path) {
  9574. return cli_->Options(path);
  9575. }
  9576. inline Result Client::Options(const std::string &path, const Headers &headers) {
  9577. return cli_->Options(path, headers);
  9578. }
  9579. inline bool Client::send(Request &req, Response &res, Error &error) {
  9580. return cli_->send(req, res, error);
  9581. }
  9582. inline Result Client::send(const Request &req) { return cli_->send(req); }
  9583. inline void Client::stop() { cli_->stop(); }
  9584. inline std::string Client::host() const { return cli_->host(); }
  9585. inline int Client::port() const { return cli_->port(); }
  9586. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  9587. inline socket_t Client::socket() const { return cli_->socket(); }
  9588. inline void
  9589. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  9590. cli_->set_hostname_addr_map(std::move(addr_map));
  9591. }
  9592. inline void Client::set_default_headers(Headers headers) {
  9593. cli_->set_default_headers(std::move(headers));
  9594. }
  9595. inline void Client::set_header_writer(
  9596. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9597. cli_->set_header_writer(writer);
  9598. }
  9599. inline void Client::set_address_family(int family) {
  9600. cli_->set_address_family(family);
  9601. }
  9602. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  9603. inline void Client::set_socket_options(SocketOptions socket_options) {
  9604. cli_->set_socket_options(std::move(socket_options));
  9605. }
  9606. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  9607. cli_->set_connection_timeout(sec, usec);
  9608. }
  9609. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  9610. cli_->set_read_timeout(sec, usec);
  9611. }
  9612. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  9613. cli_->set_write_timeout(sec, usec);
  9614. }
  9615. inline void Client::set_basic_auth(const std::string &username,
  9616. const std::string &password) {
  9617. cli_->set_basic_auth(username, password);
  9618. }
  9619. inline void Client::set_bearer_token_auth(const std::string &token) {
  9620. cli_->set_bearer_token_auth(token);
  9621. }
  9622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9623. inline void Client::set_digest_auth(const std::string &username,
  9624. const std::string &password) {
  9625. cli_->set_digest_auth(username, password);
  9626. }
  9627. #endif
  9628. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  9629. inline void Client::set_follow_location(bool on) {
  9630. cli_->set_follow_location(on);
  9631. }
  9632. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  9633. [[deprecated("Use set_path_encode instead")]]
  9634. inline void Client::set_url_encode(bool on) {
  9635. cli_->set_path_encode(on);
  9636. }
  9637. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  9638. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  9639. inline void Client::set_interface(const std::string &intf) {
  9640. cli_->set_interface(intf);
  9641. }
  9642. inline void Client::set_proxy(const std::string &host, int port) {
  9643. cli_->set_proxy(host, port);
  9644. }
  9645. inline void Client::set_proxy_basic_auth(const std::string &username,
  9646. const std::string &password) {
  9647. cli_->set_proxy_basic_auth(username, password);
  9648. }
  9649. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  9650. cli_->set_proxy_bearer_token_auth(token);
  9651. }
  9652. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9653. inline void Client::set_proxy_digest_auth(const std::string &username,
  9654. const std::string &password) {
  9655. cli_->set_proxy_digest_auth(username, password);
  9656. }
  9657. #endif
  9658. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9659. inline void Client::enable_server_certificate_verification(bool enabled) {
  9660. cli_->enable_server_certificate_verification(enabled);
  9661. }
  9662. inline void Client::enable_server_hostname_verification(bool enabled) {
  9663. cli_->enable_server_hostname_verification(enabled);
  9664. }
  9665. inline void Client::set_server_certificate_verifier(
  9666. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  9667. cli_->set_server_certificate_verifier(verifier);
  9668. }
  9669. #endif
  9670. inline void Client::set_logger(Logger logger) {
  9671. cli_->set_logger(std::move(logger));
  9672. }
  9673. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9674. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  9675. const std::string &ca_cert_dir_path) {
  9676. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  9677. }
  9678. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  9679. if (is_ssl_) {
  9680. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  9681. } else {
  9682. cli_->set_ca_cert_store(ca_cert_store);
  9683. }
  9684. }
  9685. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  9686. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  9687. }
  9688. inline long Client::get_openssl_verify_result() const {
  9689. if (is_ssl_) {
  9690. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  9691. }
  9692. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  9693. }
  9694. inline SSL_CTX *Client::ssl_context() const {
  9695. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  9696. return nullptr;
  9697. }
  9698. #endif
  9699. // ----------------------------------------------------------------------------
  9700. } // namespace httplib
  9701. #endif // CPPHTTPLIB_HTTPLIB_H