1
0

httplib.h 684 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2026 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.48.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003000"
  11. #ifdef _WIN32
  12. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  13. #error \
  14. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  15. #endif
  16. #endif
  17. /*
  18. * Configuration
  19. */
  20. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  21. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  22. #endif
  23. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  24. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  25. #endif
  26. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  27. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  28. #endif
  29. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  30. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  31. #endif
  32. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  33. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  34. #endif
  35. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  36. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  37. #endif
  38. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  39. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  40. #endif
  41. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  42. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  43. #endif
  44. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  45. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  46. #endif
  47. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  60. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  61. #endif
  62. #ifndef CPPHTTPLIB_EXPECT_100_THRESHOLD
  63. #define CPPHTTPLIB_EXPECT_100_THRESHOLD 1024
  64. #endif
  65. #ifndef CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND
  66. #define CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND 1000
  67. #endif
  68. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD
  69. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD (1024 * 1024)
  70. #endif
  71. #ifndef CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND
  72. #define CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND 50
  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 _WIN32
  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 (100 * 1024 * 1024) // 100MB
  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_THREAD_POOL_MAX_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_MAX_COUNT (CPPHTTPLIB_THREAD_POOL_COUNT * 4)
  131. #endif
  132. #ifndef CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT
  133. #define CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT 3 // seconds
  134. #endif
  135. #ifndef CPPHTTPLIB_RECV_FLAGS
  136. #define CPPHTTPLIB_RECV_FLAGS 0
  137. #endif
  138. #ifndef CPPHTTPLIB_SEND_FLAGS
  139. #define CPPHTTPLIB_SEND_FLAGS 0
  140. #endif
  141. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  142. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  143. #endif
  144. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  145. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  146. #endif
  147. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH
  148. #define CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH 16777216
  149. #endif
  150. #ifndef CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND
  151. #define CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND 300
  152. #endif
  153. #ifndef CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND
  154. #define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 5
  155. #endif
  156. #ifndef CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND
  157. #define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 30
  158. #endif
  159. #ifndef CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS
  160. #define CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS 0
  161. #endif
  162. /*
  163. * Headers
  164. */
  165. #ifdef _WIN32
  166. #ifndef _CRT_SECURE_NO_WARNINGS
  167. #define _CRT_SECURE_NO_WARNINGS
  168. #endif //_CRT_SECURE_NO_WARNINGS
  169. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  170. #define _CRT_NONSTDC_NO_DEPRECATE
  171. #endif //_CRT_NONSTDC_NO_DEPRECATE
  172. #if defined(_MSC_VER)
  173. #if _MSC_VER < 1900
  174. #error Sorry, Visual Studio versions prior to 2015 are not supported
  175. #endif
  176. #pragma comment(lib, "ws2_32.lib")
  177. #ifndef _SSIZE_T_DEFINED
  178. using ssize_t = __int64;
  179. #define _SSIZE_T_DEFINED
  180. #endif
  181. #endif // _MSC_VER
  182. #ifndef S_ISREG
  183. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  184. #endif // S_ISREG
  185. #ifndef S_ISDIR
  186. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  187. #endif // S_ISDIR
  188. #ifndef NOMINMAX
  189. #define NOMINMAX
  190. #endif // NOMINMAX
  191. #include <io.h>
  192. #include <winsock2.h>
  193. #include <ws2tcpip.h>
  194. #if defined(__has_include)
  195. #if __has_include(<afunix.h>)
  196. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  197. #include <afunix.h>
  198. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  199. #endif
  200. #endif
  201. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  202. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  203. #endif
  204. using nfds_t = unsigned long;
  205. using socket_t = SOCKET;
  206. using socklen_t = int;
  207. #else // not _WIN32
  208. #include <arpa/inet.h>
  209. #if !defined(_AIX) && !defined(__MVS__)
  210. #include <ifaddrs.h>
  211. #endif
  212. #ifdef __MVS__
  213. #include <strings.h>
  214. #ifndef NI_MAXHOST
  215. #define NI_MAXHOST 1025
  216. #endif
  217. #endif
  218. #include <net/if.h>
  219. #include <netdb.h>
  220. #include <netinet/in.h>
  221. #ifdef __linux__
  222. #include <resolv.h>
  223. #undef _res // Undefine _res macro to avoid conflicts with user code (#2278)
  224. #endif
  225. #include <csignal>
  226. #include <netinet/tcp.h>
  227. #include <poll.h>
  228. #include <pthread.h>
  229. #include <sys/mman.h>
  230. #include <sys/socket.h>
  231. #include <sys/un.h>
  232. #include <unistd.h>
  233. using socket_t = int;
  234. #ifndef INVALID_SOCKET
  235. #define INVALID_SOCKET (-1)
  236. #endif
  237. #endif //_WIN32
  238. #if defined(__APPLE__)
  239. #include <TargetConditionals.h>
  240. #endif
  241. #include <algorithm>
  242. #include <array>
  243. #include <atomic>
  244. #include <cassert>
  245. #include <cctype>
  246. #include <chrono>
  247. #include <climits>
  248. #include <condition_variable>
  249. #include <cstdlib>
  250. #include <cstring>
  251. #include <errno.h>
  252. #include <exception>
  253. #include <fcntl.h>
  254. #include <fstream>
  255. #include <functional>
  256. #include <iomanip>
  257. #include <iostream>
  258. #include <list>
  259. #include <map>
  260. #include <memory>
  261. #include <mutex>
  262. #include <random>
  263. #include <regex>
  264. #include <set>
  265. #include <sstream>
  266. #include <string>
  267. #include <sys/stat.h>
  268. #include <system_error>
  269. #include <thread>
  270. #include <unordered_map>
  271. #include <unordered_set>
  272. #include <utility>
  273. // On macOS with a TLS backend, enable Keychain root certificates by default
  274. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  275. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  276. // only; on those platforms the user must provide a CA bundle explicitly.
  277. #if defined(__APPLE__) && defined(__clang__) && \
  278. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  279. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  280. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  281. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  282. #if TARGET_OS_OSX
  283. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  284. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  285. #endif
  286. #endif
  287. #endif
  288. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  289. defined(__APPLE__) && !TARGET_OS_OSX
  290. #error \
  291. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  292. #endif
  293. // On Windows, enable Schannel certificate verification by default
  294. // unless the user explicitly opts out.
  295. #if defined(_WIN32) && \
  296. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  297. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  298. #endif
  299. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  300. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  301. #if TARGET_OS_MAC && defined(__clang__)
  302. #include <CFNetwork/CFHost.h>
  303. #include <CoreFoundation/CoreFoundation.h>
  304. #endif
  305. #endif
  306. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  307. #ifdef _WIN32
  308. #include <wincrypt.h>
  309. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  310. // used
  311. #undef X509_NAME
  312. #undef X509_CERT_PAIR
  313. #undef X509_EXTENSIONS
  314. #undef PKCS7_SIGNER_INFO
  315. #ifdef _MSC_VER
  316. #pragma comment(lib, "crypt32.lib")
  317. #endif
  318. #endif // _WIN32
  319. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  320. #if TARGET_OS_OSX
  321. #include <Security/Security.h>
  322. #endif
  323. #endif
  324. #include <openssl/err.h>
  325. #include <openssl/evp.h>
  326. #include <openssl/ssl.h>
  327. #include <openssl/x509v3.h>
  328. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  329. #include <openssl/applink.c>
  330. #endif
  331. #include <iostream>
  332. #include <sstream>
  333. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  334. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  335. #error Please use OpenSSL or a current version of BoringSSL
  336. #endif
  337. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  338. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  339. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  340. #endif
  341. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  342. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  343. #include <mbedtls/ctr_drbg.h>
  344. #include <mbedtls/entropy.h>
  345. #include <mbedtls/error.h>
  346. #include <mbedtls/md5.h>
  347. #include <mbedtls/net_sockets.h>
  348. #include <mbedtls/oid.h>
  349. #include <mbedtls/pk.h>
  350. #include <mbedtls/sha1.h>
  351. #include <mbedtls/sha256.h>
  352. #include <mbedtls/sha512.h>
  353. #include <mbedtls/ssl.h>
  354. #include <mbedtls/x509_crt.h>
  355. #ifdef _WIN32
  356. #include <wincrypt.h>
  357. #ifdef _MSC_VER
  358. #pragma comment(lib, "crypt32.lib")
  359. #endif
  360. #endif // _WIN32
  361. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  362. #if TARGET_OS_OSX
  363. #include <Security/Security.h>
  364. #endif
  365. #endif
  366. // Mbed TLS 3.x API compatibility
  367. #if MBEDTLS_VERSION_MAJOR >= 3
  368. #define CPPHTTPLIB_MBEDTLS_V3
  369. #endif
  370. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  371. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  372. #include <wolfssl/options.h>
  373. #include <wolfssl/openssl/x509v3.h>
  374. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  375. #ifndef WOLFSSL_GEN_EMAIL
  376. #define WOLFSSL_GEN_EMAIL 1
  377. #endif
  378. #ifndef WOLFSSL_GEN_DNS
  379. #define WOLFSSL_GEN_DNS 2
  380. #endif
  381. #ifndef WOLFSSL_GEN_URI
  382. #define WOLFSSL_GEN_URI 6
  383. #endif
  384. #ifndef WOLFSSL_GEN_IPADD
  385. #define WOLFSSL_GEN_IPADD 7
  386. #endif
  387. #include <wolfssl/ssl.h>
  388. #include <wolfssl/wolfcrypt/hash.h>
  389. #include <wolfssl/wolfcrypt/md5.h>
  390. #include <wolfssl/wolfcrypt/sha256.h>
  391. #include <wolfssl/wolfcrypt/sha512.h>
  392. #ifdef _WIN32
  393. #include <wincrypt.h>
  394. #ifdef _MSC_VER
  395. #pragma comment(lib, "crypt32.lib")
  396. #endif
  397. #endif // _WIN32
  398. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  399. #if TARGET_OS_OSX
  400. #include <Security/Security.h>
  401. #endif
  402. #endif
  403. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  404. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  405. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  406. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  407. #define CPPHTTPLIB_SSL_ENABLED
  408. #endif
  409. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  410. #include <zlib.h>
  411. #endif
  412. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  413. #include <brotli/decode.h>
  414. #include <brotli/encode.h>
  415. #endif
  416. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  417. #include <zstd.h>
  418. #endif
  419. /*
  420. * Declaration
  421. */
  422. namespace httplib {
  423. namespace ws {
  424. class WebSocket;
  425. } // namespace ws
  426. namespace detail {
  427. /*
  428. * Backport std::make_unique from C++14.
  429. *
  430. * NOTE: This code came up with the following stackoverflow post:
  431. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  432. *
  433. */
  434. template <class T, class... Args>
  435. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  436. make_unique(Args &&...args) {
  437. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  438. }
  439. template <class T>
  440. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  441. make_unique(std::size_t n) {
  442. typedef typename std::remove_extent<T>::type RT;
  443. return std::unique_ptr<T>(new RT[n]);
  444. }
  445. namespace case_ignore {
  446. inline unsigned char to_lower(int c) {
  447. const static unsigned char table[256] = {
  448. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  449. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  450. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  451. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  452. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  453. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  454. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  455. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  456. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  457. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  458. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  459. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  460. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  461. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  462. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  463. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  464. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  465. 255,
  466. };
  467. return table[(unsigned char)(char)c];
  468. }
  469. inline std::string to_lower(const std::string &s) {
  470. std::string result = s;
  471. std::transform(
  472. result.begin(), result.end(), result.begin(),
  473. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  474. return result;
  475. }
  476. inline bool equal(const std::string &a, const std::string &b) {
  477. return a.size() == b.size() &&
  478. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  479. return to_lower(ca) == to_lower(cb);
  480. });
  481. }
  482. struct equal_to {
  483. bool operator()(const std::string &a, const std::string &b) const {
  484. return equal(a, b);
  485. }
  486. };
  487. struct hash {
  488. size_t operator()(const std::string &key) const {
  489. return hash_core(key.data(), key.size(), 0);
  490. }
  491. size_t hash_core(const char *s, size_t l, size_t h) const {
  492. return (l == 0) ? h
  493. : hash_core(s + 1, l - 1,
  494. // Unsets the 6 high bits of h, therefore no
  495. // overflow happens
  496. (((std::numeric_limits<size_t>::max)() >> 6) &
  497. h * 33) ^
  498. static_cast<unsigned char>(to_lower(*s)));
  499. }
  500. };
  501. template <typename T>
  502. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  503. detail::case_ignore::equal_to>;
  504. } // namespace case_ignore
  505. // This is based on
  506. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  507. struct scope_exit {
  508. explicit scope_exit(std::function<void(void)> &&f)
  509. : exit_function(std::move(f)), execute_on_destruction{true} {}
  510. scope_exit(scope_exit &&rhs) noexcept
  511. : exit_function(std::move(rhs.exit_function)),
  512. execute_on_destruction{rhs.execute_on_destruction} {
  513. rhs.release();
  514. }
  515. ~scope_exit() {
  516. if (execute_on_destruction) { this->exit_function(); }
  517. }
  518. void release() { this->execute_on_destruction = false; }
  519. private:
  520. scope_exit(const scope_exit &) = delete;
  521. void operator=(const scope_exit &) = delete;
  522. scope_exit &operator=(scope_exit &&) = delete;
  523. std::function<void(void)> exit_function;
  524. bool execute_on_destruction;
  525. };
  526. // Simple from_chars implementation for integer and double types (C++17
  527. // substitute)
  528. template <typename T> struct from_chars_result {
  529. const char *ptr;
  530. std::errc ec;
  531. };
  532. template <typename T>
  533. inline from_chars_result<T> from_chars(const char *first, const char *last,
  534. T &value, int base = 10) {
  535. value = 0;
  536. const char *p = first;
  537. bool negative = false;
  538. if (p != last && *p == '-') {
  539. negative = true;
  540. ++p;
  541. }
  542. if (p == last) { return {first, std::errc::invalid_argument}; }
  543. T result = 0;
  544. for (; p != last; ++p) {
  545. char c = *p;
  546. int digit = -1;
  547. if ('0' <= c && c <= '9') {
  548. digit = c - '0';
  549. } else if ('a' <= c && c <= 'z') {
  550. digit = c - 'a' + 10;
  551. } else if ('A' <= c && c <= 'Z') {
  552. digit = c - 'A' + 10;
  553. } else {
  554. break;
  555. }
  556. if (digit < 0 || digit >= base) { break; }
  557. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  558. return {p, std::errc::result_out_of_range};
  559. }
  560. result = result * base + digit;
  561. }
  562. if (p == first || (negative && p == first + 1)) {
  563. return {first, std::errc::invalid_argument};
  564. }
  565. value = negative ? -result : result;
  566. return {p, std::errc{}};
  567. }
  568. // from_chars for double (hand-written, locale-independent)
  569. //
  570. // The only double consumed by this library is the HTTP quality value, whose
  571. // grammar is (RFC 9110 12.4.2):
  572. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  573. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  574. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  575. // '.' always the decimal separator (std::strtod would instead read it from the
  576. // global C locale, mis-parsing q-values once an embedder calls
  577. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  578. // the result to [0, 1], so inputs outside that range need not be distinguished
  579. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  580. // cases that exponent and wide-range handling would introduce.
  581. inline from_chars_result<double> from_chars(const char *first, const char *last,
  582. double &value) {
  583. value = 0.0;
  584. const char *p = first;
  585. // Each 1eN is exactly representable, so a single final division by the
  586. // matching entry yields a correctly-rounded result.
  587. static const double powers_of_ten[] = {
  588. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  589. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  590. const int max_frac_digits =
  591. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  592. // Accumulate digits into a 64-bit integer and remember how many were
  593. // fractional. Two independent caps keep this bounded and safe:
  594. // * accumulation saturates before mantissa could overflow uint64_t, and
  595. // * frac_digits is capped at max_frac_digits so it is always a valid index
  596. // into powers_of_ten (without this an input like "0.000...0" would never
  597. // grow mantissa, so the saturation cap alone would not bound it).
  598. // Both caps only drop digits far beyond the precision a q-value needs; any
  599. // value they would change is well outside [0, 1] and rejected by the caller.
  600. uint64_t mantissa = 0;
  601. int frac_digits = 0;
  602. bool seen_digit = false;
  603. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  604. auto accumulate = [&](char c) {
  605. if (mantissa <= limit) {
  606. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  607. return true;
  608. }
  609. return false;
  610. };
  611. for (; p != last && '0' <= *p && *p <= '9'; ++p) {
  612. seen_digit = true;
  613. accumulate(*p);
  614. }
  615. if (p != last && *p == '.') {
  616. ++p;
  617. for (; p != last && '0' <= *p && *p <= '9'; ++p) {
  618. seen_digit = true;
  619. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  620. }
  621. }
  622. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  623. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  624. return {p, std::errc{}};
  625. }
  626. inline bool parse_port(const char *s, size_t len, int &port) {
  627. int val = 0;
  628. auto r = from_chars(s, s + len, val);
  629. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  630. port = val;
  631. return true;
  632. }
  633. inline bool parse_port(const std::string &s, int &port) {
  634. return parse_port(s.data(), s.size(), port);
  635. }
  636. struct UrlComponents {
  637. std::string scheme;
  638. std::string host;
  639. std::string port;
  640. std::string path;
  641. std::string query;
  642. };
  643. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  644. uc = {};
  645. size_t pos = 0;
  646. auto sep = url.find("://");
  647. if (sep != std::string::npos) {
  648. uc.scheme = url.substr(0, sep);
  649. // Scheme must be [a-z]+ only
  650. if (uc.scheme.empty()) { return false; }
  651. for (auto c : uc.scheme) {
  652. if (c < 'a' || c > 'z') { return false; }
  653. }
  654. pos = sep + 3;
  655. } else if (url.compare(0, 2, "//") == 0) {
  656. pos = 2;
  657. }
  658. auto has_authority_prefix = pos > 0;
  659. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  660. url[0] != '?' && url[0] != '#');
  661. if (has_authority) {
  662. if (pos < url.size() && url[pos] == '[') {
  663. auto close = url.find(']', pos);
  664. if (close == std::string::npos) { return false; }
  665. uc.host = url.substr(pos + 1, close - pos - 1);
  666. // IPv6 host must be [a-fA-F0-9:]+ only
  667. if (uc.host.empty()) { return false; }
  668. for (auto c : uc.host) {
  669. if (!((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') ||
  670. (c >= '0' && c <= '9') || c == ':')) {
  671. return false;
  672. }
  673. }
  674. pos = close + 1;
  675. } else {
  676. auto end = url.find_first_of(":/?#", pos);
  677. if (end == std::string::npos) { end = url.size(); }
  678. uc.host = url.substr(pos, end - pos);
  679. pos = end;
  680. }
  681. if (pos < url.size() && url[pos] == ':') {
  682. ++pos;
  683. auto end = url.find_first_of("/?#", pos);
  684. if (end == std::string::npos) { end = url.size(); }
  685. uc.port = url.substr(pos, end - pos);
  686. pos = end;
  687. }
  688. // Without :// or //, the entire input must be consumed as host[:port].
  689. // If there is leftover (path, query, etc.), this is not a valid
  690. // host[:port] string — clear and reparse as a plain path.
  691. if (!has_authority_prefix && pos < url.size()) {
  692. uc.host.clear();
  693. uc.port.clear();
  694. pos = 0;
  695. }
  696. }
  697. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  698. auto end = url.find_first_of("?#", pos);
  699. if (end == std::string::npos) { end = url.size(); }
  700. uc.path = url.substr(pos, end - pos);
  701. pos = end;
  702. }
  703. if (pos < url.size() && url[pos] == '?') {
  704. auto end = url.find('#', pos);
  705. if (end == std::string::npos) { end = url.size(); }
  706. uc.query = url.substr(pos, end - pos);
  707. }
  708. return true;
  709. }
  710. } // namespace detail
  711. enum class SSLVerifierResponse {
  712. // no decision has been made, use the built-in certificate verifier
  713. NoDecisionMade,
  714. // connection certificate is verified and accepted
  715. CertificateAccepted,
  716. // connection certificate was processed but is rejected
  717. CertificateRejected
  718. };
  719. // System CA loading policy for SSL clients. Auto (the default) loads system
  720. // CA certs only when no custom CA is configured; enable_system_ca() switches
  721. // to an explicit policy.
  722. enum class SystemCAMode { Auto, Enabled, Disabled };
  723. enum StatusCode {
  724. // Information responses
  725. Continue_100 = 100,
  726. SwitchingProtocol_101 = 101,
  727. Processing_102 = 102,
  728. EarlyHints_103 = 103,
  729. // Successful responses
  730. OK_200 = 200,
  731. Created_201 = 201,
  732. Accepted_202 = 202,
  733. NonAuthoritativeInformation_203 = 203,
  734. NoContent_204 = 204,
  735. ResetContent_205 = 205,
  736. PartialContent_206 = 206,
  737. MultiStatus_207 = 207,
  738. AlreadyReported_208 = 208,
  739. IMUsed_226 = 226,
  740. // Redirection messages
  741. MultipleChoices_300 = 300,
  742. MovedPermanently_301 = 301,
  743. Found_302 = 302,
  744. SeeOther_303 = 303,
  745. NotModified_304 = 304,
  746. UseProxy_305 = 305,
  747. unused_306 = 306,
  748. TemporaryRedirect_307 = 307,
  749. PermanentRedirect_308 = 308,
  750. // Client error responses
  751. BadRequest_400 = 400,
  752. Unauthorized_401 = 401,
  753. PaymentRequired_402 = 402,
  754. Forbidden_403 = 403,
  755. NotFound_404 = 404,
  756. MethodNotAllowed_405 = 405,
  757. NotAcceptable_406 = 406,
  758. ProxyAuthenticationRequired_407 = 407,
  759. RequestTimeout_408 = 408,
  760. Conflict_409 = 409,
  761. Gone_410 = 410,
  762. LengthRequired_411 = 411,
  763. PreconditionFailed_412 = 412,
  764. PayloadTooLarge_413 = 413,
  765. UriTooLong_414 = 414,
  766. UnsupportedMediaType_415 = 415,
  767. RangeNotSatisfiable_416 = 416,
  768. ExpectationFailed_417 = 417,
  769. ImATeapot_418 = 418,
  770. MisdirectedRequest_421 = 421,
  771. UnprocessableContent_422 = 422,
  772. Locked_423 = 423,
  773. FailedDependency_424 = 424,
  774. TooEarly_425 = 425,
  775. UpgradeRequired_426 = 426,
  776. PreconditionRequired_428 = 428,
  777. TooManyRequests_429 = 429,
  778. RequestHeaderFieldsTooLarge_431 = 431,
  779. UnavailableForLegalReasons_451 = 451,
  780. // Server error responses
  781. InternalServerError_500 = 500,
  782. NotImplemented_501 = 501,
  783. BadGateway_502 = 502,
  784. ServiceUnavailable_503 = 503,
  785. GatewayTimeout_504 = 504,
  786. HttpVersionNotSupported_505 = 505,
  787. VariantAlsoNegotiates_506 = 506,
  788. InsufficientStorage_507 = 507,
  789. LoopDetected_508 = 508,
  790. NotExtended_510 = 510,
  791. NetworkAuthenticationRequired_511 = 511,
  792. };
  793. using Headers =
  794. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  795. detail::case_ignore::equal_to>;
  796. using Params = std::multimap<std::string, std::string>;
  797. using Match = std::smatch;
  798. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  799. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  800. /*
  801. * detail: type-erased storage used by UserData.
  802. * ABI-stable regardless of C++ standard — always uses this custom
  803. * implementation instead of std::any.
  804. */
  805. namespace detail {
  806. using any_type_id = const void *;
  807. template <typename T> any_type_id any_typeid() noexcept {
  808. static const char id = 0;
  809. return &id;
  810. }
  811. struct any_storage {
  812. virtual ~any_storage() = default;
  813. virtual std::unique_ptr<any_storage> clone() const = 0;
  814. virtual any_type_id type_id() const noexcept = 0;
  815. };
  816. template <typename T> struct any_value final : any_storage {
  817. T value;
  818. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  819. std::unique_ptr<any_storage> clone() const override {
  820. return std::unique_ptr<any_storage>(new any_value<T>(value));
  821. }
  822. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  823. };
  824. } // namespace detail
  825. class UserData {
  826. public:
  827. UserData() = default;
  828. UserData(UserData &&) noexcept = default;
  829. UserData &operator=(UserData &&) noexcept = default;
  830. UserData(const UserData &o) {
  831. for (const auto &e : o.entries_) {
  832. if (e.second) { entries_[e.first] = e.second->clone(); }
  833. }
  834. }
  835. UserData &operator=(const UserData &o) {
  836. if (this != &o) {
  837. entries_.clear();
  838. for (const auto &e : o.entries_) {
  839. if (e.second) { entries_[e.first] = e.second->clone(); }
  840. }
  841. }
  842. return *this;
  843. }
  844. template <typename T> void set(const std::string &key, T &&value) {
  845. using D = typename std::decay<T>::type;
  846. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  847. }
  848. template <typename T> T *get(const std::string &key) noexcept {
  849. auto it = entries_.find(key);
  850. if (it == entries_.end() || !it->second) { return nullptr; }
  851. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  852. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  853. }
  854. template <typename T> const T *get(const std::string &key) const noexcept {
  855. auto it = entries_.find(key);
  856. if (it == entries_.end() || !it->second) { return nullptr; }
  857. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  858. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  859. }
  860. bool has(const std::string &key) const noexcept {
  861. return entries_.find(key) != entries_.end();
  862. }
  863. void erase(const std::string &key) { entries_.erase(key); }
  864. void clear() noexcept { entries_.clear(); }
  865. private:
  866. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  867. entries_;
  868. };
  869. struct Response;
  870. using ResponseHandler = std::function<bool(const Response &response)>;
  871. struct FormData {
  872. std::string name;
  873. std::string content;
  874. std::string filename;
  875. std::string content_type;
  876. Headers headers;
  877. };
  878. struct FormField {
  879. std::string name;
  880. std::string content;
  881. Headers headers;
  882. };
  883. using FormFields = std::multimap<std::string, FormField>;
  884. using FormFiles = std::multimap<std::string, FormData>;
  885. struct MultipartFormData {
  886. FormFields fields; // Text fields from multipart
  887. FormFiles files; // Files from multipart
  888. // Text field access
  889. std::string get_field(const std::string &key, size_t id = 0) const;
  890. std::vector<std::string> get_fields(const std::string &key) const;
  891. bool has_field(const std::string &key) const;
  892. size_t get_field_count(const std::string &key) const;
  893. // File access
  894. FormData get_file(const std::string &key, size_t id = 0) const;
  895. std::vector<FormData> get_files(const std::string &key) const;
  896. bool has_file(const std::string &key) const;
  897. size_t get_file_count(const std::string &key) const;
  898. };
  899. struct UploadFormData {
  900. std::string name;
  901. std::string content;
  902. std::string filename;
  903. std::string content_type;
  904. };
  905. using UploadFormDataItems = std::vector<UploadFormData>;
  906. class DataSink {
  907. public:
  908. DataSink() : os(&sb_), sb_(*this) {}
  909. DataSink(const DataSink &) = delete;
  910. DataSink &operator=(const DataSink &) = delete;
  911. DataSink(DataSink &&) = delete;
  912. DataSink &operator=(DataSink &&) = delete;
  913. std::function<bool(const char *data, size_t data_len)> write;
  914. std::function<bool()> is_writable;
  915. std::function<void()> done;
  916. std::function<void(const Headers &trailer)> done_with_trailer;
  917. std::ostream os;
  918. private:
  919. class data_sink_streambuf final : public std::streambuf {
  920. public:
  921. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  922. protected:
  923. std::streamsize xsputn(const char *s, std::streamsize n) override {
  924. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  925. return 0;
  926. }
  927. private:
  928. DataSink &sink_;
  929. };
  930. data_sink_streambuf sb_;
  931. };
  932. using ContentProvider =
  933. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  934. using ContentProviderWithoutLength =
  935. std::function<bool(size_t offset, DataSink &sink)>;
  936. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  937. struct FormDataProvider {
  938. std::string name;
  939. ContentProviderWithoutLength provider;
  940. std::string filename;
  941. std::string content_type;
  942. };
  943. using FormDataProviderItems = std::vector<FormDataProvider>;
  944. inline FormDataProvider
  945. make_file_provider(const std::string &name, const std::string &filepath,
  946. const std::string &filename = std::string(),
  947. const std::string &content_type = std::string()) {
  948. FormDataProvider fdp;
  949. fdp.name = name;
  950. fdp.filename = filename.empty() ? filepath : filename;
  951. fdp.content_type = content_type;
  952. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  953. std::ifstream f(filepath, std::ios::binary);
  954. if (!f) { return false; }
  955. if (offset > 0) {
  956. f.seekg(static_cast<std::streamoff>(offset));
  957. if (!f.good()) {
  958. sink.done();
  959. return true;
  960. }
  961. }
  962. char buf[8192];
  963. f.read(buf, sizeof(buf));
  964. auto n = static_cast<size_t>(f.gcount());
  965. if (n > 0) { return sink.write(buf, n); }
  966. sink.done(); // EOF
  967. return true;
  968. };
  969. return fdp;
  970. }
  971. inline std::pair<size_t, ContentProvider>
  972. make_file_body(const std::string &filepath) {
  973. size_t size = 0;
  974. {
  975. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  976. if (!f) { return {0, ContentProvider{}}; }
  977. size = static_cast<size_t>(f.tellg());
  978. }
  979. ContentProvider provider = [filepath](size_t offset, size_t length,
  980. DataSink &sink) -> bool {
  981. std::ifstream f(filepath, std::ios::binary);
  982. if (!f) { return false; }
  983. f.seekg(static_cast<std::streamoff>(offset));
  984. if (!f.good()) { return false; }
  985. char buf[8192];
  986. while (length > 0) {
  987. auto to_read = (std::min)(sizeof(buf), length);
  988. f.read(buf, static_cast<std::streamsize>(to_read));
  989. auto n = static_cast<size_t>(f.gcount());
  990. if (n == 0) { break; }
  991. if (!sink.write(buf, n)) { return false; }
  992. length -= n;
  993. }
  994. return true;
  995. };
  996. return {size, std::move(provider)};
  997. }
  998. using ContentReceiverWithProgress = std::function<bool(
  999. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1000. using ContentReceiver =
  1001. std::function<bool(const char *data, size_t data_length)>;
  1002. using FormDataHeader = std::function<bool(const FormData &file)>;
  1003. class ContentReader {
  1004. public:
  1005. using Reader = std::function<bool(ContentReceiver receiver)>;
  1006. using FormDataReader =
  1007. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1008. ContentReader(Reader reader, FormDataReader multipart_reader)
  1009. : reader_(std::move(reader)),
  1010. formdata_reader_(std::move(multipart_reader)) {}
  1011. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1012. return formdata_reader_(std::move(header), std::move(receiver));
  1013. }
  1014. bool operator()(ContentReceiver receiver) const {
  1015. return reader_(std::move(receiver));
  1016. }
  1017. Reader reader_;
  1018. FormDataReader formdata_reader_;
  1019. };
  1020. using Range = std::pair<ssize_t, ssize_t>;
  1021. using Ranges = std::vector<Range>;
  1022. #ifdef CPPHTTPLIB_SSL_ENABLED
  1023. // TLS abstraction layer - public type definitions and API
  1024. namespace tls {
  1025. // Opaque handles (defined as void* for abstraction)
  1026. using ctx_t = void *;
  1027. using session_t = void *;
  1028. using const_session_t = const void *; // For read-only session access
  1029. using cert_t = void *;
  1030. using ca_store_t = void *;
  1031. // TLS versions
  1032. enum class Version {
  1033. TLS1_2 = 0x0303,
  1034. TLS1_3 = 0x0304,
  1035. };
  1036. // Subject Alternative Names (SAN) entry types
  1037. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1038. // SAN entry structure
  1039. struct SanEntry {
  1040. SanType type;
  1041. std::string value;
  1042. };
  1043. // Verification context for certificate verification callback
  1044. struct VerifyContext {
  1045. session_t session; // TLS session handle
  1046. cert_t cert; // Current certificate being verified
  1047. int depth; // Certificate chain depth (0 = leaf)
  1048. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1049. long error_code; // Backend-specific error code (0 = no error)
  1050. const char *error_string; // Human-readable error description
  1051. // Certificate introspection methods
  1052. std::string subject_cn() const;
  1053. std::string issuer_name() const;
  1054. bool check_hostname(const char *hostname) const;
  1055. std::vector<SanEntry> sans() const;
  1056. bool validity(time_t &not_before, time_t &not_after) const;
  1057. std::string serial() const;
  1058. };
  1059. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1060. // TlsError codes for TLS operations (backend-independent)
  1061. enum class ErrorCode : int {
  1062. Success = 0,
  1063. WantRead, // Non-blocking: need to wait for read
  1064. WantWrite, // Non-blocking: need to wait for write
  1065. PeerClosed, // Peer closed the connection
  1066. Fatal, // Unrecoverable error
  1067. SyscallError, // System call error (check sys_errno)
  1068. CertVerifyFailed, // Certificate verification failed
  1069. HostnameMismatch, // Hostname verification failed
  1070. };
  1071. // TLS error information
  1072. struct TlsError {
  1073. ErrorCode code = ErrorCode::Fatal;
  1074. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1075. int sys_errno = 0; // errno when SyscallError
  1076. // Convert verification error code to human-readable string
  1077. static std::string verify_error_to_string(long error_code);
  1078. };
  1079. // RAII wrapper for peer certificate
  1080. class PeerCert {
  1081. public:
  1082. PeerCert();
  1083. PeerCert(PeerCert &&other) noexcept;
  1084. PeerCert &operator=(PeerCert &&other) noexcept;
  1085. ~PeerCert();
  1086. PeerCert(const PeerCert &) = delete;
  1087. PeerCert &operator=(const PeerCert &) = delete;
  1088. explicit operator bool() const;
  1089. std::string subject_cn() const;
  1090. std::string issuer_name() const;
  1091. bool check_hostname(const char *hostname) const;
  1092. std::vector<SanEntry> sans() const;
  1093. bool validity(time_t &not_before, time_t &not_after) const;
  1094. std::string serial() const;
  1095. private:
  1096. explicit PeerCert(cert_t cert);
  1097. cert_t cert_ = nullptr;
  1098. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1099. };
  1100. // Callback for TLS context setup (used by SSLServer constructor)
  1101. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1102. } // namespace tls
  1103. #endif
  1104. struct Request {
  1105. std::string method;
  1106. std::string path;
  1107. std::string matched_route;
  1108. Params params;
  1109. Headers headers;
  1110. Headers trailers;
  1111. std::string body;
  1112. std::string remote_addr;
  1113. int remote_port = -1;
  1114. std::string local_addr;
  1115. int local_port = -1;
  1116. // for server
  1117. std::string version;
  1118. std::string target;
  1119. MultipartFormData form;
  1120. Ranges ranges;
  1121. Match matches;
  1122. std::unordered_map<std::string, std::string> path_params;
  1123. std::function<bool()> is_connection_closed = []() { return true; };
  1124. // for client
  1125. std::vector<std::string> accept_content_types;
  1126. ResponseHandler response_handler;
  1127. ContentReceiverWithProgress content_receiver;
  1128. DownloadProgress download_progress;
  1129. UploadProgress upload_progress;
  1130. bool has_header(const std::string &key) const;
  1131. std::string get_header_value(const std::string &key, const char *def = "",
  1132. size_t id = 0) const;
  1133. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1134. size_t id = 0) const;
  1135. size_t get_header_value_count(const std::string &key) const;
  1136. void set_header(const std::string &key, const std::string &val);
  1137. bool has_trailer(const std::string &key) const;
  1138. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1139. size_t get_trailer_value_count(const std::string &key) const;
  1140. bool has_param(const std::string &key) const;
  1141. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1142. std::vector<std::string> get_param_values(const std::string &key) const;
  1143. size_t get_param_value_count(const std::string &key) const;
  1144. bool is_multipart_form_data() const;
  1145. // private members...
  1146. bool body_consumed_ = false;
  1147. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1148. size_t content_length_ = 0;
  1149. ContentProvider content_provider_;
  1150. bool is_chunked_content_provider_ = false;
  1151. size_t authorization_count_ = 0;
  1152. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1153. (std::chrono::steady_clock::time_point::min)();
  1154. #ifdef CPPHTTPLIB_SSL_ENABLED
  1155. tls::const_session_t ssl = nullptr;
  1156. tls::PeerCert peer_cert() const;
  1157. std::string sni() const;
  1158. #endif
  1159. };
  1160. struct Response {
  1161. std::string version;
  1162. int status = -1;
  1163. std::string reason;
  1164. Headers headers;
  1165. Headers trailers;
  1166. std::string body;
  1167. std::string location; // Redirect location
  1168. // User-defined context — set by pre-routing/pre-request handlers and read
  1169. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1170. UserData user_data;
  1171. bool has_header(const std::string &key) const;
  1172. std::string get_header_value(const std::string &key, const char *def = "",
  1173. size_t id = 0) const;
  1174. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1175. size_t id = 0) const;
  1176. size_t get_header_value_count(const std::string &key) const;
  1177. void set_header(const std::string &key, const std::string &val);
  1178. bool has_trailer(const std::string &key) const;
  1179. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1180. size_t get_trailer_value_count(const std::string &key) const;
  1181. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1182. void set_content(const char *s, size_t n, const std::string &content_type);
  1183. void set_content(const std::string &s, const std::string &content_type);
  1184. void set_content(std::string &&s, const std::string &content_type);
  1185. void set_content_provider(
  1186. size_t length, const std::string &content_type, ContentProvider provider,
  1187. ContentProviderResourceReleaser resource_releaser = nullptr);
  1188. void set_content_provider(
  1189. const std::string &content_type, ContentProviderWithoutLength provider,
  1190. ContentProviderResourceReleaser resource_releaser = nullptr);
  1191. void set_chunked_content_provider(
  1192. const std::string &content_type, ContentProviderWithoutLength provider,
  1193. ContentProviderResourceReleaser resource_releaser = nullptr);
  1194. void set_file_content(const std::string &path,
  1195. const std::string &content_type);
  1196. void set_file_content(const std::string &path);
  1197. Response() = default;
  1198. Response(const Response &) = default;
  1199. Response &operator=(const Response &) = default;
  1200. Response(Response &&) = default;
  1201. Response &operator=(Response &&) = default;
  1202. ~Response() {
  1203. if (content_provider_resource_releaser_) {
  1204. content_provider_resource_releaser_(content_provider_success_);
  1205. }
  1206. }
  1207. // private members...
  1208. size_t content_length_ = 0;
  1209. ContentProvider content_provider_;
  1210. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1211. bool is_chunked_content_provider_ = false;
  1212. bool content_provider_success_ = false;
  1213. std::string file_content_path_;
  1214. std::string file_content_content_type_;
  1215. };
  1216. enum class Error {
  1217. Success = 0,
  1218. Unknown,
  1219. Connection,
  1220. BindIPAddress,
  1221. Read,
  1222. Write,
  1223. ExceedRedirectCount,
  1224. Canceled,
  1225. SSLConnection,
  1226. SSLLoadingCerts,
  1227. SSLServerVerification,
  1228. SSLServerHostnameVerification,
  1229. UnsupportedMultipartBoundaryChars,
  1230. Compression,
  1231. ConnectionTimeout,
  1232. ProxyConnection,
  1233. ConnectionClosed,
  1234. Timeout,
  1235. ResourceExhaustion,
  1236. TooManyFormDataFiles,
  1237. ExceedMaxPayloadSize,
  1238. ExceedUriMaxLength,
  1239. ExceedMaxSocketDescriptorCount,
  1240. InvalidRequestLine,
  1241. InvalidHTTPMethod,
  1242. InvalidHTTPVersion,
  1243. InvalidHeaders,
  1244. MultipartParsing,
  1245. OpenFile,
  1246. Listen,
  1247. GetSockName,
  1248. UnsupportedAddressFamily,
  1249. HTTPParsing,
  1250. InvalidRangeHeader,
  1251. // For internal use only
  1252. SSLPeerCouldBeClosed_,
  1253. };
  1254. std::string to_string(Error error);
  1255. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1256. class Stream {
  1257. public:
  1258. virtual ~Stream() = default;
  1259. virtual bool is_readable() const = 0;
  1260. virtual bool wait_readable() const = 0;
  1261. virtual bool wait_writable() const = 0;
  1262. virtual bool is_peer_alive() const { return wait_writable(); }
  1263. virtual ssize_t read(char *ptr, size_t size) = 0;
  1264. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1265. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1266. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1267. virtual socket_t socket() const = 0;
  1268. virtual time_t duration() const = 0;
  1269. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1270. (void)sec;
  1271. (void)usec;
  1272. }
  1273. ssize_t write(const char *ptr);
  1274. ssize_t write(const std::string &s);
  1275. Error get_error() const { return error_; }
  1276. protected:
  1277. Error error_ = Error::Success;
  1278. };
  1279. class TaskQueue {
  1280. public:
  1281. TaskQueue() = default;
  1282. virtual ~TaskQueue() = default;
  1283. virtual bool enqueue(std::function<void()> fn) = 0;
  1284. virtual void shutdown() = 0;
  1285. virtual void on_idle() {}
  1286. };
  1287. class ThreadPool final : public TaskQueue {
  1288. public:
  1289. explicit ThreadPool(
  1290. size_t n, size_t max_n = 0, size_t mqr = 0,
  1291. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1292. ThreadPool(const ThreadPool &) = delete;
  1293. ~ThreadPool() override = default;
  1294. bool enqueue(std::function<void()> fn) override;
  1295. void shutdown() override;
  1296. private:
  1297. void worker(bool is_dynamic);
  1298. void move_to_finished(std::thread::id id);
  1299. void cleanup_finished_threads();
  1300. size_t base_thread_count_;
  1301. size_t max_thread_count_;
  1302. size_t max_queued_requests_;
  1303. time_t idle_timeout_sec_;
  1304. size_t idle_thread_count_;
  1305. bool shutdown_;
  1306. std::list<std::function<void()>> jobs_;
  1307. std::vector<std::thread> threads_; // base threads
  1308. std::list<std::thread> dynamic_threads_; // dynamic threads
  1309. std::vector<std::thread>
  1310. finished_threads_; // exited dynamic threads awaiting join
  1311. std::condition_variable cond_;
  1312. std::mutex mutex_;
  1313. };
  1314. using Logger = std::function<void(const Request &, const Response &)>;
  1315. // Forward declaration for Error type
  1316. enum class Error;
  1317. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1318. using SocketOptions = std::function<void(socket_t sock)>;
  1319. void default_socket_options(socket_t sock);
  1320. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1321. const char *status_message(int status);
  1322. std::string to_string(Error error);
  1323. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1324. std::string get_bearer_token_auth(const Request &req);
  1325. namespace detail {
  1326. class MatcherBase {
  1327. public:
  1328. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1329. virtual ~MatcherBase() = default;
  1330. const std::string &pattern() const { return pattern_; }
  1331. // Match request path and populate its matches and
  1332. virtual bool match(Request &request) const = 0;
  1333. private:
  1334. std::string pattern_;
  1335. };
  1336. /**
  1337. * Captures parameters in request path and stores them in Request::path_params
  1338. *
  1339. * Capture name is a substring of a pattern from : to /.
  1340. * The rest of the pattern is matched against the request path directly
  1341. * Parameters are captured starting from the next character after
  1342. * the end of the last matched static pattern fragment until the next /.
  1343. *
  1344. * Example pattern:
  1345. * "/path/fragments/:capture/more/fragments/:second_capture"
  1346. * Static fragments:
  1347. * "/path/fragments/", "more/fragments/"
  1348. *
  1349. * Given the following request path:
  1350. * "/path/fragments/:1/more/fragments/:2"
  1351. * the resulting capture will be
  1352. * {{"capture", "1"}, {"second_capture", "2"}}
  1353. */
  1354. class PathParamsMatcher final : public MatcherBase {
  1355. public:
  1356. PathParamsMatcher(const std::string &pattern);
  1357. bool match(Request &request) const override;
  1358. private:
  1359. // Treat segment separators as the end of path parameter capture
  1360. // Does not need to handle query parameters as they are parsed before path
  1361. // matching
  1362. static constexpr char separator = '/';
  1363. // Contains static path fragments to match against, excluding the '/' after
  1364. // path params
  1365. // Fragments are separated by path params
  1366. std::vector<std::string> static_fragments_;
  1367. // Stores the names of the path parameters to be used as keys in the
  1368. // Request::path_params map
  1369. std::vector<std::string> param_names_;
  1370. };
  1371. /**
  1372. * Performs std::regex_match on request path
  1373. * and stores the result in Request::matches
  1374. *
  1375. * Note that regex match is performed directly on the whole request.
  1376. * This means that wildcard patterns may match multiple path segments with /:
  1377. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1378. */
  1379. class RegexMatcher final : public MatcherBase {
  1380. public:
  1381. RegexMatcher(const std::string &pattern)
  1382. : MatcherBase(pattern), regex_(pattern) {}
  1383. bool match(Request &request) const override;
  1384. private:
  1385. std::regex regex_;
  1386. };
  1387. int close_socket(socket_t sock) noexcept;
  1388. ssize_t write_headers(Stream &strm, const Headers &headers);
  1389. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1390. time_t usec);
  1391. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1392. const std::string &boundary);
  1393. ContentProvider
  1394. make_multipart_content_provider(const UploadFormDataItems &items,
  1395. const std::string &boundary);
  1396. } // namespace detail
  1397. bool is_valid_multipart_boundary(const std::string &boundary);
  1398. // Serializer for multipart/form-data request bodies. The boundary is owned
  1399. // by the writer so that per-part framing and the final terminator always
  1400. // agree. Field names and filenames are escaped following the WHATWG HTML
  1401. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1402. // in content types.
  1403. class MultipartFormDataWriter {
  1404. public:
  1405. MultipartFormDataWriter();
  1406. // precondition: is_valid_multipart_boundary(boundary)
  1407. explicit MultipartFormDataWriter(std::string boundary);
  1408. const std::string &boundary() const;
  1409. std::string content_type() const;
  1410. // In-memory items -> whole body (known length)
  1411. std::string serialize(const UploadFormDataItems &items) const;
  1412. size_t content_length(const UploadFormDataItems &items) const;
  1413. // Per-part framing for streaming via a content provider
  1414. std::string item_begin(const UploadFormData &item) const;
  1415. static std::string item_end();
  1416. std::string finish() const;
  1417. private:
  1418. std::string boundary_;
  1419. };
  1420. class Server {
  1421. public:
  1422. using Handler = std::function<void(const Request &, Response &)>;
  1423. using ExceptionHandler =
  1424. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1425. enum class HandlerResponse {
  1426. Handled,
  1427. Unhandled,
  1428. };
  1429. using HandlerWithResponse =
  1430. std::function<HandlerResponse(const Request &, Response &)>;
  1431. using HandlerWithContentReader = std::function<void(
  1432. const Request &, Response &, const ContentReader &content_reader)>;
  1433. using Expect100ContinueHandler =
  1434. std::function<int(const Request &, Response &)>;
  1435. using StartHandler = std::function<void()>;
  1436. using WebSocketHandler =
  1437. std::function<void(const Request &, ws::WebSocket &)>;
  1438. using SubProtocolSelector =
  1439. std::function<std::string(const std::vector<std::string> &protocols)>;
  1440. Server();
  1441. virtual ~Server();
  1442. virtual bool is_valid() const;
  1443. Server &Get(const std::string &pattern, Handler handler);
  1444. Server &Post(const std::string &pattern, Handler handler);
  1445. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1446. Server &Put(const std::string &pattern, Handler handler);
  1447. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1448. Server &Patch(const std::string &pattern, Handler handler);
  1449. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1450. Server &Delete(const std::string &pattern, Handler handler);
  1451. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1452. Server &Options(const std::string &pattern, Handler handler);
  1453. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1454. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1455. SubProtocolSelector sub_protocol_selector);
  1456. bool set_base_dir(const std::string &dir,
  1457. const std::string &mount_point = std::string());
  1458. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1459. Headers headers = Headers());
  1460. bool remove_mount_point(const std::string &mount_point);
  1461. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1462. const std::string &mime);
  1463. Server &set_default_file_mimetype(const std::string &mime);
  1464. Server &set_file_request_handler(Handler handler);
  1465. template <class ErrorHandlerFunc>
  1466. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1467. return set_error_handler_core(
  1468. std::forward<ErrorHandlerFunc>(handler),
  1469. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1470. }
  1471. Server &set_exception_handler(ExceptionHandler handler);
  1472. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1473. Server &set_post_routing_handler(Handler handler);
  1474. Server &set_pre_request_handler(HandlerWithResponse handler);
  1475. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1476. Server &set_start_handler(StartHandler handler);
  1477. Server &set_logger(Logger logger);
  1478. Server &set_pre_compression_logger(Logger logger);
  1479. Server &set_error_logger(ErrorLogger error_logger);
  1480. Server &set_address_family(int family);
  1481. Server &set_tcp_nodelay(bool on);
  1482. Server &set_ipv6_v6only(bool on);
  1483. Server &set_socket_options(SocketOptions socket_options);
  1484. Server &set_default_headers(Headers headers);
  1485. Server &
  1486. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1487. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1488. Server &set_keep_alive_max_count(size_t count);
  1489. Server &set_keep_alive_timeout(time_t sec);
  1490. template <class Rep, class Period>
  1491. Server &
  1492. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1493. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1494. template <class Rep, class Period>
  1495. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1496. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1497. template <class Rep, class Period>
  1498. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1499. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1500. template <class Rep, class Period>
  1501. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1502. Server &set_payload_max_length(size_t length);
  1503. Server &set_websocket_ping_interval(time_t sec);
  1504. template <class Rep, class Period>
  1505. Server &set_websocket_ping_interval(
  1506. const std::chrono::duration<Rep, Period> &duration);
  1507. Server &set_websocket_max_missed_pongs(int count);
  1508. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1509. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1510. bool listen_after_bind();
  1511. bool listen(const std::string &host, int port, int socket_flags = 0);
  1512. bool is_running() const;
  1513. void wait_until_ready() const;
  1514. void stop() noexcept;
  1515. void decommission();
  1516. std::function<TaskQueue *(void)> new_task_queue;
  1517. protected:
  1518. bool process_request(Stream &strm, const std::string &remote_addr,
  1519. int remote_port, const std::string &local_addr,
  1520. int local_port, bool close_connection,
  1521. bool &connection_closed,
  1522. const std::function<void(Request &)> &setup_request,
  1523. bool *websocket_upgraded = nullptr);
  1524. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1525. std::vector<std::string> trusted_proxies_;
  1526. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1527. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1528. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1529. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1530. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1531. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1532. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1533. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1534. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1535. time_t websocket_ping_interval_sec_ =
  1536. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1537. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1538. private:
  1539. using Handlers =
  1540. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1541. using HandlersForContentReader =
  1542. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1543. HandlerWithContentReader>>;
  1544. static std::unique_ptr<detail::MatcherBase>
  1545. make_matcher(const std::string &pattern);
  1546. template <typename H>
  1547. Server &add_handler(
  1548. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1549. const std::string &pattern, H handler) {
  1550. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1551. return *this;
  1552. }
  1553. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1554. Server &set_error_handler_core(Handler handler, std::false_type);
  1555. socket_t create_server_socket(const std::string &host, int port,
  1556. int socket_flags,
  1557. SocketOptions socket_options) const;
  1558. int bind_internal(const std::string &host, int port, int socket_flags);
  1559. bool listen_internal();
  1560. bool routing(Request &req, Response &res, Stream &strm);
  1561. bool handle_file_request(Request &req, Response &res);
  1562. bool check_if_not_modified(const Request &req, Response &res,
  1563. const std::string &etag, time_t mtime) const;
  1564. bool check_if_range(Request &req, const std::string &etag,
  1565. time_t mtime) const;
  1566. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1567. Stream &strm);
  1568. bool dispatch_request_for_content_reader(
  1569. Request &req, Response &res, ContentReader content_reader,
  1570. const HandlersForContentReader &handlers) const;
  1571. bool parse_request_line(const char *s, Request &req) const;
  1572. void apply_ranges(const Request &req, Response &res,
  1573. std::string &content_type, std::string &boundary) const;
  1574. bool write_response(Stream &strm, bool close_connection, Request &req,
  1575. Response &res);
  1576. bool write_response_with_content(Stream &strm, bool close_connection,
  1577. const Request &req, Response &res);
  1578. bool write_response_core(Stream &strm, bool close_connection,
  1579. const Request &req, Response &res,
  1580. bool need_apply_ranges);
  1581. bool write_content_with_provider(Stream &strm, const Request &req,
  1582. Response &res, const std::string &boundary,
  1583. const std::string &content_type);
  1584. bool read_content(Stream &strm, Request &req, Response &res);
  1585. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1586. Response &res,
  1587. ContentReceiver receiver,
  1588. FormDataHeader multipart_header,
  1589. ContentReceiver multipart_receiver);
  1590. bool read_content_core(Stream &strm, Request &req, Response &res,
  1591. ContentReceiver receiver,
  1592. FormDataHeader multipart_header,
  1593. ContentReceiver multipart_receiver) const;
  1594. virtual bool process_and_close_socket(socket_t sock);
  1595. void output_log(const Request &req, const Response &res) const;
  1596. void output_pre_compression_log(const Request &req,
  1597. const Response &res) const;
  1598. void output_error_log(const Error &err, const Request *req) const;
  1599. std::atomic<bool> is_running_{false};
  1600. std::atomic<bool> is_decommissioned{false};
  1601. struct MountPointEntry {
  1602. std::string mount_point;
  1603. std::string base_dir;
  1604. std::string resolved_base_dir;
  1605. Headers headers;
  1606. };
  1607. std::vector<MountPointEntry> base_dirs_;
  1608. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1609. std::string default_file_mimetype_ = "application/octet-stream";
  1610. Handler file_request_handler_;
  1611. Handlers get_handlers_;
  1612. Handlers post_handlers_;
  1613. HandlersForContentReader post_handlers_for_content_reader_;
  1614. Handlers put_handlers_;
  1615. HandlersForContentReader put_handlers_for_content_reader_;
  1616. Handlers patch_handlers_;
  1617. HandlersForContentReader patch_handlers_for_content_reader_;
  1618. Handlers delete_handlers_;
  1619. HandlersForContentReader delete_handlers_for_content_reader_;
  1620. Handlers options_handlers_;
  1621. struct WebSocketHandlerEntry {
  1622. std::unique_ptr<detail::MatcherBase> matcher;
  1623. WebSocketHandler handler;
  1624. SubProtocolSelector sub_protocol_selector;
  1625. };
  1626. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1627. WebSocketHandlers websocket_handlers_;
  1628. HandlerWithResponse error_handler_;
  1629. ExceptionHandler exception_handler_;
  1630. HandlerWithResponse pre_routing_handler_;
  1631. Handler post_routing_handler_;
  1632. HandlerWithResponse pre_request_handler_;
  1633. Expect100ContinueHandler expect_100_continue_handler_;
  1634. StartHandler start_handler_;
  1635. mutable std::mutex logger_mutex_;
  1636. Logger logger_;
  1637. Logger pre_compression_logger_;
  1638. ErrorLogger error_logger_;
  1639. int address_family_ = AF_UNSPEC;
  1640. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1641. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1642. SocketOptions socket_options_ = default_socket_options;
  1643. Headers default_headers_;
  1644. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1645. detail::write_headers;
  1646. };
  1647. class Result {
  1648. public:
  1649. Result() = default;
  1650. Result(std::unique_ptr<Response> &&res, Error err,
  1651. Headers &&request_headers = Headers{})
  1652. : res_(std::move(res)), err_(err),
  1653. request_headers_(std::move(request_headers)) {}
  1654. // Response
  1655. operator bool() const { return res_ != nullptr; }
  1656. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1657. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1658. const Response &value() const { return *res_; }
  1659. Response &value() { return *res_; }
  1660. const Response &operator*() const { return *res_; }
  1661. Response &operator*() { return *res_; }
  1662. const Response *operator->() const { return res_.get(); }
  1663. Response *operator->() { return res_.get(); }
  1664. // Error
  1665. Error error() const { return err_; }
  1666. // Request Headers
  1667. bool has_request_header(const std::string &key) const;
  1668. std::string get_request_header_value(const std::string &key,
  1669. const char *def = "",
  1670. size_t id = 0) const;
  1671. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1672. size_t id = 0) const;
  1673. size_t get_request_header_value_count(const std::string &key) const;
  1674. private:
  1675. std::unique_ptr<Response> res_;
  1676. Error err_ = Error::Unknown;
  1677. Headers request_headers_;
  1678. #ifdef CPPHTTPLIB_SSL_ENABLED
  1679. public:
  1680. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1681. int ssl_error)
  1682. : res_(std::move(res)), err_(err),
  1683. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1684. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1685. int ssl_error, uint64_t ssl_backend_error)
  1686. : res_(std::move(res)), err_(err),
  1687. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1688. ssl_backend_error_(ssl_backend_error) {}
  1689. int ssl_error() const { return ssl_error_; }
  1690. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1691. private:
  1692. int ssl_error_ = 0;
  1693. uint64_t ssl_backend_error_ = 0;
  1694. #endif
  1695. };
  1696. struct ClientConnection {
  1697. socket_t sock = INVALID_SOCKET;
  1698. bool is_open() const { return sock != INVALID_SOCKET; }
  1699. ClientConnection() = default;
  1700. ~ClientConnection();
  1701. ClientConnection(const ClientConnection &) = delete;
  1702. ClientConnection &operator=(const ClientConnection &) = delete;
  1703. ClientConnection(ClientConnection &&other) noexcept
  1704. : sock(other.sock)
  1705. #ifdef CPPHTTPLIB_SSL_ENABLED
  1706. ,
  1707. session(other.session)
  1708. #endif
  1709. {
  1710. other.sock = INVALID_SOCKET;
  1711. #ifdef CPPHTTPLIB_SSL_ENABLED
  1712. other.session = nullptr;
  1713. #endif
  1714. }
  1715. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1716. if (this != &other) {
  1717. sock = other.sock;
  1718. other.sock = INVALID_SOCKET;
  1719. #ifdef CPPHTTPLIB_SSL_ENABLED
  1720. session = other.session;
  1721. other.session = nullptr;
  1722. #endif
  1723. }
  1724. return *this;
  1725. }
  1726. #ifdef CPPHTTPLIB_SSL_ENABLED
  1727. tls::session_t session = nullptr;
  1728. #endif
  1729. };
  1730. namespace detail {
  1731. struct ChunkedDecoder;
  1732. struct BodyReader {
  1733. Stream *stream = nullptr;
  1734. bool has_content_length = false;
  1735. size_t content_length = 0;
  1736. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1737. size_t bytes_read = 0;
  1738. bool chunked = false;
  1739. bool eof = false;
  1740. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1741. Error last_error = Error::Success;
  1742. ssize_t read(char *buf, size_t len);
  1743. bool has_error() const { return last_error != Error::Success; }
  1744. };
  1745. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1746. size_t len) {
  1747. (void)stream;
  1748. return br.read(buf, len);
  1749. }
  1750. class decompressor;
  1751. enum class NoProxyKind {
  1752. Wildcard, // "*"
  1753. HostnameSuffix, // "example.com" or ".example.com"
  1754. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  1755. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  1756. };
  1757. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  1758. // Lets one CIDR matcher cover both families.
  1759. using IPBytes = std::array<uint8_t, 16>;
  1760. struct NoProxyEntry {
  1761. NoProxyKind kind = NoProxyKind::Wildcard;
  1762. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  1763. IPBytes net{};
  1764. int prefix_bits = 0;
  1765. };
  1766. struct NormalizedTarget {
  1767. std::string hostname; // lowercase; brackets and trailing dot removed
  1768. bool is_ipv4 = false;
  1769. bool is_ipv6 = false;
  1770. IPBytes ip{};
  1771. };
  1772. } // namespace detail
  1773. class ClientImpl {
  1774. public:
  1775. explicit ClientImpl(const std::string &host);
  1776. explicit ClientImpl(const std::string &host, int port);
  1777. explicit ClientImpl(const std::string &host, int port,
  1778. const std::string &client_cert_path,
  1779. const std::string &client_key_path);
  1780. virtual ~ClientImpl();
  1781. virtual bool is_valid() const;
  1782. struct StreamHandle {
  1783. std::unique_ptr<Response> response;
  1784. Error error = Error::Success;
  1785. StreamHandle() = default;
  1786. StreamHandle(const StreamHandle &) = delete;
  1787. StreamHandle &operator=(const StreamHandle &) = delete;
  1788. StreamHandle(StreamHandle &&) = default;
  1789. StreamHandle &operator=(StreamHandle &&) = default;
  1790. ~StreamHandle() = default;
  1791. bool is_valid() const {
  1792. return response != nullptr && error == Error::Success;
  1793. }
  1794. ssize_t read(char *buf, size_t len);
  1795. void parse_trailers_if_needed();
  1796. Error get_read_error() const { return body_reader_.last_error; }
  1797. bool has_read_error() const { return body_reader_.has_error(); }
  1798. bool trailers_parsed_ = false;
  1799. private:
  1800. friend class ClientImpl;
  1801. ssize_t read_with_decompression(char *buf, size_t len);
  1802. std::unique_ptr<ClientConnection> connection_;
  1803. std::unique_ptr<Stream> socket_stream_;
  1804. Stream *stream_ = nullptr;
  1805. detail::BodyReader body_reader_;
  1806. std::unique_ptr<detail::decompressor> decompressor_;
  1807. std::string decompress_buffer_;
  1808. size_t decompress_offset_ = 0;
  1809. size_t decompressed_bytes_read_ = 0;
  1810. };
  1811. // clang-format off
  1812. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1813. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1814. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1815. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1816. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1817. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1818. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1819. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1820. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1821. Result Head(const std::string &path);
  1822. Result Head(const std::string &path, const Headers &headers);
  1823. Result Post(const std::string &path);
  1824. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1825. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1826. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1827. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1828. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1829. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1830. Result Post(const std::string &path, const Params &params);
  1831. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1832. Result Post(const std::string &path, const Headers &headers);
  1833. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1834. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1835. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1836. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1837. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1838. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1839. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1840. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1841. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1842. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1843. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1844. Result Put(const std::string &path);
  1845. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1846. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1847. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1848. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1849. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1850. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1851. Result Put(const std::string &path, const Params &params);
  1852. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1853. Result Put(const std::string &path, const Headers &headers);
  1854. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1855. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1856. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1857. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1858. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1859. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1860. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1861. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1862. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1863. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1864. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1865. Result Patch(const std::string &path);
  1866. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1867. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1868. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1869. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1870. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1871. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1872. Result Patch(const std::string &path, const Params &params);
  1873. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1874. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1875. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1876. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1877. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1878. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1879. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1880. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1881. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1882. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1883. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1884. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1885. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1886. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1887. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1888. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1889. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1890. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1891. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1892. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1893. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1894. Result Options(const std::string &path);
  1895. Result Options(const std::string &path, const Headers &headers);
  1896. // clang-format on
  1897. // Streaming API: Open a stream for reading response body incrementally
  1898. // Socket ownership is transferred to StreamHandle for true streaming
  1899. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1900. StreamHandle open_stream(const std::string &method, const std::string &path,
  1901. const Params &params = {},
  1902. const Headers &headers = {},
  1903. const std::string &body = {},
  1904. const std::string &content_type = {});
  1905. bool send(Request &req, Response &res, Error &error);
  1906. Result send(const Request &req);
  1907. void stop();
  1908. std::string host() const;
  1909. int port() const;
  1910. size_t is_socket_open() const;
  1911. socket_t socket() const;
  1912. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1913. void set_default_headers(Headers headers);
  1914. void
  1915. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1916. void set_address_family(int family);
  1917. void set_tcp_nodelay(bool on);
  1918. void set_ipv6_v6only(bool on);
  1919. void set_socket_options(SocketOptions socket_options);
  1920. void set_connection_timeout(time_t sec, time_t usec = 0);
  1921. template <class Rep, class Period>
  1922. void
  1923. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1924. void set_read_timeout(time_t sec, time_t usec = 0);
  1925. template <class Rep, class Period>
  1926. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1927. void set_write_timeout(time_t sec, time_t usec = 0);
  1928. template <class Rep, class Period>
  1929. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1930. void set_max_timeout(time_t msec);
  1931. template <class Rep, class Period>
  1932. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1933. void set_basic_auth(const std::string &username, const std::string &password);
  1934. void set_bearer_token_auth(const std::string &token);
  1935. void set_keep_alive(bool on);
  1936. void set_follow_location(bool on);
  1937. void set_path_encode(bool on);
  1938. void set_compress(bool on);
  1939. void set_decompress(bool on);
  1940. void set_payload_max_length(size_t length);
  1941. void set_interface(const std::string &intf);
  1942. void set_proxy(const std::string &host, int port);
  1943. void set_proxy_basic_auth(const std::string &username,
  1944. const std::string &password);
  1945. void set_proxy_bearer_token_auth(const std::string &token);
  1946. void set_no_proxy(const std::vector<std::string> &patterns);
  1947. void set_logger(Logger logger);
  1948. void set_error_logger(ErrorLogger error_logger);
  1949. protected:
  1950. struct Socket {
  1951. socket_t sock = INVALID_SOCKET;
  1952. // For Mbed TLS compatibility: start_time for request timeout tracking
  1953. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1954. bool is_open() const { return sock != INVALID_SOCKET; }
  1955. #ifdef CPPHTTPLIB_SSL_ENABLED
  1956. tls::session_t ssl = nullptr;
  1957. #endif
  1958. };
  1959. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1960. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1961. virtual bool setup_proxy_connection(
  1962. Socket &socket,
  1963. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1964. Response &res, bool &success, Error &error);
  1965. bool is_proxy_enabled_for_host(const std::string &host) const;
  1966. // All of:
  1967. // shutdown_ssl
  1968. // shutdown_socket
  1969. // close_socket
  1970. // disconnect
  1971. // should ONLY be called when socket_mutex_ is locked, and only when
  1972. // no other thread is using the socket.
  1973. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1974. void shutdown_socket(Socket &socket) const;
  1975. void close_socket(Socket &socket);
  1976. void disconnect(bool gracefully);
  1977. bool process_request(Stream &strm, Request &req, Response &res,
  1978. bool close_connection, Error &error);
  1979. bool write_content_with_provider(Stream &strm, const Request &req,
  1980. Error &error) const;
  1981. void copy_settings(const ClientImpl &rhs);
  1982. void output_log(const Request &req, const Response &res) const;
  1983. void output_error_log(const Error &err, const Request *req) const;
  1984. // Socket endpoint information
  1985. const std::string host_;
  1986. const int port_;
  1987. // Current open socket
  1988. Socket socket_;
  1989. mutable std::mutex socket_mutex_;
  1990. std::recursive_mutex request_mutex_;
  1991. // These are all protected under socket_mutex
  1992. size_t socket_requests_in_flight_ = 0;
  1993. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1994. bool socket_should_be_closed_when_request_is_done_ = false;
  1995. // Hostname-IP map
  1996. std::map<std::string, std::string> addr_map_;
  1997. // Default headers
  1998. Headers default_headers_;
  1999. // Header writer
  2000. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2001. detail::write_headers;
  2002. // Settings
  2003. std::string client_cert_path_;
  2004. std::string client_key_path_;
  2005. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2006. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2007. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2008. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2009. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2010. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2011. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2012. std::string basic_auth_username_;
  2013. std::string basic_auth_password_;
  2014. std::string bearer_token_auth_token_;
  2015. bool keep_alive_ = false;
  2016. bool follow_location_ = false;
  2017. bool path_encode_ = true;
  2018. int address_family_ = AF_UNSPEC;
  2019. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2020. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2021. SocketOptions socket_options_ = nullptr;
  2022. bool compress_ = false;
  2023. bool decompress_ = true;
  2024. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2025. bool has_payload_max_length_ = false;
  2026. std::string interface_;
  2027. std::string proxy_host_;
  2028. int proxy_port_ = -1;
  2029. std::string proxy_basic_auth_username_;
  2030. std::string proxy_basic_auth_password_;
  2031. std::string proxy_bearer_token_auth_token_;
  2032. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2033. mutable detail::NormalizedTarget host_normalized_;
  2034. mutable bool host_normalized_valid_ = false;
  2035. mutable std::mutex logger_mutex_;
  2036. Logger logger_;
  2037. ErrorLogger error_logger_;
  2038. private:
  2039. bool send_(Request &req, Response &res, Error &error);
  2040. Result send_(Request &&req);
  2041. socket_t create_client_socket(Error &error) const;
  2042. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2043. bool skip_100_continue = true) const;
  2044. bool write_request(Stream &strm, Request &req, bool close_connection,
  2045. Error &error, bool skip_body = false);
  2046. bool write_request_body(Stream &strm, Request &req, Error &error);
  2047. void prepare_default_headers(Request &r, bool for_stream,
  2048. const std::string &ct);
  2049. bool redirect(Request &req, Response &res, Error &error);
  2050. bool create_redirect_client(const std::string &scheme,
  2051. const std::string &host, int port, Request &req,
  2052. Response &res, const std::string &path,
  2053. const std::string &location, Error &error);
  2054. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2055. bool handle_request(Stream &strm, Request &req, Response &res,
  2056. bool close_connection, Error &error);
  2057. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2058. Request &req, const char *body, size_t content_length,
  2059. ContentProvider content_provider,
  2060. ContentProviderWithoutLength content_provider_without_length,
  2061. const std::string &content_type, ContentReceiver content_receiver,
  2062. Error &error);
  2063. Result send_with_content_provider_and_receiver(
  2064. const std::string &method, const std::string &path,
  2065. const Headers &headers, const char *body, size_t content_length,
  2066. ContentProvider content_provider,
  2067. ContentProviderWithoutLength content_provider_without_length,
  2068. const std::string &content_type, ContentReceiver content_receiver,
  2069. UploadProgress progress);
  2070. ContentProviderWithoutLength get_multipart_content_provider(
  2071. const std::string &boundary, const UploadFormDataItems &items,
  2072. const FormDataProviderItems &provider_items) const;
  2073. virtual bool
  2074. process_socket(const Socket &socket,
  2075. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2076. std::function<bool(Stream &strm)> callback);
  2077. virtual bool is_ssl() const;
  2078. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2079. #ifdef CPPHTTPLIB_SSL_ENABLED
  2080. public:
  2081. void set_digest_auth(const std::string &username,
  2082. const std::string &password);
  2083. void set_proxy_digest_auth(const std::string &username,
  2084. const std::string &password);
  2085. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2086. const std::string &ca_cert_dir_path = std::string());
  2087. void enable_server_certificate_verification(bool enabled);
  2088. void enable_server_hostname_verification(bool enabled);
  2089. void enable_system_ca(bool enabled);
  2090. protected:
  2091. std::string digest_auth_username_;
  2092. std::string digest_auth_password_;
  2093. std::string proxy_digest_auth_username_;
  2094. std::string proxy_digest_auth_password_;
  2095. std::string ca_cert_file_path_;
  2096. std::string ca_cert_dir_path_;
  2097. bool server_certificate_verification_ = true;
  2098. bool server_hostname_verification_ = true;
  2099. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2100. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2101. int last_ssl_error_ = 0;
  2102. uint64_t last_backend_error_ = 0;
  2103. #endif
  2104. };
  2105. class Client {
  2106. public:
  2107. // Universal interface
  2108. explicit Client(const std::string &scheme_host_port);
  2109. explicit Client(const std::string &scheme_host_port,
  2110. const std::string &client_cert_path,
  2111. const std::string &client_key_path);
  2112. // HTTP only interface
  2113. explicit Client(const std::string &host, int port);
  2114. explicit Client(const std::string &host, int port,
  2115. const std::string &client_cert_path,
  2116. const std::string &client_key_path);
  2117. Client(Client &&) = default;
  2118. Client &operator=(Client &&) = default;
  2119. ~Client();
  2120. bool is_valid() const;
  2121. // clang-format off
  2122. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2123. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2124. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2125. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2126. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2127. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2128. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2129. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2130. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2131. Result Head(const std::string &path);
  2132. Result Head(const std::string &path, const Headers &headers);
  2133. Result Post(const std::string &path);
  2134. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2135. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2136. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2137. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2138. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2139. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2140. Result Post(const std::string &path, const Params &params);
  2141. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2142. Result Post(const std::string &path, const Headers &headers);
  2143. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2144. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2145. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2146. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2147. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2148. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2149. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2150. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2151. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2152. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2153. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2154. Result Put(const std::string &path);
  2155. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2156. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2157. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2158. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2159. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2160. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2161. Result Put(const std::string &path, const Params &params);
  2162. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2163. Result Put(const std::string &path, const Headers &headers);
  2164. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2165. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2166. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2167. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2168. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2169. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2170. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2171. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2172. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2173. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2174. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2175. Result Patch(const std::string &path);
  2176. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2177. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2178. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2179. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2180. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2181. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2182. Result Patch(const std::string &path, const Params &params);
  2183. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2184. Result Patch(const std::string &path, const Headers &headers);
  2185. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2186. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2187. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2188. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2189. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2190. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2191. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2192. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2193. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2194. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2195. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2196. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2197. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2198. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2199. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2200. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2201. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2202. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2203. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2204. Result Options(const std::string &path);
  2205. Result Options(const std::string &path, const Headers &headers);
  2206. // clang-format on
  2207. // Streaming API: Open a stream for reading response body incrementally
  2208. // Socket ownership is transferred to StreamHandle for true streaming
  2209. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2210. ClientImpl::StreamHandle open_stream(const std::string &method,
  2211. const std::string &path,
  2212. const Params &params = {},
  2213. const Headers &headers = {},
  2214. const std::string &body = {},
  2215. const std::string &content_type = {});
  2216. bool send(Request &req, Response &res, Error &error);
  2217. Result send(const Request &req);
  2218. void stop();
  2219. std::string host() const;
  2220. int port() const;
  2221. size_t is_socket_open() const;
  2222. socket_t socket() const;
  2223. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2224. void set_default_headers(Headers headers);
  2225. void
  2226. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2227. void set_address_family(int family);
  2228. void set_tcp_nodelay(bool on);
  2229. void set_socket_options(SocketOptions socket_options);
  2230. void set_connection_timeout(time_t sec, time_t usec = 0);
  2231. template <class Rep, class Period>
  2232. void
  2233. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2234. void set_read_timeout(time_t sec, time_t usec = 0);
  2235. template <class Rep, class Period>
  2236. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2237. void set_write_timeout(time_t sec, time_t usec = 0);
  2238. template <class Rep, class Period>
  2239. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2240. void set_max_timeout(time_t msec);
  2241. template <class Rep, class Period>
  2242. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2243. void set_basic_auth(const std::string &username, const std::string &password);
  2244. void set_bearer_token_auth(const std::string &token);
  2245. void set_keep_alive(bool on);
  2246. void set_follow_location(bool on);
  2247. void set_path_encode(bool on);
  2248. void set_compress(bool on);
  2249. void set_decompress(bool on);
  2250. void set_payload_max_length(size_t length);
  2251. void set_interface(const std::string &intf);
  2252. void set_proxy(const std::string &host, int port);
  2253. void set_proxy_basic_auth(const std::string &username,
  2254. const std::string &password);
  2255. void set_proxy_bearer_token_auth(const std::string &token);
  2256. void set_no_proxy(const std::vector<std::string> &patterns);
  2257. void set_logger(Logger logger);
  2258. void set_error_logger(ErrorLogger error_logger);
  2259. private:
  2260. std::unique_ptr<ClientImpl> cli_;
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. public:
  2263. void set_digest_auth(const std::string &username,
  2264. const std::string &password);
  2265. void set_proxy_digest_auth(const std::string &username,
  2266. const std::string &password);
  2267. void enable_server_certificate_verification(bool enabled);
  2268. void enable_server_hostname_verification(bool enabled);
  2269. void enable_system_ca(bool enabled);
  2270. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2271. const std::string &ca_cert_dir_path = std::string());
  2272. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2273. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2274. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2275. void set_session_verifier(
  2276. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2277. tls::ctx_t tls_context() const;
  2278. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2279. void enable_windows_certificate_verification(bool enabled);
  2280. #endif
  2281. private:
  2282. bool is_ssl_ = false;
  2283. #endif
  2284. };
  2285. #ifdef CPPHTTPLIB_SSL_ENABLED
  2286. class SSLServer : public Server {
  2287. public:
  2288. SSLServer(const char *cert_path, const char *private_key_path,
  2289. const char *client_ca_cert_file_path = nullptr,
  2290. const char *client_ca_cert_dir_path = nullptr,
  2291. const char *private_key_password = nullptr);
  2292. struct PemMemory {
  2293. const char *cert_pem;
  2294. size_t cert_pem_len;
  2295. const char *key_pem;
  2296. size_t key_pem_len;
  2297. const char *client_ca_pem;
  2298. size_t client_ca_pem_len;
  2299. const char *private_key_password;
  2300. };
  2301. explicit SSLServer(const PemMemory &pem);
  2302. // The callback receives the ctx_t handle which can be cast to the
  2303. // appropriate backend type (SSL_CTX* for OpenSSL,
  2304. // tls::impl::MbedTlsContext* for Mbed TLS)
  2305. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2306. ~SSLServer() override;
  2307. bool is_valid() const override;
  2308. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2309. const char *client_ca_pem = nullptr,
  2310. const char *password = nullptr);
  2311. tls::ctx_t tls_context() const { return ctx_; }
  2312. int ssl_last_error() const { return last_ssl_error_; }
  2313. private:
  2314. bool process_and_close_socket(socket_t sock) override;
  2315. tls::ctx_t ctx_ = nullptr;
  2316. std::mutex ctx_mutex_;
  2317. int last_ssl_error_ = 0;
  2318. };
  2319. class SSLClient final : public ClientImpl {
  2320. public:
  2321. explicit SSLClient(const std::string &host);
  2322. explicit SSLClient(const std::string &host, int port);
  2323. explicit SSLClient(const std::string &host, int port,
  2324. const std::string &client_cert_path,
  2325. const std::string &client_key_path,
  2326. const std::string &private_key_password = std::string());
  2327. struct PemMemory {
  2328. const char *cert_pem;
  2329. size_t cert_pem_len;
  2330. const char *key_pem;
  2331. size_t key_pem_len;
  2332. const char *private_key_password;
  2333. };
  2334. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2335. ~SSLClient() override;
  2336. bool is_valid() const override;
  2337. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2338. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2339. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2340. // Post-handshake session verifier (backend-independent)
  2341. void set_session_verifier(
  2342. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2343. tls::ctx_t tls_context() const { return ctx_; }
  2344. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2345. void enable_windows_certificate_verification(bool enabled);
  2346. #endif
  2347. private:
  2348. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2349. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2350. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2351. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2352. bool
  2353. process_socket(const Socket &socket,
  2354. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2355. std::function<bool(Stream &strm)> callback) override;
  2356. bool is_ssl() const override;
  2357. bool setup_proxy_connection(
  2358. Socket &socket,
  2359. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2360. Response &res, bool &success, Error &error) override;
  2361. bool connect_with_proxy(
  2362. Socket &sock,
  2363. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2364. Response &res, bool &success, Error &error);
  2365. bool initialize_ssl(Socket &socket, Error &error);
  2366. void init_ctx();
  2367. void reset_ctx_on_error();
  2368. bool load_certs();
  2369. tls::ctx_t ctx_ = nullptr;
  2370. std::mutex ctx_mutex_;
  2371. std::once_flag initialize_cert_;
  2372. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2373. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2374. // Used to keep custom CA configuration exclusive with system CA loading.
  2375. bool ca_cert_store_set_ = false;
  2376. long verify_result_ = 0;
  2377. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2378. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2379. bool enable_windows_cert_verification_ = true;
  2380. #endif
  2381. friend class ClientImpl;
  2382. };
  2383. #endif // CPPHTTPLIB_SSL_ENABLED
  2384. namespace detail {
  2385. template <typename T, typename U>
  2386. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2387. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2388. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2389. duration - std::chrono::seconds(sec))
  2390. .count();
  2391. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2392. }
  2393. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2394. return N - 1;
  2395. }
  2396. inline bool is_numeric(const std::string &str) {
  2397. return !str.empty() &&
  2398. std::all_of(str.cbegin(), str.cend(),
  2399. [](unsigned char c) { return std::isdigit(c); });
  2400. }
  2401. inline size_t get_header_value_u64(const Headers &headers,
  2402. const std::string &key, size_t def,
  2403. size_t id, bool &is_invalid_value) {
  2404. is_invalid_value = false;
  2405. auto rng = headers.equal_range(key);
  2406. auto it = rng.first;
  2407. std::advance(it, static_cast<ssize_t>(id));
  2408. if (it != rng.second) {
  2409. if (is_numeric(it->second)) {
  2410. return static_cast<size_t>(std::strtoull(it->second.data(), nullptr, 10));
  2411. } else {
  2412. is_invalid_value = true;
  2413. }
  2414. }
  2415. return def;
  2416. }
  2417. inline size_t get_header_value_u64(const Headers &headers,
  2418. const std::string &key, size_t def,
  2419. size_t id) {
  2420. auto dummy = false;
  2421. return get_header_value_u64(headers, key, def, id, dummy);
  2422. }
  2423. } // namespace detail
  2424. template <class Rep, class Period>
  2425. inline Server &
  2426. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2427. detail::duration_to_sec_and_usec(
  2428. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2429. return *this;
  2430. }
  2431. template <class Rep, class Period>
  2432. inline Server &
  2433. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2434. detail::duration_to_sec_and_usec(
  2435. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2436. return *this;
  2437. }
  2438. template <class Rep, class Period>
  2439. inline Server &
  2440. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2441. detail::duration_to_sec_and_usec(
  2442. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2443. return *this;
  2444. }
  2445. template <class Rep, class Period>
  2446. inline void ClientImpl::set_connection_timeout(
  2447. const std::chrono::duration<Rep, Period> &duration) {
  2448. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2449. set_connection_timeout(sec, usec);
  2450. });
  2451. }
  2452. template <class Rep, class Period>
  2453. inline void ClientImpl::set_read_timeout(
  2454. const std::chrono::duration<Rep, Period> &duration) {
  2455. detail::duration_to_sec_and_usec(
  2456. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2457. }
  2458. template <class Rep, class Period>
  2459. inline void ClientImpl::set_write_timeout(
  2460. const std::chrono::duration<Rep, Period> &duration) {
  2461. detail::duration_to_sec_and_usec(
  2462. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2463. }
  2464. template <class Rep, class Period>
  2465. inline void ClientImpl::set_max_timeout(
  2466. const std::chrono::duration<Rep, Period> &duration) {
  2467. auto msec =
  2468. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2469. set_max_timeout(msec);
  2470. }
  2471. template <class Rep, class Period>
  2472. inline void Client::set_connection_timeout(
  2473. const std::chrono::duration<Rep, Period> &duration) {
  2474. cli_->set_connection_timeout(duration);
  2475. }
  2476. template <class Rep, class Period>
  2477. inline void
  2478. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2479. cli_->set_read_timeout(duration);
  2480. }
  2481. template <class Rep, class Period>
  2482. inline void
  2483. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2484. cli_->set_write_timeout(duration);
  2485. }
  2486. inline void Client::set_max_timeout(time_t msec) {
  2487. cli_->set_max_timeout(msec);
  2488. }
  2489. template <class Rep, class Period>
  2490. inline void
  2491. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2492. cli_->set_max_timeout(duration);
  2493. }
  2494. /*
  2495. * Forward declarations and types that will be part of the .h file if split into
  2496. * .h + .cc.
  2497. */
  2498. std::string hosted_at(const std::string &hostname);
  2499. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2500. // JavaScript-style URL encoding/decoding functions
  2501. std::string encode_uri_component(const std::string &value);
  2502. std::string encode_uri(const std::string &value);
  2503. std::string decode_uri_component(const std::string &value);
  2504. std::string decode_uri(const std::string &value);
  2505. // RFC 3986 compliant URL component encoding/decoding functions
  2506. std::string encode_path_component(const std::string &component);
  2507. std::string decode_path_component(const std::string &component);
  2508. std::string encode_query_component(const std::string &component,
  2509. bool space_as_plus = true);
  2510. std::string decode_query_component(const std::string &component,
  2511. bool plus_as_space = true);
  2512. std::string sanitize_filename(const std::string &filename);
  2513. std::string append_query_params(const std::string &path, const Params &params);
  2514. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2515. std::pair<std::string, std::string>
  2516. make_basic_authentication_header(const std::string &username,
  2517. const std::string &password,
  2518. bool is_proxy = false);
  2519. namespace detail {
  2520. #if defined(_WIN32)
  2521. inline std::wstring u8string_to_wstring(const char *s) {
  2522. if (!s) { return std::wstring(); }
  2523. auto len = static_cast<int>(strlen(s));
  2524. if (!len) { return std::wstring(); }
  2525. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2526. if (!wlen) { return std::wstring(); }
  2527. std::wstring ws;
  2528. ws.resize(wlen);
  2529. wlen = ::MultiByteToWideChar(
  2530. CP_UTF8, 0, s, len,
  2531. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2532. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2533. return ws;
  2534. }
  2535. #endif
  2536. struct FileStat {
  2537. FileStat(const std::string &path);
  2538. bool is_file() const;
  2539. bool is_dir() const;
  2540. time_t mtime() const;
  2541. size_t size() const;
  2542. private:
  2543. #if defined(_WIN32)
  2544. struct _stat st_;
  2545. #else
  2546. struct stat st_;
  2547. #endif
  2548. int ret_ = -1;
  2549. };
  2550. std::string make_host_and_port_string(const std::string &host, int port,
  2551. bool is_ssl);
  2552. std::string trim_copy(const std::string &s);
  2553. void divide(
  2554. const char *data, std::size_t size, char d,
  2555. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2556. fn);
  2557. void divide(
  2558. const std::string &str, char d,
  2559. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2560. fn);
  2561. void split(const char *b, const char *e, char d,
  2562. std::function<void(const char *, const char *)> fn);
  2563. void split(const char *b, const char *e, char d, size_t m,
  2564. std::function<void(const char *, const char *)> fn);
  2565. bool process_client_socket(
  2566. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2567. time_t write_timeout_sec, time_t write_timeout_usec,
  2568. time_t max_timeout_msec,
  2569. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2570. std::function<bool(Stream &)> callback);
  2571. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2572. int port, int address_family, bool tcp_nodelay,
  2573. bool ipv6_v6only, SocketOptions socket_options,
  2574. time_t connection_timeout_sec,
  2575. time_t connection_timeout_usec,
  2576. time_t read_timeout_sec, time_t read_timeout_usec,
  2577. time_t write_timeout_sec,
  2578. time_t write_timeout_usec,
  2579. const std::string &intf, Error &error);
  2580. const char *get_header_value(const Headers &headers, const std::string &key,
  2581. const char *def, size_t id);
  2582. std::string params_to_query_str(const Params &params);
  2583. void parse_query_text(const char *data, std::size_t size, Params &params);
  2584. void parse_query_text(const std::string &s, Params &params);
  2585. bool parse_multipart_boundary(const std::string &content_type,
  2586. std::string &boundary);
  2587. bool parse_range_header(const std::string &s, Ranges &ranges);
  2588. bool parse_accept_header(const std::string &s,
  2589. std::vector<std::string> &content_types);
  2590. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2591. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2592. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2593. EncodingType encoding_type(const Request &req, const Response &res);
  2594. class BufferStream final : public Stream {
  2595. public:
  2596. BufferStream() = default;
  2597. ~BufferStream() override = default;
  2598. bool is_readable() const override;
  2599. bool wait_readable() const override;
  2600. bool wait_writable() const override;
  2601. ssize_t read(char *ptr, size_t size) override;
  2602. ssize_t write(const char *ptr, size_t size) override;
  2603. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2604. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2605. socket_t socket() const override;
  2606. time_t duration() const override;
  2607. const std::string &get_buffer() const;
  2608. private:
  2609. std::string buffer;
  2610. size_t position = 0;
  2611. };
  2612. class compressor {
  2613. public:
  2614. virtual ~compressor() = default;
  2615. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2616. virtual bool compress(const char *data, size_t data_length, bool last,
  2617. Callback callback) = 0;
  2618. };
  2619. class decompressor {
  2620. public:
  2621. virtual ~decompressor() = default;
  2622. virtual bool is_valid() const = 0;
  2623. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2624. virtual bool decompress(const char *data, size_t data_length,
  2625. Callback callback) = 0;
  2626. };
  2627. class nocompressor final : public compressor {
  2628. public:
  2629. ~nocompressor() override = default;
  2630. bool compress(const char *data, size_t data_length, bool /*last*/,
  2631. Callback callback) override;
  2632. };
  2633. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2634. class gzip_compressor final : public compressor {
  2635. public:
  2636. gzip_compressor();
  2637. ~gzip_compressor() override;
  2638. bool compress(const char *data, size_t data_length, bool last,
  2639. Callback callback) override;
  2640. private:
  2641. bool is_valid_ = false;
  2642. z_stream strm_;
  2643. };
  2644. class gzip_decompressor final : public decompressor {
  2645. public:
  2646. gzip_decompressor();
  2647. ~gzip_decompressor() override;
  2648. bool is_valid() const override;
  2649. bool decompress(const char *data, size_t data_length,
  2650. Callback callback) override;
  2651. private:
  2652. bool is_valid_ = false;
  2653. z_stream strm_;
  2654. };
  2655. #endif
  2656. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2657. class brotli_compressor final : public compressor {
  2658. public:
  2659. brotli_compressor();
  2660. ~brotli_compressor();
  2661. bool compress(const char *data, size_t data_length, bool last,
  2662. Callback callback) override;
  2663. private:
  2664. BrotliEncoderState *state_ = nullptr;
  2665. };
  2666. class brotli_decompressor final : public decompressor {
  2667. public:
  2668. brotli_decompressor();
  2669. ~brotli_decompressor();
  2670. bool is_valid() const override;
  2671. bool decompress(const char *data, size_t data_length,
  2672. Callback callback) override;
  2673. private:
  2674. BrotliDecoderResult decoder_r;
  2675. BrotliDecoderState *decoder_s = nullptr;
  2676. };
  2677. #endif
  2678. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2679. class zstd_compressor : public compressor {
  2680. public:
  2681. zstd_compressor();
  2682. ~zstd_compressor();
  2683. bool compress(const char *data, size_t data_length, bool last,
  2684. Callback callback) override;
  2685. private:
  2686. ZSTD_CCtx *ctx_ = nullptr;
  2687. };
  2688. class zstd_decompressor : public decompressor {
  2689. public:
  2690. zstd_decompressor();
  2691. ~zstd_decompressor();
  2692. bool is_valid() const override;
  2693. bool decompress(const char *data, size_t data_length,
  2694. Callback callback) override;
  2695. private:
  2696. ZSTD_DCtx *ctx_ = nullptr;
  2697. };
  2698. #endif
  2699. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2700. // to store data. The call can set memory on stack for performance.
  2701. class stream_line_reader {
  2702. public:
  2703. stream_line_reader(Stream &strm, char *fixed_buffer,
  2704. size_t fixed_buffer_size);
  2705. const char *ptr() const;
  2706. size_t size() const;
  2707. bool end_with_crlf() const;
  2708. bool getline();
  2709. private:
  2710. void append(char c);
  2711. Stream &strm_;
  2712. char *fixed_buffer_;
  2713. const size_t fixed_buffer_size_;
  2714. size_t fixed_buffer_used_size_ = 0;
  2715. std::string growable_buffer_;
  2716. };
  2717. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2718. const Headers &src_headers);
  2719. struct ChunkedDecoder {
  2720. Stream &strm;
  2721. size_t chunk_remaining = 0;
  2722. bool finished = false;
  2723. char line_buf[64];
  2724. size_t last_chunk_total = 0;
  2725. size_t last_chunk_offset = 0;
  2726. explicit ChunkedDecoder(Stream &s);
  2727. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2728. size_t &out_chunk_total);
  2729. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2730. };
  2731. class mmap {
  2732. public:
  2733. mmap(const char *path);
  2734. ~mmap();
  2735. bool open(const char *path);
  2736. void close();
  2737. bool is_open() const;
  2738. size_t size() const;
  2739. const char *data() const;
  2740. private:
  2741. #if defined(_WIN32)
  2742. HANDLE hFile_ = NULL;
  2743. HANDLE hMapping_ = NULL;
  2744. #else
  2745. int fd_ = -1;
  2746. #endif
  2747. size_t size_ = 0;
  2748. void *addr_ = nullptr;
  2749. bool is_open_empty_file = false;
  2750. };
  2751. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2752. namespace fields {
  2753. bool is_token_char(char c);
  2754. bool is_token(const std::string &s);
  2755. bool is_field_name(const std::string &s);
  2756. bool is_vchar(char c);
  2757. bool is_obs_text(char c);
  2758. bool is_field_vchar(char c);
  2759. bool is_field_content(const std::string &s);
  2760. bool is_field_value(const std::string &s);
  2761. } // namespace fields
  2762. } // namespace detail
  2763. /*
  2764. * TLS Abstraction Layer Declarations
  2765. */
  2766. #ifdef CPPHTTPLIB_SSL_ENABLED
  2767. // TLS abstraction layer - backend-specific type declarations
  2768. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2769. namespace tls {
  2770. namespace impl {
  2771. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2772. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2773. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2774. struct MbedTlsContext {
  2775. mbedtls_ssl_config conf;
  2776. mbedtls_entropy_context entropy;
  2777. mbedtls_ctr_drbg_context ctr_drbg;
  2778. mbedtls_x509_crt ca_chain;
  2779. mbedtls_x509_crt own_cert;
  2780. mbedtls_pk_context own_key;
  2781. bool is_server = false;
  2782. bool verify_client = false;
  2783. bool has_verify_callback = false;
  2784. MbedTlsContext();
  2785. ~MbedTlsContext();
  2786. MbedTlsContext(const MbedTlsContext &) = delete;
  2787. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2788. };
  2789. } // namespace impl
  2790. } // namespace tls
  2791. #endif
  2792. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2793. namespace tls {
  2794. namespace impl {
  2795. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2796. // This struct is accessible via tls::impl for use in SSL context
  2797. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2798. struct WolfSSLContext {
  2799. WOLFSSL_CTX *ctx = nullptr;
  2800. bool is_server = false;
  2801. bool verify_client = false;
  2802. bool has_verify_callback = false;
  2803. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2804. WolfSSLContext();
  2805. ~WolfSSLContext();
  2806. WolfSSLContext(const WolfSSLContext &) = delete;
  2807. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2808. };
  2809. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2810. struct WolfSSLCAStore {
  2811. std::string pem_data;
  2812. };
  2813. } // namespace impl
  2814. } // namespace tls
  2815. #endif
  2816. #endif // CPPHTTPLIB_SSL_ENABLED
  2817. namespace stream {
  2818. class Result {
  2819. public:
  2820. Result();
  2821. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2822. Result(Result &&other) noexcept;
  2823. Result &operator=(Result &&other) noexcept;
  2824. Result(const Result &) = delete;
  2825. Result &operator=(const Result &) = delete;
  2826. // Response info
  2827. bool is_valid() const;
  2828. explicit operator bool() const;
  2829. int status() const;
  2830. const Headers &headers() const;
  2831. std::string get_header_value(const std::string &key,
  2832. const char *def = "") const;
  2833. bool has_header(const std::string &key) const;
  2834. Error error() const;
  2835. Error read_error() const;
  2836. bool has_read_error() const;
  2837. // Stream reading
  2838. bool next();
  2839. const char *data() const;
  2840. size_t size() const;
  2841. std::string read_all();
  2842. private:
  2843. ClientImpl::StreamHandle handle_;
  2844. std::string buffer_;
  2845. size_t current_size_ = 0;
  2846. size_t chunk_size_;
  2847. bool finished_ = false;
  2848. };
  2849. // GET
  2850. template <typename ClientType>
  2851. inline Result Get(ClientType &cli, const std::string &path,
  2852. size_t chunk_size = 8192) {
  2853. return Result{cli.open_stream("GET", path), chunk_size};
  2854. }
  2855. template <typename ClientType>
  2856. inline Result Get(ClientType &cli, const std::string &path,
  2857. const Headers &headers, size_t chunk_size = 8192) {
  2858. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2859. }
  2860. template <typename ClientType>
  2861. inline Result Get(ClientType &cli, const std::string &path,
  2862. const Params &params, size_t chunk_size = 8192) {
  2863. return Result{cli.open_stream("GET", path, params), chunk_size};
  2864. }
  2865. template <typename ClientType>
  2866. inline Result Get(ClientType &cli, const std::string &path,
  2867. const Params &params, const Headers &headers,
  2868. size_t chunk_size = 8192) {
  2869. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2870. }
  2871. // POST
  2872. template <typename ClientType>
  2873. inline Result Post(ClientType &cli, const std::string &path,
  2874. const std::string &body, const std::string &content_type,
  2875. size_t chunk_size = 8192) {
  2876. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2877. chunk_size};
  2878. }
  2879. template <typename ClientType>
  2880. inline Result Post(ClientType &cli, const std::string &path,
  2881. const Headers &headers, const std::string &body,
  2882. const std::string &content_type, size_t chunk_size = 8192) {
  2883. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2884. chunk_size};
  2885. }
  2886. template <typename ClientType>
  2887. inline Result Post(ClientType &cli, const std::string &path,
  2888. const Params &params, const std::string &body,
  2889. const std::string &content_type, size_t chunk_size = 8192) {
  2890. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2891. chunk_size};
  2892. }
  2893. template <typename ClientType>
  2894. inline Result Post(ClientType &cli, const std::string &path,
  2895. const Params &params, const Headers &headers,
  2896. const std::string &body, const std::string &content_type,
  2897. size_t chunk_size = 8192) {
  2898. return Result{
  2899. cli.open_stream("POST", path, params, headers, body, content_type),
  2900. chunk_size};
  2901. }
  2902. // PUT
  2903. template <typename ClientType>
  2904. inline Result Put(ClientType &cli, const std::string &path,
  2905. const std::string &body, const std::string &content_type,
  2906. size_t chunk_size = 8192) {
  2907. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2908. chunk_size};
  2909. }
  2910. template <typename ClientType>
  2911. inline Result Put(ClientType &cli, const std::string &path,
  2912. const Headers &headers, const std::string &body,
  2913. const std::string &content_type, size_t chunk_size = 8192) {
  2914. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2915. chunk_size};
  2916. }
  2917. template <typename ClientType>
  2918. inline Result Put(ClientType &cli, const std::string &path,
  2919. const Params &params, const std::string &body,
  2920. const std::string &content_type, size_t chunk_size = 8192) {
  2921. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2922. chunk_size};
  2923. }
  2924. template <typename ClientType>
  2925. inline Result Put(ClientType &cli, const std::string &path,
  2926. const Params &params, const Headers &headers,
  2927. const std::string &body, const std::string &content_type,
  2928. size_t chunk_size = 8192) {
  2929. return Result{
  2930. cli.open_stream("PUT", path, params, headers, body, content_type),
  2931. chunk_size};
  2932. }
  2933. // PATCH
  2934. template <typename ClientType>
  2935. inline Result Patch(ClientType &cli, const std::string &path,
  2936. const std::string &body, const std::string &content_type,
  2937. size_t chunk_size = 8192) {
  2938. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2939. chunk_size};
  2940. }
  2941. template <typename ClientType>
  2942. inline Result Patch(ClientType &cli, const std::string &path,
  2943. const Headers &headers, const std::string &body,
  2944. const std::string &content_type, size_t chunk_size = 8192) {
  2945. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2946. chunk_size};
  2947. }
  2948. template <typename ClientType>
  2949. inline Result Patch(ClientType &cli, const std::string &path,
  2950. const Params &params, const std::string &body,
  2951. const std::string &content_type, size_t chunk_size = 8192) {
  2952. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2953. chunk_size};
  2954. }
  2955. template <typename ClientType>
  2956. inline Result Patch(ClientType &cli, const std::string &path,
  2957. const Params &params, const Headers &headers,
  2958. const std::string &body, const std::string &content_type,
  2959. size_t chunk_size = 8192) {
  2960. return Result{
  2961. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2962. chunk_size};
  2963. }
  2964. // DELETE
  2965. template <typename ClientType>
  2966. inline Result Delete(ClientType &cli, const std::string &path,
  2967. size_t chunk_size = 8192) {
  2968. return Result{cli.open_stream("DELETE", path), chunk_size};
  2969. }
  2970. template <typename ClientType>
  2971. inline Result Delete(ClientType &cli, const std::string &path,
  2972. const Headers &headers, size_t chunk_size = 8192) {
  2973. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2974. }
  2975. template <typename ClientType>
  2976. inline Result Delete(ClientType &cli, const std::string &path,
  2977. const std::string &body, const std::string &content_type,
  2978. size_t chunk_size = 8192) {
  2979. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2980. chunk_size};
  2981. }
  2982. template <typename ClientType>
  2983. inline Result Delete(ClientType &cli, const std::string &path,
  2984. const Headers &headers, const std::string &body,
  2985. const std::string &content_type,
  2986. size_t chunk_size = 8192) {
  2987. return Result{
  2988. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  2989. chunk_size};
  2990. }
  2991. template <typename ClientType>
  2992. inline Result Delete(ClientType &cli, const std::string &path,
  2993. const Params &params, size_t chunk_size = 8192) {
  2994. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  2995. }
  2996. template <typename ClientType>
  2997. inline Result Delete(ClientType &cli, const std::string &path,
  2998. const Params &params, const Headers &headers,
  2999. size_t chunk_size = 8192) {
  3000. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3001. }
  3002. template <typename ClientType>
  3003. inline Result Delete(ClientType &cli, const std::string &path,
  3004. const Params &params, const std::string &body,
  3005. const std::string &content_type,
  3006. size_t chunk_size = 8192) {
  3007. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3008. chunk_size};
  3009. }
  3010. template <typename ClientType>
  3011. inline Result Delete(ClientType &cli, const std::string &path,
  3012. const Params &params, const Headers &headers,
  3013. const std::string &body, const std::string &content_type,
  3014. size_t chunk_size = 8192) {
  3015. return Result{
  3016. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3017. chunk_size};
  3018. }
  3019. // HEAD
  3020. template <typename ClientType>
  3021. inline Result Head(ClientType &cli, const std::string &path,
  3022. size_t chunk_size = 8192) {
  3023. return Result{cli.open_stream("HEAD", path), chunk_size};
  3024. }
  3025. template <typename ClientType>
  3026. inline Result Head(ClientType &cli, const std::string &path,
  3027. const Headers &headers, size_t chunk_size = 8192) {
  3028. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3029. }
  3030. template <typename ClientType>
  3031. inline Result Head(ClientType &cli, const std::string &path,
  3032. const Params &params, size_t chunk_size = 8192) {
  3033. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3034. }
  3035. template <typename ClientType>
  3036. inline Result Head(ClientType &cli, const std::string &path,
  3037. const Params &params, const Headers &headers,
  3038. size_t chunk_size = 8192) {
  3039. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3040. }
  3041. // OPTIONS
  3042. template <typename ClientType>
  3043. inline Result Options(ClientType &cli, const std::string &path,
  3044. size_t chunk_size = 8192) {
  3045. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3046. }
  3047. template <typename ClientType>
  3048. inline Result Options(ClientType &cli, const std::string &path,
  3049. const Headers &headers, size_t chunk_size = 8192) {
  3050. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3051. }
  3052. template <typename ClientType>
  3053. inline Result Options(ClientType &cli, const std::string &path,
  3054. const Params &params, size_t chunk_size = 8192) {
  3055. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3056. }
  3057. template <typename ClientType>
  3058. inline Result Options(ClientType &cli, const std::string &path,
  3059. const Params &params, const Headers &headers,
  3060. size_t chunk_size = 8192) {
  3061. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3062. }
  3063. } // namespace stream
  3064. namespace sse {
  3065. struct SSEMessage {
  3066. std::string event; // Event type (default: "message")
  3067. std::string data; // Event payload
  3068. std::string id; // Event ID for Last-Event-ID header
  3069. SSEMessage();
  3070. void clear();
  3071. };
  3072. class SSEClient {
  3073. public:
  3074. using MessageHandler = std::function<void(const SSEMessage &)>;
  3075. using ErrorHandler = std::function<void(Error)>;
  3076. using OpenHandler = std::function<void()>;
  3077. SSEClient(Client &client, const std::string &path);
  3078. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3079. ~SSEClient();
  3080. SSEClient(const SSEClient &) = delete;
  3081. SSEClient &operator=(const SSEClient &) = delete;
  3082. // Event handlers
  3083. SSEClient &on_message(MessageHandler handler);
  3084. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3085. SSEClient &on_open(OpenHandler handler);
  3086. SSEClient &on_error(ErrorHandler handler);
  3087. SSEClient &set_reconnect_interval(int ms);
  3088. SSEClient &set_max_reconnect_attempts(int n);
  3089. // Update headers (thread-safe)
  3090. SSEClient &set_headers(const Headers &headers);
  3091. // State accessors
  3092. bool is_connected() const;
  3093. const std::string &last_event_id() const;
  3094. // Blocking start - runs event loop with auto-reconnect
  3095. void start();
  3096. // Non-blocking start - runs in background thread
  3097. void start_async();
  3098. // Stop the client (thread-safe)
  3099. void stop();
  3100. private:
  3101. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3102. void run_event_loop();
  3103. void dispatch_event(const SSEMessage &msg);
  3104. bool should_reconnect(int count) const;
  3105. void wait_for_reconnect();
  3106. // Client and path
  3107. Client &client_;
  3108. std::string path_;
  3109. Headers headers_;
  3110. mutable std::mutex headers_mutex_;
  3111. // Callbacks
  3112. MessageHandler on_message_;
  3113. std::map<std::string, MessageHandler> event_handlers_;
  3114. OpenHandler on_open_;
  3115. ErrorHandler on_error_;
  3116. // Configuration
  3117. int reconnect_interval_ms_ = 3000;
  3118. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3119. // State
  3120. std::atomic<bool> running_{false};
  3121. std::atomic<bool> connected_{false};
  3122. std::string last_event_id_;
  3123. // Async support
  3124. std::thread async_thread_;
  3125. };
  3126. } // namespace sse
  3127. namespace ws {
  3128. enum class Opcode : uint8_t {
  3129. Continuation = 0x0,
  3130. Text = 0x1,
  3131. Binary = 0x2,
  3132. Close = 0x8,
  3133. Ping = 0x9,
  3134. Pong = 0xA,
  3135. };
  3136. enum class CloseStatus : uint16_t {
  3137. Normal = 1000,
  3138. GoingAway = 1001,
  3139. ProtocolError = 1002,
  3140. UnsupportedData = 1003,
  3141. NoStatus = 1005,
  3142. Abnormal = 1006,
  3143. InvalidPayload = 1007,
  3144. PolicyViolation = 1008,
  3145. MessageTooBig = 1009,
  3146. MandatoryExtension = 1010,
  3147. InternalError = 1011,
  3148. };
  3149. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3150. class WebSocket {
  3151. public:
  3152. WebSocket(const WebSocket &) = delete;
  3153. WebSocket &operator=(const WebSocket &) = delete;
  3154. ~WebSocket();
  3155. ReadResult read(std::string &msg);
  3156. bool send(const std::string &data);
  3157. bool send(const char *data, size_t len);
  3158. void close(CloseStatus status = CloseStatus::Normal,
  3159. const std::string &reason = "");
  3160. const Request &request() const;
  3161. bool is_open() const;
  3162. private:
  3163. friend class httplib::Server;
  3164. friend class WebSocketClient;
  3165. WebSocket(
  3166. Stream &strm, const Request &req, bool is_server,
  3167. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3168. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3169. : strm_(strm), req_(req), is_server_(is_server),
  3170. ping_interval_sec_(ping_interval_sec),
  3171. max_missed_pongs_(max_missed_pongs) {
  3172. start_heartbeat();
  3173. }
  3174. WebSocket(
  3175. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3176. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3177. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3178. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3179. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3180. max_missed_pongs_(max_missed_pongs) {
  3181. start_heartbeat();
  3182. }
  3183. void start_heartbeat();
  3184. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3185. Stream &strm_;
  3186. std::unique_ptr<Stream> owned_strm_;
  3187. Request req_;
  3188. bool is_server_;
  3189. time_t ping_interval_sec_;
  3190. int max_missed_pongs_;
  3191. int unacked_pings_ = 0;
  3192. std::atomic<bool> closed_{false};
  3193. std::mutex write_mutex_;
  3194. std::thread ping_thread_;
  3195. std::mutex ping_mutex_;
  3196. std::condition_variable ping_cv_;
  3197. };
  3198. class WebSocketClient {
  3199. public:
  3200. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3201. const Headers &headers = {});
  3202. ~WebSocketClient();
  3203. WebSocketClient(const WebSocketClient &) = delete;
  3204. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3205. bool is_valid() const;
  3206. bool connect();
  3207. ReadResult read(std::string &msg);
  3208. bool send(const std::string &data);
  3209. bool send(const char *data, size_t len);
  3210. void close(CloseStatus status = CloseStatus::Normal,
  3211. const std::string &reason = "");
  3212. bool is_open() const;
  3213. const std::string &subprotocol() const;
  3214. void set_read_timeout(time_t sec, time_t usec = 0);
  3215. void set_write_timeout(time_t sec, time_t usec = 0);
  3216. void set_websocket_ping_interval(time_t sec);
  3217. void set_websocket_max_missed_pongs(int count);
  3218. void set_tcp_nodelay(bool on);
  3219. void set_address_family(int family);
  3220. void set_ipv6_v6only(bool on);
  3221. void set_socket_options(SocketOptions socket_options);
  3222. void set_connection_timeout(time_t sec, time_t usec = 0);
  3223. void set_interface(const std::string &intf);
  3224. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3225. #ifdef CPPHTTPLIB_SSL_ENABLED
  3226. void set_ca_cert_path(const std::string &path);
  3227. void set_ca_cert_store(tls::ca_store_t store);
  3228. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3229. void enable_server_certificate_verification(bool enabled);
  3230. void enable_system_ca(bool enabled);
  3231. #endif
  3232. private:
  3233. void shutdown_and_close();
  3234. bool create_stream(std::unique_ptr<Stream> &strm);
  3235. std::string host_;
  3236. int port_;
  3237. std::string path_;
  3238. Headers headers_;
  3239. std::string subprotocol_;
  3240. bool is_valid_ = false;
  3241. socket_t sock_ = INVALID_SOCKET;
  3242. std::unique_ptr<WebSocket> ws_;
  3243. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3244. time_t read_timeout_usec_ = 0;
  3245. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3246. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3247. time_t websocket_ping_interval_sec_ =
  3248. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3249. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3250. int address_family_ = AF_UNSPEC;
  3251. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3252. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3253. SocketOptions socket_options_ = nullptr;
  3254. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3255. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3256. std::string interface_;
  3257. // Hostname-IP map
  3258. std::map<std::string, std::string> addr_map_;
  3259. #ifdef CPPHTTPLIB_SSL_ENABLED
  3260. bool is_ssl_ = false;
  3261. tls::ctx_t tls_ctx_ = nullptr;
  3262. tls::session_t tls_session_ = nullptr;
  3263. std::string ca_cert_file_path_;
  3264. bool custom_ca_loaded_ = false;
  3265. bool certs_loaded_ = false;
  3266. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3267. bool server_certificate_verification_ = true;
  3268. #endif
  3269. };
  3270. namespace impl {
  3271. bool is_valid_utf8(const std::string &s);
  3272. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3273. bool &fin, bool expect_masked, size_t max_len);
  3274. } // namespace impl
  3275. } // namespace ws
  3276. // ----------------------------------------------------------------------------
  3277. /*
  3278. * Implementation that will be part of the .cc file if split into .h + .cc.
  3279. */
  3280. namespace stream {
  3281. // stream::Result implementations
  3282. inline Result::Result() : chunk_size_(8192) {}
  3283. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3284. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3285. inline Result::Result(Result &&other) noexcept
  3286. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3287. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3288. finished_(other.finished_) {
  3289. other.current_size_ = 0;
  3290. other.finished_ = true;
  3291. }
  3292. inline Result &Result::operator=(Result &&other) noexcept {
  3293. if (this != &other) {
  3294. handle_ = std::move(other.handle_);
  3295. buffer_ = std::move(other.buffer_);
  3296. current_size_ = other.current_size_;
  3297. chunk_size_ = other.chunk_size_;
  3298. finished_ = other.finished_;
  3299. other.current_size_ = 0;
  3300. other.finished_ = true;
  3301. }
  3302. return *this;
  3303. }
  3304. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3305. inline Result::operator bool() const { return is_valid(); }
  3306. inline int Result::status() const {
  3307. return handle_.response ? handle_.response->status : -1;
  3308. }
  3309. inline const Headers &Result::headers() const {
  3310. static const Headers empty_headers;
  3311. return handle_.response ? handle_.response->headers : empty_headers;
  3312. }
  3313. inline std::string Result::get_header_value(const std::string &key,
  3314. const char *def) const {
  3315. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3316. }
  3317. inline bool Result::has_header(const std::string &key) const {
  3318. return handle_.response ? handle_.response->has_header(key) : false;
  3319. }
  3320. inline Error Result::error() const { return handle_.error; }
  3321. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3322. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3323. inline bool Result::next() {
  3324. if (!handle_.is_valid() || finished_) { return false; }
  3325. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3326. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3327. if (n > 0) {
  3328. current_size_ = static_cast<size_t>(n);
  3329. return true;
  3330. }
  3331. current_size_ = 0;
  3332. finished_ = true;
  3333. return false;
  3334. }
  3335. inline const char *Result::data() const { return buffer_.data(); }
  3336. inline size_t Result::size() const { return current_size_; }
  3337. inline std::string Result::read_all() {
  3338. std::string result;
  3339. while (next()) {
  3340. result.append(data(), size());
  3341. }
  3342. return result;
  3343. }
  3344. } // namespace stream
  3345. namespace sse {
  3346. // SSEMessage implementations
  3347. inline SSEMessage::SSEMessage() : event("message") {}
  3348. inline void SSEMessage::clear() {
  3349. event = "message";
  3350. data.clear();
  3351. id.clear();
  3352. }
  3353. // SSEClient implementations
  3354. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3355. : client_(client), path_(path) {}
  3356. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3357. const Headers &headers)
  3358. : client_(client), path_(path), headers_(headers) {}
  3359. inline SSEClient::~SSEClient() { stop(); }
  3360. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3361. on_message_ = std::move(handler);
  3362. return *this;
  3363. }
  3364. inline SSEClient &SSEClient::on_event(const std::string &type,
  3365. MessageHandler handler) {
  3366. event_handlers_[type] = std::move(handler);
  3367. return *this;
  3368. }
  3369. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3370. on_open_ = std::move(handler);
  3371. return *this;
  3372. }
  3373. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3374. on_error_ = std::move(handler);
  3375. return *this;
  3376. }
  3377. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3378. reconnect_interval_ms_ = ms;
  3379. return *this;
  3380. }
  3381. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3382. max_reconnect_attempts_ = n;
  3383. return *this;
  3384. }
  3385. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3386. std::lock_guard<std::mutex> lock(headers_mutex_);
  3387. headers_ = headers;
  3388. return *this;
  3389. }
  3390. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3391. inline const std::string &SSEClient::last_event_id() const {
  3392. return last_event_id_;
  3393. }
  3394. inline void SSEClient::start() {
  3395. running_.store(true);
  3396. run_event_loop();
  3397. }
  3398. inline void SSEClient::start_async() {
  3399. running_.store(true);
  3400. async_thread_ = std::thread([this]() { run_event_loop(); });
  3401. }
  3402. inline void SSEClient::stop() {
  3403. running_.store(false);
  3404. client_.stop(); // Cancel any pending operations
  3405. if (async_thread_.joinable()) { async_thread_.join(); }
  3406. }
  3407. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3408. int &retry_ms) {
  3409. // Blank line signals end of event
  3410. if (line.empty() || line == "\r") { return true; }
  3411. // Lines starting with ':' are comments (ignored)
  3412. if (!line.empty() && line[0] == ':') { return false; }
  3413. // Find the colon separator
  3414. auto colon_pos = line.find(':');
  3415. if (colon_pos == std::string::npos) {
  3416. // Line with no colon is treated as field name with empty value
  3417. return false;
  3418. }
  3419. auto field = line.substr(0, colon_pos);
  3420. std::string value;
  3421. // Value starts after colon, skip optional single space
  3422. if (colon_pos + 1 < line.size()) {
  3423. auto value_start = colon_pos + 1;
  3424. if (line[value_start] == ' ') { value_start++; }
  3425. value = line.substr(value_start);
  3426. // Remove trailing \r if present
  3427. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3428. }
  3429. // Handle known fields
  3430. if (field == "event") {
  3431. msg.event = value;
  3432. } else if (field == "data") {
  3433. // Multiple data lines are concatenated with newlines
  3434. if (!msg.data.empty()) { msg.data += "\n"; }
  3435. msg.data += value;
  3436. } else if (field == "id") {
  3437. // Empty id is valid (clears the last event ID)
  3438. msg.id = value;
  3439. } else if (field == "retry") {
  3440. // Parse retry interval in milliseconds
  3441. {
  3442. int v = 0;
  3443. auto res =
  3444. detail::from_chars(value.data(), value.data() + value.size(), v);
  3445. if (res.ec == std::errc{}) { retry_ms = v; }
  3446. }
  3447. }
  3448. // Unknown fields are ignored per SSE spec
  3449. return false;
  3450. }
  3451. inline void SSEClient::run_event_loop() {
  3452. auto reconnect_count = 0;
  3453. while (running_.load()) {
  3454. // Build headers, including Last-Event-ID if we have one
  3455. Headers request_headers;
  3456. {
  3457. std::lock_guard<std::mutex> lock(headers_mutex_);
  3458. request_headers = headers_;
  3459. }
  3460. if (!last_event_id_.empty()) {
  3461. request_headers.emplace("Last-Event-ID", last_event_id_);
  3462. }
  3463. // Open streaming connection
  3464. auto result = stream::Get(client_, path_, request_headers);
  3465. // Connection error handling
  3466. if (!result) {
  3467. connected_.store(false);
  3468. if (on_error_) { on_error_(result.error()); }
  3469. if (!should_reconnect(reconnect_count)) { break; }
  3470. wait_for_reconnect();
  3471. reconnect_count++;
  3472. continue;
  3473. }
  3474. if (result.status() != StatusCode::OK_200) {
  3475. connected_.store(false);
  3476. if (on_error_) { on_error_(Error::Connection); }
  3477. // For certain errors, don't reconnect.
  3478. // Note: 401 is intentionally absent so that handlers can refresh
  3479. // credentials via set_headers() and let the client reconnect.
  3480. if (result.status() == StatusCode::NoContent_204 ||
  3481. result.status() == StatusCode::NotFound_404 ||
  3482. result.status() == StatusCode::Forbidden_403) {
  3483. break;
  3484. }
  3485. if (!should_reconnect(reconnect_count)) { break; }
  3486. wait_for_reconnect();
  3487. reconnect_count++;
  3488. continue;
  3489. }
  3490. // Connection successful
  3491. connected_.store(true);
  3492. reconnect_count = 0;
  3493. if (on_open_) { on_open_(); }
  3494. // Event receiving loop
  3495. std::string buffer;
  3496. SSEMessage current_msg;
  3497. while (running_.load() && result.next()) {
  3498. buffer.append(result.data(), result.size());
  3499. // Process complete lines in the buffer
  3500. size_t line_start = 0;
  3501. size_t newline_pos;
  3502. while ((newline_pos = buffer.find('\n', line_start)) !=
  3503. std::string::npos) {
  3504. auto line = buffer.substr(line_start, newline_pos - line_start);
  3505. line_start = newline_pos + 1;
  3506. // Parse the line and check if event is complete
  3507. auto event_complete =
  3508. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3509. if (event_complete && !current_msg.data.empty()) {
  3510. // Update last_event_id for reconnection
  3511. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3512. // Dispatch event to appropriate handler
  3513. dispatch_event(current_msg);
  3514. current_msg.clear();
  3515. }
  3516. }
  3517. // Keep unprocessed data in buffer
  3518. buffer.erase(0, line_start);
  3519. }
  3520. // Connection ended
  3521. connected_.store(false);
  3522. if (!running_.load()) { break; }
  3523. // Check for read errors
  3524. if (result.has_read_error()) {
  3525. if (on_error_) { on_error_(result.read_error()); }
  3526. }
  3527. if (!should_reconnect(reconnect_count)) { break; }
  3528. wait_for_reconnect();
  3529. reconnect_count++;
  3530. }
  3531. connected_.store(false);
  3532. }
  3533. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3534. // Check for specific event type handler first
  3535. auto it = event_handlers_.find(msg.event);
  3536. if (it != event_handlers_.end()) {
  3537. it->second(msg);
  3538. return;
  3539. }
  3540. // Fall back to generic message handler
  3541. if (on_message_) { on_message_(msg); }
  3542. }
  3543. inline bool SSEClient::should_reconnect(int count) const {
  3544. if (!running_.load()) { return false; }
  3545. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3546. return count < max_reconnect_attempts_;
  3547. }
  3548. inline void SSEClient::wait_for_reconnect() {
  3549. // Use small increments to check running_ flag frequently
  3550. auto waited = 0;
  3551. while (running_.load() && waited < reconnect_interval_ms_) {
  3552. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3553. waited += 100;
  3554. }
  3555. }
  3556. } // namespace sse
  3557. #ifdef CPPHTTPLIB_SSL_ENABLED
  3558. /*
  3559. * TLS abstraction layer - internal function declarations
  3560. * These are implementation details and not part of the public API.
  3561. */
  3562. namespace tls {
  3563. // Client context
  3564. ctx_t create_client_context();
  3565. void free_context(ctx_t ctx);
  3566. bool set_min_version(ctx_t ctx, Version version);
  3567. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3568. bool load_ca_file(ctx_t ctx, const char *file_path);
  3569. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3570. bool load_system_certs(ctx_t ctx);
  3571. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3572. const char *password);
  3573. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3574. const char *key_path, const char *password);
  3575. // Server context
  3576. ctx_t create_server_context();
  3577. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3578. const char *password);
  3579. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3580. const char *key_path, const char *password);
  3581. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3582. void set_verify_client(ctx_t ctx, bool require);
  3583. // Session management
  3584. session_t create_session(ctx_t ctx, socket_t sock);
  3585. void free_session(session_t session);
  3586. bool set_sni(session_t session, const char *hostname);
  3587. bool set_hostname(session_t session, const char *hostname);
  3588. // Handshake (non-blocking capable)
  3589. TlsError connect(session_t session);
  3590. TlsError accept(session_t session);
  3591. // Handshake with timeout (blocking until timeout)
  3592. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3593. time_t timeout_usec, TlsError *err);
  3594. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3595. time_t timeout_usec, TlsError *err);
  3596. // I/O (non-blocking capable)
  3597. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3598. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3599. int pending(const_session_t session);
  3600. void shutdown(session_t session, bool graceful);
  3601. // Connection state
  3602. bool is_peer_closed(session_t session, socket_t sock);
  3603. // Certificate verification
  3604. cert_t get_peer_cert(const_session_t session);
  3605. void free_cert(cert_t cert);
  3606. bool verify_hostname(cert_t cert, const char *hostname);
  3607. uint64_t hostname_mismatch_code();
  3608. long get_verify_result(const_session_t session);
  3609. // Certificate introspection
  3610. std::string get_cert_subject_cn(cert_t cert);
  3611. std::string get_cert_issuer_name(cert_t cert);
  3612. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3613. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3614. std::string get_cert_serial(cert_t cert);
  3615. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3616. const char *get_sni(const_session_t session);
  3617. // CA store management
  3618. ca_store_t create_ca_store(const char *pem, size_t len);
  3619. void free_ca_store(ca_store_t store);
  3620. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3621. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3622. std::vector<std::string> get_ca_names(ctx_t ctx);
  3623. // Dynamic certificate update (for servers)
  3624. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3625. const char *password);
  3626. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3627. // Certificate verification callback
  3628. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3629. long get_verify_error(const_session_t session);
  3630. std::string verify_error_string(long error_code);
  3631. // TlsError information
  3632. uint64_t peek_error();
  3633. uint64_t get_error();
  3634. std::string error_string(uint64_t code);
  3635. } // namespace tls
  3636. #endif // CPPHTTPLIB_SSL_ENABLED
  3637. /*
  3638. * Group 1: detail namespace - Non-SSL utilities
  3639. */
  3640. namespace detail {
  3641. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3642. const void *optval, socklen_t optlen) {
  3643. return setsockopt(sock, level, optname,
  3644. #ifdef _WIN32
  3645. reinterpret_cast<const char *>(optval),
  3646. #else
  3647. optval,
  3648. #endif
  3649. optlen) == 0;
  3650. }
  3651. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3652. time_t sec, time_t usec) {
  3653. #ifdef _WIN32
  3654. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3655. #else
  3656. timeval timeout;
  3657. timeout.tv_sec = static_cast<long>(sec);
  3658. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3659. #endif
  3660. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3661. }
  3662. inline bool is_hex(char c, int &v) {
  3663. if (isdigit(static_cast<unsigned char>(c))) {
  3664. v = c - '0';
  3665. return true;
  3666. } else if ('A' <= c && c <= 'F') {
  3667. v = c - 'A' + 10;
  3668. return true;
  3669. } else if ('a' <= c && c <= 'f') {
  3670. v = c - 'a' + 10;
  3671. return true;
  3672. }
  3673. return false;
  3674. }
  3675. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3676. int &val) {
  3677. if (i >= s.size()) { return false; }
  3678. val = 0;
  3679. for (; cnt; i++, cnt--) {
  3680. if (!s[i]) { return false; }
  3681. auto v = 0;
  3682. if (is_hex(s[i], v)) {
  3683. val = val * 16 + v;
  3684. } else {
  3685. return false;
  3686. }
  3687. }
  3688. return true;
  3689. }
  3690. inline std::string from_i_to_hex(size_t n) {
  3691. static const auto charset = "0123456789abcdef";
  3692. std::string ret;
  3693. do {
  3694. ret = charset[n & 15] + ret;
  3695. n >>= 4;
  3696. } while (n > 0);
  3697. return ret;
  3698. }
  3699. inline std::string compute_etag(const FileStat &fs) {
  3700. if (!fs.is_file()) { return std::string(); }
  3701. // If mtime cannot be determined (negative value indicates an error
  3702. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3703. // value like 0 could collide with a real file that legitimately has
  3704. // mtime == 0 (epoch) and lead to misleading validators.
  3705. auto mtime_raw = fs.mtime();
  3706. if (mtime_raw < 0) { return std::string(); }
  3707. auto mtime = static_cast<size_t>(mtime_raw);
  3708. auto size = fs.size();
  3709. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3710. from_i_to_hex(size) + "\"";
  3711. }
  3712. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3713. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3714. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3715. inline std::string file_mtime_to_http_date(time_t mtime) {
  3716. if (mtime < 0) { return std::string(); }
  3717. struct tm tm_buf;
  3718. #ifdef _WIN32
  3719. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3720. #else
  3721. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3722. #endif
  3723. char buf[64];
  3724. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3725. return std::string();
  3726. }
  3727. return std::string(buf);
  3728. }
  3729. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3730. inline time_t parse_http_date(const std::string &date_str) {
  3731. struct tm tm_buf;
  3732. // Create a classic locale object once for all parsing attempts
  3733. const std::locale classic_locale = std::locale::classic();
  3734. // Try to parse using std::get_time (C++11, cross-platform)
  3735. auto try_parse = [&](const char *fmt) -> bool {
  3736. std::istringstream ss(date_str);
  3737. ss.imbue(classic_locale);
  3738. memset(&tm_buf, 0, sizeof(tm_buf));
  3739. ss >> std::get_time(&tm_buf, fmt);
  3740. return !ss.fail();
  3741. };
  3742. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3743. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3744. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3745. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3746. // asctime format: "Sun Nov 6 08:49:37 1994"
  3747. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3748. return static_cast<time_t>(-1);
  3749. }
  3750. }
  3751. }
  3752. #ifdef _WIN32
  3753. return _mkgmtime(&tm_buf);
  3754. #elif defined _AIX
  3755. return mktime(&tm_buf);
  3756. #else
  3757. return timegm(&tm_buf);
  3758. #endif
  3759. }
  3760. inline bool is_weak_etag(const std::string &s) {
  3761. // Check if the string is a weak ETag (starts with 'W/"')
  3762. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3763. }
  3764. inline bool is_strong_etag(const std::string &s) {
  3765. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3766. // chars)
  3767. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3768. }
  3769. inline size_t to_utf8(int code, char *buff) {
  3770. if (code < 0x0080) {
  3771. buff[0] = static_cast<char>(code & 0x7F);
  3772. return 1;
  3773. } else if (code < 0x0800) {
  3774. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3775. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3776. return 2;
  3777. } else if (code < 0xD800) {
  3778. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3779. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3780. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3781. return 3;
  3782. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3783. return 0;
  3784. } else if (code < 0x10000) {
  3785. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3786. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3787. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3788. return 3;
  3789. } else if (code < 0x110000) {
  3790. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3791. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3792. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3793. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3794. return 4;
  3795. }
  3796. // NOTREACHED
  3797. return 0;
  3798. }
  3799. } // namespace detail
  3800. namespace ws {
  3801. namespace impl {
  3802. inline bool is_valid_utf8(const std::string &s) {
  3803. size_t i = 0;
  3804. auto n = s.size();
  3805. while (i < n) {
  3806. auto c = static_cast<unsigned char>(s[i]);
  3807. size_t len;
  3808. uint32_t cp;
  3809. if (c < 0x80) {
  3810. i++;
  3811. continue;
  3812. } else if ((c & 0xE0) == 0xC0) {
  3813. len = 2;
  3814. cp = c & 0x1F;
  3815. } else if ((c & 0xF0) == 0xE0) {
  3816. len = 3;
  3817. cp = c & 0x0F;
  3818. } else if ((c & 0xF8) == 0xF0) {
  3819. len = 4;
  3820. cp = c & 0x07;
  3821. } else {
  3822. return false;
  3823. }
  3824. if (i + len > n) { return false; }
  3825. for (size_t j = 1; j < len; j++) {
  3826. auto b = static_cast<unsigned char>(s[i + j]);
  3827. if ((b & 0xC0) != 0x80) { return false; }
  3828. cp = (cp << 6) | (b & 0x3F);
  3829. }
  3830. // Overlong encoding check
  3831. if (len == 2 && cp < 0x80) { return false; }
  3832. if (len == 3 && cp < 0x800) { return false; }
  3833. if (len == 4 && cp < 0x10000) { return false; }
  3834. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3835. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3836. if (cp > 0x10FFFF) { return false; }
  3837. i += len;
  3838. }
  3839. return true;
  3840. }
  3841. } // namespace impl
  3842. } // namespace ws
  3843. namespace detail {
  3844. // NOTE: This code came up with the following stackoverflow post:
  3845. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3846. inline std::string base64_encode(const std::string &in) {
  3847. static const auto lookup =
  3848. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3849. std::string out;
  3850. out.reserve(in.size());
  3851. // Unsigned: the accumulator is never masked, so with a signed int the
  3852. // `val << 8` below overflows once enough bytes are folded in (undefined
  3853. // behaviour before C++20). Only the low bits are ever emitted, so the
  3854. // wrap-around of an unsigned accumulator does not affect the output.
  3855. uint32_t val = 0;
  3856. auto valb = -6;
  3857. for (auto c : in) {
  3858. val = (val << 8) + static_cast<uint8_t>(c);
  3859. valb += 8;
  3860. while (valb >= 0) {
  3861. out.push_back(lookup[(val >> valb) & 0x3F]);
  3862. valb -= 6;
  3863. }
  3864. }
  3865. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3866. while (out.size() % 4) {
  3867. out.push_back('=');
  3868. }
  3869. return out;
  3870. }
  3871. inline std::string sha1(const std::string &input) {
  3872. // RFC 3174 SHA-1 implementation
  3873. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3874. return (x << n) | (x >> (32 - n));
  3875. };
  3876. uint32_t h0 = 0x67452301;
  3877. uint32_t h1 = 0xEFCDAB89;
  3878. uint32_t h2 = 0x98BADCFE;
  3879. uint32_t h3 = 0x10325476;
  3880. uint32_t h4 = 0xC3D2E1F0;
  3881. // Pre-processing: adding padding bits
  3882. std::string msg = input;
  3883. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3884. msg.push_back(static_cast<char>(0x80u));
  3885. while (msg.size() % 64 != 56) {
  3886. msg.push_back(0);
  3887. }
  3888. // Append original length in bits as 64-bit big-endian
  3889. for (int i = 56; i >= 0; i -= 8) {
  3890. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3891. }
  3892. // Process each 512-bit chunk
  3893. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3894. uint32_t w[80];
  3895. for (size_t i = 0; i < 16; i++) {
  3896. w[i] =
  3897. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3898. << 24) |
  3899. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3900. << 16) |
  3901. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3902. << 8) |
  3903. (static_cast<uint32_t>(
  3904. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3905. }
  3906. for (int i = 16; i < 80; i++) {
  3907. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3908. }
  3909. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3910. for (int i = 0; i < 80; i++) {
  3911. uint32_t f, k;
  3912. if (i < 20) {
  3913. f = (b & c) | ((~b) & d);
  3914. k = 0x5A827999;
  3915. } else if (i < 40) {
  3916. f = b ^ c ^ d;
  3917. k = 0x6ED9EBA1;
  3918. } else if (i < 60) {
  3919. f = (b & c) | (b & d) | (c & d);
  3920. k = 0x8F1BBCDC;
  3921. } else {
  3922. f = b ^ c ^ d;
  3923. k = 0xCA62C1D6;
  3924. }
  3925. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3926. e = d;
  3927. d = c;
  3928. c = left_rotate(b, 30);
  3929. b = a;
  3930. a = temp;
  3931. }
  3932. h0 += a;
  3933. h1 += b;
  3934. h2 += c;
  3935. h3 += d;
  3936. h4 += e;
  3937. }
  3938. // Produce the final hash as a 20-byte binary string
  3939. std::string hash(20, '\0');
  3940. for (size_t i = 0; i < 4; i++) {
  3941. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3942. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3943. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3944. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3945. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3946. }
  3947. return hash;
  3948. }
  3949. inline std::string websocket_accept_key(const std::string &client_key) {
  3950. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3951. return base64_encode(sha1(client_key + magic));
  3952. }
  3953. inline bool is_websocket_upgrade(const Request &req) {
  3954. if (req.method != "GET") { return false; }
  3955. // Check Upgrade: websocket (case-insensitive)
  3956. auto upgrade_it = req.headers.find("Upgrade");
  3957. if (upgrade_it == req.headers.end()) { return false; }
  3958. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3959. if (upgrade_val != "websocket") { return false; }
  3960. // Check Connection header contains "Upgrade"
  3961. auto connection_it = req.headers.find("Connection");
  3962. if (connection_it == req.headers.end()) { return false; }
  3963. auto connection_val = case_ignore::to_lower(connection_it->second);
  3964. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3965. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3966. // RFC 6455 Section 4.2.1
  3967. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3968. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3969. return false;
  3970. }
  3971. static const std::string b64chars =
  3972. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3973. for (size_t i = 0; i < 22; i++) {
  3974. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3975. }
  3976. // Check Sec-WebSocket-Version: 13
  3977. auto version = req.get_header_value("Sec-WebSocket-Version");
  3978. if (version != "13") { return false; }
  3979. return true;
  3980. }
  3981. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3982. const char *data, size_t len, bool fin,
  3983. bool mask) {
  3984. // First byte: FIN + opcode
  3985. uint8_t header[2];
  3986. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3987. (static_cast<uint8_t>(opcode) & 0x0F));
  3988. // Second byte: MASK + payload length
  3989. if (len < 126) {
  3990. header[1] = static_cast<uint8_t>(len);
  3991. if (mask) { header[1] |= 0x80; }
  3992. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3993. } else if (len <= 0xFFFF) {
  3994. header[1] = 126;
  3995. if (mask) { header[1] |= 0x80; }
  3996. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  3997. uint8_t ext[2];
  3998. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  3999. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4000. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4001. } else {
  4002. header[1] = 127;
  4003. if (mask) { header[1] |= 0x80; }
  4004. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4005. uint8_t ext[8];
  4006. for (int i = 7; i >= 0; i--) {
  4007. ext[7 - i] =
  4008. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4009. }
  4010. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4011. }
  4012. if (mask) {
  4013. // Generate random mask key
  4014. thread_local std::mt19937 rng(std::random_device{}());
  4015. uint8_t mask_key[4];
  4016. auto r = rng();
  4017. std::memcpy(mask_key, &r, 4);
  4018. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4019. // Write masked payload in chunks
  4020. const size_t chunk_size = 4096;
  4021. std::vector<char> buf((std::min)(len, chunk_size));
  4022. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4023. size_t n = (std::min)(chunk_size, len - offset);
  4024. for (size_t i = 0; i < n; i++) {
  4025. buf[i] =
  4026. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4027. }
  4028. if (strm.write(buf.data(), n) < 0) { return false; }
  4029. }
  4030. } else {
  4031. if (len > 0) {
  4032. if (strm.write(data, len) < 0) { return false; }
  4033. }
  4034. }
  4035. return true;
  4036. }
  4037. } // namespace detail
  4038. namespace ws {
  4039. namespace impl {
  4040. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4041. std::string &payload, bool &fin,
  4042. bool expect_masked, size_t max_len) {
  4043. // Read first 2 bytes
  4044. uint8_t header[2];
  4045. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4046. fin = (header[0] & 0x80) != 0;
  4047. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4048. if (header[0] & 0x70) { return false; }
  4049. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4050. bool masked = (header[1] & 0x80) != 0;
  4051. uint64_t payload_len = header[1] & 0x7F;
  4052. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4053. // MUST have a payload length of 125 bytes or less
  4054. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4055. if (is_control) {
  4056. if (!fin) { return false; }
  4057. if (payload_len > 125) { return false; }
  4058. }
  4059. if (masked != expect_masked) { return false; }
  4060. // Extended payload length
  4061. if (payload_len == 126) {
  4062. uint8_t ext[2];
  4063. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4064. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4065. } else if (payload_len == 127) {
  4066. uint8_t ext[8];
  4067. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4068. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4069. if (ext[0] & 0x80) { return false; }
  4070. payload_len = 0;
  4071. for (int i = 0; i < 8; i++) {
  4072. payload_len = (payload_len << 8) | ext[i];
  4073. }
  4074. }
  4075. if (payload_len > max_len) { return false; }
  4076. // Read mask key if present
  4077. uint8_t mask_key[4] = {0};
  4078. if (masked) {
  4079. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4080. }
  4081. // Read payload
  4082. payload.resize(static_cast<size_t>(payload_len));
  4083. if (payload_len > 0) {
  4084. size_t total_read = 0;
  4085. while (total_read < payload_len) {
  4086. auto n = strm.read(&payload[total_read],
  4087. static_cast<size_t>(payload_len - total_read));
  4088. if (n <= 0) { return false; }
  4089. total_read += static_cast<size_t>(n);
  4090. }
  4091. }
  4092. // Unmask if needed
  4093. if (masked) {
  4094. for (size_t i = 0; i < payload.size(); i++) {
  4095. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4096. }
  4097. }
  4098. return true;
  4099. }
  4100. } // namespace impl
  4101. } // namespace ws
  4102. namespace detail {
  4103. inline bool is_valid_path(const std::string &path) {
  4104. size_t level = 0;
  4105. size_t i = 0;
  4106. // Skip slash
  4107. while (i < path.size() && path[i] == '/') {
  4108. i++;
  4109. }
  4110. while (i < path.size()) {
  4111. // Read component
  4112. auto beg = i;
  4113. while (i < path.size() && path[i] != '/') {
  4114. if (path[i] == '\0') {
  4115. return false;
  4116. } else if (path[i] == '\\') {
  4117. return false;
  4118. }
  4119. i++;
  4120. }
  4121. auto len = i - beg;
  4122. assert(len > 0);
  4123. if (!path.compare(beg, len, ".")) {
  4124. ;
  4125. } else if (!path.compare(beg, len, "..")) {
  4126. if (level == 0) { return false; }
  4127. level--;
  4128. } else {
  4129. level++;
  4130. }
  4131. // Skip slash
  4132. while (i < path.size() && path[i] == '/') {
  4133. i++;
  4134. }
  4135. }
  4136. return true;
  4137. }
  4138. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4139. #if defined(_WIN32)
  4140. char buf[_MAX_PATH];
  4141. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4142. resolved = buf;
  4143. #elif defined(PATH_MAX)
  4144. char buf[PATH_MAX];
  4145. if (realpath(path, buf) == nullptr) { return false; }
  4146. resolved = buf;
  4147. #else
  4148. auto buf = realpath(path, nullptr);
  4149. auto guard = scope_exit([&]() { std::free(buf); });
  4150. if (buf == nullptr) { return false; }
  4151. resolved = buf;
  4152. #endif
  4153. return true;
  4154. }
  4155. inline bool is_path_within_base(const std::string &resolved_path,
  4156. const std::string &resolved_base) {
  4157. #if defined(_WIN32)
  4158. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4159. resolved_base.size()) == 0;
  4160. #else
  4161. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4162. resolved_base.size()) == 0;
  4163. #endif
  4164. }
  4165. inline FileStat::FileStat(const std::string &path) {
  4166. #if defined(_WIN32)
  4167. auto wpath = u8string_to_wstring(path.c_str());
  4168. ret_ = _wstat(wpath.c_str(), &st_);
  4169. #else
  4170. ret_ = stat(path.c_str(), &st_);
  4171. #endif
  4172. }
  4173. inline bool FileStat::is_file() const {
  4174. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4175. }
  4176. inline bool FileStat::is_dir() const {
  4177. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4178. }
  4179. inline time_t FileStat::mtime() const {
  4180. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4181. : static_cast<time_t>(-1);
  4182. }
  4183. inline size_t FileStat::size() const {
  4184. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4185. }
  4186. inline std::string encode_path(const std::string &s) {
  4187. std::string result;
  4188. result.reserve(s.size());
  4189. for (size_t i = 0; s[i]; i++) {
  4190. switch (s[i]) {
  4191. case ' ': result += "%20"; break;
  4192. case '+': result += "%2B"; break;
  4193. case '\r': result += "%0D"; break;
  4194. case '\n': result += "%0A"; break;
  4195. case '\'': result += "%27"; break;
  4196. case ',': result += "%2C"; break;
  4197. // case ':': result += "%3A"; break; // ok? probably...
  4198. case ';': result += "%3B"; break;
  4199. default:
  4200. auto c = static_cast<uint8_t>(s[i]);
  4201. if (c >= 0x80) {
  4202. result += '%';
  4203. char hex[4];
  4204. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4205. assert(len == 2);
  4206. result.append(hex, static_cast<size_t>(len));
  4207. } else {
  4208. result += s[i];
  4209. }
  4210. break;
  4211. }
  4212. }
  4213. return result;
  4214. }
  4215. inline std::string file_extension(const std::string &path) {
  4216. std::smatch m;
  4217. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4218. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4219. return std::string();
  4220. }
  4221. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4222. template <typename T>
  4223. inline bool parse_header(const char *beg, const char *end, T fn);
  4224. template <typename T>
  4225. inline bool parse_header(const char *beg, const char *end, T fn) {
  4226. // Skip trailing spaces and tabs.
  4227. while (beg < end && is_space_or_tab(end[-1])) {
  4228. end--;
  4229. }
  4230. auto p = beg;
  4231. while (p < end && *p != ':') {
  4232. p++;
  4233. }
  4234. auto name = std::string(beg, p);
  4235. if (!detail::fields::is_field_name(name)) { return false; }
  4236. if (p == end) { return false; }
  4237. auto key_end = p;
  4238. if (*p++ != ':') { return false; }
  4239. while (p < end && is_space_or_tab(*p)) {
  4240. p++;
  4241. }
  4242. if (p <= end) {
  4243. auto key_len = key_end - beg;
  4244. if (!key_len) { return false; }
  4245. auto key = std::string(beg, key_end);
  4246. auto val = std::string(p, end);
  4247. if (!detail::fields::is_field_value(val)) { return false; }
  4248. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4249. // percent-decoded by the recipient. Applications that need to interpret a
  4250. // value as a URI component should call httplib::decode_uri_component()
  4251. // (or decode_path_component()) explicitly.
  4252. fn(key, val);
  4253. return true;
  4254. }
  4255. return false;
  4256. }
  4257. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4258. const Headers &src_headers) {
  4259. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4260. // transfer coding is complete when a chunk with a chunk-size of zero is
  4261. // received, possibly followed by a trailer section, and finally terminated by
  4262. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4263. //
  4264. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4265. // doesn't care for the existence of the final CRLF. In other words, it seems
  4266. // to be ok whether the final CRLF exists or not in the chunked data.
  4267. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4268. //
  4269. // According to the reference code in RFC 9112, cpp-httplib now allows
  4270. // chunked transfer coding data without the final CRLF.
  4271. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4272. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4273. "transfer-encoding",
  4274. "content-length",
  4275. "host",
  4276. "authorization",
  4277. "www-authenticate",
  4278. "proxy-authenticate",
  4279. "proxy-authorization",
  4280. "cookie",
  4281. "set-cookie",
  4282. "cache-control",
  4283. "expect",
  4284. "max-forwards",
  4285. "pragma",
  4286. "range",
  4287. "te",
  4288. "age",
  4289. "expires",
  4290. "date",
  4291. "location",
  4292. "retry-after",
  4293. "vary",
  4294. "warning",
  4295. "content-encoding",
  4296. "content-type",
  4297. "content-range",
  4298. "trailer"};
  4299. case_ignore::unordered_set<std::string> declared_trailers;
  4300. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4301. if (trailer_header && std::strlen(trailer_header)) {
  4302. auto len = std::strlen(trailer_header);
  4303. split(trailer_header, trailer_header + len, ',',
  4304. [&](const char *b, const char *e) {
  4305. const char *kbeg = b;
  4306. const char *kend = e;
  4307. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4308. ++kbeg;
  4309. }
  4310. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4311. --kend;
  4312. }
  4313. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4314. if (!key.empty() &&
  4315. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4316. declared_trailers.insert(key);
  4317. }
  4318. });
  4319. }
  4320. size_t trailer_header_count = 0;
  4321. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4322. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4323. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4324. constexpr auto line_terminator_len = 2;
  4325. auto line_beg = line_reader.ptr();
  4326. auto line_end =
  4327. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4328. if (!parse_header(line_beg, line_end,
  4329. [&](const std::string &key, const std::string &val) {
  4330. if (declared_trailers.find(key) !=
  4331. declared_trailers.end()) {
  4332. dest.emplace(key, val);
  4333. trailer_header_count++;
  4334. }
  4335. })) {
  4336. return false;
  4337. }
  4338. if (!line_reader.getline()) { return false; }
  4339. }
  4340. return true;
  4341. }
  4342. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4343. size_t right) {
  4344. while (b + left < e && is_space_or_tab(b[left])) {
  4345. left++;
  4346. }
  4347. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4348. right--;
  4349. }
  4350. return std::make_pair(left, right);
  4351. }
  4352. inline std::string trim_copy(const std::string &s) {
  4353. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4354. return s.substr(r.first, r.second - r.first);
  4355. }
  4356. inline std::string trim_double_quotes_copy(const std::string &s) {
  4357. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4358. return s.substr(1, s.size() - 2);
  4359. }
  4360. return s;
  4361. }
  4362. inline void
  4363. divide(const char *data, std::size_t size, char d,
  4364. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4365. fn) {
  4366. const auto it = std::find(data, data + size, d);
  4367. const auto found = static_cast<std::size_t>(it != data + size);
  4368. const auto lhs_data = data;
  4369. const auto lhs_size = static_cast<std::size_t>(it - data);
  4370. const auto rhs_data = it + found;
  4371. const auto rhs_size = size - lhs_size - found;
  4372. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4373. }
  4374. inline void
  4375. divide(const std::string &str, char d,
  4376. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4377. fn) {
  4378. divide(str.data(), str.size(), d, std::move(fn));
  4379. }
  4380. inline void split(const char *b, const char *e, char d,
  4381. std::function<void(const char *, const char *)> fn) {
  4382. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4383. }
  4384. inline void split(const char *b, const char *e, char d, size_t m,
  4385. std::function<void(const char *, const char *)> fn) {
  4386. size_t i = 0;
  4387. size_t beg = 0;
  4388. size_t count = 1;
  4389. while (e ? (b + i < e) : (b[i] != '\0')) {
  4390. if (b[i] == d && count < m) {
  4391. auto r = trim(b, e, beg, i);
  4392. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4393. beg = i + 1;
  4394. count++;
  4395. }
  4396. i++;
  4397. }
  4398. if (i) {
  4399. auto r = trim(b, e, beg, i);
  4400. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4401. }
  4402. }
  4403. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4404. std::function<bool(const char *, const char *)> fn) {
  4405. size_t i = 0;
  4406. size_t beg = 0;
  4407. size_t count = 1;
  4408. while (e ? (b + i < e) : (b[i] != '\0')) {
  4409. if (b[i] == d && count < m) {
  4410. auto r = trim(b, e, beg, i);
  4411. if (r.first < r.second) {
  4412. auto found = fn(&b[r.first], &b[r.second]);
  4413. if (found) { return true; }
  4414. }
  4415. beg = i + 1;
  4416. count++;
  4417. }
  4418. i++;
  4419. }
  4420. if (i) {
  4421. auto r = trim(b, e, beg, i);
  4422. if (r.first < r.second) {
  4423. auto found = fn(&b[r.first], &b[r.second]);
  4424. if (found) { return true; }
  4425. }
  4426. }
  4427. return false;
  4428. }
  4429. inline bool split_find(const char *b, const char *e, char d,
  4430. std::function<bool(const char *, const char *)> fn) {
  4431. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4432. std::move(fn));
  4433. }
  4434. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4435. size_t fixed_buffer_size)
  4436. : strm_(strm), fixed_buffer_(fixed_buffer),
  4437. fixed_buffer_size_(fixed_buffer_size) {}
  4438. inline const char *stream_line_reader::ptr() const {
  4439. if (growable_buffer_.empty()) {
  4440. return fixed_buffer_;
  4441. } else {
  4442. return growable_buffer_.data();
  4443. }
  4444. }
  4445. inline size_t stream_line_reader::size() const {
  4446. if (growable_buffer_.empty()) {
  4447. return fixed_buffer_used_size_;
  4448. } else {
  4449. return growable_buffer_.size();
  4450. }
  4451. }
  4452. inline bool stream_line_reader::end_with_crlf() const {
  4453. auto end = ptr() + size();
  4454. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4455. }
  4456. inline bool stream_line_reader::getline() {
  4457. fixed_buffer_used_size_ = 0;
  4458. growable_buffer_.clear();
  4459. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4460. char prev_byte = 0;
  4461. #endif
  4462. for (size_t i = 0;; i++) {
  4463. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4464. // Treat exceptionally long lines as an error to
  4465. // prevent infinite loops/memory exhaustion
  4466. return false;
  4467. }
  4468. char byte;
  4469. auto n = strm_.read(&byte, 1);
  4470. if (n < 0) {
  4471. return false;
  4472. } else if (n == 0) {
  4473. if (i == 0) {
  4474. return false;
  4475. } else {
  4476. break;
  4477. }
  4478. }
  4479. append(byte);
  4480. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4481. if (byte == '\n') { break; }
  4482. #else
  4483. if (prev_byte == '\r' && byte == '\n') { break; }
  4484. prev_byte = byte;
  4485. #endif
  4486. }
  4487. return true;
  4488. }
  4489. inline void stream_line_reader::append(char c) {
  4490. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4491. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4492. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4493. } else {
  4494. if (growable_buffer_.empty()) {
  4495. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4496. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4497. }
  4498. growable_buffer_ += c;
  4499. }
  4500. }
  4501. inline mmap::mmap(const char *path) { open(path); }
  4502. inline mmap::~mmap() { close(); }
  4503. inline bool mmap::open(const char *path) {
  4504. close();
  4505. #if defined(_WIN32)
  4506. auto wpath = u8string_to_wstring(path);
  4507. if (wpath.empty()) { return false; }
  4508. hFile_ =
  4509. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4510. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4511. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4512. LARGE_INTEGER size{};
  4513. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4514. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4515. // See:
  4516. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4517. if (static_cast<ULONGLONG>(size.QuadPart) >
  4518. (std::numeric_limits<decltype(size_)>::max)()) {
  4519. // `size_t` might be 32-bits, on 32-bits Windows.
  4520. return false;
  4521. }
  4522. size_ = static_cast<size_t>(size.QuadPart);
  4523. hMapping_ =
  4524. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4525. // Special treatment for an empty file...
  4526. if (hMapping_ == NULL && size_ == 0) {
  4527. close();
  4528. is_open_empty_file = true;
  4529. return true;
  4530. }
  4531. if (hMapping_ == NULL) {
  4532. close();
  4533. return false;
  4534. }
  4535. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4536. if (addr_ == nullptr) {
  4537. close();
  4538. return false;
  4539. }
  4540. #else
  4541. fd_ = ::open(path, O_RDONLY);
  4542. if (fd_ == -1) { return false; }
  4543. struct stat sb;
  4544. if (fstat(fd_, &sb) == -1) {
  4545. close();
  4546. return false;
  4547. }
  4548. size_ = static_cast<size_t>(sb.st_size);
  4549. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4550. // Special treatment for an empty file...
  4551. if (addr_ == MAP_FAILED && size_ == 0) {
  4552. close();
  4553. is_open_empty_file = true;
  4554. return false;
  4555. }
  4556. #endif
  4557. return true;
  4558. }
  4559. inline bool mmap::is_open() const {
  4560. return is_open_empty_file ? true : addr_ != nullptr;
  4561. }
  4562. inline size_t mmap::size() const { return size_; }
  4563. inline const char *mmap::data() const {
  4564. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4565. }
  4566. inline void mmap::close() {
  4567. #if defined(_WIN32)
  4568. if (addr_) {
  4569. ::UnmapViewOfFile(addr_);
  4570. addr_ = nullptr;
  4571. }
  4572. if (hMapping_) {
  4573. ::CloseHandle(hMapping_);
  4574. hMapping_ = NULL;
  4575. }
  4576. if (hFile_ != INVALID_HANDLE_VALUE) {
  4577. ::CloseHandle(hFile_);
  4578. hFile_ = INVALID_HANDLE_VALUE;
  4579. }
  4580. is_open_empty_file = false;
  4581. #else
  4582. if (addr_ != nullptr) {
  4583. munmap(addr_, size_);
  4584. addr_ = nullptr;
  4585. }
  4586. if (fd_ != -1) {
  4587. ::close(fd_);
  4588. fd_ = -1;
  4589. }
  4590. #endif
  4591. size_ = 0;
  4592. }
  4593. inline int close_socket(socket_t sock) noexcept {
  4594. #ifdef _WIN32
  4595. return closesocket(sock);
  4596. #else
  4597. return close(sock);
  4598. #endif
  4599. }
  4600. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4601. ssize_t res = 0;
  4602. while (true) {
  4603. res = fn();
  4604. if (res < 0 && errno == EINTR) {
  4605. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4606. continue;
  4607. }
  4608. break;
  4609. }
  4610. return res;
  4611. }
  4612. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4613. return handle_EINTR([&]() {
  4614. return recv(sock,
  4615. #ifdef _WIN32
  4616. static_cast<char *>(ptr), static_cast<int>(size),
  4617. #else
  4618. ptr, size,
  4619. #endif
  4620. flags);
  4621. });
  4622. }
  4623. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4624. int flags) {
  4625. return handle_EINTR([&]() {
  4626. return send(sock,
  4627. #ifdef _WIN32
  4628. static_cast<const char *>(ptr), static_cast<int>(size),
  4629. #else
  4630. ptr, size,
  4631. #endif
  4632. flags);
  4633. });
  4634. }
  4635. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4636. #ifdef _WIN32
  4637. return ::WSAPoll(fds, nfds, timeout);
  4638. #else
  4639. return ::poll(fds, nfds, timeout);
  4640. #endif
  4641. }
  4642. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4643. time_t usec) {
  4644. struct pollfd pfd;
  4645. pfd.fd = sock;
  4646. pfd.events = events;
  4647. pfd.revents = 0;
  4648. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4649. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4650. }
  4651. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4652. return select_impl(sock, POLLIN, sec, usec);
  4653. }
  4654. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4655. return select_impl(sock, POLLOUT, sec, usec);
  4656. }
  4657. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4658. time_t usec) {
  4659. struct pollfd pfd_read;
  4660. pfd_read.fd = sock;
  4661. pfd_read.events = POLLIN | POLLOUT;
  4662. pfd_read.revents = 0;
  4663. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4664. auto poll_res =
  4665. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4666. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4667. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4668. auto error = 0;
  4669. socklen_t len = sizeof(error);
  4670. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4671. reinterpret_cast<char *>(&error), &len);
  4672. auto successful = res >= 0 && !error;
  4673. return successful ? Error::Success : Error::Connection;
  4674. }
  4675. return Error::Connection;
  4676. }
  4677. inline bool is_socket_alive(socket_t sock) {
  4678. const auto val = detail::select_read(sock, 0, 0);
  4679. if (val == 0) {
  4680. return true;
  4681. } else if (val < 0 && errno == EBADF) {
  4682. return false;
  4683. }
  4684. char buf[1];
  4685. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4686. }
  4687. class SocketStream final : public Stream {
  4688. public:
  4689. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4690. time_t write_timeout_sec, time_t write_timeout_usec,
  4691. time_t max_timeout_msec = 0,
  4692. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4693. (std::chrono::steady_clock::time_point::min)());
  4694. ~SocketStream() override;
  4695. bool is_readable() const override;
  4696. bool wait_readable() const override;
  4697. bool wait_writable() const override;
  4698. bool is_peer_alive() const override;
  4699. ssize_t read(char *ptr, size_t size) override;
  4700. ssize_t write(const char *ptr, size_t size) override;
  4701. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4702. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4703. socket_t socket() const override;
  4704. time_t duration() const override;
  4705. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4706. private:
  4707. socket_t sock_;
  4708. time_t read_timeout_sec_;
  4709. time_t read_timeout_usec_;
  4710. time_t write_timeout_sec_;
  4711. time_t write_timeout_usec_;
  4712. time_t max_timeout_msec_;
  4713. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4714. std::vector<char> read_buff_;
  4715. size_t read_buff_off_ = 0;
  4716. size_t read_buff_content_size_ = 0;
  4717. static const size_t read_buff_size_ = 1024l * 4;
  4718. };
  4719. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4720. time_t keep_alive_timeout_sec) {
  4721. using namespace std::chrono;
  4722. const auto interval_usec =
  4723. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4724. // Avoid expensive `steady_clock::now()` call for the first time
  4725. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4726. const auto start = steady_clock::now() - microseconds{interval_usec};
  4727. const auto timeout = seconds{keep_alive_timeout_sec};
  4728. while (true) {
  4729. if (svr_sock == INVALID_SOCKET) {
  4730. break; // Server socket is closed
  4731. }
  4732. auto val = select_read(sock, 0, interval_usec);
  4733. if (val < 0) {
  4734. break; // Ssocket error
  4735. } else if (val == 0) {
  4736. if (steady_clock::now() - start > timeout) {
  4737. break; // Timeout
  4738. }
  4739. } else {
  4740. return true; // Ready for read
  4741. }
  4742. }
  4743. return false;
  4744. }
  4745. template <typename T>
  4746. inline bool
  4747. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4748. size_t keep_alive_max_count,
  4749. time_t keep_alive_timeout_sec, T callback) {
  4750. assert(keep_alive_max_count > 0);
  4751. auto ret = false;
  4752. auto count = keep_alive_max_count;
  4753. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4754. auto close_connection = count == 1;
  4755. auto connection_closed = false;
  4756. ret = callback(close_connection, connection_closed);
  4757. if (!ret || connection_closed) { break; }
  4758. count--;
  4759. }
  4760. return ret;
  4761. }
  4762. template <typename T>
  4763. inline bool
  4764. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4765. size_t keep_alive_max_count,
  4766. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4767. time_t read_timeout_usec, time_t write_timeout_sec,
  4768. time_t write_timeout_usec, T callback) {
  4769. return process_server_socket_core(
  4770. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4771. [&](bool close_connection, bool &connection_closed) {
  4772. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4773. write_timeout_sec, write_timeout_usec);
  4774. return callback(strm, close_connection, connection_closed);
  4775. });
  4776. }
  4777. inline bool process_client_socket(
  4778. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4779. time_t write_timeout_sec, time_t write_timeout_usec,
  4780. time_t max_timeout_msec,
  4781. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4782. std::function<bool(Stream &)> callback) {
  4783. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4784. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4785. start_time);
  4786. return callback(strm);
  4787. }
  4788. inline int shutdown_socket(socket_t sock) noexcept {
  4789. #ifdef _WIN32
  4790. return shutdown(sock, SD_BOTH);
  4791. #else
  4792. return shutdown(sock, SHUT_RDWR);
  4793. #endif
  4794. }
  4795. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4796. if (s.size() > 1 && s[0] == '\0') {
  4797. auto ret = s;
  4798. ret[0] = '@';
  4799. return ret;
  4800. }
  4801. return s;
  4802. }
  4803. inline std::string
  4804. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4805. if (s.size() > 1 && s[0] == '@') {
  4806. auto ret = s;
  4807. ret[0] = '\0';
  4808. return ret;
  4809. }
  4810. return s;
  4811. }
  4812. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4813. const struct addrinfo *hints,
  4814. struct addrinfo **res, time_t timeout_sec) {
  4815. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4816. if (timeout_sec <= 0) {
  4817. // No timeout specified, use standard getaddrinfo
  4818. return getaddrinfo(node, service, hints, res);
  4819. }
  4820. #ifdef _WIN32
  4821. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4822. OVERLAPPED overlapped = {};
  4823. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4824. if (!event) { return EAI_FAIL; }
  4825. overlapped.hEvent = event;
  4826. PADDRINFOEXW result_addrinfo = nullptr;
  4827. HANDLE cancel_handle = nullptr;
  4828. ADDRINFOEXW hints_ex = {};
  4829. if (hints) {
  4830. hints_ex.ai_flags = hints->ai_flags;
  4831. hints_ex.ai_family = hints->ai_family;
  4832. hints_ex.ai_socktype = hints->ai_socktype;
  4833. hints_ex.ai_protocol = hints->ai_protocol;
  4834. }
  4835. auto wnode = u8string_to_wstring(node);
  4836. auto wservice = u8string_to_wstring(service);
  4837. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4838. hints ? &hints_ex : nullptr, &result_addrinfo,
  4839. nullptr, &overlapped, nullptr, &cancel_handle);
  4840. if (ret == WSA_IO_PENDING) {
  4841. auto wait_result =
  4842. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4843. if (wait_result == WAIT_TIMEOUT) {
  4844. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4845. ::CloseHandle(event);
  4846. return EAI_AGAIN;
  4847. }
  4848. DWORD bytes_returned;
  4849. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4850. &bytes_returned, FALSE)) {
  4851. ::CloseHandle(event);
  4852. return ::WSAGetLastError();
  4853. }
  4854. }
  4855. ::CloseHandle(event);
  4856. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4857. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4858. return 0;
  4859. }
  4860. return ret;
  4861. #elif TARGET_OS_MAC && defined(__clang__)
  4862. if (!node) { return EAI_NONAME; }
  4863. // macOS implementation using CFHost API for asynchronous DNS resolution
  4864. CFStringRef hostname_ref = CFStringCreateWithCString(
  4865. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4866. if (!hostname_ref) { return EAI_MEMORY; }
  4867. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4868. CFRelease(hostname_ref);
  4869. if (!host_ref) { return EAI_MEMORY; }
  4870. // Set up context for callback
  4871. struct CFHostContext {
  4872. bool completed = false;
  4873. bool success = false;
  4874. CFArrayRef addresses = nullptr;
  4875. std::mutex mutex;
  4876. std::condition_variable cv;
  4877. } context;
  4878. CFHostClientContext client_context;
  4879. memset(&client_context, 0, sizeof(client_context));
  4880. client_context.info = &context;
  4881. // Set callback
  4882. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4883. const CFStreamError *error, void *info) {
  4884. auto ctx = static_cast<CFHostContext *>(info);
  4885. std::lock_guard<std::mutex> lock(ctx->mutex);
  4886. if (error && error->error != 0) {
  4887. ctx->success = false;
  4888. } else {
  4889. Boolean hasBeenResolved;
  4890. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4891. if (ctx->addresses && hasBeenResolved) {
  4892. CFRetain(ctx->addresses);
  4893. ctx->success = true;
  4894. } else {
  4895. ctx->success = false;
  4896. }
  4897. }
  4898. ctx->completed = true;
  4899. ctx->cv.notify_one();
  4900. };
  4901. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4902. CFRelease(host_ref);
  4903. return EAI_SYSTEM;
  4904. }
  4905. // Schedule on run loop
  4906. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4907. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4908. // Start resolution
  4909. CFStreamError stream_error;
  4910. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4911. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4912. CFRelease(host_ref);
  4913. return EAI_FAIL;
  4914. }
  4915. // Wait for completion with timeout
  4916. auto timeout_time =
  4917. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4918. bool timed_out = false;
  4919. {
  4920. std::unique_lock<std::mutex> lock(context.mutex);
  4921. while (!context.completed) {
  4922. auto now = std::chrono::steady_clock::now();
  4923. if (now >= timeout_time) {
  4924. timed_out = true;
  4925. break;
  4926. }
  4927. // Run the runloop for a short time
  4928. lock.unlock();
  4929. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4930. lock.lock();
  4931. }
  4932. }
  4933. // Clean up
  4934. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4935. CFHostSetClient(host_ref, nullptr, nullptr);
  4936. if (timed_out || !context.completed) {
  4937. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4938. CFRelease(host_ref);
  4939. return EAI_AGAIN;
  4940. }
  4941. if (!context.success || !context.addresses) {
  4942. CFRelease(host_ref);
  4943. return EAI_NODATA;
  4944. }
  4945. // Convert CFArray to addrinfo
  4946. CFIndex count = CFArrayGetCount(context.addresses);
  4947. if (count == 0) {
  4948. CFRelease(context.addresses);
  4949. CFRelease(host_ref);
  4950. return EAI_NODATA;
  4951. }
  4952. struct addrinfo *result_addrinfo = nullptr;
  4953. struct addrinfo **current = &result_addrinfo;
  4954. for (CFIndex i = 0; i < count; i++) {
  4955. CFDataRef addr_data =
  4956. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4957. if (!addr_data) continue;
  4958. const struct sockaddr *sockaddr_ptr =
  4959. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4960. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4961. // Allocate addrinfo structure
  4962. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4963. if (!*current) {
  4964. freeaddrinfo(result_addrinfo);
  4965. CFRelease(context.addresses);
  4966. CFRelease(host_ref);
  4967. return EAI_MEMORY;
  4968. }
  4969. memset(*current, 0, sizeof(struct addrinfo));
  4970. // Set up addrinfo fields
  4971. (*current)->ai_family = sockaddr_ptr->sa_family;
  4972. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4973. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4974. (*current)->ai_addrlen = sockaddr_len;
  4975. // Copy sockaddr
  4976. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4977. if (!(*current)->ai_addr) {
  4978. freeaddrinfo(result_addrinfo);
  4979. CFRelease(context.addresses);
  4980. CFRelease(host_ref);
  4981. return EAI_MEMORY;
  4982. }
  4983. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4984. // Set port if service is specified
  4985. if (service && *service) {
  4986. int port = 0;
  4987. if (parse_port(service, strlen(service), port)) {
  4988. if (sockaddr_ptr->sa_family == AF_INET) {
  4989. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  4990. ->sin_port = htons(static_cast<uint16_t>(port));
  4991. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  4992. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  4993. ->sin6_port = htons(static_cast<uint16_t>(port));
  4994. }
  4995. }
  4996. }
  4997. current = &((*current)->ai_next);
  4998. }
  4999. CFRelease(context.addresses);
  5000. CFRelease(host_ref);
  5001. *res = result_addrinfo;
  5002. return 0;
  5003. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5004. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5005. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5006. // the resolver worker still references the stack-local gaicb. The cancel
  5007. // path therefore waits (gai_suspend with no timeout) for the worker to
  5008. // actually finish before letting the stack frame go. The trade-off is that
  5009. // a wedged DNS server can hold this thread for the system resolver timeout
  5010. // (~30s by default) past the caller's connection timeout.
  5011. struct gaicb request {};
  5012. struct gaicb *requests[1] = {&request};
  5013. struct sigevent sevp {};
  5014. struct timespec timeout {
  5015. timeout_sec, 0
  5016. };
  5017. request.ar_name = node;
  5018. request.ar_service = service;
  5019. request.ar_request = hints;
  5020. sevp.sigev_notify = SIGEV_NONE;
  5021. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5022. if (rc != 0) { return rc; }
  5023. auto cleanup = scope_exit([&] {
  5024. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5025. });
  5026. int wait_result = gai_suspend(requests, 1, &timeout);
  5027. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5028. int gai_result = gai_error(&request);
  5029. if (gai_result == 0) {
  5030. *res = request.ar_result;
  5031. request.ar_result = nullptr;
  5032. return 0;
  5033. }
  5034. return gai_result;
  5035. }
  5036. gai_cancel(&request);
  5037. while (gai_error(&request) == EAI_INPROGRESS) {
  5038. gai_suspend(requests, 1, nullptr);
  5039. }
  5040. return wait_result;
  5041. #else
  5042. // Fallback implementation using thread-based timeout for other Unix systems.
  5043. struct GetAddrInfoState {
  5044. ~GetAddrInfoState() {
  5045. if (info) { freeaddrinfo(info); }
  5046. }
  5047. std::mutex mutex;
  5048. std::condition_variable result_cv;
  5049. bool completed = false;
  5050. int result = EAI_SYSTEM;
  5051. std::string node;
  5052. std::string service;
  5053. struct addrinfo hints;
  5054. struct addrinfo *info = nullptr;
  5055. };
  5056. // Allocate on the heap, so the resolver thread can keep using the data.
  5057. auto state = std::make_shared<GetAddrInfoState>();
  5058. if (node) { state->node = node; }
  5059. state->service = service;
  5060. state->hints = *hints;
  5061. std::thread resolve_thread([state]() {
  5062. auto thread_result =
  5063. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5064. &state->info);
  5065. std::lock_guard<std::mutex> lock(state->mutex);
  5066. state->result = thread_result;
  5067. state->completed = true;
  5068. state->result_cv.notify_one();
  5069. });
  5070. // Wait for completion or timeout
  5071. std::unique_lock<std::mutex> lock(state->mutex);
  5072. auto finished =
  5073. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5074. [&] { return state->completed; });
  5075. if (finished) {
  5076. // Operation completed within timeout
  5077. resolve_thread.join();
  5078. *res = state->info;
  5079. state->info = nullptr; // Pass ownership to caller
  5080. return state->result;
  5081. } else {
  5082. // Timeout occurred
  5083. resolve_thread.detach(); // Let the thread finish in background
  5084. return EAI_AGAIN; // Return timeout error
  5085. }
  5086. #endif
  5087. #else
  5088. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5089. return getaddrinfo(node, service, hints, res);
  5090. #endif
  5091. }
  5092. template <typename BindOrConnect>
  5093. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5094. int address_family, int socket_flags, bool tcp_nodelay,
  5095. bool ipv6_v6only, SocketOptions socket_options,
  5096. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5097. // Get address info
  5098. const char *node = nullptr;
  5099. struct addrinfo hints;
  5100. struct addrinfo *result;
  5101. memset(&hints, 0, sizeof(struct addrinfo));
  5102. hints.ai_socktype = SOCK_STREAM;
  5103. hints.ai_protocol = IPPROTO_IP;
  5104. if (!ip.empty()) {
  5105. node = ip.c_str();
  5106. // Ask getaddrinfo to convert IP in c-string to address
  5107. hints.ai_family = AF_UNSPEC;
  5108. hints.ai_flags = AI_NUMERICHOST;
  5109. } else {
  5110. if (!host.empty()) { node = host.c_str(); }
  5111. hints.ai_family = address_family;
  5112. hints.ai_flags = socket_flags;
  5113. }
  5114. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5115. if (hints.ai_family == AF_UNIX) {
  5116. const auto addrlen = host.length();
  5117. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5118. #ifdef SOCK_CLOEXEC
  5119. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5120. hints.ai_protocol);
  5121. #else
  5122. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5123. #endif
  5124. if (sock != INVALID_SOCKET) {
  5125. sockaddr_un addr{};
  5126. addr.sun_family = AF_UNIX;
  5127. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5128. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5129. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5130. hints.ai_addrlen = static_cast<socklen_t>(
  5131. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5132. #ifndef SOCK_CLOEXEC
  5133. #ifndef _WIN32
  5134. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5135. #endif
  5136. #endif
  5137. if (socket_options) { socket_options(sock); }
  5138. #ifdef _WIN32
  5139. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5140. // remove the option.
  5141. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5142. #endif
  5143. bool dummy;
  5144. if (!bind_or_connect(sock, hints, dummy)) {
  5145. close_socket(sock);
  5146. sock = INVALID_SOCKET;
  5147. }
  5148. }
  5149. return sock;
  5150. }
  5151. #endif
  5152. auto service = std::to_string(port);
  5153. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5154. timeout_sec)) {
  5155. #if defined __linux__ && !defined __ANDROID__
  5156. res_init();
  5157. #endif
  5158. return INVALID_SOCKET;
  5159. }
  5160. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5161. for (auto rp = result; rp; rp = rp->ai_next) {
  5162. // Create a socket
  5163. #ifdef _WIN32
  5164. auto sock =
  5165. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5166. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5167. /**
  5168. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5169. * and above the socket creation fails on older Windows Systems.
  5170. *
  5171. * Let's try to create a socket the old way in this case.
  5172. *
  5173. * Reference:
  5174. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5175. *
  5176. * WSA_FLAG_NO_HANDLE_INHERIT:
  5177. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5178. * SP1, and later
  5179. *
  5180. */
  5181. if (sock == INVALID_SOCKET) {
  5182. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5183. }
  5184. #else
  5185. #ifdef SOCK_CLOEXEC
  5186. auto sock =
  5187. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5188. #else
  5189. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5190. #endif
  5191. #endif
  5192. if (sock == INVALID_SOCKET) { continue; }
  5193. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5194. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5195. close_socket(sock);
  5196. continue;
  5197. }
  5198. #endif
  5199. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5200. if (rp->ai_family == AF_INET6) {
  5201. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5202. }
  5203. if (socket_options) { socket_options(sock); }
  5204. // bind or connect
  5205. auto quit = false;
  5206. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5207. close_socket(sock);
  5208. if (quit) { break; }
  5209. }
  5210. return INVALID_SOCKET;
  5211. }
  5212. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5213. #ifdef _WIN32
  5214. auto flags = nonblocking ? 1UL : 0UL;
  5215. ioctlsocket(sock, FIONBIO, &flags);
  5216. #else
  5217. auto flags = fcntl(sock, F_GETFL, 0);
  5218. fcntl(sock, F_SETFL,
  5219. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5220. #endif
  5221. }
  5222. inline bool is_connection_error() {
  5223. #ifdef _WIN32
  5224. return WSAGetLastError() != WSAEWOULDBLOCK;
  5225. #else
  5226. return errno != EINPROGRESS;
  5227. #endif
  5228. }
  5229. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5230. struct addrinfo hints;
  5231. struct addrinfo *result;
  5232. memset(&hints, 0, sizeof(struct addrinfo));
  5233. hints.ai_family = AF_UNSPEC;
  5234. hints.ai_socktype = SOCK_STREAM;
  5235. hints.ai_protocol = 0;
  5236. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5237. return false;
  5238. }
  5239. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5240. auto ret = false;
  5241. for (auto rp = result; rp; rp = rp->ai_next) {
  5242. const auto &ai = *rp;
  5243. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5244. ret = true;
  5245. break;
  5246. }
  5247. }
  5248. return ret;
  5249. }
  5250. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5251. #define USE_IF2IP
  5252. #endif
  5253. #ifdef USE_IF2IP
  5254. inline std::string if2ip(int address_family, const std::string &ifn) {
  5255. struct ifaddrs *ifap;
  5256. getifaddrs(&ifap);
  5257. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5258. std::string addr_candidate;
  5259. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5260. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5261. (AF_UNSPEC == address_family ||
  5262. ifa->ifa_addr->sa_family == address_family)) {
  5263. if (ifa->ifa_addr->sa_family == AF_INET) {
  5264. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5265. char buf[INET_ADDRSTRLEN];
  5266. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5267. return std::string(buf, INET_ADDRSTRLEN);
  5268. }
  5269. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5270. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5271. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5272. char buf[INET6_ADDRSTRLEN] = {};
  5273. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5274. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5275. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5276. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5277. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5278. } else {
  5279. return std::string(buf, INET6_ADDRSTRLEN);
  5280. }
  5281. }
  5282. }
  5283. }
  5284. }
  5285. }
  5286. return addr_candidate;
  5287. }
  5288. #endif
  5289. inline socket_t create_client_socket(
  5290. const std::string &host, const std::string &ip, int port,
  5291. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5292. SocketOptions socket_options, time_t connection_timeout_sec,
  5293. time_t connection_timeout_usec, time_t read_timeout_sec,
  5294. time_t read_timeout_usec, time_t write_timeout_sec,
  5295. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5296. auto sock = create_socket(
  5297. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5298. std::move(socket_options),
  5299. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5300. if (!intf.empty()) {
  5301. #ifdef USE_IF2IP
  5302. auto ip_from_if = if2ip(address_family, intf);
  5303. if (ip_from_if.empty()) { ip_from_if = intf; }
  5304. if (!bind_ip_address(sock2, ip_from_if)) {
  5305. error = Error::BindIPAddress;
  5306. return false;
  5307. }
  5308. #endif
  5309. }
  5310. set_nonblocking(sock2, true);
  5311. auto ret =
  5312. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5313. if (ret < 0) {
  5314. if (is_connection_error()) {
  5315. error = Error::Connection;
  5316. return false;
  5317. }
  5318. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5319. connection_timeout_usec);
  5320. if (error != Error::Success) {
  5321. if (error == Error::ConnectionTimeout) { quit = true; }
  5322. return false;
  5323. }
  5324. }
  5325. set_nonblocking(sock2, false);
  5326. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5327. read_timeout_usec);
  5328. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5329. write_timeout_usec);
  5330. error = Error::Success;
  5331. return true;
  5332. },
  5333. connection_timeout_sec); // Pass DNS timeout
  5334. if (sock != INVALID_SOCKET) {
  5335. error = Error::Success;
  5336. } else {
  5337. if (error == Error::Success) { error = Error::Connection; }
  5338. }
  5339. return sock;
  5340. }
  5341. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5342. socklen_t addr_len, std::string &ip, int &port) {
  5343. if (addr.ss_family == AF_INET) {
  5344. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5345. } else if (addr.ss_family == AF_INET6) {
  5346. port =
  5347. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5348. } else {
  5349. return false;
  5350. }
  5351. std::array<char, NI_MAXHOST> ipstr{};
  5352. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5353. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5354. 0, NI_NUMERICHOST)) {
  5355. return false;
  5356. }
  5357. ip = ipstr.data();
  5358. return true;
  5359. }
  5360. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5361. struct sockaddr_storage addr;
  5362. socklen_t addr_len = sizeof(addr);
  5363. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5364. &addr_len)) {
  5365. get_ip_and_port(addr, addr_len, ip, port);
  5366. }
  5367. }
  5368. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5369. struct sockaddr_storage addr;
  5370. socklen_t addr_len = sizeof(addr);
  5371. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5372. &addr_len)) {
  5373. #ifndef _WIN32
  5374. if (addr.ss_family == AF_UNIX) {
  5375. #if defined(__linux__)
  5376. struct ucred ucred;
  5377. socklen_t len = sizeof(ucred);
  5378. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5379. port = ucred.pid;
  5380. }
  5381. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5382. pid_t pid;
  5383. socklen_t len = sizeof(pid);
  5384. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5385. port = pid;
  5386. }
  5387. #endif
  5388. return;
  5389. }
  5390. #endif
  5391. get_ip_and_port(addr, addr_len, ip, port);
  5392. }
  5393. }
  5394. // Recursive form retained so operator""_t below can compute hashes for
  5395. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5396. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5397. // instead, which is iterative and stack-safe.
  5398. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5399. unsigned int h) {
  5400. return (l == 0)
  5401. ? h
  5402. : str2tag_core(
  5403. s + 1, l - 1,
  5404. // Unsets the 6 high bits of h, therefore no overflow happens
  5405. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5406. h * 33) ^
  5407. static_cast<unsigned char>(*s));
  5408. }
  5409. inline unsigned int str2tag(const std::string &s) {
  5410. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5411. // for compile-time UDL evaluation of short string literals, but at runtime
  5412. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5413. // would blow the stack with one frame per character.
  5414. unsigned int h = 0;
  5415. for (auto c : s) {
  5416. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5417. static_cast<unsigned char>(c);
  5418. }
  5419. return h;
  5420. }
  5421. namespace udl {
  5422. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5423. return str2tag_core(s, l, 0);
  5424. }
  5425. } // namespace udl
  5426. inline std::string
  5427. find_content_type(const std::string &path,
  5428. const std::map<std::string, std::string> &user_data,
  5429. const std::string &default_content_type) {
  5430. auto ext = file_extension(path);
  5431. auto it = user_data.find(ext);
  5432. if (it != user_data.end()) { return it->second; }
  5433. using udl::operator""_t;
  5434. switch (str2tag(ext)) {
  5435. default: return default_content_type;
  5436. case "css"_t: return "text/css";
  5437. case "csv"_t: return "text/csv";
  5438. case "htm"_t:
  5439. case "html"_t: return "text/html";
  5440. case "js"_t:
  5441. case "mjs"_t: return "text/javascript";
  5442. case "txt"_t: return "text/plain";
  5443. case "vtt"_t: return "text/vtt";
  5444. case "apng"_t: return "image/apng";
  5445. case "avif"_t: return "image/avif";
  5446. case "bmp"_t: return "image/bmp";
  5447. case "gif"_t: return "image/gif";
  5448. case "png"_t: return "image/png";
  5449. case "svg"_t: return "image/svg+xml";
  5450. case "webp"_t: return "image/webp";
  5451. case "ico"_t: return "image/x-icon";
  5452. case "tif"_t: return "image/tiff";
  5453. case "tiff"_t: return "image/tiff";
  5454. case "jpg"_t:
  5455. case "jpeg"_t: return "image/jpeg";
  5456. case "mp4"_t: return "video/mp4";
  5457. case "mpeg"_t: return "video/mpeg";
  5458. case "webm"_t: return "video/webm";
  5459. case "mp3"_t: return "audio/mp3";
  5460. case "mpga"_t: return "audio/mpeg";
  5461. case "weba"_t: return "audio/webm";
  5462. case "wav"_t: return "audio/wave";
  5463. case "otf"_t: return "font/otf";
  5464. case "ttf"_t: return "font/ttf";
  5465. case "woff"_t: return "font/woff";
  5466. case "woff2"_t: return "font/woff2";
  5467. case "7z"_t: return "application/x-7z-compressed";
  5468. case "atom"_t: return "application/atom+xml";
  5469. case "pdf"_t: return "application/pdf";
  5470. case "json"_t: return "application/json";
  5471. case "rss"_t: return "application/rss+xml";
  5472. case "tar"_t: return "application/x-tar";
  5473. case "xht"_t:
  5474. case "xhtml"_t: return "application/xhtml+xml";
  5475. case "xslt"_t: return "application/xslt+xml";
  5476. case "xml"_t: return "application/xml";
  5477. case "gz"_t: return "application/gzip";
  5478. case "zip"_t: return "application/zip";
  5479. case "wasm"_t: return "application/wasm";
  5480. }
  5481. }
  5482. inline std::string
  5483. extract_media_type(const std::string &content_type,
  5484. std::map<std::string, std::string> *params = nullptr) {
  5485. // Extract type/subtype from Content-Type value (RFC 2045)
  5486. // e.g. "application/json; charset=utf-8" -> "application/json"
  5487. auto media_type = content_type;
  5488. auto semicolon_pos = media_type.find(';');
  5489. if (semicolon_pos != std::string::npos) {
  5490. auto param_str = media_type.substr(semicolon_pos + 1);
  5491. media_type = media_type.substr(0, semicolon_pos);
  5492. if (params) {
  5493. // Parse parameters: key=value pairs separated by ';'
  5494. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5495. [&](const char *b, const char *e) {
  5496. std::string key;
  5497. std::string val;
  5498. split(b, e, '=', [&](const char *b2, const char *e2) {
  5499. if (key.empty()) {
  5500. key.assign(b2, e2);
  5501. } else {
  5502. val.assign(b2, e2);
  5503. }
  5504. });
  5505. if (!key.empty()) {
  5506. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5507. }
  5508. });
  5509. }
  5510. }
  5511. // Trim whitespace from media type
  5512. return trim_copy(media_type);
  5513. }
  5514. inline bool can_compress_content_type(const std::string &content_type) {
  5515. using udl::operator""_t;
  5516. auto mime_type = extract_media_type(content_type);
  5517. auto tag = str2tag(mime_type);
  5518. switch (tag) {
  5519. case "image/svg+xml"_t:
  5520. case "application/javascript"_t:
  5521. case "application/x-javascript"_t:
  5522. case "application/json"_t:
  5523. case "application/ld+json"_t:
  5524. case "application/xml"_t:
  5525. case "application/xhtml+xml"_t:
  5526. case "application/rss+xml"_t:
  5527. case "application/atom+xml"_t:
  5528. case "application/xslt+xml"_t:
  5529. case "application/protobuf"_t: return true;
  5530. case "text/event-stream"_t: return false;
  5531. default: return !mime_type.rfind("text/", 0);
  5532. }
  5533. }
  5534. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5535. double &quality) {
  5536. quality = 1.0;
  5537. token.clear();
  5538. // Split on first ';': left = token name, right = parameters
  5539. const char *params_b = nullptr;
  5540. std::size_t params_len = 0;
  5541. divide(
  5542. b, static_cast<std::size_t>(e - b), ';',
  5543. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5544. auto r = trim(lb, lb + llen, 0, llen);
  5545. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5546. params_b = rb;
  5547. params_len = rlen;
  5548. });
  5549. if (token.empty()) { return false; }
  5550. if (params_len == 0) { return true; }
  5551. // Scan parameters for q= (stops on first match)
  5552. bool invalid = false;
  5553. split_find(params_b, params_b + params_len, ';',
  5554. (std::numeric_limits<size_t>::max)(),
  5555. [&](const char *pb, const char *pe) -> bool {
  5556. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5557. auto len = static_cast<size_t>(pe - pb);
  5558. if (len < 2) { return false; }
  5559. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5560. return false;
  5561. }
  5562. // Trim the value portion
  5563. auto r = trim(pb, pe, 2, len);
  5564. if (r.first >= r.second) {
  5565. invalid = true;
  5566. return true;
  5567. }
  5568. double v = 0.0;
  5569. auto res = from_chars(pb + r.first, pb + r.second, v);
  5570. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5571. invalid = true;
  5572. return true;
  5573. }
  5574. quality = v;
  5575. return true;
  5576. });
  5577. return !invalid;
  5578. }
  5579. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5580. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5581. return EncodingType::None;
  5582. }
  5583. const auto &s = req.get_header_value("Accept-Encoding");
  5584. if (s.empty()) { return EncodingType::None; }
  5585. // Single-pass: iterate tokens and track the best supported encoding.
  5586. // Server preference breaks ties (br > gzip > zstd).
  5587. EncodingType best = EncodingType::None;
  5588. double best_q = 0.0; // q=0 means "not acceptable"
  5589. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5590. auto priority = [](EncodingType t) -> int {
  5591. switch (t) {
  5592. case EncodingType::Brotli: return 0;
  5593. case EncodingType::Gzip: return 1;
  5594. case EncodingType::Zstd: return 2;
  5595. default: return 3;
  5596. }
  5597. };
  5598. std::string name;
  5599. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5600. double quality = 1.0;
  5601. if (!parse_quality(b, e, name, quality)) { return; }
  5602. if (quality <= 0.0) { return; }
  5603. EncodingType type = EncodingType::None;
  5604. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5605. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5606. #endif
  5607. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5608. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5609. type = EncodingType::Gzip;
  5610. }
  5611. #endif
  5612. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5613. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5614. type = EncodingType::Zstd;
  5615. }
  5616. #endif
  5617. if (type == EncodingType::None) { return; }
  5618. // Higher q-value wins; for equal q, server preference breaks ties
  5619. if (quality > best_q ||
  5620. (quality == best_q && priority(type) < priority(best))) {
  5621. best_q = quality;
  5622. best = type;
  5623. }
  5624. });
  5625. return best;
  5626. }
  5627. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5628. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5629. if (type == EncodingType::Gzip) {
  5630. return detail::make_unique<gzip_compressor>();
  5631. }
  5632. #endif
  5633. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5634. if (type == EncodingType::Brotli) {
  5635. return detail::make_unique<brotli_compressor>();
  5636. }
  5637. #endif
  5638. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5639. if (type == EncodingType::Zstd) {
  5640. return detail::make_unique<zstd_compressor>();
  5641. }
  5642. #endif
  5643. (void)type;
  5644. return nullptr;
  5645. }
  5646. inline const char *encoding_name(EncodingType type) {
  5647. switch (type) {
  5648. case EncodingType::Gzip: return "gzip";
  5649. case EncodingType::Brotli: return "br";
  5650. case EncodingType::Zstd: return "zstd";
  5651. default: return "";
  5652. }
  5653. }
  5654. inline bool nocompressor::compress(const char *data, size_t data_length,
  5655. bool /*last*/, Callback callback) {
  5656. if (!data_length) { return true; }
  5657. return callback(data, data_length);
  5658. }
  5659. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5660. inline gzip_compressor::gzip_compressor() {
  5661. std::memset(&strm_, 0, sizeof(strm_));
  5662. strm_.zalloc = Z_NULL;
  5663. strm_.zfree = Z_NULL;
  5664. strm_.opaque = Z_NULL;
  5665. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5666. Z_DEFAULT_STRATEGY) == Z_OK;
  5667. }
  5668. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5669. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5670. bool last, Callback callback) {
  5671. assert(is_valid_);
  5672. do {
  5673. constexpr size_t max_avail_in =
  5674. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5675. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5676. (std::min)(data_length, max_avail_in));
  5677. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5678. data_length -= strm_.avail_in;
  5679. data += strm_.avail_in;
  5680. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5681. auto ret = Z_OK;
  5682. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5683. do {
  5684. strm_.avail_out = static_cast<uInt>(buff.size());
  5685. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5686. ret = deflate(&strm_, flush);
  5687. if (ret == Z_STREAM_ERROR) { return false; }
  5688. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5689. return false;
  5690. }
  5691. } while (strm_.avail_out == 0);
  5692. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5693. (flush == Z_NO_FLUSH && ret == Z_OK));
  5694. assert(strm_.avail_in == 0);
  5695. } while (data_length > 0);
  5696. return true;
  5697. }
  5698. inline gzip_decompressor::gzip_decompressor() {
  5699. std::memset(&strm_, 0, sizeof(strm_));
  5700. strm_.zalloc = Z_NULL;
  5701. strm_.zfree = Z_NULL;
  5702. strm_.opaque = Z_NULL;
  5703. // 15 is the value of wbits, which should be at the maximum possible value
  5704. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5705. // that the stream type should be automatically detected either gzip or
  5706. // deflate.
  5707. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5708. }
  5709. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5710. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5711. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5712. Callback callback) {
  5713. assert(is_valid_);
  5714. auto ret = Z_OK;
  5715. do {
  5716. constexpr size_t max_avail_in =
  5717. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5718. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5719. (std::min)(data_length, max_avail_in));
  5720. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5721. data_length -= strm_.avail_in;
  5722. data += strm_.avail_in;
  5723. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5724. while (strm_.avail_in > 0 && ret == Z_OK) {
  5725. strm_.avail_out = static_cast<uInt>(buff.size());
  5726. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5727. ret = inflate(&strm_, Z_NO_FLUSH);
  5728. assert(ret != Z_STREAM_ERROR);
  5729. switch (ret) {
  5730. case Z_NEED_DICT:
  5731. case Z_DATA_ERROR:
  5732. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5733. }
  5734. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5735. return false;
  5736. }
  5737. }
  5738. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5739. } while (data_length > 0);
  5740. return true;
  5741. }
  5742. #endif
  5743. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5744. inline brotli_compressor::brotli_compressor() {
  5745. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5746. }
  5747. inline brotli_compressor::~brotli_compressor() {
  5748. BrotliEncoderDestroyInstance(state_);
  5749. }
  5750. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5751. bool last, Callback callback) {
  5752. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5753. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5754. auto available_in = data_length;
  5755. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5756. for (;;) {
  5757. if (last) {
  5758. if (BrotliEncoderIsFinished(state_)) { break; }
  5759. } else {
  5760. if (!available_in) { break; }
  5761. }
  5762. auto available_out = buff.size();
  5763. auto next_out = buff.data();
  5764. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5765. &available_out, &next_out, nullptr)) {
  5766. return false;
  5767. }
  5768. auto output_bytes = buff.size() - available_out;
  5769. if (output_bytes) {
  5770. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5771. }
  5772. }
  5773. return true;
  5774. }
  5775. inline brotli_decompressor::brotli_decompressor() {
  5776. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5777. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5778. : BROTLI_DECODER_RESULT_ERROR;
  5779. }
  5780. inline brotli_decompressor::~brotli_decompressor() {
  5781. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5782. }
  5783. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5784. inline bool brotli_decompressor::decompress(const char *data,
  5785. size_t data_length,
  5786. Callback callback) {
  5787. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5788. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5789. return 0;
  5790. }
  5791. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5792. size_t avail_in = data_length;
  5793. size_t total_out;
  5794. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5795. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5796. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5797. char *next_out = buff.data();
  5798. size_t avail_out = buff.size();
  5799. decoder_r = BrotliDecoderDecompressStream(
  5800. decoder_s, &avail_in, &next_in, &avail_out,
  5801. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5802. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5803. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5804. }
  5805. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5806. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5807. }
  5808. #endif
  5809. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5810. inline zstd_compressor::zstd_compressor() {
  5811. ctx_ = ZSTD_createCCtx();
  5812. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5813. }
  5814. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5815. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5816. bool last, Callback callback) {
  5817. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5818. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5819. ZSTD_inBuffer input = {data, data_length, 0};
  5820. bool finished;
  5821. do {
  5822. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5823. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5824. if (ZSTD_isError(remaining)) { return false; }
  5825. if (!callback(buff.data(), output.pos)) { return false; }
  5826. finished = last ? (remaining == 0) : (input.pos == input.size);
  5827. } while (!finished);
  5828. return true;
  5829. }
  5830. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5831. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5832. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5833. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5834. Callback callback) {
  5835. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5836. ZSTD_inBuffer input = {data, data_length, 0};
  5837. while (input.pos < input.size) {
  5838. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5839. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5840. if (ZSTD_isError(remaining)) { return false; }
  5841. if (!callback(buff.data(), output.pos)) { return false; }
  5842. }
  5843. return true;
  5844. }
  5845. #endif
  5846. inline std::unique_ptr<decompressor>
  5847. create_decompressor(const std::string &encoding) {
  5848. std::unique_ptr<decompressor> decompressor;
  5849. if (encoding == "gzip" || encoding == "deflate") {
  5850. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5851. decompressor = detail::make_unique<gzip_decompressor>();
  5852. #endif
  5853. } else if (encoding.find("br") != std::string::npos) {
  5854. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5855. decompressor = detail::make_unique<brotli_decompressor>();
  5856. #endif
  5857. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5858. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5859. decompressor = detail::make_unique<zstd_decompressor>();
  5860. #endif
  5861. }
  5862. return decompressor;
  5863. }
  5864. // Returns the best available compressor and its Content-Encoding name.
  5865. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5866. inline std::pair<std::unique_ptr<compressor>, const char *>
  5867. create_compressor() {
  5868. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5869. return {detail::make_unique<brotli_compressor>(), "br"};
  5870. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5871. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5872. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5873. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5874. #else
  5875. return {nullptr, nullptr};
  5876. #endif
  5877. }
  5878. inline bool is_prohibited_header_name(const std::string &name) {
  5879. using udl::operator""_t;
  5880. switch (str2tag(name)) {
  5881. case "REMOTE_ADDR"_t:
  5882. case "REMOTE_PORT"_t:
  5883. case "LOCAL_ADDR"_t:
  5884. case "LOCAL_PORT"_t: return true;
  5885. default: return false;
  5886. }
  5887. }
  5888. inline bool has_header(const Headers &headers, const std::string &key) {
  5889. if (is_prohibited_header_name(key)) { return false; }
  5890. return headers.find(key) != headers.end();
  5891. }
  5892. inline const char *get_header_value(const Headers &headers,
  5893. const std::string &key, const char *def,
  5894. size_t id) {
  5895. if (is_prohibited_header_name(key)) {
  5896. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5897. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5898. throw std::invalid_argument(msg);
  5899. #else
  5900. return "";
  5901. #endif
  5902. }
  5903. auto rng = headers.equal_range(key);
  5904. auto it = rng.first;
  5905. std::advance(it, static_cast<ssize_t>(id));
  5906. if (it != rng.second) { return it->second.c_str(); }
  5907. return def;
  5908. }
  5909. inline size_t get_header_value_count(const Headers &headers,
  5910. const std::string &key) {
  5911. auto r = headers.equal_range(key);
  5912. return static_cast<size_t>(std::distance(r.first, r.second));
  5913. }
  5914. template <typename Map>
  5915. inline typename Map::mapped_type
  5916. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5917. auto rng = m.equal_range(key);
  5918. auto it = rng.first;
  5919. std::advance(it, static_cast<ssize_t>(id));
  5920. if (it != rng.second) { return it->second; }
  5921. return typename Map::mapped_type();
  5922. }
  5923. inline void set_header(Headers &headers, const std::string &key,
  5924. const std::string &val) {
  5925. if (fields::is_field_name(key) && fields::is_field_value(val)) {
  5926. headers.emplace(key, val);
  5927. }
  5928. }
  5929. inline bool read_headers(Stream &strm, Headers &headers) {
  5930. const auto bufsiz = 2048;
  5931. char buf[bufsiz];
  5932. stream_line_reader line_reader(strm, buf, bufsiz);
  5933. size_t header_count = 0;
  5934. for (;;) {
  5935. if (!line_reader.getline()) { return false; }
  5936. // Check if the line ends with CRLF.
  5937. auto line_terminator_len = 2;
  5938. if (line_reader.end_with_crlf()) {
  5939. // Blank line indicates end of headers.
  5940. if (line_reader.size() == 2) { break; }
  5941. } else {
  5942. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5943. // Blank line indicates end of headers.
  5944. if (line_reader.size() == 1) { break; }
  5945. line_terminator_len = 1;
  5946. #else
  5947. continue; // Skip invalid line.
  5948. #endif
  5949. }
  5950. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5951. // Check header count limit
  5952. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5953. // Exclude line terminator
  5954. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5955. if (!parse_header(line_reader.ptr(), end,
  5956. [&](const std::string &key, const std::string &val) {
  5957. headers.emplace(key, val);
  5958. })) {
  5959. return false;
  5960. }
  5961. header_count++;
  5962. }
  5963. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5964. // headers that have different values to prevent request smuggling.
  5965. auto cl_range = headers.equal_range("Content-Length");
  5966. if (cl_range.first != cl_range.second) {
  5967. const auto &first_val = cl_range.first->second;
  5968. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5969. if (it->second != first_val) { return false; }
  5970. }
  5971. }
  5972. return true;
  5973. }
  5974. inline bool read_websocket_upgrade_response(Stream &strm,
  5975. const std::string &expected_accept,
  5976. std::string &selected_subprotocol) {
  5977. // Read status line
  5978. const auto bufsiz = 2048;
  5979. char buf[bufsiz];
  5980. stream_line_reader line_reader(strm, buf, bufsiz);
  5981. if (!line_reader.getline()) { return false; }
  5982. // Check for "HTTP/1.1 101"
  5983. auto line = std::string(line_reader.ptr(), line_reader.size());
  5984. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5985. // Parse headers using existing read_headers
  5986. Headers headers;
  5987. if (!read_headers(strm, headers)) { return false; }
  5988. // Verify Upgrade: websocket (case-insensitive)
  5989. auto upgrade_it = headers.find("Upgrade");
  5990. if (upgrade_it == headers.end()) { return false; }
  5991. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  5992. if (upgrade_val != "websocket") { return false; }
  5993. // Verify Connection header contains "Upgrade" (case-insensitive)
  5994. auto connection_it = headers.find("Connection");
  5995. if (connection_it == headers.end()) { return false; }
  5996. auto connection_val = case_ignore::to_lower(connection_it->second);
  5997. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  5998. // Verify Sec-WebSocket-Accept header value
  5999. auto it = headers.find("Sec-WebSocket-Accept");
  6000. if (it == headers.end() || it->second != expected_accept) { return false; }
  6001. // Extract negotiated subprotocol
  6002. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6003. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  6004. return true;
  6005. }
  6006. enum class ReadContentResult {
  6007. Success, // Successfully read the content
  6008. PayloadTooLarge, // The content exceeds the specified payload limit
  6009. Error // An error occurred while reading the content
  6010. };
  6011. inline ReadContentResult read_content_with_length(
  6012. Stream &strm, size_t len, DownloadProgress progress,
  6013. ContentReceiverWithProgress out,
  6014. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6015. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6016. detail::BodyReader br;
  6017. br.stream = &strm;
  6018. br.has_content_length = true;
  6019. br.content_length = len;
  6020. br.payload_max_length = payload_max_length;
  6021. br.chunked = false;
  6022. br.bytes_read = 0;
  6023. br.last_error = Error::Success;
  6024. size_t r = 0;
  6025. while (r < len) {
  6026. auto read_len = static_cast<size_t>(len - r);
  6027. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6028. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6029. if (n <= 0) {
  6030. // Check if it was a payload size error
  6031. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6032. return ReadContentResult::PayloadTooLarge;
  6033. }
  6034. return ReadContentResult::Error;
  6035. }
  6036. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6037. return ReadContentResult::Error;
  6038. }
  6039. r += static_cast<size_t>(n);
  6040. if (progress) {
  6041. if (!progress(r, len)) { return ReadContentResult::Error; }
  6042. }
  6043. }
  6044. return ReadContentResult::Success;
  6045. }
  6046. inline ReadContentResult
  6047. read_content_without_length(Stream &strm, size_t payload_max_length,
  6048. ContentReceiverWithProgress out) {
  6049. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6050. size_t r = 0;
  6051. for (;;) {
  6052. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6053. if (n == 0) { return ReadContentResult::Success; }
  6054. if (n < 0) { return ReadContentResult::Error; }
  6055. // Check if adding this data would exceed the payload limit
  6056. if (r > payload_max_length ||
  6057. payload_max_length - r < static_cast<size_t>(n)) {
  6058. return ReadContentResult::PayloadTooLarge;
  6059. }
  6060. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6061. return ReadContentResult::Error;
  6062. }
  6063. r += static_cast<size_t>(n);
  6064. }
  6065. return ReadContentResult::Success;
  6066. }
  6067. template <typename T>
  6068. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6069. size_t payload_max_length,
  6070. ContentReceiverWithProgress out) {
  6071. detail::ChunkedDecoder dec(strm);
  6072. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6073. size_t total_len = 0;
  6074. for (;;) {
  6075. size_t chunk_offset = 0;
  6076. size_t chunk_total = 0;
  6077. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6078. if (n < 0) { return ReadContentResult::Error; }
  6079. if (n == 0) {
  6080. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6081. return ReadContentResult::Error;
  6082. }
  6083. return ReadContentResult::Success;
  6084. }
  6085. if (total_len > payload_max_length ||
  6086. payload_max_length - total_len < static_cast<size_t>(n)) {
  6087. return ReadContentResult::PayloadTooLarge;
  6088. }
  6089. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6090. return ReadContentResult::Error;
  6091. }
  6092. total_len += static_cast<size_t>(n);
  6093. }
  6094. }
  6095. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6096. return case_ignore::equal(
  6097. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  6098. }
  6099. template <typename T, typename U>
  6100. bool prepare_content_receiver(T &x, int &status,
  6101. ContentReceiverWithProgress receiver,
  6102. bool decompress, size_t payload_max_length,
  6103. bool &exceed_payload_max_length, U callback) {
  6104. if (decompress) {
  6105. std::string encoding = x.get_header_value("Content-Encoding");
  6106. std::unique_ptr<decompressor> decompressor;
  6107. if (!encoding.empty()) {
  6108. decompressor = detail::create_decompressor(encoding);
  6109. if (!decompressor) {
  6110. // Unsupported encoding or no support compiled in
  6111. status = StatusCode::UnsupportedMediaType_415;
  6112. return false;
  6113. }
  6114. }
  6115. if (decompressor) {
  6116. if (decompressor->is_valid()) {
  6117. size_t decompressed_size = 0;
  6118. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6119. size_t off, size_t len) {
  6120. return decompressor->decompress(
  6121. buf, n, [&](const char *buf2, size_t n2) {
  6122. // Guard against zip-bomb: check
  6123. // decompressed size against limit.
  6124. if (payload_max_length > 0 &&
  6125. (decompressed_size >= payload_max_length ||
  6126. n2 > payload_max_length - decompressed_size)) {
  6127. exceed_payload_max_length = true;
  6128. return false;
  6129. }
  6130. decompressed_size += n2;
  6131. return receiver(buf2, n2, off, len);
  6132. });
  6133. };
  6134. return callback(std::move(out));
  6135. } else {
  6136. status = StatusCode::InternalServerError_500;
  6137. return false;
  6138. }
  6139. }
  6140. }
  6141. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6142. size_t len) {
  6143. return receiver(buf, n, off, len);
  6144. };
  6145. return callback(std::move(out));
  6146. }
  6147. template <typename T>
  6148. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6149. DownloadProgress progress,
  6150. ContentReceiverWithProgress receiver, bool decompress) {
  6151. bool exceed_payload_max_length = false;
  6152. return prepare_content_receiver(
  6153. x, status, std::move(receiver), decompress, payload_max_length,
  6154. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6155. auto ret = true;
  6156. // Note: exceed_payload_max_length may also be set by the decompressor
  6157. // wrapper in prepare_content_receiver when the decompressed payload
  6158. // size exceeds the limit.
  6159. if (is_chunked_transfer_encoding(x.headers)) {
  6160. auto result = read_content_chunked(strm, x, payload_max_length, out);
  6161. if (result == ReadContentResult::Success) {
  6162. ret = true;
  6163. } else if (result == ReadContentResult::PayloadTooLarge) {
  6164. exceed_payload_max_length = true;
  6165. ret = false;
  6166. } else {
  6167. ret = false;
  6168. }
  6169. } else if (!has_header(x.headers, "Content-Length")) {
  6170. auto result =
  6171. read_content_without_length(strm, payload_max_length, out);
  6172. if (result == ReadContentResult::Success) {
  6173. ret = true;
  6174. } else if (result == ReadContentResult::PayloadTooLarge) {
  6175. exceed_payload_max_length = true;
  6176. ret = false;
  6177. } else {
  6178. ret = false;
  6179. }
  6180. } else {
  6181. auto is_invalid_value = false;
  6182. auto len = get_header_value_u64(x.headers, "Content-Length",
  6183. (std::numeric_limits<size_t>::max)(),
  6184. 0, is_invalid_value);
  6185. if (is_invalid_value) {
  6186. ret = false;
  6187. } else if (len > 0) {
  6188. auto result = read_content_with_length(
  6189. strm, len, std::move(progress), out, payload_max_length);
  6190. ret = (result == ReadContentResult::Success);
  6191. if (result == ReadContentResult::PayloadTooLarge) {
  6192. exceed_payload_max_length = true;
  6193. }
  6194. }
  6195. }
  6196. if (!ret) {
  6197. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6198. : StatusCode::BadRequest_400;
  6199. }
  6200. return ret;
  6201. });
  6202. }
  6203. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6204. const std::string &path) {
  6205. std::string s = method;
  6206. s += ' ';
  6207. s += path;
  6208. s += " HTTP/1.1\r\n";
  6209. return strm.write(s.data(), s.size());
  6210. }
  6211. inline ssize_t write_response_line(Stream &strm, int status) {
  6212. std::string s = "HTTP/1.1 ";
  6213. s += std::to_string(status);
  6214. s += ' ';
  6215. s += httplib::status_message(status);
  6216. s += "\r\n";
  6217. return strm.write(s.data(), s.size());
  6218. }
  6219. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6220. ssize_t write_len = 0;
  6221. for (const auto &x : headers) {
  6222. std::string s;
  6223. s = x.first;
  6224. s += ": ";
  6225. s += x.second;
  6226. s += "\r\n";
  6227. auto len = strm.write(s.data(), s.size());
  6228. if (len < 0) { return len; }
  6229. write_len += len;
  6230. }
  6231. auto len = strm.write("\r\n");
  6232. if (len < 0) { return len; }
  6233. write_len += len;
  6234. return write_len;
  6235. }
  6236. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6237. size_t offset = 0;
  6238. while (offset < l) {
  6239. auto length = strm.write(d + offset, l - offset);
  6240. if (length < 0) { return false; }
  6241. offset += static_cast<size_t>(length);
  6242. }
  6243. return true;
  6244. }
  6245. template <typename T>
  6246. inline bool write_content_with_progress(Stream &strm,
  6247. const ContentProvider &content_provider,
  6248. size_t offset, size_t length,
  6249. T is_shutting_down,
  6250. const UploadProgress &upload_progress,
  6251. Error &error) {
  6252. size_t end_offset = offset + length;
  6253. size_t start_offset = offset;
  6254. auto ok = true;
  6255. DataSink data_sink;
  6256. data_sink.write = [&](const char *d, size_t l) -> bool {
  6257. if (ok) {
  6258. if (write_data(strm, d, l)) {
  6259. offset += l;
  6260. if (upload_progress && length > 0) {
  6261. size_t current_written = offset - start_offset;
  6262. if (!upload_progress(current_written, length)) {
  6263. ok = false;
  6264. return false;
  6265. }
  6266. }
  6267. } else {
  6268. ok = false;
  6269. }
  6270. }
  6271. return ok;
  6272. };
  6273. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6274. while (offset < end_offset && !is_shutting_down()) {
  6275. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6276. error = Error::Write;
  6277. return false;
  6278. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6279. error = Error::Canceled;
  6280. return false;
  6281. } else if (!ok) {
  6282. error = Error::Write;
  6283. return false;
  6284. }
  6285. }
  6286. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6287. error = Error::Write;
  6288. return false;
  6289. }
  6290. error = Error::Success;
  6291. return true;
  6292. }
  6293. template <typename T>
  6294. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6295. size_t offset, size_t length, T is_shutting_down,
  6296. Error &error) {
  6297. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6298. is_shutting_down, nullptr, error);
  6299. }
  6300. template <typename T>
  6301. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6302. size_t offset, size_t length,
  6303. const T &is_shutting_down) {
  6304. auto error = Error::Success;
  6305. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6306. error);
  6307. }
  6308. template <typename T>
  6309. inline bool
  6310. write_content_without_length(Stream &strm,
  6311. const ContentProvider &content_provider,
  6312. const T &is_shutting_down) {
  6313. size_t offset = 0;
  6314. auto data_available = true;
  6315. auto ok = true;
  6316. DataSink data_sink;
  6317. data_sink.write = [&](const char *d, size_t l) -> bool {
  6318. if (ok) {
  6319. offset += l;
  6320. if (!write_data(strm, d, l)) { ok = false; }
  6321. }
  6322. return ok;
  6323. };
  6324. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6325. data_sink.done = [&](void) { data_available = false; };
  6326. while (data_available && !is_shutting_down()) {
  6327. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6328. return false;
  6329. } else if (!content_provider(offset, 0, data_sink)) {
  6330. return false;
  6331. } else if (!ok) {
  6332. return false;
  6333. }
  6334. }
  6335. return !data_available; // true only if done() was called, false if shutting
  6336. // down
  6337. }
  6338. template <typename T, typename U>
  6339. inline bool
  6340. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6341. const T &is_shutting_down, U &compressor, Error &error) {
  6342. size_t offset = 0;
  6343. auto data_available = true;
  6344. auto ok = true;
  6345. DataSink data_sink;
  6346. data_sink.write = [&](const char *d, size_t l) -> bool {
  6347. if (ok) {
  6348. data_available = l > 0;
  6349. offset += l;
  6350. std::string payload;
  6351. if (compressor.compress(d, l, false,
  6352. [&](const char *data, size_t data_len) {
  6353. payload.append(data, data_len);
  6354. return true;
  6355. })) {
  6356. if (!payload.empty()) {
  6357. // Emit chunked response header and footer for each chunk
  6358. auto chunk =
  6359. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6360. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6361. }
  6362. } else {
  6363. ok = false;
  6364. }
  6365. }
  6366. return ok;
  6367. };
  6368. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6369. auto done_with_trailer = [&](const Headers *trailer) {
  6370. if (!ok) { return; }
  6371. data_available = false;
  6372. std::string payload;
  6373. if (!compressor.compress(nullptr, 0, true,
  6374. [&](const char *data, size_t data_len) {
  6375. payload.append(data, data_len);
  6376. return true;
  6377. })) {
  6378. ok = false;
  6379. return;
  6380. }
  6381. if (!payload.empty()) {
  6382. // Emit chunked response header and footer for each chunk
  6383. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6384. if (!write_data(strm, chunk.data(), chunk.size())) {
  6385. ok = false;
  6386. return;
  6387. }
  6388. }
  6389. constexpr const char done_marker[] = "0\r\n";
  6390. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6391. // Trailer
  6392. if (trailer) {
  6393. for (const auto &kv : *trailer) {
  6394. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6395. if (!write_data(strm, field_line.data(), field_line.size())) {
  6396. ok = false;
  6397. }
  6398. }
  6399. }
  6400. constexpr const char crlf[] = "\r\n";
  6401. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6402. };
  6403. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6404. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6405. done_with_trailer(&trailer);
  6406. };
  6407. while (data_available && !is_shutting_down()) {
  6408. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6409. error = Error::Write;
  6410. return false;
  6411. } else if (!content_provider(offset, 0, data_sink)) {
  6412. error = Error::Canceled;
  6413. return false;
  6414. } else if (!ok) {
  6415. error = Error::Write;
  6416. return false;
  6417. }
  6418. }
  6419. if (data_available) { // exited due to is_shutting_down(), not done()
  6420. error = Error::Write;
  6421. return false;
  6422. }
  6423. error = Error::Success;
  6424. return true;
  6425. }
  6426. template <typename T, typename U>
  6427. inline bool write_content_chunked(Stream &strm,
  6428. const ContentProvider &content_provider,
  6429. const T &is_shutting_down, U &compressor) {
  6430. auto error = Error::Success;
  6431. return write_content_chunked(strm, content_provider, is_shutting_down,
  6432. compressor, error);
  6433. }
  6434. template <typename T>
  6435. inline bool redirect(T &cli, Request &req, Response &res,
  6436. const std::string &path, const std::string &location,
  6437. Error &error) {
  6438. Request new_req = req;
  6439. new_req.path = path;
  6440. new_req.redirect_count_ -= 1;
  6441. if (res.status == StatusCode::SeeOther_303 &&
  6442. (req.method != "GET" && req.method != "HEAD")) {
  6443. new_req.method = "GET";
  6444. new_req.body.clear();
  6445. new_req.headers.clear();
  6446. }
  6447. Response new_res;
  6448. auto ret = cli.send(new_req, new_res, error);
  6449. if (ret) {
  6450. req = std::move(new_req);
  6451. res = std::move(new_res);
  6452. if (res.location.empty()) { res.location = location; }
  6453. }
  6454. return ret;
  6455. }
  6456. inline std::string params_to_query_str(const Params &params) {
  6457. std::string query;
  6458. for (auto it = params.begin(); it != params.end(); ++it) {
  6459. if (it != params.begin()) { query += '&'; }
  6460. query += encode_query_component(it->first);
  6461. query += '=';
  6462. query += encode_query_component(it->second);
  6463. }
  6464. return query;
  6465. }
  6466. inline void parse_query_text(const char *data, std::size_t size,
  6467. Params &params) {
  6468. std::set<std::string> cache;
  6469. split(data, data + size, '&', [&](const char *b, const char *e) {
  6470. std::string kv(b, e);
  6471. if (cache.find(kv) != cache.end()) { return; }
  6472. cache.insert(std::move(kv));
  6473. std::string key;
  6474. std::string val;
  6475. divide(b, static_cast<std::size_t>(e - b), '=',
  6476. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6477. std::size_t rhs_size) {
  6478. key.assign(lhs_data, lhs_size);
  6479. val.assign(rhs_data, rhs_size);
  6480. });
  6481. if (!key.empty()) {
  6482. params.emplace(decode_query_component(key), decode_query_component(val));
  6483. }
  6484. });
  6485. }
  6486. inline void parse_query_text(const std::string &s, Params &params) {
  6487. parse_query_text(s.data(), s.size(), params);
  6488. }
  6489. // Normalize a query string by decoding and re-encoding each key/value pair
  6490. // while preserving the original parameter order. This avoids double-encoding
  6491. // and ensures consistent encoding without reordering (unlike Params which
  6492. // uses std::multimap and sorts keys).
  6493. inline std::string normalize_query_string(const std::string &query) {
  6494. std::string result;
  6495. split(query.data(), query.data() + query.size(), '&',
  6496. [&](const char *b, const char *e) {
  6497. std::string key;
  6498. std::string val;
  6499. divide(b, static_cast<std::size_t>(e - b), '=',
  6500. [&](const char *lhs_data, std::size_t lhs_size,
  6501. const char *rhs_data, std::size_t rhs_size) {
  6502. key.assign(lhs_data, lhs_size);
  6503. val.assign(rhs_data, rhs_size);
  6504. });
  6505. if (!key.empty()) {
  6506. auto dec_key = decode_query_component(key);
  6507. auto dec_val = decode_query_component(val);
  6508. if (!result.empty()) { result += '&'; }
  6509. result += encode_query_component(dec_key);
  6510. if (!val.empty() || std::find(b, e, '=') != e) {
  6511. result += '=';
  6512. result += encode_query_component(dec_val);
  6513. }
  6514. }
  6515. });
  6516. return result;
  6517. }
  6518. inline bool parse_multipart_boundary(const std::string &content_type,
  6519. std::string &boundary) {
  6520. std::map<std::string, std::string> params;
  6521. extract_media_type(content_type, &params);
  6522. auto it = params.find("boundary");
  6523. if (it == params.end()) { return false; }
  6524. boundary = it->second;
  6525. return !boundary.empty();
  6526. }
  6527. inline void parse_disposition_params(const std::string &s, Params &params) {
  6528. std::set<std::string> cache;
  6529. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6530. std::string kv(b, e);
  6531. if (cache.find(kv) != cache.end()) { return; }
  6532. cache.insert(kv);
  6533. std::string key;
  6534. std::string val;
  6535. split(b, e, '=', [&](const char *b2, const char *e2) {
  6536. if (key.empty()) {
  6537. key.assign(b2, e2);
  6538. } else {
  6539. val.assign(b2, e2);
  6540. }
  6541. });
  6542. if (!key.empty()) {
  6543. params.emplace(trim_double_quotes_copy((key)),
  6544. trim_double_quotes_copy((val)));
  6545. }
  6546. });
  6547. }
  6548. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6549. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6550. #else
  6551. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6552. #endif
  6553. auto is_valid = [](const std::string &str) {
  6554. return std::all_of(str.cbegin(), str.cend(),
  6555. [](unsigned char c) { return std::isdigit(c); });
  6556. };
  6557. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6558. const auto pos = static_cast<size_t>(6);
  6559. const auto len = static_cast<size_t>(s.size() - 6);
  6560. auto all_valid_ranges = true;
  6561. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6562. if (!all_valid_ranges) { return; }
  6563. const auto it = std::find(b, e, '-');
  6564. if (it == e) {
  6565. all_valid_ranges = false;
  6566. return;
  6567. }
  6568. const auto lhs = std::string(b, it);
  6569. const auto rhs = std::string(it + 1, e);
  6570. if (!is_valid(lhs) || !is_valid(rhs)) {
  6571. all_valid_ranges = false;
  6572. return;
  6573. }
  6574. ssize_t first = -1;
  6575. if (!lhs.empty()) {
  6576. ssize_t v;
  6577. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6578. if (res.ec == std::errc{}) { first = v; }
  6579. }
  6580. ssize_t last = -1;
  6581. if (!rhs.empty()) {
  6582. ssize_t v;
  6583. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6584. if (res.ec == std::errc{}) { last = v; }
  6585. }
  6586. if ((first == -1 && last == -1) ||
  6587. (first != -1 && last != -1 && first > last)) {
  6588. all_valid_ranges = false;
  6589. return;
  6590. }
  6591. ranges.emplace_back(first, last);
  6592. });
  6593. return all_valid_ranges && !ranges.empty();
  6594. }
  6595. return false;
  6596. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6597. }
  6598. #else
  6599. } catch (...) { return false; }
  6600. #endif
  6601. inline bool parse_accept_header(const std::string &s,
  6602. std::vector<std::string> &content_types) {
  6603. content_types.clear();
  6604. // Empty string is considered valid (no preference)
  6605. if (s.empty()) { return true; }
  6606. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6607. if (s.front() == ',' || s.back() == ',' ||
  6608. s.find(",,") != std::string::npos) {
  6609. return false;
  6610. }
  6611. struct AcceptEntry {
  6612. std::string media_type;
  6613. double quality;
  6614. int order;
  6615. };
  6616. std::vector<AcceptEntry> entries;
  6617. int order = 0;
  6618. bool has_invalid_entry = false;
  6619. // Split by comma and parse each entry
  6620. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6621. std::string entry(b, e);
  6622. entry = trim_copy(entry);
  6623. if (entry.empty()) {
  6624. has_invalid_entry = true;
  6625. return;
  6626. }
  6627. AcceptEntry accept_entry;
  6628. accept_entry.order = order++;
  6629. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6630. accept_entry.media_type, accept_entry.quality)) {
  6631. has_invalid_entry = true;
  6632. return;
  6633. }
  6634. // Remove additional parameters from media type
  6635. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6636. // Basic validation of media type format
  6637. if (accept_entry.media_type.empty()) {
  6638. has_invalid_entry = true;
  6639. return;
  6640. }
  6641. // Check for basic media type format (should contain '/' or be '*')
  6642. if (accept_entry.media_type != "*" &&
  6643. accept_entry.media_type.find('/') == std::string::npos) {
  6644. has_invalid_entry = true;
  6645. return;
  6646. }
  6647. entries.push_back(std::move(accept_entry));
  6648. });
  6649. // Return false if any invalid entry was found
  6650. if (has_invalid_entry) { return false; }
  6651. // Sort by quality (descending), then by original order (ascending)
  6652. std::sort(entries.begin(), entries.end(),
  6653. [](const AcceptEntry &a, const AcceptEntry &b) {
  6654. if (a.quality != b.quality) {
  6655. return a.quality > b.quality; // Higher quality first
  6656. }
  6657. return a.order < b.order; // Earlier order first for same quality
  6658. });
  6659. // Extract sorted media types
  6660. content_types.reserve(entries.size());
  6661. for (auto &entry : entries) {
  6662. content_types.push_back(std::move(entry.media_type));
  6663. }
  6664. return true;
  6665. }
  6666. class FormDataParser {
  6667. public:
  6668. FormDataParser() = default;
  6669. void set_boundary(std::string &&boundary) {
  6670. boundary_ = std::move(boundary);
  6671. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6672. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6673. }
  6674. bool is_valid() const { return is_valid_; }
  6675. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6676. const ContentReceiver &content_callback) {
  6677. buf_append(buf, n);
  6678. while (buf_size() > 0) {
  6679. switch (state_) {
  6680. case 0: { // Initial boundary
  6681. auto pos = buf_find(dash_boundary_crlf_);
  6682. if (pos == buf_size()) { return true; }
  6683. buf_erase(pos + dash_boundary_crlf_.size());
  6684. state_ = 1;
  6685. break;
  6686. }
  6687. case 1: { // New entry
  6688. clear_file_info();
  6689. state_ = 2;
  6690. break;
  6691. }
  6692. case 2: { // Headers
  6693. auto pos = buf_find(crlf_);
  6694. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6695. while (pos < buf_size()) {
  6696. // Empty line
  6697. if (pos == 0) {
  6698. if (!header_callback(file_)) {
  6699. is_valid_ = false;
  6700. return false;
  6701. }
  6702. buf_erase(crlf_.size());
  6703. state_ = 3;
  6704. break;
  6705. }
  6706. const auto header = buf_head(pos);
  6707. if (!parse_header(header.data(), header.data() + header.size(),
  6708. [&](const std::string &, const std::string &) {})) {
  6709. is_valid_ = false;
  6710. return false;
  6711. }
  6712. // Parse and emplace space trimmed headers into a map
  6713. if (!parse_header(
  6714. header.data(), header.data() + header.size(),
  6715. [&](const std::string &key, const std::string &val) {
  6716. file_.headers.emplace(key, val);
  6717. })) {
  6718. is_valid_ = false;
  6719. return false;
  6720. }
  6721. constexpr const char header_content_type[] = "Content-Type:";
  6722. if (start_with_case_ignore(header, header_content_type)) {
  6723. file_.content_type =
  6724. trim_copy(header.substr(str_len(header_content_type)));
  6725. } else {
  6726. std::string disposition_params;
  6727. if (parse_content_disposition(header, disposition_params)) {
  6728. Params params;
  6729. parse_disposition_params(disposition_params, params);
  6730. auto it = params.find("name");
  6731. if (it != params.end()) {
  6732. file_.name = it->second;
  6733. } else {
  6734. is_valid_ = false;
  6735. return false;
  6736. }
  6737. it = params.find("filename");
  6738. if (it != params.end()) { file_.filename = it->second; }
  6739. it = params.find("filename*");
  6740. if (it != params.end()) {
  6741. // RFC 5987: only UTF-8 encoding is allowed
  6742. const auto &val = it->second;
  6743. constexpr const char utf8_prefix[] = "UTF-8''";
  6744. constexpr size_t prefix_len = str_len(utf8_prefix);
  6745. if (val.size() > prefix_len &&
  6746. start_with_case_ignore(val, utf8_prefix)) {
  6747. file_.filename = decode_path_component(
  6748. val.substr(prefix_len)); // override...
  6749. } else {
  6750. is_valid_ = false;
  6751. return false;
  6752. }
  6753. }
  6754. }
  6755. }
  6756. buf_erase(pos + crlf_.size());
  6757. pos = buf_find(crlf_);
  6758. }
  6759. if (state_ != 3) { return true; }
  6760. break;
  6761. }
  6762. case 3: { // Body
  6763. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6764. auto pos = buf_find(crlf_dash_boundary_);
  6765. if (pos < buf_size()) {
  6766. if (!content_callback(buf_data(), pos)) {
  6767. is_valid_ = false;
  6768. return false;
  6769. }
  6770. buf_erase(pos + crlf_dash_boundary_.size());
  6771. state_ = 4;
  6772. } else {
  6773. auto len = buf_size() - crlf_dash_boundary_.size();
  6774. if (len > 0) {
  6775. if (!content_callback(buf_data(), len)) {
  6776. is_valid_ = false;
  6777. return false;
  6778. }
  6779. buf_erase(len);
  6780. }
  6781. return true;
  6782. }
  6783. break;
  6784. }
  6785. case 4: { // Boundary
  6786. if (crlf_.size() > buf_size()) { return true; }
  6787. if (buf_start_with(crlf_)) {
  6788. buf_erase(crlf_.size());
  6789. state_ = 1;
  6790. } else {
  6791. if (dash_.size() > buf_size()) { return true; }
  6792. if (buf_start_with(dash_)) {
  6793. buf_erase(dash_.size());
  6794. is_valid_ = true;
  6795. buf_erase(buf_size()); // Remove epilogue
  6796. } else {
  6797. return true;
  6798. }
  6799. }
  6800. break;
  6801. }
  6802. }
  6803. }
  6804. return true;
  6805. }
  6806. private:
  6807. void clear_file_info() {
  6808. file_.name.clear();
  6809. file_.filename.clear();
  6810. file_.content_type.clear();
  6811. file_.headers.clear();
  6812. }
  6813. bool start_with_case_ignore(const std::string &a, const char *b,
  6814. size_t offset = 0) const {
  6815. const auto b_len = strlen(b);
  6816. if (a.size() < offset + b_len) { return false; }
  6817. for (size_t i = 0; i < b_len; i++) {
  6818. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6819. return false;
  6820. }
  6821. }
  6822. return true;
  6823. }
  6824. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6825. // Returns true if header matches, with the params portion in `params_out`.
  6826. bool parse_content_disposition(const std::string &header,
  6827. std::string &params_out) const {
  6828. constexpr const char prefix[] = "Content-Disposition:";
  6829. constexpr size_t prefix_len = str_len(prefix);
  6830. if (!start_with_case_ignore(header, prefix)) { return false; }
  6831. // Skip whitespace after "Content-Disposition:"
  6832. auto pos = prefix_len;
  6833. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6834. pos++;
  6835. }
  6836. // Match "form-data;" (case-insensitive)
  6837. constexpr const char form_data[] = "form-data;";
  6838. constexpr size_t form_data_len = str_len(form_data);
  6839. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6840. pos += form_data_len;
  6841. // Skip whitespace after "form-data;"
  6842. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6843. pos++;
  6844. }
  6845. params_out = header.substr(pos);
  6846. return true;
  6847. }
  6848. const std::string dash_ = "--";
  6849. const std::string crlf_ = "\r\n";
  6850. std::string boundary_;
  6851. std::string dash_boundary_crlf_;
  6852. std::string crlf_dash_boundary_;
  6853. size_t state_ = 0;
  6854. bool is_valid_ = false;
  6855. FormData file_;
  6856. // Buffer
  6857. bool start_with(const std::string &a, size_t spos, size_t epos,
  6858. const std::string &b) const {
  6859. if (epos - spos < b.size()) { return false; }
  6860. for (size_t i = 0; i < b.size(); i++) {
  6861. if (a[i + spos] != b[i]) { return false; }
  6862. }
  6863. return true;
  6864. }
  6865. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6866. const char *buf_data() const { return &buf_[buf_spos_]; }
  6867. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6868. bool buf_start_with(const std::string &s) const {
  6869. return start_with(buf_, buf_spos_, buf_epos_, s);
  6870. }
  6871. size_t buf_find(const std::string &s) const {
  6872. auto c = s.front();
  6873. size_t off = buf_spos_;
  6874. while (off < buf_epos_) {
  6875. auto pos = off;
  6876. while (true) {
  6877. if (pos == buf_epos_) { return buf_size(); }
  6878. if (buf_[pos] == c) { break; }
  6879. pos++;
  6880. }
  6881. auto remaining_size = buf_epos_ - pos;
  6882. if (s.size() > remaining_size) { return buf_size(); }
  6883. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6884. off = pos + 1;
  6885. }
  6886. return buf_size();
  6887. }
  6888. void buf_append(const char *data, size_t n) {
  6889. auto remaining_size = buf_size();
  6890. if (remaining_size > 0 && buf_spos_ > 0) {
  6891. for (size_t i = 0; i < remaining_size; i++) {
  6892. buf_[i] = buf_[buf_spos_ + i];
  6893. }
  6894. }
  6895. buf_spos_ = 0;
  6896. buf_epos_ = remaining_size;
  6897. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6898. for (size_t i = 0; i < n; i++) {
  6899. buf_[buf_epos_ + i] = data[i];
  6900. }
  6901. buf_epos_ += n;
  6902. }
  6903. void buf_erase(size_t size) { buf_spos_ += size; }
  6904. std::string buf_;
  6905. size_t buf_spos_ = 0;
  6906. size_t buf_epos_ = 0;
  6907. };
  6908. inline std::string random_string(size_t length) {
  6909. constexpr const char data[] =
  6910. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6911. thread_local auto engine([]() {
  6912. // std::random_device might actually be deterministic on some
  6913. // platforms, but due to lack of support in the c++ standard library,
  6914. // doing better requires either some ugly hacks or breaking portability.
  6915. std::random_device seed_gen;
  6916. // Request 128 bits of entropy for initialization
  6917. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6918. return std::mt19937(seed_sequence);
  6919. }());
  6920. std::string result;
  6921. for (size_t i = 0; i < length; i++) {
  6922. result += data[engine() % (sizeof(data) - 1)];
  6923. }
  6924. return result;
  6925. }
  6926. inline std::string make_multipart_data_boundary() {
  6927. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6928. }
  6929. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6930. auto valid = true;
  6931. for (size_t i = 0; i < boundary.size(); i++) {
  6932. auto c = boundary[i];
  6933. if (!std::isalnum(static_cast<unsigned char>(c)) && c != '-' && c != '_') {
  6934. valid = false;
  6935. break;
  6936. }
  6937. }
  6938. return valid;
  6939. }
  6940. // Escape a multipart field name/filename following the WHATWG HTML standard
  6941. // ("escape a multipart form-data name"), which is what browsers send:
  6942. // '"' -> %22, CR -> %0D, LF -> %0A
  6943. // With escape_quote = false, only CR and LF are escaped; this is for header
  6944. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  6945. inline std::string escape_multipart_field(const std::string &s,
  6946. bool escape_quote = true) {
  6947. std::string result;
  6948. result.reserve(s.size());
  6949. for (auto c : s) {
  6950. switch (c) {
  6951. case '"':
  6952. if (escape_quote) {
  6953. result += "%22";
  6954. } else {
  6955. result += c;
  6956. }
  6957. break;
  6958. case '\r': result += "%0D"; break;
  6959. case '\n': result += "%0A"; break;
  6960. default: result += c; break;
  6961. }
  6962. }
  6963. return result;
  6964. }
  6965. template <typename T>
  6966. inline std::string
  6967. serialize_multipart_formdata_item_begin(const T &item,
  6968. const std::string &boundary) {
  6969. std::string body = "--" + boundary + "\r\n";
  6970. body += "Content-Disposition: form-data; name=\"" +
  6971. escape_multipart_field(item.name) + "\"";
  6972. if (!item.filename.empty()) {
  6973. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  6974. }
  6975. body += "\r\n";
  6976. if (!item.content_type.empty()) {
  6977. body +=
  6978. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  6979. "\r\n";
  6980. }
  6981. body += "\r\n";
  6982. return body;
  6983. }
  6984. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  6985. inline std::string
  6986. serialize_multipart_formdata_finish(const std::string &boundary) {
  6987. return "--" + boundary + "--\r\n";
  6988. }
  6989. inline std::string
  6990. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  6991. return "multipart/form-data; boundary=" + boundary;
  6992. }
  6993. inline std::string
  6994. serialize_multipart_formdata(const UploadFormDataItems &items,
  6995. const std::string &boundary, bool finish = true) {
  6996. std::string body;
  6997. for (const auto &item : items) {
  6998. body += serialize_multipart_formdata_item_begin(item, boundary);
  6999. body += item.content + serialize_multipart_formdata_item_end();
  7000. }
  7001. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7002. return body;
  7003. }
  7004. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7005. const std::string &boundary) {
  7006. size_t total = 0;
  7007. for (const auto &item : items) {
  7008. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7009. total += item.content.size();
  7010. total += serialize_multipart_formdata_item_end().size();
  7011. }
  7012. total += serialize_multipart_formdata_finish(boundary).size();
  7013. return total;
  7014. }
  7015. struct MultipartSegment {
  7016. const char *data;
  7017. size_t size;
  7018. };
  7019. // NOTE: items must outlive the returned ContentProvider
  7020. // (safe for synchronous use inside Post/Put/Patch)
  7021. inline ContentProvider
  7022. make_multipart_content_provider(const UploadFormDataItems &items,
  7023. const std::string &boundary) {
  7024. // Own the per-item header strings and the finish string
  7025. std::vector<std::string> owned;
  7026. owned.reserve(items.size() + 1);
  7027. for (const auto &item : items)
  7028. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7029. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7030. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7031. std::vector<MultipartSegment> segs;
  7032. segs.reserve(items.size() * 3 + 1);
  7033. static const char crlf[] = "\r\n";
  7034. for (size_t i = 0; i < items.size(); i++) {
  7035. segs.push_back({owned[i].data(), owned[i].size()});
  7036. segs.push_back({items[i].content.data(), items[i].content.size()});
  7037. segs.push_back({crlf, 2});
  7038. }
  7039. segs.push_back({owned.back().data(), owned.back().size()});
  7040. struct MultipartState {
  7041. std::vector<std::string> owned;
  7042. std::vector<MultipartSegment> segs;
  7043. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7044. };
  7045. auto state = std::make_shared<MultipartState>();
  7046. state->owned = std::move(owned);
  7047. // `segs` holds raw pointers into owned strings; std::string move preserves
  7048. // the data pointer, so these pointers remain valid after the move above.
  7049. state->segs = std::move(segs);
  7050. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7051. // Buffer multiple small segments into fewer, larger writes to avoid
  7052. // excessive TCP packets when there are many form data items (#2410)
  7053. auto &buf = state->buf;
  7054. auto buf_size = buf.size();
  7055. size_t buf_len = 0;
  7056. size_t remaining = length;
  7057. // Find the first segment containing 'offset'
  7058. size_t pos = 0;
  7059. size_t seg_idx = 0;
  7060. for (; seg_idx < state->segs.size(); seg_idx++) {
  7061. const auto &seg = state->segs[seg_idx];
  7062. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7063. pos += seg.size;
  7064. }
  7065. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7066. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7067. const auto &seg = state->segs[seg_idx];
  7068. size_t available = seg.size - seg_offset;
  7069. size_t to_copy = (std::min)(available, remaining);
  7070. const char *src = seg.data + seg_offset;
  7071. seg_offset = 0; // only the first segment has a non-zero offset
  7072. while (to_copy > 0) {
  7073. size_t space = buf_size - buf_len;
  7074. size_t chunk = (std::min)(to_copy, space);
  7075. std::memcpy(buf.data() + buf_len, src, chunk);
  7076. buf_len += chunk;
  7077. src += chunk;
  7078. to_copy -= chunk;
  7079. remaining -= chunk;
  7080. if (buf_len == buf_size) {
  7081. if (!sink.write(buf.data(), buf_len)) { return false; }
  7082. buf_len = 0;
  7083. }
  7084. }
  7085. }
  7086. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7087. return true;
  7088. };
  7089. }
  7090. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7091. if (ranges.size() <= 1) return;
  7092. // Sort ranges by start position
  7093. std::sort(ranges.begin(), ranges.end(),
  7094. [](const Range &a, const Range &b) { return a.first < b.first; });
  7095. Ranges coalesced;
  7096. coalesced.reserve(ranges.size());
  7097. for (auto &r : ranges) {
  7098. auto first_pos = r.first;
  7099. auto last_pos = r.second;
  7100. // Handle special cases like in range_error
  7101. if (first_pos == -1 && last_pos == -1) {
  7102. first_pos = 0;
  7103. last_pos = static_cast<ssize_t>(content_length);
  7104. }
  7105. if (first_pos == -1) {
  7106. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7107. last_pos = static_cast<ssize_t>(content_length) - 1;
  7108. }
  7109. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7110. last_pos = static_cast<ssize_t>(content_length) - 1;
  7111. }
  7112. // Skip invalid ranges
  7113. if (!(0 <= first_pos && first_pos <= last_pos &&
  7114. last_pos < static_cast<ssize_t>(content_length))) {
  7115. continue;
  7116. }
  7117. // Coalesce with previous range if overlapping or adjacent (but not
  7118. // identical)
  7119. if (!coalesced.empty()) {
  7120. auto &prev = coalesced.back();
  7121. // Check if current range overlaps or is adjacent to previous range
  7122. // but don't coalesce identical ranges (allow duplicates)
  7123. if (first_pos <= prev.second + 1 &&
  7124. !(first_pos == prev.first && last_pos == prev.second)) {
  7125. // Extend the previous range
  7126. prev.second = (std::max)(prev.second, last_pos);
  7127. continue;
  7128. }
  7129. }
  7130. // Add new range
  7131. coalesced.emplace_back(first_pos, last_pos);
  7132. }
  7133. ranges = std::move(coalesced);
  7134. }
  7135. inline bool range_error(Request &req, Response &res) {
  7136. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7137. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7138. req.ranges.clear();
  7139. if (res.status == StatusCode::PartialContent_206) {
  7140. res.status = StatusCode::OK_200;
  7141. }
  7142. return false;
  7143. }
  7144. ssize_t content_len = static_cast<ssize_t>(
  7145. res.content_length_ ? res.content_length_ : res.body.size());
  7146. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7147. size_t overwrapping_count = 0;
  7148. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7149. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7150. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7151. // Too many ranges
  7152. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7153. for (auto &r : req.ranges) {
  7154. auto &first_pos = r.first;
  7155. auto &last_pos = r.second;
  7156. if (first_pos == -1 && last_pos == -1) {
  7157. first_pos = 0;
  7158. last_pos = content_len;
  7159. }
  7160. if (first_pos == -1) {
  7161. first_pos = content_len - last_pos;
  7162. last_pos = content_len - 1;
  7163. }
  7164. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7165. // A client can limit the number of bytes requested without knowing the
  7166. // size of the selected representation. If the last-pos value is absent,
  7167. // or if the value is greater than or equal to the current length of the
  7168. // representation data, the byte range is interpreted as the remainder of
  7169. // the representation (i.e., the server replaces the value of last-pos
  7170. // with a value that is one less than the current length of the selected
  7171. // representation).
  7172. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7173. if (last_pos == -1 || last_pos >= content_len) {
  7174. last_pos = content_len - 1;
  7175. }
  7176. // Range must be within content length
  7177. if (!(0 <= first_pos && first_pos <= last_pos &&
  7178. last_pos <= content_len - 1)) {
  7179. return true;
  7180. }
  7181. // Request must not have more than two overlapping ranges
  7182. for (const auto &processed_range : processed_ranges) {
  7183. if (!(last_pos < processed_range.first ||
  7184. first_pos > processed_range.second)) {
  7185. overwrapping_count++;
  7186. if (overwrapping_count > 2) { return true; }
  7187. break; // Only count once per range
  7188. }
  7189. }
  7190. processed_ranges.emplace_back(first_pos, last_pos);
  7191. }
  7192. // After validation, coalesce overlapping ranges as per RFC 9110
  7193. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7194. }
  7195. return false;
  7196. }
  7197. inline std::pair<size_t, size_t>
  7198. get_range_offset_and_length(Range r, size_t content_length) {
  7199. assert(r.first != -1 && r.second != -1);
  7200. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7201. assert(r.first <= r.second &&
  7202. r.second < static_cast<ssize_t>(content_length));
  7203. (void)(content_length);
  7204. return std::make_pair(static_cast<size_t>(r.first),
  7205. static_cast<size_t>(r.second - r.first) + 1);
  7206. }
  7207. inline std::string make_content_range_header_field(
  7208. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7209. auto st = offset_and_length.first;
  7210. auto ed = st + offset_and_length.second - 1;
  7211. std::string field = "bytes ";
  7212. field += std::to_string(st);
  7213. field += '-';
  7214. field += std::to_string(ed);
  7215. field += '/';
  7216. field += std::to_string(content_length);
  7217. return field;
  7218. }
  7219. template <typename SToken, typename CToken, typename Content>
  7220. bool process_multipart_ranges_data(const Request &req,
  7221. const std::string &boundary,
  7222. const std::string &content_type,
  7223. size_t content_length, SToken stoken,
  7224. CToken ctoken, Content content) {
  7225. for (size_t i = 0; i < req.ranges.size(); i++) {
  7226. ctoken("--");
  7227. stoken(boundary);
  7228. ctoken("\r\n");
  7229. if (!content_type.empty()) {
  7230. ctoken("Content-Type: ");
  7231. stoken(content_type);
  7232. ctoken("\r\n");
  7233. }
  7234. auto offset_and_length =
  7235. get_range_offset_and_length(req.ranges[i], content_length);
  7236. ctoken("Content-Range: ");
  7237. stoken(make_content_range_header_field(offset_and_length, content_length));
  7238. ctoken("\r\n");
  7239. ctoken("\r\n");
  7240. if (!content(offset_and_length.first, offset_and_length.second)) {
  7241. return false;
  7242. }
  7243. ctoken("\r\n");
  7244. }
  7245. ctoken("--");
  7246. stoken(boundary);
  7247. ctoken("--");
  7248. return true;
  7249. }
  7250. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7251. const std::string &boundary,
  7252. const std::string &content_type,
  7253. size_t content_length,
  7254. std::string &data) {
  7255. process_multipart_ranges_data(
  7256. req, boundary, content_type, content_length,
  7257. [&](const std::string &token) { data += token; },
  7258. [&](const std::string &token) { data += token; },
  7259. [&](size_t offset, size_t length) {
  7260. assert(offset + length <= content_length);
  7261. data += res.body.substr(offset, length);
  7262. return true;
  7263. });
  7264. }
  7265. inline size_t get_multipart_ranges_data_length(const Request &req,
  7266. const std::string &boundary,
  7267. const std::string &content_type,
  7268. size_t content_length) {
  7269. size_t data_length = 0;
  7270. process_multipart_ranges_data(
  7271. req, boundary, content_type, content_length,
  7272. [&](const std::string &token) { data_length += token.size(); },
  7273. [&](const std::string &token) { data_length += token.size(); },
  7274. [&](size_t /*offset*/, size_t length) {
  7275. data_length += length;
  7276. return true;
  7277. });
  7278. return data_length;
  7279. }
  7280. template <typename T>
  7281. inline bool
  7282. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7283. const std::string &boundary,
  7284. const std::string &content_type,
  7285. size_t content_length, const T &is_shutting_down) {
  7286. return process_multipart_ranges_data(
  7287. req, boundary, content_type, content_length,
  7288. [&](const std::string &token) { strm.write(token); },
  7289. [&](const std::string &token) { strm.write(token); },
  7290. [&](size_t offset, size_t length) {
  7291. return write_content(strm, res.content_provider_, offset, length,
  7292. is_shutting_down);
  7293. });
  7294. }
  7295. inline bool has_framed_body(const Request &req) {
  7296. return is_chunked_transfer_encoding(req.headers) ||
  7297. req.get_header_value_u64("Content-Length") > 0;
  7298. }
  7299. inline bool is_connection_persistent(const Request &req) {
  7300. auto conn = req.get_header_value("Connection");
  7301. if (conn == "close") { return false; }
  7302. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7303. return true;
  7304. }
  7305. inline bool expect_content(const Request &req) {
  7306. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7307. req.method == "DELETE") {
  7308. return true;
  7309. }
  7310. return has_framed_body(req);
  7311. }
  7312. #ifdef _WIN32
  7313. class WSInit {
  7314. public:
  7315. WSInit() {
  7316. WSADATA wsaData;
  7317. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7318. }
  7319. ~WSInit() {
  7320. if (is_valid_) WSACleanup();
  7321. }
  7322. bool is_valid_ = false;
  7323. };
  7324. static WSInit wsinit_;
  7325. #endif
  7326. inline bool parse_www_authenticate(const Response &res,
  7327. std::map<std::string, std::string> &auth,
  7328. bool is_proxy) {
  7329. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7330. if (res.has_header(auth_key)) {
  7331. thread_local auto re =
  7332. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7333. auto s = res.get_header_value(auth_key);
  7334. auto pos = s.find(' ');
  7335. if (pos != std::string::npos) {
  7336. auto type = s.substr(0, pos);
  7337. if (type == "Basic") {
  7338. return false;
  7339. } else if (type == "Digest") {
  7340. s = s.substr(pos + 1);
  7341. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7342. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7343. const auto &m = *i;
  7344. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7345. static_cast<size_t>(m.length(1)));
  7346. auto val = m.length(2) > 0
  7347. ? s.substr(static_cast<size_t>(m.position(2)),
  7348. static_cast<size_t>(m.length(2)))
  7349. : s.substr(static_cast<size_t>(m.position(3)),
  7350. static_cast<size_t>(m.length(3)));
  7351. auth[std::move(key)] = std::move(val);
  7352. }
  7353. return true;
  7354. }
  7355. }
  7356. }
  7357. return false;
  7358. }
  7359. class ContentProviderAdapter {
  7360. public:
  7361. explicit ContentProviderAdapter(
  7362. ContentProviderWithoutLength &&content_provider)
  7363. : content_provider_(std::move(content_provider)) {}
  7364. bool operator()(size_t offset, size_t, DataSink &sink) {
  7365. return content_provider_(offset, sink);
  7366. }
  7367. private:
  7368. ContentProviderWithoutLength content_provider_;
  7369. };
  7370. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7371. namespace fields {
  7372. inline bool is_token_char(char c) {
  7373. return std::isalnum(static_cast<unsigned char>(c)) || c == '!' || c == '#' ||
  7374. c == '$' || c == '%' || c == '&' || c == '\'' || c == '*' ||
  7375. c == '+' || c == '-' || c == '.' || c == '^' || c == '_' || c == '`' ||
  7376. c == '|' || c == '~';
  7377. }
  7378. inline bool is_token(const std::string &s) {
  7379. if (s.empty()) { return false; }
  7380. for (auto c : s) {
  7381. if (!is_token_char(c)) { return false; }
  7382. }
  7383. return true;
  7384. }
  7385. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7386. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7387. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7388. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7389. inline bool is_field_content(const std::string &s) {
  7390. if (s.empty()) { return true; }
  7391. if (s.size() == 1) {
  7392. return is_field_vchar(s[0]);
  7393. } else if (s.size() == 2) {
  7394. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7395. } else {
  7396. size_t i = 0;
  7397. if (!is_field_vchar(s[i])) { return false; }
  7398. i++;
  7399. while (i < s.size() - 1) {
  7400. auto c = s[i++];
  7401. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7402. } else {
  7403. return false;
  7404. }
  7405. }
  7406. return is_field_vchar(s[i]);
  7407. }
  7408. }
  7409. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7410. } // namespace fields
  7411. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7412. int port, bool is_ssl,
  7413. const std::string &path,
  7414. const Headers &headers,
  7415. std::string &selected_subprotocol) {
  7416. // Validate path and host
  7417. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7418. return false;
  7419. }
  7420. // Validate user-provided headers
  7421. for (const auto &h : headers) {
  7422. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7423. return false;
  7424. }
  7425. }
  7426. // Generate random Sec-WebSocket-Key
  7427. thread_local std::mt19937 rng(std::random_device{}());
  7428. std::string key_bytes(16, '\0');
  7429. for (size_t i = 0; i < 16; i += 4) {
  7430. auto r = rng();
  7431. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7432. }
  7433. auto client_key = base64_encode(key_bytes);
  7434. // Build upgrade request
  7435. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7436. req_str += "Host: " + make_host_and_port_string(host, port, is_ssl) + "\r\n";
  7437. req_str += "Upgrade: websocket\r\n";
  7438. req_str += "Connection: Upgrade\r\n";
  7439. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7440. req_str += "Sec-WebSocket-Version: 13\r\n";
  7441. for (const auto &h : headers) {
  7442. req_str += h.first + ": " + h.second + "\r\n";
  7443. }
  7444. req_str += "\r\n";
  7445. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7446. // Verify 101 response and Sec-WebSocket-Accept header
  7447. auto expected_accept = websocket_accept_key(client_key);
  7448. return read_websocket_upgrade_response(strm, expected_accept,
  7449. selected_subprotocol);
  7450. }
  7451. } // namespace detail
  7452. /*
  7453. * Group 2: detail namespace - SSL common utilities
  7454. */
  7455. #ifdef CPPHTTPLIB_SSL_ENABLED
  7456. namespace detail {
  7457. class SSLSocketStream final : public Stream {
  7458. public:
  7459. SSLSocketStream(
  7460. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7461. time_t read_timeout_usec, time_t write_timeout_sec,
  7462. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7463. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7464. (std::chrono::steady_clock::time_point::min)());
  7465. ~SSLSocketStream() override;
  7466. bool is_readable() const override;
  7467. bool wait_readable() const override;
  7468. bool wait_writable() const override;
  7469. bool is_peer_alive() const override;
  7470. ssize_t read(char *ptr, size_t size) override;
  7471. ssize_t write(const char *ptr, size_t size) override;
  7472. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7473. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7474. socket_t socket() const override;
  7475. time_t duration() const override;
  7476. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7477. private:
  7478. socket_t sock_;
  7479. tls::session_t session_;
  7480. time_t read_timeout_sec_;
  7481. time_t read_timeout_usec_;
  7482. time_t write_timeout_sec_;
  7483. time_t write_timeout_usec_;
  7484. time_t max_timeout_msec_;
  7485. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7486. };
  7487. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7488. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7489. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7490. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7491. unsigned int hash_length = 0;
  7492. unsigned char hash[EVP_MAX_MD_SIZE];
  7493. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7494. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7495. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7496. std::stringstream ss;
  7497. for (auto i = 0u; i < hash_length; ++i) {
  7498. ss << std::hex << std::setw(2) << std::setfill('0')
  7499. << static_cast<unsigned int>(hash[i]);
  7500. }
  7501. return ss.str();
  7502. }
  7503. inline std::string MD5(const std::string &s) {
  7504. return message_digest(s, EVP_md5());
  7505. }
  7506. inline std::string SHA_256(const std::string &s) {
  7507. return message_digest(s, EVP_sha256());
  7508. }
  7509. inline std::string SHA_512(const std::string &s) {
  7510. return message_digest(s, EVP_sha512());
  7511. }
  7512. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7513. namespace {
  7514. template <size_t N>
  7515. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7516. std::stringstream ss;
  7517. for (size_t i = 0; i < N; ++i) {
  7518. ss << std::hex << std::setw(2) << std::setfill('0')
  7519. << static_cast<unsigned int>(hash[i]);
  7520. }
  7521. return ss.str();
  7522. }
  7523. } // namespace
  7524. inline std::string MD5(const std::string &s) {
  7525. unsigned char hash[16];
  7526. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7527. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7528. hash);
  7529. #else
  7530. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7531. hash);
  7532. #endif
  7533. return hash_to_hex(hash);
  7534. }
  7535. inline std::string SHA_256(const std::string &s) {
  7536. unsigned char hash[32];
  7537. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7538. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7539. hash, 0);
  7540. #else
  7541. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7542. s.size(), hash, 0);
  7543. #endif
  7544. return hash_to_hex(hash);
  7545. }
  7546. inline std::string SHA_512(const std::string &s) {
  7547. unsigned char hash[64];
  7548. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7549. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7550. hash, 0);
  7551. #else
  7552. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7553. s.size(), hash, 0);
  7554. #endif
  7555. return hash_to_hex(hash);
  7556. }
  7557. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7558. namespace {
  7559. template <size_t N>
  7560. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7561. std::stringstream ss;
  7562. for (size_t i = 0; i < N; ++i) {
  7563. ss << std::hex << std::setw(2) << std::setfill('0')
  7564. << static_cast<unsigned int>(hash[i]);
  7565. }
  7566. return ss.str();
  7567. }
  7568. } // namespace
  7569. inline std::string MD5(const std::string &s) {
  7570. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7571. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7572. static_cast<word32>(s.size()), hash);
  7573. return hash_to_hex(hash);
  7574. }
  7575. inline std::string SHA_256(const std::string &s) {
  7576. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7577. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7578. static_cast<word32>(s.size()), hash);
  7579. return hash_to_hex(hash);
  7580. }
  7581. inline std::string SHA_512(const std::string &s) {
  7582. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7583. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7584. static_cast<word32>(s.size()), hash);
  7585. return hash_to_hex(hash);
  7586. }
  7587. #endif
  7588. inline bool is_ip_address(const std::string &host) {
  7589. struct in_addr addr4;
  7590. struct in6_addr addr6;
  7591. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7592. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7593. }
  7594. template <typename T>
  7595. inline bool process_server_socket_ssl(
  7596. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7597. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7598. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7599. time_t write_timeout_usec, T callback) {
  7600. return process_server_socket_core(
  7601. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7602. [&](bool close_connection, bool &connection_closed) {
  7603. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7604. write_timeout_sec, write_timeout_usec);
  7605. return callback(strm, close_connection, connection_closed);
  7606. });
  7607. }
  7608. template <typename T>
  7609. inline bool process_client_socket_ssl(
  7610. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7611. time_t read_timeout_usec, time_t write_timeout_sec,
  7612. time_t write_timeout_usec, time_t max_timeout_msec,
  7613. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7614. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7615. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7616. start_time);
  7617. return callback(strm);
  7618. }
  7619. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7620. const Request &req, const std::map<std::string, std::string> &auth,
  7621. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7622. const std::string &password, bool is_proxy = false) {
  7623. std::string nc;
  7624. {
  7625. std::stringstream ss;
  7626. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7627. nc = ss.str();
  7628. }
  7629. std::string qop;
  7630. if (auth.find("qop") != auth.end()) {
  7631. qop = auth.at("qop");
  7632. if (qop.find("auth-int") != std::string::npos) {
  7633. qop = "auth-int";
  7634. } else if (qop.find("auth") != std::string::npos) {
  7635. qop = "auth";
  7636. } else {
  7637. qop.clear();
  7638. }
  7639. }
  7640. std::string algo = "MD5";
  7641. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7642. std::string response;
  7643. {
  7644. auto H = algo == "SHA-256" ? detail::SHA_256
  7645. : algo == "SHA-512" ? detail::SHA_512
  7646. : detail::MD5;
  7647. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7648. auto A2 = req.method + ":" + req.path;
  7649. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7650. if (qop.empty()) {
  7651. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7652. } else {
  7653. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7654. ":" + qop + ":" + H(A2));
  7655. }
  7656. }
  7657. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7658. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7659. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7660. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7661. (qop.empty() ? ", response=\""
  7662. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7663. cnonce + "\", response=\"") +
  7664. response + "\"" +
  7665. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7666. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7667. return std::make_pair(key, field);
  7668. }
  7669. inline bool match_hostname(const std::string &pattern,
  7670. const std::string &hostname) {
  7671. // Exact match (case-insensitive)
  7672. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7673. // Split both pattern and hostname into components by '.'
  7674. std::vector<std::string> pattern_components;
  7675. if (!pattern.empty()) {
  7676. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7677. [&](const char *b, const char *e) {
  7678. pattern_components.emplace_back(b, e);
  7679. });
  7680. }
  7681. std::vector<std::string> host_components;
  7682. if (!hostname.empty()) {
  7683. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7684. [&](const char *b, const char *e) {
  7685. host_components.emplace_back(b, e);
  7686. });
  7687. }
  7688. // Component count must match
  7689. if (host_components.size() != pattern_components.size()) { return false; }
  7690. // Compare each component with wildcard support
  7691. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7692. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7693. auto itr = pattern_components.begin();
  7694. for (const auto &h : host_components) {
  7695. auto &p = *itr;
  7696. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7697. bool partial_match = false;
  7698. if (!p.empty() && p[p.size() - 1] == '*') {
  7699. const auto prefix_length = p.size() - 1;
  7700. if (prefix_length == 0) {
  7701. partial_match = true;
  7702. } else if (h.size() >= prefix_length) {
  7703. partial_match =
  7704. std::equal(p.begin(),
  7705. p.begin() + static_cast<std::string::difference_type>(
  7706. prefix_length),
  7707. h.begin(), [](const char ca, const char cb) {
  7708. return detail::case_ignore::to_lower(ca) ==
  7709. detail::case_ignore::to_lower(cb);
  7710. });
  7711. }
  7712. }
  7713. if (!partial_match) { return false; }
  7714. }
  7715. ++itr;
  7716. }
  7717. return true;
  7718. }
  7719. #ifdef _WIN32
  7720. // Verify certificate using Windows CertGetCertificateChain API.
  7721. // This provides real-time certificate validation with Windows Update
  7722. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7723. inline bool
  7724. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7725. const std::string &hostname,
  7726. bool verify_hostname, uint64_t &out_error) {
  7727. if (der_cert.empty()) { return false; }
  7728. out_error = 0;
  7729. // Create Windows certificate context from DER data
  7730. auto cert_context = CertCreateCertificateContext(
  7731. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7732. static_cast<DWORD>(der_cert.size()));
  7733. if (!cert_context) {
  7734. out_error = GetLastError();
  7735. return false;
  7736. }
  7737. auto cert_guard =
  7738. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7739. // Setup chain parameters
  7740. CERT_CHAIN_PARA chain_para = {};
  7741. chain_para.cbSize = sizeof(chain_para);
  7742. // Build certificate chain with revocation checking
  7743. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7744. auto chain_result = CertGetCertificateChain(
  7745. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7746. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7747. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7748. nullptr, &chain_context);
  7749. if (!chain_result || !chain_context) {
  7750. out_error = GetLastError();
  7751. return false;
  7752. }
  7753. auto chain_guard =
  7754. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7755. // Check if chain has errors
  7756. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7757. out_error = chain_context->TrustStatus.dwErrorStatus;
  7758. return false;
  7759. }
  7760. // Verify SSL policy
  7761. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7762. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7763. #ifdef AUTHTYPE_SERVER
  7764. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7765. #endif
  7766. std::wstring whost;
  7767. if (verify_hostname) {
  7768. whost = u8string_to_wstring(hostname.c_str());
  7769. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7770. }
  7771. CERT_CHAIN_POLICY_PARA policy_para = {};
  7772. policy_para.cbSize = sizeof(policy_para);
  7773. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7774. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7775. #else
  7776. policy_para.dwFlags = 0;
  7777. #endif
  7778. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7779. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7780. policy_status.cbSize = sizeof(policy_status);
  7781. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7782. &policy_para, &policy_status)) {
  7783. out_error = GetLastError();
  7784. return false;
  7785. }
  7786. if (policy_status.dwError != 0) {
  7787. out_error = policy_status.dwError;
  7788. return false;
  7789. }
  7790. return true;
  7791. }
  7792. #endif // _WIN32
  7793. // Loads CA file/dir configuration and applies the system CA policy to a
  7794. // client TLS context. PEM data and native stores are applied to the context
  7795. // directly at set time; has_custom_store reflects them for the Auto policy
  7796. // decision.
  7797. inline bool load_client_ca_config(tls::ctx_t ctx,
  7798. const std::string &ca_cert_file_path,
  7799. const std::string &ca_cert_dir_path,
  7800. bool has_custom_store, SystemCAMode mode,
  7801. uint64_t &backend_error) {
  7802. auto ret = true;
  7803. if (!ca_cert_file_path.empty()) {
  7804. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7805. backend_error = tls::get_error();
  7806. ret = false;
  7807. }
  7808. } else if (!ca_cert_dir_path.empty()) {
  7809. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7810. backend_error = tls::get_error();
  7811. ret = false;
  7812. }
  7813. }
  7814. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7815. !ca_cert_dir_path.empty() || has_custom_store;
  7816. if (mode == SystemCAMode::Enabled ||
  7817. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7818. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7819. }
  7820. return ret;
  7821. }
  7822. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7823. tls::session_t &session, socket_t sock,
  7824. bool server_certificate_verification,
  7825. time_t timeout_sec, time_t timeout_usec) {
  7826. using namespace tls;
  7827. if (!ctx) { return false; }
  7828. bool is_ip = is_ip_address(host);
  7829. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7830. // Chain verification happens during the handshake even for IP hosts; the
  7831. // certificate identity is verified post-handshake via verify_hostname()
  7832. set_verify_client(ctx, server_certificate_verification);
  7833. #endif
  7834. session = create_session(ctx, sock);
  7835. if (!session) { return false; }
  7836. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  7837. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  7838. // their identity is checked post-handshake below instead.
  7839. if (!is_ip) {
  7840. if (server_certificate_verification) {
  7841. set_hostname(session, host.c_str());
  7842. } else {
  7843. set_sni(session, host.c_str());
  7844. }
  7845. }
  7846. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7847. return false;
  7848. }
  7849. if (server_certificate_verification) {
  7850. if (get_verify_result(session) != 0) { return false; }
  7851. // Identity check against the peer certificate, post-handshake for all
  7852. // backends (same as SSLClient). For IP hosts this is the only identity
  7853. // verification since no hostname is bound during the handshake.
  7854. auto server_cert = get_peer_cert(session);
  7855. if (!server_cert) { return false; }
  7856. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  7857. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  7858. }
  7859. return true;
  7860. }
  7861. } // namespace detail
  7862. #endif // CPPHTTPLIB_SSL_ENABLED
  7863. /*
  7864. * Group 3: httplib namespace - Non-SSL public API implementations
  7865. */
  7866. inline void default_socket_options(socket_t sock) {
  7867. set_socket_opt(sock, SOL_SOCKET,
  7868. #ifdef SO_REUSEPORT
  7869. SO_REUSEPORT,
  7870. #else
  7871. SO_REUSEADDR,
  7872. #endif
  7873. 1);
  7874. }
  7875. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7876. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7877. sizeof(optval));
  7878. }
  7879. inline std::string get_bearer_token_auth(const Request &req) {
  7880. if (req.has_header("Authorization")) {
  7881. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7882. return req.get_header_value("Authorization")
  7883. .substr(bearer_header_prefix_len);
  7884. }
  7885. return "";
  7886. }
  7887. inline const char *status_message(int status) {
  7888. switch (status) {
  7889. case StatusCode::Continue_100: return "Continue";
  7890. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7891. case StatusCode::Processing_102: return "Processing";
  7892. case StatusCode::EarlyHints_103: return "Early Hints";
  7893. case StatusCode::OK_200: return "OK";
  7894. case StatusCode::Created_201: return "Created";
  7895. case StatusCode::Accepted_202: return "Accepted";
  7896. case StatusCode::NonAuthoritativeInformation_203:
  7897. return "Non-Authoritative Information";
  7898. case StatusCode::NoContent_204: return "No Content";
  7899. case StatusCode::ResetContent_205: return "Reset Content";
  7900. case StatusCode::PartialContent_206: return "Partial Content";
  7901. case StatusCode::MultiStatus_207: return "Multi-Status";
  7902. case StatusCode::AlreadyReported_208: return "Already Reported";
  7903. case StatusCode::IMUsed_226: return "IM Used";
  7904. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7905. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7906. case StatusCode::Found_302: return "Found";
  7907. case StatusCode::SeeOther_303: return "See Other";
  7908. case StatusCode::NotModified_304: return "Not Modified";
  7909. case StatusCode::UseProxy_305: return "Use Proxy";
  7910. case StatusCode::unused_306: return "unused";
  7911. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7912. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7913. case StatusCode::BadRequest_400: return "Bad Request";
  7914. case StatusCode::Unauthorized_401: return "Unauthorized";
  7915. case StatusCode::PaymentRequired_402: return "Payment Required";
  7916. case StatusCode::Forbidden_403: return "Forbidden";
  7917. case StatusCode::NotFound_404: return "Not Found";
  7918. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7919. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7920. case StatusCode::ProxyAuthenticationRequired_407:
  7921. return "Proxy Authentication Required";
  7922. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7923. case StatusCode::Conflict_409: return "Conflict";
  7924. case StatusCode::Gone_410: return "Gone";
  7925. case StatusCode::LengthRequired_411: return "Length Required";
  7926. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7927. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7928. case StatusCode::UriTooLong_414: return "URI Too Long";
  7929. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7930. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7931. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7932. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7933. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7934. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7935. case StatusCode::Locked_423: return "Locked";
  7936. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7937. case StatusCode::TooEarly_425: return "Too Early";
  7938. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7939. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7940. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7941. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7942. return "Request Header Fields Too Large";
  7943. case StatusCode::UnavailableForLegalReasons_451:
  7944. return "Unavailable For Legal Reasons";
  7945. case StatusCode::NotImplemented_501: return "Not Implemented";
  7946. case StatusCode::BadGateway_502: return "Bad Gateway";
  7947. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7948. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7949. case StatusCode::HttpVersionNotSupported_505:
  7950. return "HTTP Version Not Supported";
  7951. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  7952. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  7953. case StatusCode::LoopDetected_508: return "Loop Detected";
  7954. case StatusCode::NotExtended_510: return "Not Extended";
  7955. case StatusCode::NetworkAuthenticationRequired_511:
  7956. return "Network Authentication Required";
  7957. default:
  7958. case StatusCode::InternalServerError_500: return "Internal Server Error";
  7959. }
  7960. }
  7961. inline std::string to_string(const Error error) {
  7962. switch (error) {
  7963. case Error::Success: return "Success (no error)";
  7964. case Error::Unknown: return "Unknown";
  7965. case Error::Connection: return "Could not establish connection";
  7966. case Error::BindIPAddress: return "Failed to bind IP address";
  7967. case Error::Read: return "Failed to read connection";
  7968. case Error::Write: return "Failed to write connection";
  7969. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  7970. case Error::Canceled: return "Connection handling canceled";
  7971. case Error::SSLConnection: return "SSL connection failed";
  7972. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  7973. case Error::SSLServerVerification: return "SSL server verification failed";
  7974. case Error::SSLServerHostnameVerification:
  7975. return "SSL server hostname verification failed";
  7976. case Error::UnsupportedMultipartBoundaryChars:
  7977. return "Unsupported HTTP multipart boundary characters";
  7978. case Error::Compression: return "Compression failed";
  7979. case Error::ConnectionTimeout: return "Connection timed out";
  7980. case Error::ProxyConnection: return "Proxy connection failed";
  7981. case Error::ConnectionClosed: return "Connection closed by server";
  7982. case Error::Timeout: return "Read timeout";
  7983. case Error::ResourceExhaustion: return "Resource exhaustion";
  7984. case Error::TooManyFormDataFiles: return "Too many form data files";
  7985. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  7986. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  7987. case Error::ExceedMaxSocketDescriptorCount:
  7988. return "Exceeded maximum socket descriptor count";
  7989. case Error::InvalidRequestLine: return "Invalid request line";
  7990. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  7991. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  7992. case Error::InvalidHeaders: return "Invalid headers";
  7993. case Error::MultipartParsing: return "Multipart parsing failed";
  7994. case Error::OpenFile: return "Failed to open file";
  7995. case Error::Listen: return "Failed to listen on socket";
  7996. case Error::GetSockName: return "Failed to get socket name";
  7997. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  7998. case Error::HTTPParsing: return "HTTP parsing failed";
  7999. case Error::InvalidRangeHeader: return "Invalid Range header";
  8000. default: break;
  8001. }
  8002. return "Invalid";
  8003. }
  8004. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  8005. os << to_string(obj);
  8006. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  8007. return os;
  8008. }
  8009. inline std::string hosted_at(const std::string &hostname) {
  8010. std::vector<std::string> addrs;
  8011. hosted_at(hostname, addrs);
  8012. if (addrs.empty()) { return std::string(); }
  8013. return addrs[0];
  8014. }
  8015. inline void hosted_at(const std::string &hostname,
  8016. std::vector<std::string> &addrs) {
  8017. struct addrinfo hints;
  8018. struct addrinfo *result;
  8019. memset(&hints, 0, sizeof(struct addrinfo));
  8020. hints.ai_family = AF_UNSPEC;
  8021. hints.ai_socktype = SOCK_STREAM;
  8022. hints.ai_protocol = 0;
  8023. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8024. &result, 0)) {
  8025. #if defined __linux__ && !defined __ANDROID__
  8026. res_init();
  8027. #endif
  8028. return;
  8029. }
  8030. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8031. for (auto rp = result; rp; rp = rp->ai_next) {
  8032. const auto &addr =
  8033. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8034. std::string ip;
  8035. auto dummy = -1;
  8036. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8037. dummy)) {
  8038. addrs.emplace_back(std::move(ip));
  8039. }
  8040. }
  8041. }
  8042. inline std::string encode_uri_component(const std::string &value) {
  8043. std::ostringstream escaped;
  8044. escaped.fill('0');
  8045. escaped << std::hex;
  8046. for (auto c : value) {
  8047. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  8048. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  8049. c == ')') {
  8050. escaped << c;
  8051. } else {
  8052. escaped << std::uppercase;
  8053. escaped << '%' << std::setw(2)
  8054. << static_cast<int>(static_cast<unsigned char>(c));
  8055. escaped << std::nouppercase;
  8056. }
  8057. }
  8058. return escaped.str();
  8059. }
  8060. inline std::string encode_uri(const std::string &value) {
  8061. std::ostringstream escaped;
  8062. escaped.fill('0');
  8063. escaped << std::hex;
  8064. for (auto c : value) {
  8065. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  8066. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  8067. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  8068. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8069. escaped << c;
  8070. } else {
  8071. escaped << std::uppercase;
  8072. escaped << '%' << std::setw(2)
  8073. << static_cast<int>(static_cast<unsigned char>(c));
  8074. escaped << std::nouppercase;
  8075. }
  8076. }
  8077. return escaped.str();
  8078. }
  8079. inline std::string decode_uri_component(const std::string &value) {
  8080. std::string result;
  8081. for (size_t i = 0; i < value.size(); i++) {
  8082. if (value[i] == '%' && i + 2 < value.size()) {
  8083. auto val = 0;
  8084. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8085. result += static_cast<char>(val);
  8086. i += 2;
  8087. } else {
  8088. result += value[i];
  8089. }
  8090. } else {
  8091. result += value[i];
  8092. }
  8093. }
  8094. return result;
  8095. }
  8096. inline std::string decode_uri(const std::string &value) {
  8097. std::string result;
  8098. for (size_t i = 0; i < value.size(); i++) {
  8099. if (value[i] == '%' && i + 2 < value.size()) {
  8100. auto val = 0;
  8101. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8102. result += static_cast<char>(val);
  8103. i += 2;
  8104. } else {
  8105. result += value[i];
  8106. }
  8107. } else {
  8108. result += value[i];
  8109. }
  8110. }
  8111. return result;
  8112. }
  8113. inline std::string encode_path_component(const std::string &component) {
  8114. std::string result;
  8115. result.reserve(component.size() * 3);
  8116. for (size_t i = 0; i < component.size(); i++) {
  8117. auto c = static_cast<unsigned char>(component[i]);
  8118. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8119. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  8120. result += static_cast<char>(c);
  8121. }
  8122. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8123. // "," / ";" / "="
  8124. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8125. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8126. c == '=') {
  8127. result += static_cast<char>(c);
  8128. }
  8129. // Colon is allowed in path segments except first segment
  8130. else if (c == ':') {
  8131. result += static_cast<char>(c);
  8132. }
  8133. // @ is allowed in path
  8134. else if (c == '@') {
  8135. result += static_cast<char>(c);
  8136. } else {
  8137. result += '%';
  8138. char hex[3];
  8139. snprintf(hex, sizeof(hex), "%02X", c);
  8140. result.append(hex, 2);
  8141. }
  8142. }
  8143. return result;
  8144. }
  8145. inline std::string decode_path_component(const std::string &component) {
  8146. std::string result;
  8147. result.reserve(component.size());
  8148. for (size_t i = 0; i < component.size(); i++) {
  8149. if (component[i] == '%' && i + 1 < component.size()) {
  8150. if (component[i + 1] == 'u') {
  8151. // Unicode %uXXXX encoding
  8152. auto val = 0;
  8153. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8154. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8155. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8156. char buff[4];
  8157. size_t len = detail::to_utf8(val, buff);
  8158. if (len > 0) { result.append(buff, len); }
  8159. i += 5; // 'u0000'
  8160. } else {
  8161. result += component[i];
  8162. }
  8163. } else {
  8164. // Standard %XX encoding
  8165. auto val = 0;
  8166. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8167. // 2 digits hex codes
  8168. result += static_cast<char>(val);
  8169. i += 2; // 'XX'
  8170. } else {
  8171. result += component[i];
  8172. }
  8173. }
  8174. } else {
  8175. result += component[i];
  8176. }
  8177. }
  8178. return result;
  8179. }
  8180. inline std::string encode_query_component(const std::string &component,
  8181. bool space_as_plus) {
  8182. std::string result;
  8183. result.reserve(component.size() * 3);
  8184. for (size_t i = 0; i < component.size(); i++) {
  8185. auto c = static_cast<unsigned char>(component[i]);
  8186. // Unreserved characters per RFC 3986
  8187. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  8188. result += static_cast<char>(c);
  8189. }
  8190. // Space handling
  8191. else if (c == ' ') {
  8192. if (space_as_plus) {
  8193. result += '+';
  8194. } else {
  8195. result += "%20";
  8196. }
  8197. }
  8198. // Plus sign handling
  8199. else if (c == '+') {
  8200. if (space_as_plus) {
  8201. result += "%2B";
  8202. } else {
  8203. result += static_cast<char>(c);
  8204. }
  8205. }
  8206. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8207. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8208. c == '*' || c == ',' || c == ';') {
  8209. result += static_cast<char>(c);
  8210. }
  8211. // Colon and @ are allowed in query
  8212. else if (c == ':' || c == '@') {
  8213. result += static_cast<char>(c);
  8214. }
  8215. // Forward slash is allowed in query values
  8216. else if (c == '/') {
  8217. result += static_cast<char>(c);
  8218. }
  8219. // Question mark is allowed in query values (after first ?)
  8220. else if (c == '?') {
  8221. result += static_cast<char>(c);
  8222. } else {
  8223. result += '%';
  8224. char hex[3];
  8225. snprintf(hex, sizeof(hex), "%02X", c);
  8226. result.append(hex, 2);
  8227. }
  8228. }
  8229. return result;
  8230. }
  8231. inline std::string decode_query_component(const std::string &component,
  8232. bool plus_as_space) {
  8233. std::string result;
  8234. result.reserve(component.size());
  8235. for (size_t i = 0; i < component.size(); i++) {
  8236. if (component[i] == '%' && i + 2 < component.size()) {
  8237. auto val = 0;
  8238. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8239. result += static_cast<char>(val);
  8240. i += 2;
  8241. } else {
  8242. result += component[i];
  8243. }
  8244. } else if (component[i] == '+' && plus_as_space) {
  8245. result += ' '; // + becomes space in form-urlencoded
  8246. } else {
  8247. result += component[i];
  8248. }
  8249. }
  8250. return result;
  8251. }
  8252. inline std::string sanitize_filename(const std::string &filename) {
  8253. // Extract basename: find the last path separator (/ or \)
  8254. auto pos = filename.find_last_of("/\\");
  8255. auto result =
  8256. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8257. // Strip null bytes
  8258. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8259. // Trim whitespace
  8260. {
  8261. auto start = result.find_first_not_of(" \t");
  8262. auto end = result.find_last_not_of(" \t");
  8263. result = (start == std::string::npos)
  8264. ? ""
  8265. : result.substr(start, end - start + 1);
  8266. }
  8267. // Reject . and ..
  8268. if (result == "." || result == "..") { return ""; }
  8269. return result;
  8270. }
  8271. inline std::string append_query_params(const std::string &path,
  8272. const Params &params) {
  8273. std::string path_with_query = path;
  8274. thread_local const std::regex re("[^?]+\\?.*");
  8275. auto delm = std::regex_match(path, re) ? '&' : '?';
  8276. path_with_query += delm + detail::params_to_query_str(params);
  8277. return path_with_query;
  8278. }
  8279. // Header utilities
  8280. inline std::pair<std::string, std::string>
  8281. make_range_header(const Ranges &ranges) {
  8282. std::string field = "bytes=";
  8283. auto i = 0;
  8284. for (const auto &r : ranges) {
  8285. if (i != 0) { field += ", "; }
  8286. if (r.first != -1) { field += std::to_string(r.first); }
  8287. field += '-';
  8288. if (r.second != -1) { field += std::to_string(r.second); }
  8289. i++;
  8290. }
  8291. return std::make_pair("Range", std::move(field));
  8292. }
  8293. inline std::pair<std::string, std::string>
  8294. make_basic_authentication_header(const std::string &username,
  8295. const std::string &password, bool is_proxy) {
  8296. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8297. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8298. return std::make_pair(key, std::move(field));
  8299. }
  8300. inline std::pair<std::string, std::string>
  8301. make_bearer_token_authentication_header(const std::string &token,
  8302. bool is_proxy = false) {
  8303. auto field = "Bearer " + token;
  8304. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8305. return std::make_pair(key, std::move(field));
  8306. }
  8307. // Request implementation
  8308. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8309. size_t id) const {
  8310. return detail::get_header_value_u64(headers, key, def, id);
  8311. }
  8312. inline bool Request::has_header(const std::string &key) const {
  8313. return detail::has_header(headers, key);
  8314. }
  8315. inline std::string Request::get_header_value(const std::string &key,
  8316. const char *def, size_t id) const {
  8317. return detail::get_header_value(headers, key, def, id);
  8318. }
  8319. inline size_t Request::get_header_value_count(const std::string &key) const {
  8320. return detail::get_header_value_count(headers, key);
  8321. }
  8322. inline void Request::set_header(const std::string &key,
  8323. const std::string &val) {
  8324. detail::set_header(headers, key, val);
  8325. }
  8326. inline bool Request::has_trailer(const std::string &key) const {
  8327. return trailers.find(key) != trailers.end();
  8328. }
  8329. inline std::string Request::get_trailer_value(const std::string &key,
  8330. size_t id) const {
  8331. return detail::get_multimap_value(trailers, key, id);
  8332. }
  8333. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8334. auto r = trailers.equal_range(key);
  8335. return static_cast<size_t>(std::distance(r.first, r.second));
  8336. }
  8337. inline bool Request::has_param(const std::string &key) const {
  8338. return params.find(key) != params.end();
  8339. }
  8340. inline std::string Request::get_param_value(const std::string &key,
  8341. size_t id) const {
  8342. return detail::get_multimap_value(params, key, id);
  8343. }
  8344. inline std::vector<std::string>
  8345. Request::get_param_values(const std::string &key) const {
  8346. auto rng = params.equal_range(key);
  8347. std::vector<std::string> values;
  8348. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8349. for (auto it = rng.first; it != rng.second; ++it) {
  8350. values.push_back(it->second);
  8351. }
  8352. return values;
  8353. }
  8354. inline size_t Request::get_param_value_count(const std::string &key) const {
  8355. auto r = params.equal_range(key);
  8356. return static_cast<size_t>(std::distance(r.first, r.second));
  8357. }
  8358. inline bool Request::is_multipart_form_data() const {
  8359. const auto &content_type = get_header_value("Content-Type");
  8360. return detail::extract_media_type(content_type) == "multipart/form-data";
  8361. }
  8362. // Multipart FormData implementation
  8363. inline std::string MultipartFormData::get_field(const std::string &key,
  8364. size_t id) const {
  8365. auto rng = fields.equal_range(key);
  8366. auto it = rng.first;
  8367. std::advance(it, static_cast<ssize_t>(id));
  8368. if (it != rng.second) { return it->second.content; }
  8369. return std::string();
  8370. }
  8371. inline std::vector<std::string>
  8372. MultipartFormData::get_fields(const std::string &key) const {
  8373. std::vector<std::string> values;
  8374. auto rng = fields.equal_range(key);
  8375. for (auto it = rng.first; it != rng.second; it++) {
  8376. values.push_back(it->second.content);
  8377. }
  8378. return values;
  8379. }
  8380. inline bool MultipartFormData::has_field(const std::string &key) const {
  8381. return fields.find(key) != fields.end();
  8382. }
  8383. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8384. auto r = fields.equal_range(key);
  8385. return static_cast<size_t>(std::distance(r.first, r.second));
  8386. }
  8387. inline FormData MultipartFormData::get_file(const std::string &key,
  8388. size_t id) const {
  8389. return detail::get_multimap_value(files, key, id);
  8390. }
  8391. inline std::vector<FormData>
  8392. MultipartFormData::get_files(const std::string &key) const {
  8393. std::vector<FormData> values;
  8394. auto rng = files.equal_range(key);
  8395. for (auto it = rng.first; it != rng.second; it++) {
  8396. values.push_back(it->second);
  8397. }
  8398. return values;
  8399. }
  8400. inline bool MultipartFormData::has_file(const std::string &key) const {
  8401. return files.find(key) != files.end();
  8402. }
  8403. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8404. auto r = files.equal_range(key);
  8405. return static_cast<size_t>(std::distance(r.first, r.second));
  8406. }
  8407. // Multipart FormData writer implementation
  8408. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8409. return detail::is_multipart_boundary_chars_valid(boundary);
  8410. }
  8411. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8412. : boundary_(detail::make_multipart_data_boundary()) {}
  8413. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8414. : boundary_(std::move(boundary)) {}
  8415. inline const std::string &MultipartFormDataWriter::boundary() const {
  8416. return boundary_;
  8417. }
  8418. inline std::string MultipartFormDataWriter::content_type() const {
  8419. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8420. }
  8421. inline std::string
  8422. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8423. return detail::serialize_multipart_formdata(items, boundary_);
  8424. }
  8425. inline size_t MultipartFormDataWriter::content_length(
  8426. const UploadFormDataItems &items) const {
  8427. return detail::get_multipart_content_length(items, boundary_);
  8428. }
  8429. inline std::string
  8430. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8431. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8432. }
  8433. inline std::string MultipartFormDataWriter::item_end() {
  8434. return detail::serialize_multipart_formdata_item_end();
  8435. }
  8436. inline std::string MultipartFormDataWriter::finish() const {
  8437. return detail::serialize_multipart_formdata_finish(boundary_);
  8438. }
  8439. // Response implementation
  8440. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8441. size_t id) const {
  8442. return detail::get_header_value_u64(headers, key, def, id);
  8443. }
  8444. inline bool Response::has_header(const std::string &key) const {
  8445. return headers.find(key) != headers.end();
  8446. }
  8447. inline std::string Response::get_header_value(const std::string &key,
  8448. const char *def,
  8449. size_t id) const {
  8450. return detail::get_header_value(headers, key, def, id);
  8451. }
  8452. inline size_t Response::get_header_value_count(const std::string &key) const {
  8453. return detail::get_header_value_count(headers, key);
  8454. }
  8455. inline void Response::set_header(const std::string &key,
  8456. const std::string &val) {
  8457. detail::set_header(headers, key, val);
  8458. }
  8459. inline bool Response::has_trailer(const std::string &key) const {
  8460. return trailers.find(key) != trailers.end();
  8461. }
  8462. inline std::string Response::get_trailer_value(const std::string &key,
  8463. size_t id) const {
  8464. return detail::get_multimap_value(trailers, key, id);
  8465. }
  8466. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8467. auto r = trailers.equal_range(key);
  8468. return static_cast<size_t>(std::distance(r.first, r.second));
  8469. }
  8470. inline void Response::set_redirect(const std::string &url, int stat) {
  8471. if (detail::fields::is_field_value(url)) {
  8472. set_header("Location", url);
  8473. if (300 <= stat && stat < 400) {
  8474. this->status = stat;
  8475. } else {
  8476. this->status = StatusCode::Found_302;
  8477. }
  8478. }
  8479. }
  8480. inline void Response::set_content(const char *s, size_t n,
  8481. const std::string &content_type) {
  8482. body.assign(s, n);
  8483. auto rng = headers.equal_range("Content-Type");
  8484. headers.erase(rng.first, rng.second);
  8485. set_header("Content-Type", content_type);
  8486. }
  8487. inline void Response::set_content(const std::string &s,
  8488. const std::string &content_type) {
  8489. set_content(s.data(), s.size(), content_type);
  8490. }
  8491. inline void Response::set_content(std::string &&s,
  8492. const std::string &content_type) {
  8493. body = std::move(s);
  8494. auto rng = headers.equal_range("Content-Type");
  8495. headers.erase(rng.first, rng.second);
  8496. set_header("Content-Type", content_type);
  8497. }
  8498. inline void Response::set_content_provider(
  8499. size_t in_length, const std::string &content_type, ContentProvider provider,
  8500. ContentProviderResourceReleaser resource_releaser) {
  8501. set_header("Content-Type", content_type);
  8502. content_length_ = in_length;
  8503. if (in_length > 0) { content_provider_ = std::move(provider); }
  8504. content_provider_resource_releaser_ = std::move(resource_releaser);
  8505. is_chunked_content_provider_ = false;
  8506. }
  8507. inline void Response::set_content_provider(
  8508. const std::string &content_type, ContentProviderWithoutLength provider,
  8509. ContentProviderResourceReleaser resource_releaser) {
  8510. set_header("Content-Type", content_type);
  8511. content_length_ = 0;
  8512. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8513. content_provider_resource_releaser_ = std::move(resource_releaser);
  8514. is_chunked_content_provider_ = false;
  8515. }
  8516. inline void Response::set_chunked_content_provider(
  8517. const std::string &content_type, ContentProviderWithoutLength provider,
  8518. ContentProviderResourceReleaser resource_releaser) {
  8519. set_header("Content-Type", content_type);
  8520. content_length_ = 0;
  8521. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8522. content_provider_resource_releaser_ = std::move(resource_releaser);
  8523. is_chunked_content_provider_ = true;
  8524. }
  8525. inline void Response::set_file_content(const std::string &path,
  8526. const std::string &content_type) {
  8527. file_content_path_ = path;
  8528. file_content_content_type_ = content_type;
  8529. }
  8530. inline void Response::set_file_content(const std::string &path) {
  8531. file_content_path_ = path;
  8532. }
  8533. // Result implementation
  8534. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8535. size_t def,
  8536. size_t id) const {
  8537. return detail::get_header_value_u64(request_headers_, key, def, id);
  8538. }
  8539. inline bool Result::has_request_header(const std::string &key) const {
  8540. return request_headers_.find(key) != request_headers_.end();
  8541. }
  8542. inline std::string Result::get_request_header_value(const std::string &key,
  8543. const char *def,
  8544. size_t id) const {
  8545. return detail::get_header_value(request_headers_, key, def, id);
  8546. }
  8547. inline size_t
  8548. Result::get_request_header_value_count(const std::string &key) const {
  8549. auto r = request_headers_.equal_range(key);
  8550. return static_cast<size_t>(std::distance(r.first, r.second));
  8551. }
  8552. // Stream implementation
  8553. inline ssize_t Stream::write(const char *ptr) {
  8554. return write(ptr, strlen(ptr));
  8555. }
  8556. inline ssize_t Stream::write(const std::string &s) {
  8557. return write(s.data(), s.size());
  8558. }
  8559. // BodyReader implementation
  8560. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8561. if (!stream) {
  8562. last_error = Error::Connection;
  8563. return -1;
  8564. }
  8565. if (eof) { return 0; }
  8566. if (!chunked) {
  8567. // Content-Length based reading
  8568. if (has_content_length && bytes_read >= content_length) {
  8569. eof = true;
  8570. return 0;
  8571. }
  8572. auto to_read = len;
  8573. if (has_content_length) {
  8574. auto remaining = content_length - bytes_read;
  8575. to_read = (std::min)(len, remaining);
  8576. }
  8577. auto n = stream->read(buf, to_read);
  8578. if (n < 0) {
  8579. last_error = stream->get_error();
  8580. if (last_error == Error::Success) { last_error = Error::Read; }
  8581. eof = true;
  8582. return n;
  8583. }
  8584. if (n == 0) {
  8585. // Unexpected EOF before content_length
  8586. last_error = stream->get_error();
  8587. if (last_error == Error::Success) { last_error = Error::Read; }
  8588. eof = true;
  8589. return 0;
  8590. }
  8591. bytes_read += static_cast<size_t>(n);
  8592. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8593. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8594. last_error = Error::ExceedMaxPayloadSize;
  8595. eof = true;
  8596. return -1;
  8597. }
  8598. return n;
  8599. }
  8600. // Chunked transfer encoding: delegate to shared decoder instance.
  8601. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8602. size_t chunk_offset = 0;
  8603. size_t chunk_total = 0;
  8604. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8605. if (n < 0) {
  8606. last_error = stream->get_error();
  8607. if (last_error == Error::Success) { last_error = Error::Read; }
  8608. eof = true;
  8609. return n;
  8610. }
  8611. if (n == 0) {
  8612. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8613. eof = true;
  8614. return 0;
  8615. }
  8616. bytes_read += static_cast<size_t>(n);
  8617. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8618. last_error = Error::ExceedMaxPayloadSize;
  8619. eof = true;
  8620. return -1;
  8621. }
  8622. return n;
  8623. }
  8624. // ThreadPool implementation
  8625. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  8626. time_t idle_timeout_sec)
  8627. : base_thread_count_(n), max_queued_requests_(mqr),
  8628. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  8629. shutdown_(false) {
  8630. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8631. if (max_n != 0 && max_n < n) {
  8632. std::string msg = "max_threads must be >= base_threads";
  8633. throw std::invalid_argument(msg);
  8634. }
  8635. #endif
  8636. max_thread_count_ = max_n == 0 ? n : max_n;
  8637. threads_.reserve(base_thread_count_);
  8638. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8639. try {
  8640. #endif
  8641. for (size_t i = 0; i < base_thread_count_; i++) {
  8642. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8643. }
  8644. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8645. } catch (...) {
  8646. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8647. // signal the workers we already spawned to exit and join them so the
  8648. // vector destructor does not see joinable threads (which would call
  8649. // std::terminate). Then rethrow so the caller learns of the failure.
  8650. {
  8651. std::unique_lock<std::mutex> lock(mutex_);
  8652. shutdown_ = true;
  8653. }
  8654. cond_.notify_all();
  8655. for (auto &t : threads_) {
  8656. if (t.joinable()) { t.join(); }
  8657. }
  8658. throw;
  8659. }
  8660. #endif
  8661. }
  8662. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8663. {
  8664. std::unique_lock<std::mutex> lock(mutex_);
  8665. if (shutdown_) { return false; }
  8666. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8667. return false;
  8668. }
  8669. jobs_.push_back(std::move(fn));
  8670. // Spawn a dynamic thread if no idle threads and under max
  8671. if (idle_thread_count_ == 0 &&
  8672. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8673. cleanup_finished_threads();
  8674. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8675. }
  8676. }
  8677. cond_.notify_one();
  8678. return true;
  8679. }
  8680. inline void ThreadPool::shutdown() {
  8681. {
  8682. std::unique_lock<std::mutex> lock(mutex_);
  8683. shutdown_ = true;
  8684. }
  8685. cond_.notify_all();
  8686. for (auto &t : threads_) {
  8687. if (t.joinable()) { t.join(); }
  8688. }
  8689. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8690. // with worker threads that call move_to_finished() concurrently.
  8691. std::list<std::thread> remaining_dynamic;
  8692. {
  8693. std::unique_lock<std::mutex> lock(mutex_);
  8694. remaining_dynamic = std::move(dynamic_threads_);
  8695. }
  8696. for (auto &t : remaining_dynamic) {
  8697. if (t.joinable()) { t.join(); }
  8698. }
  8699. std::unique_lock<std::mutex> lock(mutex_);
  8700. cleanup_finished_threads();
  8701. }
  8702. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8703. // Must be called with mutex_ held
  8704. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8705. if (it->get_id() == id) {
  8706. finished_threads_.push_back(std::move(*it));
  8707. dynamic_threads_.erase(it);
  8708. return;
  8709. }
  8710. }
  8711. }
  8712. inline void ThreadPool::cleanup_finished_threads() {
  8713. // Must be called with mutex_ held
  8714. for (auto &t : finished_threads_) {
  8715. if (t.joinable()) { t.join(); }
  8716. }
  8717. finished_threads_.clear();
  8718. }
  8719. inline void ThreadPool::worker(bool is_dynamic) {
  8720. for (;;) {
  8721. std::function<void()> fn;
  8722. {
  8723. std::unique_lock<std::mutex> lock(mutex_);
  8724. idle_thread_count_++;
  8725. if (is_dynamic) {
  8726. auto has_work =
  8727. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  8728. [&] { return !jobs_.empty() || shutdown_; });
  8729. if (!has_work) {
  8730. // Timed out with no work - exit this dynamic thread
  8731. idle_thread_count_--;
  8732. move_to_finished(std::this_thread::get_id());
  8733. break;
  8734. }
  8735. } else {
  8736. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8737. }
  8738. idle_thread_count_--;
  8739. if (shutdown_ && jobs_.empty()) { break; }
  8740. fn = std::move(jobs_.front());
  8741. jobs_.pop_front();
  8742. }
  8743. assert(true == static_cast<bool>(fn));
  8744. fn();
  8745. }
  8746. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8747. !defined(LIBRESSL_VERSION_NUMBER)
  8748. OPENSSL_thread_stop();
  8749. #endif
  8750. }
  8751. /*
  8752. * Group 1 (continued): detail namespace - Stream implementations
  8753. */
  8754. namespace detail {
  8755. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8756. time_t timeout_sec, time_t timeout_usec,
  8757. time_t &actual_timeout_sec,
  8758. time_t &actual_timeout_usec) {
  8759. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8760. auto actual_timeout_msec =
  8761. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8762. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8763. actual_timeout_sec = actual_timeout_msec / 1000;
  8764. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8765. }
  8766. // Socket stream implementation
  8767. inline SocketStream::SocketStream(
  8768. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8769. time_t write_timeout_sec, time_t write_timeout_usec,
  8770. time_t max_timeout_msec,
  8771. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8772. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8773. read_timeout_usec_(read_timeout_usec),
  8774. write_timeout_sec_(write_timeout_sec),
  8775. write_timeout_usec_(write_timeout_usec),
  8776. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8777. read_buff_(read_buff_size_, 0) {}
  8778. inline SocketStream::~SocketStream() = default;
  8779. inline bool SocketStream::is_readable() const {
  8780. return read_buff_off_ < read_buff_content_size_;
  8781. }
  8782. inline bool SocketStream::wait_readable() const {
  8783. if (max_timeout_msec_ <= 0) {
  8784. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8785. }
  8786. time_t read_timeout_sec;
  8787. time_t read_timeout_usec;
  8788. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8789. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8790. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8791. }
  8792. inline bool SocketStream::wait_writable() const {
  8793. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8794. }
  8795. inline bool SocketStream::is_peer_alive() const {
  8796. return detail::is_socket_alive(sock_);
  8797. }
  8798. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8799. #ifdef _WIN32
  8800. size =
  8801. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8802. #else
  8803. size = (std::min)(size,
  8804. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8805. #endif
  8806. if (read_buff_off_ < read_buff_content_size_) {
  8807. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8808. if (size <= remaining_size) {
  8809. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8810. read_buff_off_ += size;
  8811. return static_cast<ssize_t>(size);
  8812. } else {
  8813. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8814. read_buff_off_ += remaining_size;
  8815. return static_cast<ssize_t>(remaining_size);
  8816. }
  8817. }
  8818. if (!wait_readable()) {
  8819. error_ = Error::Timeout;
  8820. return -1;
  8821. }
  8822. read_buff_off_ = 0;
  8823. read_buff_content_size_ = 0;
  8824. if (size < read_buff_size_) {
  8825. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8826. CPPHTTPLIB_RECV_FLAGS);
  8827. if (n <= 0) {
  8828. if (n == 0) {
  8829. error_ = Error::ConnectionClosed;
  8830. } else {
  8831. error_ = Error::Read;
  8832. }
  8833. return n;
  8834. } else if (n <= static_cast<ssize_t>(size)) {
  8835. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8836. return n;
  8837. } else {
  8838. memcpy(ptr, read_buff_.data(), size);
  8839. read_buff_off_ = size;
  8840. read_buff_content_size_ = static_cast<size_t>(n);
  8841. return static_cast<ssize_t>(size);
  8842. }
  8843. } else {
  8844. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8845. if (n <= 0) {
  8846. if (n == 0) {
  8847. error_ = Error::ConnectionClosed;
  8848. } else {
  8849. error_ = Error::Read;
  8850. }
  8851. }
  8852. return n;
  8853. }
  8854. }
  8855. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8856. if (!wait_writable()) { return -1; }
  8857. #if defined(_WIN32) && !defined(_WIN64)
  8858. size =
  8859. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8860. #endif
  8861. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8862. }
  8863. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8864. int &port) const {
  8865. return detail::get_remote_ip_and_port(sock_, ip, port);
  8866. }
  8867. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8868. int &port) const {
  8869. return detail::get_local_ip_and_port(sock_, ip, port);
  8870. }
  8871. inline socket_t SocketStream::socket() const { return sock_; }
  8872. inline time_t SocketStream::duration() const {
  8873. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8874. std::chrono::steady_clock::now() - start_time_)
  8875. .count();
  8876. }
  8877. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8878. read_timeout_sec_ = sec;
  8879. read_timeout_usec_ = usec;
  8880. }
  8881. // Buffer stream implementation
  8882. inline bool BufferStream::is_readable() const { return true; }
  8883. inline bool BufferStream::wait_readable() const { return true; }
  8884. inline bool BufferStream::wait_writable() const { return true; }
  8885. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8886. #if defined(_MSC_VER) && _MSC_VER < 1910
  8887. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8888. #else
  8889. auto len_read = buffer.copy(ptr, size, position);
  8890. #endif
  8891. position += static_cast<size_t>(len_read);
  8892. return static_cast<ssize_t>(len_read);
  8893. }
  8894. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8895. buffer.append(ptr, size);
  8896. return static_cast<ssize_t>(size);
  8897. }
  8898. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8899. int & /*port*/) const {}
  8900. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8901. int & /*port*/) const {}
  8902. inline socket_t BufferStream::socket() const { return 0; }
  8903. inline time_t BufferStream::duration() const { return 0; }
  8904. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8905. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8906. : MatcherBase(pattern) {
  8907. constexpr const char marker[] = "/:";
  8908. // One past the last ending position of a path param substring
  8909. std::size_t last_param_end = 0;
  8910. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8911. // Needed to ensure that parameter names are unique during matcher
  8912. // construction
  8913. // If exceptions are disabled, only last duplicate path
  8914. // parameter will be set
  8915. std::unordered_set<std::string> param_name_set;
  8916. #endif
  8917. while (true) {
  8918. const auto marker_pos = pattern.find(
  8919. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8920. if (marker_pos == std::string::npos) { break; }
  8921. static_fragments_.push_back(
  8922. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8923. const auto param_name_start = marker_pos + str_len(marker);
  8924. auto sep_pos = pattern.find(separator, param_name_start);
  8925. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8926. auto param_name =
  8927. pattern.substr(param_name_start, sep_pos - param_name_start);
  8928. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8929. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8930. std::string msg = "Encountered path parameter '" + param_name +
  8931. "' multiple times in route pattern '" + pattern + "'.";
  8932. throw std::invalid_argument(msg);
  8933. }
  8934. #endif
  8935. param_names_.push_back(std::move(param_name));
  8936. last_param_end = sep_pos + 1;
  8937. }
  8938. if (last_param_end < pattern.length()) {
  8939. static_fragments_.push_back(pattern.substr(last_param_end));
  8940. }
  8941. }
  8942. inline bool PathParamsMatcher::match(Request &request) const {
  8943. request.matches = std::smatch();
  8944. request.path_params.clear();
  8945. request.path_params.reserve(param_names_.size());
  8946. // One past the position at which the path matched the pattern last time
  8947. std::size_t starting_pos = 0;
  8948. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8949. const auto &fragment = static_fragments_[i];
  8950. if (starting_pos + fragment.length() > request.path.length()) {
  8951. return false;
  8952. }
  8953. // Avoid unnecessary allocation by using strncmp instead of substr +
  8954. // comparison
  8955. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  8956. fragment.length()) != 0) {
  8957. return false;
  8958. }
  8959. starting_pos += fragment.length();
  8960. // Should only happen when we have a static fragment after a param
  8961. // Example: '/users/:id/subscriptions'
  8962. // The 'subscriptions' fragment here does not have a corresponding param
  8963. if (i >= param_names_.size()) { continue; }
  8964. auto sep_pos = request.path.find(separator, starting_pos);
  8965. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  8966. const auto &param_name = param_names_[i];
  8967. request.path_params.emplace(
  8968. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  8969. // Mark everything up to '/' as matched
  8970. starting_pos = sep_pos + 1;
  8971. }
  8972. // Returns false if the path is longer than the pattern
  8973. return starting_pos >= request.path.length();
  8974. }
  8975. inline bool RegexMatcher::match(Request &request) const {
  8976. request.path_params.clear();
  8977. return std::regex_match(request.path, request.matches, regex_);
  8978. }
  8979. // Enclose IPv6 address in brackets if needed
  8980. inline std::string prepare_host_string(const std::string &host) {
  8981. // Enclose IPv6 address in brackets (but not if already enclosed)
  8982. if (host.find(':') == std::string::npos ||
  8983. (!host.empty() && host[0] == '[')) {
  8984. // IPv4, hostname, or already bracketed IPv6
  8985. return host;
  8986. } else {
  8987. // IPv6 address without brackets
  8988. return "[" + host + "]";
  8989. }
  8990. }
  8991. inline std::string make_host_and_port_string(const std::string &host, int port,
  8992. bool is_ssl) {
  8993. auto result = prepare_host_string(host);
  8994. // Append port if not default
  8995. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  8996. ; // do nothing
  8997. } else {
  8998. result += ":" + std::to_string(port);
  8999. }
  9000. return result;
  9001. }
  9002. // Create "host:port" string always including port number (for CONNECT method)
  9003. inline std::string
  9004. make_host_and_port_string_always_port(const std::string &host, int port) {
  9005. return prepare_host_string(host) + ":" + std::to_string(port);
  9006. }
  9007. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  9008. NormalizedTarget normalize_target(const std::string &host);
  9009. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  9010. bool host_matches_no_proxy(const NormalizedTarget &target,
  9011. const std::vector<NoProxyEntry> &entries);
  9012. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  9013. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  9014. if (prefix_bits == 0) { return true; }
  9015. int full_bytes = prefix_bits / 8;
  9016. int rem_bits = prefix_bits % 8;
  9017. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9018. static_cast<size_t>(full_bytes)) != 0) {
  9019. return false;
  9020. }
  9021. if (rem_bits == 0) { return true; }
  9022. auto i = static_cast<size_t>(full_bytes);
  9023. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9024. return (ip[i] & mask) == (net[i] & mask);
  9025. }
  9026. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9027. if (token.empty()) { return false; }
  9028. if (token == "*") {
  9029. out.kind = NoProxyKind::Wildcard;
  9030. return true;
  9031. }
  9032. auto slash = token.find('/');
  9033. std::string addr_part =
  9034. (slash == std::string::npos) ? token : token.substr(0, slash);
  9035. std::string prefix_part =
  9036. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9037. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9038. // don't silently treat it as a /32 (or /128).
  9039. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9040. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9041. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9042. // when brackets are present.
  9043. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9044. addr_part.back() == ']';
  9045. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9046. if (!bracketed) {
  9047. struct in_addr v4;
  9048. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9049. int prefix = 32;
  9050. if (!prefix_part.empty()) {
  9051. auto r = from_chars(prefix_part.data(),
  9052. prefix_part.data() + prefix_part.size(), prefix);
  9053. if (r.ec != std::errc{} ||
  9054. r.ptr != prefix_part.data() + prefix_part.size()) {
  9055. return false;
  9056. }
  9057. if (prefix < 0 || prefix > 32) { return false; }
  9058. }
  9059. out.kind = NoProxyKind::IPv4Cidr;
  9060. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9061. out.prefix_bits = prefix;
  9062. return true;
  9063. }
  9064. }
  9065. struct in6_addr v6;
  9066. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9067. int prefix = 128;
  9068. if (!prefix_part.empty()) {
  9069. auto r = from_chars(prefix_part.data(),
  9070. prefix_part.data() + prefix_part.size(), prefix);
  9071. if (r.ec != std::errc{} ||
  9072. r.ptr != prefix_part.data() + prefix_part.size()) {
  9073. return false;
  9074. }
  9075. if (prefix < 0 || prefix > 128) { return false; }
  9076. }
  9077. out.kind = NoProxyKind::IPv6Cidr;
  9078. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9079. out.prefix_bits = prefix;
  9080. return true;
  9081. }
  9082. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9083. // the entry is malformed — don't fall through to the hostname branch.
  9084. if (bracketed) { return false; }
  9085. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9086. if (slash != std::string::npos) { return false; }
  9087. // Port-specific entries (host:port) are not supported.
  9088. if (token.find(':') != std::string::npos) { return false; }
  9089. std::string hostname = case_ignore::to_lower(token);
  9090. while (!hostname.empty() && hostname.front() == '.') {
  9091. hostname.erase(hostname.begin());
  9092. }
  9093. while (!hostname.empty() && hostname.back() == '.') {
  9094. hostname.pop_back();
  9095. }
  9096. if (hostname.empty()) { return false; }
  9097. out.kind = NoProxyKind::HostnameSuffix;
  9098. out.hostname_pattern = std::move(hostname);
  9099. return true;
  9100. }
  9101. inline NormalizedTarget normalize_target(const std::string &host) {
  9102. NormalizedTarget t;
  9103. std::string h = host;
  9104. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9105. h = h.substr(1, h.size() - 2);
  9106. }
  9107. // Strip a single trailing dot so "example.com." canonicalizes to
  9108. // "example.com".
  9109. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9110. t.hostname = case_ignore::to_lower(h);
  9111. if (!t.hostname.empty()) {
  9112. struct in_addr v4;
  9113. struct in6_addr v6;
  9114. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9115. t.is_ipv4 = true;
  9116. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9117. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9118. t.is_ipv6 = true;
  9119. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9120. }
  9121. }
  9122. return t;
  9123. }
  9124. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9125. const std::vector<NoProxyEntry> &entries) {
  9126. if (target.hostname.empty()) { return false; }
  9127. for (const auto &e : entries) {
  9128. switch (e.kind) {
  9129. case NoProxyKind::Wildcard: return true;
  9130. case NoProxyKind::IPv4Cidr:
  9131. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9132. return true;
  9133. }
  9134. break;
  9135. case NoProxyKind::IPv6Cidr:
  9136. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9137. return true;
  9138. }
  9139. break;
  9140. case NoProxyKind::HostnameSuffix:
  9141. if (target.is_ipv4 || target.is_ipv6) { break; }
  9142. if (target.hostname == e.hostname_pattern) { return true; }
  9143. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9144. // an entry of "example.com".
  9145. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9146. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9147. if (target.hostname[offset - 1] == '.' &&
  9148. target.hostname.compare(offset, e.hostname_pattern.size(),
  9149. e.hostname_pattern) == 0) {
  9150. return true;
  9151. }
  9152. }
  9153. break;
  9154. }
  9155. }
  9156. return false;
  9157. }
  9158. template <typename T>
  9159. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9160. T header_writer, Error &error) {
  9161. for (const auto &h : headers) {
  9162. if (!detail::fields::is_field_name(h.first) ||
  9163. !detail::fields::is_field_value(h.second)) {
  9164. error = Error::InvalidHeaders;
  9165. return false;
  9166. }
  9167. }
  9168. if (header_writer(strm, headers) <= 0) {
  9169. error = Error::Write;
  9170. return false;
  9171. }
  9172. return true;
  9173. }
  9174. } // namespace detail
  9175. /*
  9176. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9177. */
  9178. #ifdef CPPHTTPLIB_SSL_ENABLED
  9179. namespace detail {
  9180. // SSL socket stream implementation
  9181. inline SSLSocketStream::SSLSocketStream(
  9182. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9183. time_t read_timeout_usec, time_t write_timeout_sec,
  9184. time_t write_timeout_usec, time_t max_timeout_msec,
  9185. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9186. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9187. read_timeout_usec_(read_timeout_usec),
  9188. write_timeout_sec_(write_timeout_sec),
  9189. write_timeout_usec_(write_timeout_usec),
  9190. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9191. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9192. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9193. // Note: create_session() also clears this, but SSLClient currently
  9194. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9195. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9196. // SSL session was created.
  9197. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9198. #endif
  9199. }
  9200. inline SSLSocketStream::~SSLSocketStream() = default;
  9201. inline bool SSLSocketStream::is_readable() const {
  9202. return tls::pending(session_) > 0;
  9203. }
  9204. inline bool SSLSocketStream::wait_readable() const {
  9205. if (max_timeout_msec_ <= 0) {
  9206. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9207. }
  9208. time_t read_timeout_sec;
  9209. time_t read_timeout_usec;
  9210. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9211. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9212. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9213. }
  9214. inline bool SSLSocketStream::wait_writable() const {
  9215. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9216. !tls::is_peer_closed(session_, sock_);
  9217. }
  9218. inline bool SSLSocketStream::is_peer_alive() const {
  9219. return !tls::is_peer_closed(session_, sock_);
  9220. }
  9221. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9222. if (tls::pending(session_) > 0) {
  9223. tls::TlsError err;
  9224. auto ret = tls::read(session_, ptr, size, err);
  9225. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9226. error_ = Error::ConnectionClosed;
  9227. }
  9228. return ret;
  9229. } else if (wait_readable()) {
  9230. tls::TlsError err;
  9231. auto ret = tls::read(session_, ptr, size, err);
  9232. if (ret < 0) {
  9233. auto n = 1000;
  9234. #ifdef _WIN32
  9235. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9236. (err.code == tls::ErrorCode::SyscallError &&
  9237. WSAGetLastError() == WSAETIMEDOUT))) {
  9238. #else
  9239. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9240. #endif
  9241. if (tls::pending(session_) > 0) {
  9242. return tls::read(session_, ptr, size, err);
  9243. } else if (wait_readable()) {
  9244. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9245. ret = tls::read(session_, ptr, size, err);
  9246. if (ret >= 0) { return ret; }
  9247. } else {
  9248. break;
  9249. }
  9250. }
  9251. assert(ret < 0);
  9252. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9253. error_ = Error::ConnectionClosed;
  9254. }
  9255. return ret;
  9256. } else {
  9257. error_ = Error::Timeout;
  9258. return -1;
  9259. }
  9260. }
  9261. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9262. if (wait_writable()) {
  9263. auto handle_size =
  9264. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9265. tls::TlsError err;
  9266. auto ret = tls::write(session_, ptr, handle_size, err);
  9267. if (ret < 0) {
  9268. auto n = 1000;
  9269. #ifdef _WIN32
  9270. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9271. (err.code == tls::ErrorCode::SyscallError &&
  9272. WSAGetLastError() == WSAETIMEDOUT))) {
  9273. #else
  9274. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9275. #endif
  9276. if (wait_writable()) {
  9277. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9278. ret = tls::write(session_, ptr, handle_size, err);
  9279. if (ret >= 0) { return ret; }
  9280. } else {
  9281. break;
  9282. }
  9283. }
  9284. assert(ret < 0);
  9285. }
  9286. return ret;
  9287. }
  9288. return -1;
  9289. }
  9290. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9291. int &port) const {
  9292. detail::get_remote_ip_and_port(sock_, ip, port);
  9293. }
  9294. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9295. int &port) const {
  9296. detail::get_local_ip_and_port(sock_, ip, port);
  9297. }
  9298. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9299. inline time_t SSLSocketStream::duration() const {
  9300. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9301. std::chrono::steady_clock::now() - start_time_)
  9302. .count();
  9303. }
  9304. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9305. read_timeout_sec_ = sec;
  9306. read_timeout_usec_ = usec;
  9307. }
  9308. } // namespace detail
  9309. #endif // CPPHTTPLIB_SSL_ENABLED
  9310. /*
  9311. * Group 4: Server implementation
  9312. */
  9313. // HTTP server implementation
  9314. inline Server::Server()
  9315. : new_task_queue([] {
  9316. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9317. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9318. }) {
  9319. #ifndef _WIN32
  9320. signal(SIGPIPE, SIG_IGN);
  9321. #endif
  9322. }
  9323. inline Server::~Server() = default;
  9324. inline std::unique_ptr<detail::MatcherBase>
  9325. Server::make_matcher(const std::string &pattern) {
  9326. if (pattern.find("/:") != std::string::npos) {
  9327. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9328. } else {
  9329. return detail::make_unique<detail::RegexMatcher>(pattern);
  9330. }
  9331. }
  9332. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9333. return add_handler(get_handlers_, pattern, std::move(handler));
  9334. }
  9335. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9336. return add_handler(post_handlers_, pattern, std::move(handler));
  9337. }
  9338. inline Server &Server::Post(const std::string &pattern,
  9339. HandlerWithContentReader handler) {
  9340. return add_handler(post_handlers_for_content_reader_, pattern,
  9341. std::move(handler));
  9342. }
  9343. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9344. return add_handler(put_handlers_, pattern, std::move(handler));
  9345. }
  9346. inline Server &Server::Put(const std::string &pattern,
  9347. HandlerWithContentReader handler) {
  9348. return add_handler(put_handlers_for_content_reader_, pattern,
  9349. std::move(handler));
  9350. }
  9351. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9352. return add_handler(patch_handlers_, pattern, std::move(handler));
  9353. }
  9354. inline Server &Server::Patch(const std::string &pattern,
  9355. HandlerWithContentReader handler) {
  9356. return add_handler(patch_handlers_for_content_reader_, pattern,
  9357. std::move(handler));
  9358. }
  9359. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9360. return add_handler(delete_handlers_, pattern, std::move(handler));
  9361. }
  9362. inline Server &Server::Delete(const std::string &pattern,
  9363. HandlerWithContentReader handler) {
  9364. return add_handler(delete_handlers_for_content_reader_, pattern,
  9365. std::move(handler));
  9366. }
  9367. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9368. return add_handler(options_handlers_, pattern, std::move(handler));
  9369. }
  9370. inline Server &Server::WebSocket(const std::string &pattern,
  9371. WebSocketHandler handler) {
  9372. websocket_handlers_.push_back(
  9373. {make_matcher(pattern), std::move(handler), nullptr});
  9374. return *this;
  9375. }
  9376. inline Server &Server::WebSocket(const std::string &pattern,
  9377. WebSocketHandler handler,
  9378. SubProtocolSelector sub_protocol_selector) {
  9379. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9380. std::move(sub_protocol_selector)});
  9381. return *this;
  9382. }
  9383. inline bool Server::set_base_dir(const std::string &dir,
  9384. const std::string &mount_point) {
  9385. return set_mount_point(mount_point, dir);
  9386. }
  9387. inline bool Server::set_mount_point(const std::string &mount_point,
  9388. const std::string &dir, Headers headers) {
  9389. detail::FileStat stat(dir);
  9390. if (stat.is_dir()) {
  9391. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9392. if (!mnt.empty() && mnt[0] == '/') {
  9393. std::string resolved_base;
  9394. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9395. #if defined(_WIN32)
  9396. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9397. resolved_base += '\\';
  9398. }
  9399. #else
  9400. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9401. #endif
  9402. }
  9403. base_dirs_.push_back(
  9404. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9405. return true;
  9406. }
  9407. }
  9408. return false;
  9409. }
  9410. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9411. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9412. if (it->mount_point == mount_point) {
  9413. base_dirs_.erase(it);
  9414. return true;
  9415. }
  9416. }
  9417. return false;
  9418. }
  9419. inline Server &
  9420. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9421. const std::string &mime) {
  9422. file_extension_and_mimetype_map_[ext] = mime;
  9423. return *this;
  9424. }
  9425. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9426. default_file_mimetype_ = mime;
  9427. return *this;
  9428. }
  9429. inline Server &Server::set_file_request_handler(Handler handler) {
  9430. file_request_handler_ = std::move(handler);
  9431. return *this;
  9432. }
  9433. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9434. std::true_type) {
  9435. error_handler_ = std::move(handler);
  9436. return *this;
  9437. }
  9438. inline Server &Server::set_error_handler_core(Handler handler,
  9439. std::false_type) {
  9440. error_handler_ = [handler](const Request &req, Response &res) {
  9441. handler(req, res);
  9442. return HandlerResponse::Handled;
  9443. };
  9444. return *this;
  9445. }
  9446. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9447. exception_handler_ = std::move(handler);
  9448. return *this;
  9449. }
  9450. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9451. pre_routing_handler_ = std::move(handler);
  9452. return *this;
  9453. }
  9454. inline Server &Server::set_post_routing_handler(Handler handler) {
  9455. post_routing_handler_ = std::move(handler);
  9456. return *this;
  9457. }
  9458. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9459. pre_request_handler_ = std::move(handler);
  9460. return *this;
  9461. }
  9462. inline Server &Server::set_logger(Logger logger) {
  9463. logger_ = std::move(logger);
  9464. return *this;
  9465. }
  9466. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9467. error_logger_ = std::move(error_logger);
  9468. return *this;
  9469. }
  9470. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9471. pre_compression_logger_ = std::move(logger);
  9472. return *this;
  9473. }
  9474. inline Server &
  9475. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9476. expect_100_continue_handler_ = std::move(handler);
  9477. return *this;
  9478. }
  9479. inline Server &Server::set_start_handler(StartHandler handler) {
  9480. start_handler_ = std::move(handler);
  9481. return *this;
  9482. }
  9483. inline Server &Server::set_address_family(int family) {
  9484. address_family_ = family;
  9485. return *this;
  9486. }
  9487. inline Server &Server::set_tcp_nodelay(bool on) {
  9488. tcp_nodelay_ = on;
  9489. return *this;
  9490. }
  9491. inline Server &Server::set_ipv6_v6only(bool on) {
  9492. ipv6_v6only_ = on;
  9493. return *this;
  9494. }
  9495. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9496. socket_options_ = std::move(socket_options);
  9497. return *this;
  9498. }
  9499. inline Server &Server::set_default_headers(Headers headers) {
  9500. default_headers_ = std::move(headers);
  9501. return *this;
  9502. }
  9503. inline Server &Server::set_header_writer(
  9504. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9505. header_writer_ = writer;
  9506. return *this;
  9507. }
  9508. inline Server &
  9509. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9510. trusted_proxies_ = proxies;
  9511. return *this;
  9512. }
  9513. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9514. keep_alive_max_count_ = count;
  9515. return *this;
  9516. }
  9517. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9518. keep_alive_timeout_sec_ = sec;
  9519. return *this;
  9520. }
  9521. template <class Rep, class Period>
  9522. inline Server &Server::set_keep_alive_timeout(
  9523. const std::chrono::duration<Rep, Period> &duration) {
  9524. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9525. set_keep_alive_timeout(sec);
  9526. });
  9527. return *this;
  9528. }
  9529. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9530. read_timeout_sec_ = sec;
  9531. read_timeout_usec_ = usec;
  9532. return *this;
  9533. }
  9534. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9535. write_timeout_sec_ = sec;
  9536. write_timeout_usec_ = usec;
  9537. return *this;
  9538. }
  9539. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9540. idle_interval_sec_ = sec;
  9541. idle_interval_usec_ = usec;
  9542. return *this;
  9543. }
  9544. inline Server &Server::set_payload_max_length(size_t length) {
  9545. payload_max_length_ = length;
  9546. return *this;
  9547. }
  9548. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9549. websocket_max_missed_pongs_ = count;
  9550. return *this;
  9551. }
  9552. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9553. websocket_ping_interval_sec_ = sec;
  9554. return *this;
  9555. }
  9556. template <class Rep, class Period>
  9557. inline Server &Server::set_websocket_ping_interval(
  9558. const std::chrono::duration<Rep, Period> &duration) {
  9559. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9560. set_websocket_ping_interval(sec);
  9561. });
  9562. return *this;
  9563. }
  9564. inline bool Server::bind_to_port(const std::string &host, int port,
  9565. int socket_flags) {
  9566. auto ret = bind_internal(host, port, socket_flags);
  9567. if (ret == -1) { is_decommissioned = true; }
  9568. return ret >= 0;
  9569. }
  9570. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9571. auto ret = bind_internal(host, 0, socket_flags);
  9572. if (ret == -1) { is_decommissioned = true; }
  9573. return ret;
  9574. }
  9575. inline bool Server::listen_after_bind() { return listen_internal(); }
  9576. inline bool Server::listen(const std::string &host, int port,
  9577. int socket_flags) {
  9578. return bind_to_port(host, port, socket_flags) && listen_internal();
  9579. }
  9580. inline bool Server::is_running() const { return is_running_; }
  9581. inline void Server::wait_until_ready() const {
  9582. while (!is_running_ && !is_decommissioned) {
  9583. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9584. }
  9585. }
  9586. inline void Server::stop() noexcept {
  9587. if (is_running_) {
  9588. assert(svr_sock_ != INVALID_SOCKET);
  9589. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9590. detail::shutdown_socket(sock);
  9591. detail::close_socket(sock);
  9592. }
  9593. is_decommissioned = false;
  9594. }
  9595. inline void Server::decommission() { is_decommissioned = true; }
  9596. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9597. auto len = strlen(s);
  9598. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9599. len -= 2;
  9600. {
  9601. size_t count = 0;
  9602. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9603. switch (count) {
  9604. case 0: req.method = std::string(b, e); break;
  9605. case 1: req.target = std::string(b, e); break;
  9606. case 2: req.version = std::string(b, e); break;
  9607. default: break;
  9608. }
  9609. count++;
  9610. });
  9611. if (count != 3) { return false; }
  9612. }
  9613. thread_local const std::set<std::string> methods{
  9614. "GET", "HEAD", "POST", "PUT", "DELETE",
  9615. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9616. if (methods.find(req.method) == methods.end()) {
  9617. output_error_log(Error::InvalidHTTPMethod, &req);
  9618. return false;
  9619. }
  9620. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9621. output_error_log(Error::InvalidHTTPVersion, &req);
  9622. return false;
  9623. }
  9624. {
  9625. // Skip URL fragment
  9626. for (size_t i = 0; i < req.target.size(); i++) {
  9627. if (req.target[i] == '#') {
  9628. req.target.erase(i);
  9629. break;
  9630. }
  9631. }
  9632. detail::divide(req.target, '?',
  9633. [&](const char *lhs_data, std::size_t lhs_size,
  9634. const char *rhs_data, std::size_t rhs_size) {
  9635. req.path =
  9636. decode_path_component(std::string(lhs_data, lhs_size));
  9637. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9638. });
  9639. }
  9640. return true;
  9641. }
  9642. inline bool Server::write_response(Stream &strm, bool close_connection,
  9643. Request &req, Response &res) {
  9644. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9645. // incorrectly to the error content.
  9646. req.ranges.clear();
  9647. return write_response_core(strm, close_connection, req, res, false);
  9648. }
  9649. inline bool Server::write_response_with_content(Stream &strm,
  9650. bool close_connection,
  9651. const Request &req,
  9652. Response &res) {
  9653. return write_response_core(strm, close_connection, req, res, true);
  9654. }
  9655. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9656. const Request &req, Response &res,
  9657. bool need_apply_ranges) {
  9658. assert(res.status != -1);
  9659. if (400 <= res.status && error_handler_ &&
  9660. error_handler_(req, res) == HandlerResponse::Handled) {
  9661. need_apply_ranges = true;
  9662. }
  9663. std::string content_type;
  9664. std::string boundary;
  9665. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9666. // Prepare additional headers
  9667. if (close_connection || req.get_header_value("Connection") == "close" ||
  9668. 400 <= res.status) { // Don't leave connections open after errors
  9669. res.set_header("Connection", "close");
  9670. } else {
  9671. std::string s = "timeout=";
  9672. s += std::to_string(keep_alive_timeout_sec_);
  9673. s += ", max=";
  9674. s += std::to_string(keep_alive_max_count_);
  9675. res.set_header("Keep-Alive", s);
  9676. }
  9677. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9678. !res.has_header("Content-Type")) {
  9679. res.set_header("Content-Type", "text/plain");
  9680. }
  9681. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9682. !res.has_header("Content-Length")) {
  9683. res.set_header("Content-Length", "0");
  9684. }
  9685. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9686. res.set_header("Accept-Ranges", "bytes");
  9687. }
  9688. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9689. // Response line and headers
  9690. detail::BufferStream bstrm;
  9691. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9692. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9693. // Combine small body with headers to reduce write syscalls
  9694. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9695. bstrm.write(res.body.data(), res.body.size());
  9696. }
  9697. // Log before writing to avoid race condition with client-side code that
  9698. // accesses logger-captured data immediately after receiving the response.
  9699. output_log(req, res);
  9700. // Flush buffer
  9701. auto &data = bstrm.get_buffer();
  9702. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9703. // Streaming body
  9704. auto ret = true;
  9705. if (req.method != "HEAD" && res.content_provider_) {
  9706. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9707. res.content_provider_success_ = true;
  9708. } else {
  9709. ret = false;
  9710. }
  9711. }
  9712. return ret;
  9713. }
  9714. inline bool
  9715. Server::write_content_with_provider(Stream &strm, const Request &req,
  9716. Response &res, const std::string &boundary,
  9717. const std::string &content_type) {
  9718. auto is_shutting_down = [this]() {
  9719. return this->svr_sock_ == INVALID_SOCKET;
  9720. };
  9721. if (res.content_length_ > 0) {
  9722. if (req.ranges.empty()) {
  9723. return detail::write_content(strm, res.content_provider_, 0,
  9724. res.content_length_, is_shutting_down);
  9725. } else if (req.ranges.size() == 1) {
  9726. auto offset_and_length = detail::get_range_offset_and_length(
  9727. req.ranges[0], res.content_length_);
  9728. return detail::write_content(strm, res.content_provider_,
  9729. offset_and_length.first,
  9730. offset_and_length.second, is_shutting_down);
  9731. } else {
  9732. return detail::write_multipart_ranges_data(
  9733. strm, req, res, boundary, content_type, res.content_length_,
  9734. is_shutting_down);
  9735. }
  9736. } else {
  9737. if (res.is_chunked_content_provider_) {
  9738. auto type = detail::encoding_type(req, res);
  9739. auto compressor = detail::make_compressor(type);
  9740. if (!compressor) {
  9741. compressor = detail::make_unique<detail::nocompressor>();
  9742. }
  9743. return detail::write_content_chunked(strm, res.content_provider_,
  9744. is_shutting_down, *compressor);
  9745. } else {
  9746. return detail::write_content_without_length(strm, res.content_provider_,
  9747. is_shutting_down);
  9748. }
  9749. }
  9750. }
  9751. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9752. FormFields::iterator cur_field;
  9753. FormFiles::iterator cur_file;
  9754. auto is_text_field = false;
  9755. size_t count = 0;
  9756. if (read_content_core(
  9757. strm, req, res,
  9758. // Regular
  9759. [&](const char *buf, size_t n) {
  9760. // Prevent arithmetic overflow when checking sizes.
  9761. // Avoid computing (req.body.size() + n) directly because
  9762. // adding two unsigned `size_t` values can wrap around and
  9763. // produce a small result instead of indicating overflow.
  9764. // Instead, check using subtraction: ensure `n` does not
  9765. // exceed the remaining capacity `max_size() - size()`.
  9766. if (req.body.size() >= req.body.max_size() ||
  9767. n > req.body.max_size() - req.body.size()) {
  9768. return false;
  9769. }
  9770. // Limit decompressed body size to payload_max_length_ to protect
  9771. // against "zip bomb" attacks where a small compressed payload
  9772. // decompresses to a massive size.
  9773. if (payload_max_length_ > 0 &&
  9774. (req.body.size() >= payload_max_length_ ||
  9775. n > payload_max_length_ - req.body.size())) {
  9776. return false;
  9777. }
  9778. req.body.append(buf, n);
  9779. return true;
  9780. },
  9781. // Multipart FormData
  9782. [&](const FormData &file) {
  9783. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9784. output_error_log(Error::TooManyFormDataFiles, &req);
  9785. return false;
  9786. }
  9787. if (file.filename.empty()) {
  9788. cur_field = req.form.fields.emplace(
  9789. file.name, FormField{file.name, file.content, file.headers});
  9790. is_text_field = true;
  9791. } else {
  9792. cur_file = req.form.files.emplace(file.name, file);
  9793. is_text_field = false;
  9794. }
  9795. return true;
  9796. },
  9797. [&](const char *buf, size_t n) {
  9798. if (is_text_field) {
  9799. auto &content = cur_field->second.content;
  9800. if (content.size() + n > content.max_size()) { return false; }
  9801. content.append(buf, n);
  9802. } else {
  9803. auto &content = cur_file->second.content;
  9804. if (content.size() + n > content.max_size()) { return false; }
  9805. content.append(buf, n);
  9806. }
  9807. return true;
  9808. })) {
  9809. const auto &content_type = req.get_header_value("Content-Type");
  9810. if (detail::extract_media_type(content_type) ==
  9811. "application/x-www-form-urlencoded") {
  9812. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9813. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9814. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9815. return false;
  9816. }
  9817. detail::parse_query_text(req.body, req.params);
  9818. }
  9819. return true;
  9820. }
  9821. return false;
  9822. }
  9823. inline bool Server::read_content_with_content_receiver(
  9824. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9825. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9826. return read_content_core(strm, req, res, std::move(receiver),
  9827. std::move(multipart_header),
  9828. std::move(multipart_receiver));
  9829. }
  9830. inline bool Server::read_content_core(
  9831. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9832. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9833. detail::FormDataParser multipart_form_data_parser;
  9834. ContentReceiverWithProgress out;
  9835. if (req.is_multipart_form_data()) {
  9836. const auto &content_type = req.get_header_value("Content-Type");
  9837. std::string boundary;
  9838. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9839. res.status = StatusCode::BadRequest_400;
  9840. output_error_log(Error::MultipartParsing, &req);
  9841. return false;
  9842. }
  9843. multipart_form_data_parser.set_boundary(std::move(boundary));
  9844. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9845. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9846. multipart_receiver);
  9847. };
  9848. } else {
  9849. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9850. size_t /*len*/) { return receiver(buf, n); };
  9851. }
  9852. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  9853. // For non-SSL builds we still scan non-persistent connections for stray
  9854. // body bytes so the payload limit is enforced (413). On keep-alive,
  9855. // pending bytes may be the next request (issue #2450), so skip.
  9856. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9857. if (!req.has_header("Content-Length") &&
  9858. !detail::is_chunked_transfer_encoding(req.headers)) {
  9859. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  9860. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9861. auto has_data = strm.is_readable();
  9862. if (!has_data) {
  9863. auto s = strm.socket();
  9864. if (s != INVALID_SOCKET) {
  9865. has_data = detail::select_read(s, 0, 0) > 0;
  9866. }
  9867. }
  9868. if (has_data) {
  9869. auto result =
  9870. detail::read_content_without_length(strm, payload_max_length_, out);
  9871. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9872. res.status = StatusCode::PayloadTooLarge_413;
  9873. return false;
  9874. } else if (result != detail::ReadContentResult::Success) {
  9875. return false;
  9876. }
  9877. return true;
  9878. }
  9879. }
  9880. return true;
  9881. }
  9882. #else
  9883. if (!req.has_header("Content-Length") &&
  9884. !detail::is_chunked_transfer_encoding(req.headers)) {
  9885. return true;
  9886. }
  9887. #endif
  9888. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9889. out, true)) {
  9890. return false;
  9891. }
  9892. req.body_consumed_ = true;
  9893. if (req.is_multipart_form_data()) {
  9894. if (!multipart_form_data_parser.is_valid()) {
  9895. res.status = StatusCode::BadRequest_400;
  9896. output_error_log(Error::MultipartParsing, &req);
  9897. return false;
  9898. }
  9899. }
  9900. return true;
  9901. }
  9902. inline bool Server::handle_file_request(Request &req, Response &res) {
  9903. for (const auto &entry : base_dirs_) {
  9904. // Prefix match
  9905. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9906. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9907. if (detail::is_valid_path(sub_path)) {
  9908. auto path = entry.base_dir + sub_path;
  9909. if (path.back() == '/') { path += "index.html"; }
  9910. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9911. // but symlinks/junctions can still escape the base directory.
  9912. if (!entry.resolved_base_dir.empty()) {
  9913. std::string resolved_path;
  9914. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9915. !detail::is_path_within_base(resolved_path,
  9916. entry.resolved_base_dir)) {
  9917. res.status = StatusCode::Forbidden_403;
  9918. return true;
  9919. }
  9920. }
  9921. detail::FileStat stat(path);
  9922. if (stat.is_dir()) {
  9923. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9924. return true;
  9925. }
  9926. if (stat.is_file()) {
  9927. for (const auto &kv : entry.headers) {
  9928. res.set_header(kv.first, kv.second);
  9929. }
  9930. auto etag = detail::compute_etag(stat);
  9931. if (!etag.empty()) { res.set_header("ETag", etag); }
  9932. auto mtime = stat.mtime();
  9933. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9934. if (!last_modified.empty()) {
  9935. res.set_header("Last-Modified", last_modified);
  9936. }
  9937. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9938. check_if_range(req, etag, mtime);
  9939. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9940. if (!mm->is_open()) {
  9941. output_error_log(Error::OpenFile, &req);
  9942. return false;
  9943. }
  9944. res.set_content_provider(
  9945. mm->size(),
  9946. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9947. default_file_mimetype_),
  9948. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9949. sink.write(mm->data() + offset, length);
  9950. return true;
  9951. });
  9952. if (req.method != "HEAD" && file_request_handler_) {
  9953. file_request_handler_(req, res);
  9954. }
  9955. return true;
  9956. } else {
  9957. output_error_log(Error::OpenFile, &req);
  9958. }
  9959. }
  9960. }
  9961. }
  9962. return false;
  9963. }
  9964. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  9965. const std::string &etag,
  9966. time_t mtime) const {
  9967. // Handle conditional GET:
  9968. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  9969. // 2. If-Modified-Since is checked only when If-None-Match is absent
  9970. if (req.has_header("If-None-Match")) {
  9971. if (!etag.empty()) {
  9972. auto val = req.get_header_value("If-None-Match");
  9973. // NOTE: We use exact string matching here. This works correctly
  9974. // because our server always generates weak ETags (W/"..."), and
  9975. // clients typically send back the same ETag they received.
  9976. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  9977. // If-None-Match, where W/"x" and "x" would match, but this
  9978. // simplified implementation requires exact matches.
  9979. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  9980. [&](const char *b, const char *e) {
  9981. auto seg_len = static_cast<size_t>(e - b);
  9982. return (seg_len == 1 && *b == '*') ||
  9983. (seg_len == etag.size() &&
  9984. std::equal(b, e, etag.begin()));
  9985. });
  9986. if (ret) {
  9987. res.status = StatusCode::NotModified_304;
  9988. return true;
  9989. }
  9990. }
  9991. } else if (req.has_header("If-Modified-Since")) {
  9992. auto val = req.get_header_value("If-Modified-Since");
  9993. auto t = detail::parse_http_date(val);
  9994. if (t != static_cast<time_t>(-1) && mtime <= t) {
  9995. res.status = StatusCode::NotModified_304;
  9996. return true;
  9997. }
  9998. }
  9999. return false;
  10000. }
  10001. inline bool Server::check_if_range(Request &req, const std::string &etag,
  10002. time_t mtime) const {
  10003. // Handle If-Range for partial content requests (RFC 9110
  10004. // Section 13.1.5). If-Range is only evaluated when Range header is
  10005. // present. If the validator matches, serve partial content; otherwise
  10006. // serve full content.
  10007. if (!req.ranges.empty() && req.has_header("If-Range")) {
  10008. auto val = req.get_header_value("If-Range");
  10009. auto is_valid_range = [&]() {
  10010. if (detail::is_strong_etag(val)) {
  10011. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  10012. // comparison.
  10013. return (!etag.empty() && val == etag);
  10014. } else if (detail::is_weak_etag(val)) {
  10015. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  10016. return false;
  10017. } else {
  10018. // HTTP-date comparison
  10019. auto t = detail::parse_http_date(val);
  10020. return (t != static_cast<time_t>(-1) && mtime <= t);
  10021. }
  10022. };
  10023. if (!is_valid_range()) {
  10024. // Validator doesn't match: ignore Range and serve full content
  10025. req.ranges.clear();
  10026. return false;
  10027. }
  10028. }
  10029. return true;
  10030. }
  10031. inline socket_t
  10032. Server::create_server_socket(const std::string &host, int port,
  10033. int socket_flags,
  10034. SocketOptions socket_options) const {
  10035. return detail::create_socket(
  10036. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10037. ipv6_v6only_, std::move(socket_options),
  10038. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10039. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10040. output_error_log(Error::BindIPAddress, nullptr);
  10041. return false;
  10042. }
  10043. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10044. output_error_log(Error::Listen, nullptr);
  10045. return false;
  10046. }
  10047. return true;
  10048. });
  10049. }
  10050. inline int Server::bind_internal(const std::string &host, int port,
  10051. int socket_flags) {
  10052. if (is_decommissioned) { return -1; }
  10053. if (!is_valid()) { return -1; }
  10054. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10055. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10056. if (port == 0) {
  10057. struct sockaddr_storage addr;
  10058. socklen_t addr_len = sizeof(addr);
  10059. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10060. &addr_len) == -1) {
  10061. output_error_log(Error::GetSockName, nullptr);
  10062. return -1;
  10063. }
  10064. if (addr.ss_family == AF_INET) {
  10065. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10066. } else if (addr.ss_family == AF_INET6) {
  10067. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10068. } else {
  10069. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10070. return -1;
  10071. }
  10072. } else {
  10073. return port;
  10074. }
  10075. }
  10076. inline bool Server::listen_internal() {
  10077. if (is_decommissioned) { return false; }
  10078. auto ret = true;
  10079. is_running_ = true;
  10080. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10081. if (start_handler_) { start_handler_(); }
  10082. {
  10083. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10084. while (svr_sock_ != INVALID_SOCKET) {
  10085. #ifndef _WIN32
  10086. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10087. #endif
  10088. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10089. idle_interval_usec_);
  10090. if (val == 0) { // Timeout
  10091. task_queue->on_idle();
  10092. continue;
  10093. }
  10094. #ifndef _WIN32
  10095. }
  10096. #endif
  10097. #if defined _WIN32
  10098. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10099. // OVERLAPPED
  10100. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10101. #elif defined SOCK_CLOEXEC
  10102. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10103. #else
  10104. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10105. #endif
  10106. if (sock == INVALID_SOCKET) {
  10107. if (errno == EMFILE) {
  10108. // The per-process limit of open file descriptors has been reached.
  10109. // Try to accept new connections after a short sleep.
  10110. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10111. continue;
  10112. } else if (errno == EINTR || errno == EAGAIN) {
  10113. continue;
  10114. }
  10115. if (svr_sock_ != INVALID_SOCKET) {
  10116. detail::close_socket(svr_sock_);
  10117. ret = false;
  10118. output_error_log(Error::Connection, nullptr);
  10119. } else {
  10120. ; // The server socket was closed by user.
  10121. }
  10122. break;
  10123. }
  10124. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10125. read_timeout_sec_, read_timeout_usec_);
  10126. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10127. write_timeout_sec_, write_timeout_usec_);
  10128. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10129. if (!task_queue->enqueue(
  10130. [this, sock]() { process_and_close_socket(sock); })) {
  10131. output_error_log(Error::ResourceExhaustion, nullptr);
  10132. detail::shutdown_socket(sock);
  10133. detail::close_socket(sock);
  10134. }
  10135. }
  10136. task_queue->shutdown();
  10137. }
  10138. is_decommissioned = !ret;
  10139. return ret;
  10140. }
  10141. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10142. if (pre_routing_handler_ &&
  10143. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10144. return true;
  10145. }
  10146. // File handler
  10147. if ((req.method == "GET" || req.method == "HEAD") &&
  10148. handle_file_request(req, res)) {
  10149. return true;
  10150. }
  10151. if (detail::expect_content(req)) {
  10152. // Content reader handler
  10153. {
  10154. // Track whether the ContentReader was aborted due to the decompressed
  10155. // payload exceeding `payload_max_length_`.
  10156. // The user handler runs after the lambda returns, so we must restore the
  10157. // 413 status if the handler overwrites it.
  10158. bool content_reader_payload_too_large = false;
  10159. ContentReader reader(
  10160. [&](ContentReceiver receiver) {
  10161. auto result = read_content_with_content_receiver(
  10162. strm, req, res, std::move(receiver), nullptr, nullptr);
  10163. if (!result) {
  10164. output_error_log(Error::Read, &req);
  10165. if (res.status == StatusCode::PayloadTooLarge_413) {
  10166. content_reader_payload_too_large = true;
  10167. }
  10168. }
  10169. return result;
  10170. },
  10171. [&](FormDataHeader header, ContentReceiver receiver) {
  10172. auto result = read_content_with_content_receiver(
  10173. strm, req, res, nullptr, std::move(header),
  10174. std::move(receiver));
  10175. if (!result) {
  10176. output_error_log(Error::Read, &req);
  10177. if (res.status == StatusCode::PayloadTooLarge_413) {
  10178. content_reader_payload_too_large = true;
  10179. }
  10180. }
  10181. return result;
  10182. });
  10183. bool dispatched = false;
  10184. if (req.method == "POST") {
  10185. dispatched = dispatch_request_for_content_reader(
  10186. req, res, std::move(reader), post_handlers_for_content_reader_);
  10187. } else if (req.method == "PUT") {
  10188. dispatched = dispatch_request_for_content_reader(
  10189. req, res, std::move(reader), put_handlers_for_content_reader_);
  10190. } else if (req.method == "PATCH") {
  10191. dispatched = dispatch_request_for_content_reader(
  10192. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10193. } else if (req.method == "DELETE") {
  10194. dispatched = dispatch_request_for_content_reader(
  10195. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10196. }
  10197. if (dispatched) {
  10198. if (content_reader_payload_too_large) {
  10199. // Enforce the limit: override any status the handler may have set
  10200. // and return false so the error path sends a plain 413 response.
  10201. res.status = StatusCode::PayloadTooLarge_413;
  10202. res.body.clear();
  10203. res.content_length_ = 0;
  10204. res.content_provider_ = nullptr;
  10205. return false;
  10206. }
  10207. return true;
  10208. }
  10209. }
  10210. // NOTE: `req.body` is not read here. For a regular handler the body is
  10211. // read inside dispatch_request(), after the route has matched and the
  10212. // pre-request handler has approved the request, so that a rejected
  10213. // request (e.g. failed authentication) never forces us to buffer a
  10214. // potentially large body.
  10215. }
  10216. // Regular handler
  10217. if (req.method == "GET" || req.method == "HEAD") {
  10218. return dispatch_request(req, res, get_handlers_, strm);
  10219. } else if (req.method == "POST") {
  10220. return dispatch_request(req, res, post_handlers_, strm);
  10221. } else if (req.method == "PUT") {
  10222. return dispatch_request(req, res, put_handlers_, strm);
  10223. } else if (req.method == "DELETE") {
  10224. return dispatch_request(req, res, delete_handlers_, strm);
  10225. } else if (req.method == "OPTIONS") {
  10226. return dispatch_request(req, res, options_handlers_, strm);
  10227. } else if (req.method == "PATCH") {
  10228. return dispatch_request(req, res, patch_handlers_, strm);
  10229. }
  10230. res.status = StatusCode::BadRequest_400;
  10231. return false;
  10232. }
  10233. inline bool Server::dispatch_request(Request &req, Response &res,
  10234. const Handlers &handlers, Stream &strm) {
  10235. for (const auto &x : handlers) {
  10236. const auto &matcher = x.first;
  10237. const auto &handler = x.second;
  10238. if (matcher->match(req)) {
  10239. req.matched_route = matcher->pattern();
  10240. // Run the pre-request handler before reading the body so a rejected
  10241. // request (e.g. failed authentication) never forces us to buffer a
  10242. // potentially large body. `req.matched_route` is available here.
  10243. if (pre_request_handler_ &&
  10244. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10245. return true;
  10246. }
  10247. // The route matched and the request was approved; read the body now.
  10248. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10249. output_error_log(Error::Read, &req);
  10250. return false;
  10251. }
  10252. handler(req, res);
  10253. return true;
  10254. }
  10255. }
  10256. return false;
  10257. }
  10258. inline void Server::apply_ranges(const Request &req, Response &res,
  10259. std::string &content_type,
  10260. std::string &boundary) const {
  10261. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10262. auto it = res.headers.find("Content-Type");
  10263. if (it != res.headers.end()) {
  10264. content_type = it->second;
  10265. res.headers.erase(it);
  10266. }
  10267. boundary = detail::make_multipart_data_boundary();
  10268. res.set_header("Content-Type",
  10269. "multipart/byteranges; boundary=" + boundary);
  10270. }
  10271. auto type = detail::encoding_type(req, res);
  10272. if (res.body.empty()) {
  10273. if (res.content_length_ > 0) {
  10274. size_t length = 0;
  10275. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10276. length = res.content_length_;
  10277. } else if (req.ranges.size() == 1) {
  10278. auto offset_and_length = detail::get_range_offset_and_length(
  10279. req.ranges[0], res.content_length_);
  10280. length = offset_and_length.second;
  10281. auto content_range = detail::make_content_range_header_field(
  10282. offset_and_length, res.content_length_);
  10283. res.set_header("Content-Range", content_range);
  10284. } else {
  10285. length = detail::get_multipart_ranges_data_length(
  10286. req, boundary, content_type, res.content_length_);
  10287. }
  10288. res.set_header("Content-Length", std::to_string(length));
  10289. } else {
  10290. if (res.content_provider_) {
  10291. if (res.is_chunked_content_provider_) {
  10292. res.set_header("Transfer-Encoding", "chunked");
  10293. if (type != detail::EncodingType::None) {
  10294. res.set_header("Content-Encoding", detail::encoding_name(type));
  10295. res.set_header("Vary", "Accept-Encoding");
  10296. }
  10297. }
  10298. }
  10299. }
  10300. } else {
  10301. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10302. ;
  10303. } else if (req.ranges.size() == 1) {
  10304. auto offset_and_length =
  10305. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10306. auto offset = offset_and_length.first;
  10307. auto length = offset_and_length.second;
  10308. auto content_range = detail::make_content_range_header_field(
  10309. offset_and_length, res.body.size());
  10310. res.set_header("Content-Range", content_range);
  10311. assert(offset + length <= res.body.size());
  10312. res.body = res.body.substr(offset, length);
  10313. } else {
  10314. std::string data;
  10315. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10316. res.body.size(), data);
  10317. res.body.swap(data);
  10318. }
  10319. if (type != detail::EncodingType::None) {
  10320. output_pre_compression_log(req, res);
  10321. if (auto compressor = detail::make_compressor(type)) {
  10322. std::string compressed;
  10323. if (compressor->compress(res.body.data(), res.body.size(), true,
  10324. [&](const char *data, size_t data_len) {
  10325. compressed.append(data, data_len);
  10326. return true;
  10327. })) {
  10328. res.body.swap(compressed);
  10329. res.set_header("Content-Encoding", detail::encoding_name(type));
  10330. res.set_header("Vary", "Accept-Encoding");
  10331. }
  10332. }
  10333. }
  10334. auto length = std::to_string(res.body.size());
  10335. res.set_header("Content-Length", length);
  10336. }
  10337. }
  10338. inline bool Server::dispatch_request_for_content_reader(
  10339. Request &req, Response &res, ContentReader content_reader,
  10340. const HandlersForContentReader &handlers) const {
  10341. for (const auto &x : handlers) {
  10342. const auto &matcher = x.first;
  10343. const auto &handler = x.second;
  10344. if (matcher->match(req)) {
  10345. req.matched_route = matcher->pattern();
  10346. if (!pre_request_handler_ ||
  10347. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10348. handler(req, res, content_reader);
  10349. }
  10350. return true;
  10351. }
  10352. }
  10353. return false;
  10354. }
  10355. inline std::string
  10356. get_client_ip(const std::string &x_forwarded_for,
  10357. const std::vector<std::string> &trusted_proxies) {
  10358. // X-Forwarded-For is a comma-separated list per RFC 7239
  10359. std::vector<std::string> ip_list;
  10360. detail::split(x_forwarded_for.data(),
  10361. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10362. [&](const char *b, const char *e) {
  10363. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10364. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10365. });
  10366. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10367. // no segments. Signal "no client IP derived" with an empty string so the
  10368. // caller can fall back to the connection-level remote address.
  10369. if (ip_list.empty()) { return std::string(); }
  10370. for (size_t i = 0; i < ip_list.size(); ++i) {
  10371. auto ip = ip_list[i];
  10372. auto is_trusted_proxy =
  10373. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10374. [&](const std::string &proxy) { return ip == proxy; });
  10375. if (is_trusted_proxy) {
  10376. if (i == 0) {
  10377. // If the trusted proxy is the first IP, there's no preceding client IP
  10378. return ip;
  10379. } else {
  10380. // Return the IP immediately before the trusted proxy
  10381. return ip_list[i - 1];
  10382. }
  10383. }
  10384. }
  10385. // If no trusted proxy is found, return the first IP in the list
  10386. return ip_list.front();
  10387. }
  10388. inline bool
  10389. Server::process_request(Stream &strm, const std::string &remote_addr,
  10390. int remote_port, const std::string &local_addr,
  10391. int local_port, bool close_connection,
  10392. bool &connection_closed,
  10393. const std::function<void(Request &)> &setup_request,
  10394. bool *websocket_upgraded) {
  10395. std::array<char, 2048> buf{};
  10396. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10397. // Connection has been closed on client
  10398. if (!line_reader.getline()) { return false; }
  10399. Request req;
  10400. req.start_time_ = std::chrono::steady_clock::now();
  10401. req.remote_addr = remote_addr;
  10402. req.remote_port = remote_port;
  10403. req.local_addr = local_addr;
  10404. req.local_port = local_port;
  10405. Response res;
  10406. res.version = "HTTP/1.1";
  10407. res.headers = default_headers_;
  10408. // Request line and headers
  10409. if (!parse_request_line(line_reader.ptr(), req)) {
  10410. res.status = StatusCode::BadRequest_400;
  10411. output_error_log(Error::InvalidRequestLine, &req);
  10412. return write_response(strm, close_connection, req, res);
  10413. }
  10414. // Request headers
  10415. if (!detail::read_headers(strm, req.headers)) {
  10416. res.status = StatusCode::BadRequest_400;
  10417. output_error_log(Error::InvalidHeaders, &req);
  10418. return write_response(strm, close_connection, req, res);
  10419. }
  10420. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10421. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10422. // tolerated for compatibility with existing clients.
  10423. if (req.get_header_value_u64("Content-Length") > 0 &&
  10424. req.has_header("Transfer-Encoding")) {
  10425. connection_closed = true;
  10426. res.status = StatusCode::BadRequest_400;
  10427. return write_response(strm, close_connection, req, res);
  10428. }
  10429. // Check if the request URI doesn't exceed the limit
  10430. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10431. connection_closed = true;
  10432. res.status = StatusCode::UriTooLong_414;
  10433. output_error_log(Error::ExceedUriMaxLength, &req);
  10434. return write_response(strm, close_connection, req, res);
  10435. }
  10436. if (req.get_header_value("Connection") == "close") {
  10437. connection_closed = true;
  10438. }
  10439. if (req.version == "HTTP/1.0" &&
  10440. req.get_header_value("Connection") != "Keep-Alive") {
  10441. connection_closed = true;
  10442. }
  10443. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10444. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10445. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10446. req.remote_addr = derived.empty() ? remote_addr : derived;
  10447. } else {
  10448. req.remote_addr = remote_addr;
  10449. }
  10450. req.remote_port = remote_port;
  10451. req.local_addr = local_addr;
  10452. req.local_port = local_port;
  10453. if (req.has_header("Accept")) {
  10454. const auto &accept_header = req.get_header_value("Accept");
  10455. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10456. connection_closed = true;
  10457. res.status = StatusCode::BadRequest_400;
  10458. output_error_log(Error::HTTPParsing, &req);
  10459. return write_response(strm, close_connection, req, res);
  10460. }
  10461. }
  10462. if (req.has_header("Range")) {
  10463. const auto &range_header_value = req.get_header_value("Range");
  10464. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10465. connection_closed = true;
  10466. res.status = StatusCode::RangeNotSatisfiable_416;
  10467. output_error_log(Error::InvalidRangeHeader, &req);
  10468. return write_response(strm, close_connection, req, res);
  10469. }
  10470. }
  10471. if (setup_request) { setup_request(req); }
  10472. if (req.get_header_value("Expect") == "100-continue") {
  10473. int status = StatusCode::Continue_100;
  10474. if (expect_100_continue_handler_) {
  10475. status = expect_100_continue_handler_(req, res);
  10476. }
  10477. switch (status) {
  10478. case StatusCode::Continue_100:
  10479. case StatusCode::ExpectationFailed_417:
  10480. detail::write_response_line(strm, status);
  10481. strm.write("\r\n");
  10482. break;
  10483. default:
  10484. connection_closed = true;
  10485. return write_response(strm, true, req, res);
  10486. }
  10487. }
  10488. // Setup `is_connection_closed` method
  10489. auto sock = strm.socket();
  10490. req.is_connection_closed = [sock]() {
  10491. return !detail::is_socket_alive(sock);
  10492. };
  10493. // WebSocket upgrade
  10494. // Check pre_routing_handler_ before upgrading so that authentication
  10495. // and other middleware can reject the request with an HTTP response
  10496. // (e.g., 401) before the protocol switches.
  10497. if (detail::is_websocket_upgrade(req)) {
  10498. if (pre_routing_handler_ &&
  10499. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10500. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10501. return write_response(strm, close_connection, req, res);
  10502. }
  10503. // Find matching WebSocket handler
  10504. for (const auto &entry : websocket_handlers_) {
  10505. if (entry.matcher->match(req)) {
  10506. // Compute accept key
  10507. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10508. auto accept_key = detail::websocket_accept_key(client_key);
  10509. // Negotiate subprotocol
  10510. std::string selected_subprotocol;
  10511. if (entry.sub_protocol_selector) {
  10512. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10513. if (!protocol_header.empty()) {
  10514. std::vector<std::string> protocols;
  10515. std::istringstream iss(protocol_header);
  10516. std::string token;
  10517. while (std::getline(iss, token, ',')) {
  10518. // Trim whitespace
  10519. auto start = token.find_first_not_of(' ');
  10520. auto end = token.find_last_not_of(' ');
  10521. if (start != std::string::npos) {
  10522. protocols.push_back(token.substr(start, end - start + 1));
  10523. }
  10524. }
  10525. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10526. }
  10527. }
  10528. // Send 101 Switching Protocols
  10529. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10530. "Upgrade: websocket\r\n"
  10531. "Connection: Upgrade\r\n"
  10532. "Sec-WebSocket-Accept: " +
  10533. accept_key + "\r\n";
  10534. if (!selected_subprotocol.empty()) {
  10535. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10536. return false;
  10537. }
  10538. handshake_response +=
  10539. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10540. }
  10541. handshake_response += "\r\n";
  10542. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10543. 0) {
  10544. return false;
  10545. }
  10546. connection_closed = true;
  10547. if (websocket_upgraded) { *websocket_upgraded = true; }
  10548. {
  10549. // Use WebSocket-specific read timeout instead of HTTP timeout
  10550. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10551. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10552. websocket_max_missed_pongs_);
  10553. entry.handler(req, ws);
  10554. }
  10555. return true;
  10556. }
  10557. }
  10558. // No matching handler - fall through to 404
  10559. }
  10560. // Routing
  10561. auto routed = false;
  10562. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10563. routed = routing(req, res, strm);
  10564. #else
  10565. try {
  10566. routed = routing(req, res, strm);
  10567. } catch (std::exception &) {
  10568. if (exception_handler_) {
  10569. auto ep = std::current_exception();
  10570. exception_handler_(req, res, ep);
  10571. routed = true;
  10572. } else {
  10573. res.status = StatusCode::InternalServerError_500;
  10574. }
  10575. } catch (...) {
  10576. if (exception_handler_) {
  10577. auto ep = std::current_exception();
  10578. exception_handler_(req, res, ep);
  10579. routed = true;
  10580. } else {
  10581. res.status = StatusCode::InternalServerError_500;
  10582. }
  10583. }
  10584. #endif
  10585. auto ret = false;
  10586. if (routed) {
  10587. if (res.status == -1) {
  10588. res.status = req.ranges.empty() ? StatusCode::OK_200
  10589. : StatusCode::PartialContent_206;
  10590. }
  10591. // Serve file content by using a content provider
  10592. auto file_open_error = false;
  10593. if (!res.file_content_path_.empty()) {
  10594. const auto &path = res.file_content_path_;
  10595. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10596. if (!mm->is_open()) {
  10597. res.body.clear();
  10598. res.content_length_ = 0;
  10599. res.content_provider_ = nullptr;
  10600. res.status = StatusCode::NotFound_404;
  10601. output_error_log(Error::OpenFile, &req);
  10602. file_open_error = true;
  10603. } else {
  10604. auto content_type = res.file_content_content_type_;
  10605. if (content_type.empty()) {
  10606. content_type = detail::find_content_type(
  10607. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10608. }
  10609. res.set_content_provider(
  10610. mm->size(), content_type,
  10611. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10612. sink.write(mm->data() + offset, length);
  10613. return true;
  10614. });
  10615. }
  10616. }
  10617. if (file_open_error) {
  10618. ret = write_response(strm, close_connection, req, res);
  10619. } else if (detail::range_error(req, res)) {
  10620. res.body.clear();
  10621. res.content_length_ = 0;
  10622. res.content_provider_ = nullptr;
  10623. res.status = StatusCode::RangeNotSatisfiable_416;
  10624. ret = write_response(strm, close_connection, req, res);
  10625. } else {
  10626. ret = write_response_with_content(strm, close_connection, req, res);
  10627. }
  10628. } else {
  10629. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10630. ret = write_response(strm, close_connection, req, res);
  10631. }
  10632. // Drain any unconsumed framed body to prevent request smuggling on
  10633. // keep-alive. Without framing there is no body to drain — reading would
  10634. // consume the next request (issue #2450).
  10635. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10636. int dummy_status;
  10637. if (!detail::read_content(
  10638. strm, req, payload_max_length_, dummy_status, nullptr,
  10639. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10640. connection_closed = true;
  10641. }
  10642. }
  10643. return ret;
  10644. }
  10645. inline bool Server::is_valid() const { return true; }
  10646. inline bool Server::process_and_close_socket(socket_t sock) {
  10647. std::string remote_addr;
  10648. int remote_port = 0;
  10649. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10650. std::string local_addr;
  10651. int local_port = 0;
  10652. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10653. bool websocket_upgraded = false;
  10654. auto ret = detail::process_server_socket(
  10655. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10656. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10657. write_timeout_usec_,
  10658. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10659. return process_request(strm, remote_addr, remote_port, local_addr,
  10660. local_port, close_connection, connection_closed,
  10661. nullptr, &websocket_upgraded);
  10662. });
  10663. detail::shutdown_socket(sock);
  10664. detail::close_socket(sock);
  10665. return ret;
  10666. }
  10667. inline void Server::output_log(const Request &req, const Response &res) const {
  10668. if (logger_) {
  10669. std::lock_guard<std::mutex> guard(logger_mutex_);
  10670. logger_(req, res);
  10671. }
  10672. }
  10673. inline void Server::output_pre_compression_log(const Request &req,
  10674. const Response &res) const {
  10675. if (pre_compression_logger_) {
  10676. std::lock_guard<std::mutex> guard(logger_mutex_);
  10677. pre_compression_logger_(req, res);
  10678. }
  10679. }
  10680. inline void Server::output_error_log(const Error &err,
  10681. const Request *req) const {
  10682. if (error_logger_) {
  10683. std::lock_guard<std::mutex> guard(logger_mutex_);
  10684. error_logger_(err, req);
  10685. }
  10686. }
  10687. /*
  10688. * Group 5: ClientImpl and Client (Universal) implementation
  10689. */
  10690. // HTTP client implementation
  10691. inline ClientImpl::ClientImpl(const std::string &host)
  10692. : ClientImpl(host, 80, std::string(), std::string()) {}
  10693. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10694. : ClientImpl(host, port, std::string(), std::string()) {}
  10695. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10696. const std::string &client_cert_path,
  10697. const std::string &client_key_path)
  10698. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10699. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10700. inline ClientImpl::~ClientImpl() {
  10701. // Wait until all the requests in flight are handled.
  10702. size_t retry_count = 10;
  10703. while (retry_count-- > 0) {
  10704. {
  10705. std::lock_guard<std::mutex> guard(socket_mutex_);
  10706. if (socket_requests_in_flight_ == 0) { break; }
  10707. }
  10708. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10709. }
  10710. std::lock_guard<std::mutex> guard(socket_mutex_);
  10711. shutdown_socket(socket_);
  10712. close_socket(socket_);
  10713. }
  10714. inline bool ClientImpl::is_valid() const { return true; }
  10715. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10716. client_cert_path_ = rhs.client_cert_path_;
  10717. client_key_path_ = rhs.client_key_path_;
  10718. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10719. read_timeout_sec_ = rhs.read_timeout_sec_;
  10720. read_timeout_usec_ = rhs.read_timeout_usec_;
  10721. write_timeout_sec_ = rhs.write_timeout_sec_;
  10722. write_timeout_usec_ = rhs.write_timeout_usec_;
  10723. max_timeout_msec_ = rhs.max_timeout_msec_;
  10724. basic_auth_username_ = rhs.basic_auth_username_;
  10725. basic_auth_password_ = rhs.basic_auth_password_;
  10726. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10727. keep_alive_ = rhs.keep_alive_;
  10728. follow_location_ = rhs.follow_location_;
  10729. path_encode_ = rhs.path_encode_;
  10730. address_family_ = rhs.address_family_;
  10731. tcp_nodelay_ = rhs.tcp_nodelay_;
  10732. ipv6_v6only_ = rhs.ipv6_v6only_;
  10733. socket_options_ = rhs.socket_options_;
  10734. compress_ = rhs.compress_;
  10735. decompress_ = rhs.decompress_;
  10736. payload_max_length_ = rhs.payload_max_length_;
  10737. has_payload_max_length_ = rhs.has_payload_max_length_;
  10738. interface_ = rhs.interface_;
  10739. proxy_host_ = rhs.proxy_host_;
  10740. proxy_port_ = rhs.proxy_port_;
  10741. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10742. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10743. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10744. no_proxy_entries_ = rhs.no_proxy_entries_;
  10745. logger_ = rhs.logger_;
  10746. error_logger_ = rhs.error_logger_;
  10747. #ifdef CPPHTTPLIB_SSL_ENABLED
  10748. digest_auth_username_ = rhs.digest_auth_username_;
  10749. digest_auth_password_ = rhs.digest_auth_password_;
  10750. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10751. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10752. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10753. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10754. server_certificate_verification_ = rhs.server_certificate_verification_;
  10755. server_hostname_verification_ = rhs.server_hostname_verification_;
  10756. system_ca_mode_ = rhs.system_ca_mode_;
  10757. #endif
  10758. }
  10759. inline bool
  10760. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10761. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10762. if (no_proxy_entries_.empty()) { return true; }
  10763. // host_ is const so its normalized form is invariant; cache it. The
  10764. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10765. if (host == host_) {
  10766. if (!host_normalized_valid_) {
  10767. host_normalized_ = detail::normalize_target(host_);
  10768. host_normalized_valid_ = true;
  10769. }
  10770. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10771. }
  10772. auto target = detail::normalize_target(host);
  10773. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10774. }
  10775. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10776. if (is_proxy_enabled_for_host(host_)) {
  10777. return detail::create_client_socket(
  10778. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10779. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10780. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10781. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10782. }
  10783. // Check is custom IP specified for host_
  10784. std::string ip;
  10785. auto it = addr_map_.find(host_);
  10786. if (it != addr_map_.end()) { ip = it->second; }
  10787. return detail::create_client_socket(
  10788. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10789. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10790. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10791. write_timeout_usec_, interface_, error);
  10792. }
  10793. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10794. Error &error) {
  10795. auto sock = create_client_socket(error);
  10796. if (sock == INVALID_SOCKET) { return false; }
  10797. socket.sock = sock;
  10798. return true;
  10799. }
  10800. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10801. return create_and_connect_socket(socket, error);
  10802. }
  10803. inline bool ClientImpl::setup_proxy_connection(
  10804. Socket & /*socket*/,
  10805. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10806. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10807. return true;
  10808. }
  10809. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10810. bool /*shutdown_gracefully*/) {
  10811. // If there are any requests in flight from threads other than us, then it's
  10812. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10813. assert(socket_requests_in_flight_ == 0 ||
  10814. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10815. }
  10816. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10817. if (socket.sock == INVALID_SOCKET) { return; }
  10818. detail::shutdown_socket(socket.sock);
  10819. }
  10820. inline void ClientImpl::close_socket(Socket &socket) {
  10821. // If there are requests in flight in another thread, usually closing
  10822. // the socket will be fine and they will simply receive an error when
  10823. // using the closed socket, but it is still a bug since rarely the OS
  10824. // may reassign the socket id to be used for a new socket, and then
  10825. // suddenly they will be operating on a live socket that is different
  10826. // than the one they intended!
  10827. assert(socket_requests_in_flight_ == 0 ||
  10828. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10829. // It is also a bug if this happens while SSL is still active
  10830. #ifdef CPPHTTPLIB_SSL_ENABLED
  10831. assert(socket.ssl == nullptr);
  10832. #endif
  10833. if (socket.sock == INVALID_SOCKET) { return; }
  10834. detail::close_socket(socket.sock);
  10835. socket.sock = INVALID_SOCKET;
  10836. }
  10837. inline void ClientImpl::disconnect(bool gracefully) {
  10838. shutdown_ssl(socket_, gracefully);
  10839. shutdown_socket(socket_);
  10840. close_socket(socket_);
  10841. }
  10842. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10843. Response &res,
  10844. bool skip_100_continue) const {
  10845. std::array<char, 2048> buf{};
  10846. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10847. if (!line_reader.getline()) { return false; }
  10848. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10849. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10850. #else
  10851. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10852. #endif
  10853. std::cmatch m;
  10854. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10855. return req.method == "CONNECT";
  10856. }
  10857. res.version = std::string(m[1]);
  10858. res.status = std::stoi(std::string(m[2]));
  10859. res.reason = std::string(m[3]);
  10860. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10861. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10862. if (!line_reader.getline()) { return false; } // CRLF
  10863. if (!line_reader.getline()) { return false; } // next response line
  10864. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10865. res.version = std::string(m[1]);
  10866. res.status = std::stoi(std::string(m[2]));
  10867. res.reason = std::string(m[3]);
  10868. }
  10869. return true;
  10870. }
  10871. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10872. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10873. auto ret = send_(req, res, error);
  10874. if (error == Error::SSLPeerCouldBeClosed_) {
  10875. assert(!ret);
  10876. ret = send_(req, res, error);
  10877. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10878. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10879. }
  10880. return ret;
  10881. }
  10882. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10883. {
  10884. std::lock_guard<std::mutex> guard(socket_mutex_);
  10885. // Set this to false immediately - if it ever gets set to true by the end
  10886. // of the request, we know another thread instructed us to close the
  10887. // socket.
  10888. socket_should_be_closed_when_request_is_done_ = false;
  10889. auto is_alive = false;
  10890. if (socket_.is_open()) {
  10891. is_alive = detail::is_socket_alive(socket_.sock);
  10892. #ifdef CPPHTTPLIB_SSL_ENABLED
  10893. if (is_alive && is_ssl()) {
  10894. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10895. is_alive = false;
  10896. }
  10897. }
  10898. #endif
  10899. if (!is_alive) {
  10900. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  10901. disconnect(/*gracefully=*/false);
  10902. }
  10903. }
  10904. if (!is_alive) {
  10905. if (!ensure_socket_connection(socket_, error)) {
  10906. output_error_log(error, &req);
  10907. return false;
  10908. }
  10909. {
  10910. auto success = true;
  10911. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10912. error)) {
  10913. if (!success) { output_error_log(error, &req); }
  10914. return success;
  10915. }
  10916. }
  10917. }
  10918. // Mark the current socket as being in use so that it cannot be closed by
  10919. // anyone else while this request is ongoing, even though we will be
  10920. // releasing the mutex.
  10921. if (socket_requests_in_flight_ > 1) {
  10922. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10923. }
  10924. socket_requests_in_flight_ += 1;
  10925. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10926. }
  10927. for (const auto &header : default_headers_) {
  10928. if (req.headers.find(header.first) == req.headers.end()) {
  10929. req.headers.insert(header);
  10930. }
  10931. }
  10932. auto ret = false;
  10933. auto close_connection = !keep_alive_;
  10934. auto se = detail::scope_exit([&]() {
  10935. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10936. std::lock_guard<std::mutex> guard(socket_mutex_);
  10937. socket_requests_in_flight_ -= 1;
  10938. if (socket_requests_in_flight_ <= 0) {
  10939. assert(socket_requests_in_flight_ == 0);
  10940. socket_requests_are_from_thread_ = std::thread::id();
  10941. }
  10942. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10943. !ret) {
  10944. disconnect(/*gracefully=*/true);
  10945. }
  10946. });
  10947. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10948. return handle_request(strm, req, res, close_connection, error);
  10949. });
  10950. if (!ret) {
  10951. if (error == Error::Success) {
  10952. error = Error::Unknown;
  10953. output_error_log(error, &req);
  10954. }
  10955. }
  10956. return ret;
  10957. }
  10958. inline Result ClientImpl::send(const Request &req) {
  10959. auto req2 = req;
  10960. return send_(std::move(req2));
  10961. }
  10962. inline Result ClientImpl::send_(Request &&req) {
  10963. auto res = detail::make_unique<Response>();
  10964. auto error = Error::Success;
  10965. auto ret = send(req, *res, error);
  10966. #ifdef CPPHTTPLIB_SSL_ENABLED
  10967. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  10968. last_ssl_error_, last_backend_error_};
  10969. #else
  10970. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  10971. #endif
  10972. }
  10973. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  10974. const std::string &ct) {
  10975. (void)for_stream;
  10976. for (const auto &header : default_headers_) {
  10977. if (!r.has_header(header.first)) { r.headers.insert(header); }
  10978. }
  10979. if (!r.has_header("Host")) {
  10980. if (address_family_ == AF_UNIX) {
  10981. r.headers.emplace("Host", "localhost");
  10982. } else {
  10983. r.headers.emplace(
  10984. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  10985. }
  10986. }
  10987. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  10988. if (!r.content_receiver) {
  10989. if (!r.has_header("Accept-Encoding")) {
  10990. std::string accept_encoding;
  10991. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10992. accept_encoding = "br";
  10993. #endif
  10994. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10995. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  10996. accept_encoding += "gzip, deflate";
  10997. #endif
  10998. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10999. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11000. accept_encoding += "zstd";
  11001. #endif
  11002. r.set_header("Accept-Encoding", accept_encoding);
  11003. }
  11004. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11005. if (!r.has_header("User-Agent")) {
  11006. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  11007. r.set_header("User-Agent", agent);
  11008. }
  11009. #endif
  11010. }
  11011. if (!r.body.empty()) {
  11012. if (!ct.empty() && !r.has_header("Content-Type")) {
  11013. r.headers.emplace("Content-Type", ct);
  11014. }
  11015. if (!r.has_header("Content-Length")) {
  11016. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  11017. }
  11018. }
  11019. }
  11020. inline ClientImpl::StreamHandle
  11021. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11022. const Params &params, const Headers &headers,
  11023. const std::string &body,
  11024. const std::string &content_type) {
  11025. StreamHandle handle;
  11026. handle.response = detail::make_unique<Response>();
  11027. handle.error = Error::Success;
  11028. auto query_path = params.empty() ? path : append_query_params(path, params);
  11029. handle.connection_ = detail::make_unique<ClientConnection>();
  11030. {
  11031. std::lock_guard<std::mutex> guard(socket_mutex_);
  11032. auto is_alive = false;
  11033. if (socket_.is_open()) {
  11034. is_alive = detail::is_socket_alive(socket_.sock);
  11035. #ifdef CPPHTTPLIB_SSL_ENABLED
  11036. if (is_alive && is_ssl()) {
  11037. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11038. is_alive = false;
  11039. }
  11040. }
  11041. #endif
  11042. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11043. }
  11044. if (!is_alive) {
  11045. if (!ensure_socket_connection(socket_, handle.error)) {
  11046. handle.response.reset();
  11047. return handle;
  11048. }
  11049. {
  11050. auto success = true;
  11051. auto start_time = std::chrono::steady_clock::now();
  11052. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11053. success, handle.error)) {
  11054. if (!success) { handle.response.reset(); }
  11055. return handle;
  11056. }
  11057. }
  11058. }
  11059. transfer_socket_ownership_to_handle(handle);
  11060. }
  11061. #ifdef CPPHTTPLIB_SSL_ENABLED
  11062. if (is_ssl() && handle.connection_->session) {
  11063. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11064. handle.connection_->sock, handle.connection_->session,
  11065. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11066. write_timeout_usec_);
  11067. } else {
  11068. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11069. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11070. write_timeout_sec_, write_timeout_usec_);
  11071. }
  11072. #else
  11073. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11074. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11075. write_timeout_sec_, write_timeout_usec_);
  11076. #endif
  11077. handle.stream_ = handle.socket_stream_.get();
  11078. Request req;
  11079. req.method = method;
  11080. req.path = query_path;
  11081. req.headers = headers;
  11082. req.body = body;
  11083. prepare_default_headers(req, true, content_type);
  11084. auto &strm = *handle.stream_;
  11085. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11086. handle.error = Error::Write;
  11087. handle.response.reset();
  11088. return handle;
  11089. }
  11090. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11091. handle.error)) {
  11092. handle.response.reset();
  11093. return handle;
  11094. }
  11095. if (!body.empty()) {
  11096. if (strm.write(body.data(), body.size()) < 0) {
  11097. handle.error = Error::Write;
  11098. handle.response.reset();
  11099. return handle;
  11100. }
  11101. }
  11102. if (!read_response_line(strm, req, *handle.response) ||
  11103. !detail::read_headers(strm, handle.response->headers)) {
  11104. handle.error = Error::Read;
  11105. handle.response.reset();
  11106. return handle;
  11107. }
  11108. handle.body_reader_.stream = handle.stream_;
  11109. handle.body_reader_.payload_max_length = payload_max_length_;
  11110. if (handle.response->has_header("Content-Length")) {
  11111. bool is_invalid = false;
  11112. auto content_length = detail::get_header_value_u64(
  11113. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11114. if (is_invalid) {
  11115. handle.error = Error::Read;
  11116. handle.response.reset();
  11117. return handle;
  11118. }
  11119. handle.body_reader_.has_content_length = true;
  11120. handle.body_reader_.content_length = content_length;
  11121. }
  11122. auto transfer_encoding =
  11123. handle.response->get_header_value("Transfer-Encoding");
  11124. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  11125. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11126. if (!content_encoding.empty()) {
  11127. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11128. }
  11129. return handle;
  11130. }
  11131. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11132. if (!is_valid() || !response) { return -1; }
  11133. if (decompressor_) { return read_with_decompression(buf, len); }
  11134. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11135. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11136. trailers_parsed_ = true;
  11137. if (body_reader_.chunked_decoder) {
  11138. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11139. response->trailers, response->headers)) {
  11140. return n;
  11141. }
  11142. } else {
  11143. detail::ChunkedDecoder dec(*stream_);
  11144. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11145. return n;
  11146. }
  11147. }
  11148. }
  11149. return n;
  11150. }
  11151. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11152. size_t len) {
  11153. if (decompress_offset_ < decompress_buffer_.size()) {
  11154. auto available = decompress_buffer_.size() - decompress_offset_;
  11155. auto to_copy = (std::min)(len, available);
  11156. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11157. decompress_offset_ += to_copy;
  11158. decompressed_bytes_read_ += to_copy;
  11159. return static_cast<ssize_t>(to_copy);
  11160. }
  11161. decompress_buffer_.clear();
  11162. decompress_offset_ = 0;
  11163. constexpr size_t kDecompressionBufferSize = 8192;
  11164. char compressed_buf[kDecompressionBufferSize];
  11165. while (true) {
  11166. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11167. sizeof(compressed_buf));
  11168. if (n <= 0) { return n; }
  11169. bool decompress_ok = decompressor_->decompress(
  11170. compressed_buf, static_cast<size_t>(n),
  11171. [this](const char *data, size_t data_len) {
  11172. decompress_buffer_.append(data, data_len);
  11173. auto limit = body_reader_.payload_max_length;
  11174. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11175. return false;
  11176. }
  11177. return true;
  11178. });
  11179. if (!decompress_ok) {
  11180. body_reader_.last_error = Error::Read;
  11181. return -1;
  11182. }
  11183. if (!decompress_buffer_.empty()) { break; }
  11184. }
  11185. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11186. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11187. decompress_offset_ = to_copy;
  11188. decompressed_bytes_read_ += to_copy;
  11189. return static_cast<ssize_t>(to_copy);
  11190. }
  11191. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11192. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11193. return;
  11194. }
  11195. trailers_parsed_ = true;
  11196. const auto bufsiz = 128;
  11197. char line_buf[bufsiz];
  11198. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11199. if (!line_reader.getline()) { return; }
  11200. if (!detail::parse_trailers(line_reader, response->trailers,
  11201. response->headers)) {
  11202. return;
  11203. }
  11204. }
  11205. namespace detail {
  11206. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11207. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11208. size_t &out_chunk_offset,
  11209. size_t &out_chunk_total) {
  11210. if (finished) { return 0; }
  11211. if (chunk_remaining == 0) {
  11212. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11213. if (!lr.getline()) { return -1; }
  11214. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11215. const char *p = lr.ptr();
  11216. int v = 0;
  11217. if (!is_hex(*p, v)) { return -1; }
  11218. size_t chunk_len = 0;
  11219. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11220. for (; is_hex(*p, v); ++p) {
  11221. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11222. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11223. }
  11224. while (is_space_or_tab(*p)) {
  11225. ++p;
  11226. }
  11227. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11228. if (chunk_len == 0) {
  11229. chunk_remaining = 0;
  11230. finished = true;
  11231. out_chunk_offset = 0;
  11232. out_chunk_total = 0;
  11233. return 0;
  11234. }
  11235. chunk_remaining = chunk_len;
  11236. last_chunk_total = chunk_remaining;
  11237. last_chunk_offset = 0;
  11238. }
  11239. auto to_read = (std::min)(chunk_remaining, len);
  11240. auto n = strm.read(buf, to_read);
  11241. if (n <= 0) { return -1; }
  11242. auto offset_before = last_chunk_offset;
  11243. last_chunk_offset += static_cast<size_t>(n);
  11244. chunk_remaining -= static_cast<size_t>(n);
  11245. out_chunk_offset = offset_before;
  11246. out_chunk_total = last_chunk_total;
  11247. if (chunk_remaining == 0) {
  11248. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11249. if (!lr.getline()) { return -1; }
  11250. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11251. }
  11252. return n;
  11253. }
  11254. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11255. const Headers &src_headers) {
  11256. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11257. if (!lr.getline()) { return false; }
  11258. return parse_trailers(lr, dest, src_headers);
  11259. }
  11260. } // namespace detail
  11261. inline void
  11262. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11263. handle.connection_->sock = socket_.sock;
  11264. #ifdef CPPHTTPLIB_SSL_ENABLED
  11265. handle.connection_->session = socket_.ssl;
  11266. socket_.ssl = nullptr;
  11267. #endif
  11268. socket_.sock = INVALID_SOCKET;
  11269. }
  11270. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11271. Response &res, bool close_connection,
  11272. Error &error) {
  11273. if (req.path.empty()) {
  11274. error = Error::Connection;
  11275. output_error_log(error, &req);
  11276. return false;
  11277. }
  11278. auto req_save = req;
  11279. bool ret;
  11280. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11281. auto req2 = req;
  11282. req2.path = "http://" +
  11283. detail::make_host_and_port_string(host_, port_, false) +
  11284. req.path;
  11285. ret = process_request(strm, req2, res, close_connection, error);
  11286. req = std::move(req2);
  11287. req.path = req_save.path;
  11288. } else {
  11289. ret = process_request(strm, req, res, close_connection, error);
  11290. }
  11291. if (!ret) { return false; }
  11292. if (res.get_header_value("Connection") == "close" ||
  11293. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11294. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11295. // for this to be safe.
  11296. // This is safe to call because handle_request is only called by send_
  11297. // which locks the request mutex during the process. It would be a bug
  11298. // to call it from a different thread since it's a thread-safety issue
  11299. // to do these things to the socket if another thread is using the socket.
  11300. std::lock_guard<std::mutex> guard(socket_mutex_);
  11301. disconnect(/*gracefully=*/true);
  11302. }
  11303. if (300 < res.status && res.status < 400 && follow_location_) {
  11304. req = std::move(req_save);
  11305. ret = redirect(req, res, error);
  11306. }
  11307. #ifdef CPPHTTPLIB_SSL_ENABLED
  11308. if ((res.status == StatusCode::Unauthorized_401 ||
  11309. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11310. req.authorization_count_ < 5) {
  11311. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11312. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11313. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11314. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11315. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11316. return ret;
  11317. }
  11318. const auto &username =
  11319. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11320. const auto &password =
  11321. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11322. if (!username.empty() && !password.empty()) {
  11323. std::map<std::string, std::string> auth;
  11324. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11325. Request new_req = req;
  11326. new_req.authorization_count_ += 1;
  11327. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11328. : "Authorization");
  11329. new_req.headers.insert(detail::make_digest_authentication_header(
  11330. req, auth, new_req.authorization_count_, detail::random_string(10),
  11331. username, password, is_proxy));
  11332. Response new_res;
  11333. ret = send(new_req, new_res, error);
  11334. if (ret) { res = std::move(new_res); }
  11335. }
  11336. }
  11337. }
  11338. #endif
  11339. return ret;
  11340. }
  11341. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11342. if (req.redirect_count_ == 0) {
  11343. error = Error::ExceedRedirectCount;
  11344. output_error_log(error, &req);
  11345. return false;
  11346. }
  11347. auto location = res.get_header_value("location");
  11348. if (location.empty()) { return false; }
  11349. detail::UrlComponents uc;
  11350. if (!detail::parse_url(location, uc)) { return false; }
  11351. // Only follow http/https redirects
  11352. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11353. return false;
  11354. }
  11355. auto scheme = is_ssl() ? "https" : "http";
  11356. auto next_scheme = std::move(uc.scheme);
  11357. auto next_host = std::move(uc.host);
  11358. auto port_str = std::move(uc.port);
  11359. auto next_path = std::move(uc.path);
  11360. auto next_query = std::move(uc.query);
  11361. auto next_port = port_;
  11362. if (!port_str.empty()) {
  11363. if (!detail::parse_port(port_str, next_port)) { return false; }
  11364. } else if (!next_scheme.empty()) {
  11365. next_port = next_scheme == "https" ? 443 : 80;
  11366. }
  11367. if (next_scheme.empty()) { next_scheme = scheme; }
  11368. if (next_host.empty()) { next_host = host_; }
  11369. if (next_path.empty()) { next_path = "/"; }
  11370. auto path = decode_path_component(next_path) + next_query;
  11371. // Same host redirect - use current client
  11372. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11373. return detail::redirect(*this, req, res, path, location, error);
  11374. }
  11375. // Cross-host/scheme redirect - create new client with robust setup
  11376. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11377. path, location, error);
  11378. }
  11379. // New method for robust redirect client creation
  11380. inline bool ClientImpl::create_redirect_client(
  11381. const std::string &scheme, const std::string &host, int port, Request &req,
  11382. Response &res, const std::string &path, const std::string &location,
  11383. Error &error) {
  11384. // Determine if we need SSL
  11385. auto need_ssl = (scheme == "https");
  11386. // Clean up request headers that are host/client specific
  11387. // Remove headers that should not be carried over to new host
  11388. auto headers_to_remove =
  11389. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  11390. for (const auto &header_name : headers_to_remove) {
  11391. auto it = req.headers.find(header_name);
  11392. while (it != req.headers.end()) {
  11393. it = req.headers.erase(it);
  11394. it = req.headers.find(header_name);
  11395. }
  11396. }
  11397. // Create appropriate client type and handle redirect
  11398. if (need_ssl) {
  11399. #ifdef CPPHTTPLIB_SSL_ENABLED
  11400. // Create SSL client for HTTPS redirect
  11401. SSLClient redirect_client(host, port);
  11402. // Setup basic client configuration first
  11403. setup_redirect_client(redirect_client);
  11404. redirect_client.enable_server_certificate_verification(
  11405. server_certificate_verification_);
  11406. redirect_client.enable_server_hostname_verification(
  11407. server_hostname_verification_);
  11408. redirect_client.system_ca_mode_ = system_ca_mode_;
  11409. // Transfer CA certificate to redirect client
  11410. if (!ca_cert_pem_.empty()) {
  11411. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11412. ca_cert_pem_.size());
  11413. }
  11414. if (!ca_cert_file_path_.empty()) {
  11415. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11416. }
  11417. // Client certificates are set through constructor for SSLClient
  11418. // NOTE: SSLClient constructor already takes client_cert_path and
  11419. // client_key_path so we need to create it properly if client certs are
  11420. // needed
  11421. // Execute the redirect
  11422. return detail::redirect(redirect_client, req, res, path, location, error);
  11423. #else
  11424. // SSL not supported - set appropriate error
  11425. error = Error::SSLConnection;
  11426. output_error_log(error, &req);
  11427. return false;
  11428. #endif
  11429. } else {
  11430. // HTTP redirect
  11431. ClientImpl redirect_client(host, port);
  11432. // Setup client with robust configuration
  11433. setup_redirect_client(redirect_client);
  11434. // Execute the redirect
  11435. return detail::redirect(redirect_client, req, res, path, location, error);
  11436. }
  11437. }
  11438. // New method for robust client setup (based on basic_manual_redirect.cpp
  11439. // logic)
  11440. template <typename ClientType>
  11441. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11442. // Copy basic settings first
  11443. client.set_connection_timeout(connection_timeout_sec_);
  11444. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11445. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11446. client.set_keep_alive(keep_alive_);
  11447. client.set_follow_location(
  11448. true); // Enable redirects to handle multi-step redirects
  11449. client.set_path_encode(path_encode_);
  11450. client.set_compress(compress_);
  11451. client.set_decompress(decompress_);
  11452. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11453. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11454. // 15.4, credentials must not be forwarded when redirecting to a different
  11455. // host. This function is only called for cross-host redirects; same-host
  11456. // redirects are handled directly in ClientImpl::redirect().
  11457. // Copy the proxy configuration unconditionally; the per-target bypass is
  11458. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11459. // still use the proxy.
  11460. client.no_proxy_entries_ = no_proxy_entries_;
  11461. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11462. client.set_proxy(proxy_host_, proxy_port_);
  11463. if (!proxy_basic_auth_username_.empty()) {
  11464. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11465. proxy_basic_auth_password_);
  11466. }
  11467. if (!proxy_bearer_token_auth_token_.empty()) {
  11468. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11469. }
  11470. #ifdef CPPHTTPLIB_SSL_ENABLED
  11471. if (!proxy_digest_auth_username_.empty()) {
  11472. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11473. proxy_digest_auth_password_);
  11474. }
  11475. #endif
  11476. }
  11477. // Copy network and socket settings
  11478. client.set_address_family(address_family_);
  11479. client.set_tcp_nodelay(tcp_nodelay_);
  11480. client.set_ipv6_v6only(ipv6_v6only_);
  11481. if (socket_options_) { client.set_socket_options(socket_options_); }
  11482. if (!interface_.empty()) { client.set_interface(interface_); }
  11483. // Copy logging and headers
  11484. if (logger_) { client.set_logger(logger_); }
  11485. if (error_logger_) { client.set_error_logger(error_logger_); }
  11486. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11487. // Each new client should generate its own headers based on its target host
  11488. }
  11489. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11490. const Request &req,
  11491. Error &error) const {
  11492. auto is_shutting_down = []() { return false; };
  11493. if (req.is_chunked_content_provider_) {
  11494. auto compressor = compress_ ? detail::create_compressor().first
  11495. : std::unique_ptr<detail::compressor>();
  11496. if (!compressor) {
  11497. compressor = detail::make_unique<detail::nocompressor>();
  11498. }
  11499. return detail::write_content_chunked(strm, req.content_provider_,
  11500. is_shutting_down, *compressor, error);
  11501. } else {
  11502. return detail::write_content_with_progress(
  11503. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11504. req.upload_progress, error);
  11505. }
  11506. }
  11507. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11508. bool close_connection, Error &error,
  11509. bool skip_body) {
  11510. // Prepare additional headers
  11511. if (close_connection) {
  11512. if (!req.has_header("Connection")) {
  11513. req.set_header("Connection", "close");
  11514. }
  11515. }
  11516. std::string ct_for_defaults;
  11517. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11518. ct_for_defaults = "text/plain";
  11519. }
  11520. prepare_default_headers(req, false, ct_for_defaults);
  11521. if (req.body.empty()) {
  11522. if (req.content_provider_) {
  11523. if (!req.is_chunked_content_provider_) {
  11524. if (!req.has_header("Content-Length")) {
  11525. auto length = std::to_string(req.content_length_);
  11526. req.set_header("Content-Length", length);
  11527. }
  11528. }
  11529. } else {
  11530. if (req.method == "POST" || req.method == "PUT" ||
  11531. req.method == "PATCH") {
  11532. req.set_header("Content-Length", "0");
  11533. }
  11534. }
  11535. }
  11536. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11537. if (!req.has_header("Authorization")) {
  11538. req.headers.insert(make_basic_authentication_header(
  11539. basic_auth_username_, basic_auth_password_, false));
  11540. }
  11541. }
  11542. if (!bearer_token_auth_token_.empty()) {
  11543. if (!req.has_header("Authorization")) {
  11544. req.headers.insert(make_bearer_token_authentication_header(
  11545. bearer_token_auth_token_, false));
  11546. }
  11547. }
  11548. // Proxy-Authorization is only sent when the proxy is actually used for
  11549. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11550. // credentials directly to the destination server.
  11551. if (is_proxy_enabled_for_host(host_)) {
  11552. if (!proxy_basic_auth_username_.empty() &&
  11553. !proxy_basic_auth_password_.empty() &&
  11554. !req.has_header("Proxy-Authorization")) {
  11555. req.headers.insert(make_basic_authentication_header(
  11556. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11557. }
  11558. if (!proxy_bearer_token_auth_token_.empty() &&
  11559. !req.has_header("Proxy-Authorization")) {
  11560. req.headers.insert(make_bearer_token_authentication_header(
  11561. proxy_bearer_token_auth_token_, true));
  11562. }
  11563. }
  11564. // Request line and headers
  11565. {
  11566. detail::BufferStream bstrm;
  11567. // Extract path and query from req.path
  11568. std::string path_part, query_part;
  11569. auto query_pos = req.path.find('?');
  11570. if (query_pos != std::string::npos) {
  11571. path_part = req.path.substr(0, query_pos);
  11572. query_part = req.path.substr(query_pos + 1);
  11573. } else {
  11574. path_part = req.path;
  11575. query_part = "";
  11576. }
  11577. // Encode path part. If the original `req.path` already contained a
  11578. // query component, preserve its raw query string (including parameter
  11579. // order) instead of reparsing and reassembling it which may reorder
  11580. // parameters due to container ordering (e.g. `Params` uses
  11581. // `std::multimap`). When there is no query in `req.path`, fall back to
  11582. // building a query from `req.params` so existing callers that pass
  11583. // `Params` continue to work.
  11584. auto path_with_query =
  11585. path_encode_ ? detail::encode_path(path_part) : path_part;
  11586. if (!query_part.empty()) {
  11587. // Normalize the query string (decode then re-encode) while preserving
  11588. // the original parameter order. When path encoding is disabled the
  11589. // caller has supplied an already-encoded target and expects the exact
  11590. // bytes to be sent on the wire, so skip normalization for the query
  11591. // too. Normalizing here would decode-then-re-encode the query and
  11592. // corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  11593. // which a strict RFC 3986 server decodes back as `+`, not a space).
  11594. if (path_encode_) {
  11595. auto normalized = detail::normalize_query_string(query_part);
  11596. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11597. } else {
  11598. path_with_query += '?' + query_part;
  11599. }
  11600. // Still populate req.params for handlers/users who read them.
  11601. detail::parse_query_text(query_part, req.params);
  11602. } else {
  11603. // No query in path; parse any query_part (empty) and append params
  11604. // from `req.params` when present (preserves prior behavior for
  11605. // callers who provide Params separately).
  11606. detail::parse_query_text(query_part, req.params);
  11607. if (!req.params.empty()) {
  11608. path_with_query = append_query_params(path_with_query, req.params);
  11609. }
  11610. }
  11611. // Write request line and headers
  11612. detail::write_request_line(bstrm, req.method, path_with_query);
  11613. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11614. error)) {
  11615. output_error_log(error, &req);
  11616. return false;
  11617. }
  11618. // Flush buffer
  11619. auto &data = bstrm.get_buffer();
  11620. if (!detail::write_data(strm, data.data(), data.size())) {
  11621. error = Error::Write;
  11622. output_error_log(error, &req);
  11623. return false;
  11624. }
  11625. }
  11626. // After sending request line and headers, wait briefly for an early server
  11627. // response (e.g. 4xx) and avoid sending a potentially large request body
  11628. // unnecessarily. This workaround is only enabled on Windows because Unix
  11629. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11630. // buffering can accept large writes even when the peer already responded.
  11631. // Check the stream first (which covers SSL via `is_readable()`), then
  11632. // fall back to select on the socket. Only perform the wait for very large
  11633. // request bodies to avoid interfering with normal small requests and
  11634. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11635. // response. Skip this check when using Expect: 100-continue, as the protocol
  11636. // handles early responses properly.
  11637. #if defined(_WIN32)
  11638. if (!skip_body &&
  11639. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11640. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11641. auto start = std::chrono::high_resolution_clock::now();
  11642. for (;;) {
  11643. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11644. // from SSL internals. If the underlying socket is readable, assume an
  11645. // early response may be present.
  11646. auto sock = strm.socket();
  11647. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11648. return false;
  11649. }
  11650. // Fallback to stream-level check for non-socket streams or when the
  11651. // socket isn't reporting readable. Avoid using `is_readable()` for
  11652. // SSL, since `SSL_pending()` may report buffered records that do not
  11653. // indicate a complete application-level response yet.
  11654. if (!is_ssl() && strm.is_readable()) { return false; }
  11655. auto now = std::chrono::high_resolution_clock::now();
  11656. auto elapsed =
  11657. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11658. .count();
  11659. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11660. break;
  11661. }
  11662. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11663. }
  11664. }
  11665. #endif
  11666. // Body
  11667. if (skip_body) { return true; }
  11668. return write_request_body(strm, req, error);
  11669. }
  11670. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11671. Error &error) {
  11672. if (req.body.empty()) {
  11673. return write_content_with_provider(strm, req, error);
  11674. }
  11675. if (req.upload_progress) {
  11676. auto body_size = req.body.size();
  11677. size_t written = 0;
  11678. auto data = req.body.data();
  11679. while (written < body_size) {
  11680. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11681. if (!detail::write_data(strm, data + written, to_write)) {
  11682. error = Error::Write;
  11683. output_error_log(error, &req);
  11684. return false;
  11685. }
  11686. written += to_write;
  11687. if (!req.upload_progress(written, body_size)) {
  11688. error = Error::Canceled;
  11689. output_error_log(error, &req);
  11690. return false;
  11691. }
  11692. }
  11693. } else {
  11694. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11695. error = Error::Write;
  11696. output_error_log(error, &req);
  11697. return false;
  11698. }
  11699. }
  11700. return true;
  11701. }
  11702. inline std::unique_ptr<Response>
  11703. ClientImpl::send_with_content_provider_and_receiver(
  11704. Request &req, const char *body, size_t content_length,
  11705. ContentProvider content_provider,
  11706. ContentProviderWithoutLength content_provider_without_length,
  11707. const std::string &content_type, ContentReceiver content_receiver,
  11708. Error &error) {
  11709. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11710. auto enc = compress_
  11711. ? detail::create_compressor()
  11712. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11713. nullptr, nullptr);
  11714. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11715. if (enc.first && !content_provider_without_length) {
  11716. auto &compressor = enc.first;
  11717. if (content_provider) {
  11718. auto ok = true;
  11719. size_t offset = 0;
  11720. DataSink data_sink;
  11721. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11722. if (ok) {
  11723. auto last = offset + data_len == content_length;
  11724. auto ret = compressor->compress(
  11725. data, data_len, last,
  11726. [&](const char *compressed_data, size_t compressed_data_len) {
  11727. req.body.append(compressed_data, compressed_data_len);
  11728. return true;
  11729. });
  11730. if (ret) {
  11731. offset += data_len;
  11732. } else {
  11733. ok = false;
  11734. }
  11735. }
  11736. return ok;
  11737. };
  11738. while (ok && offset < content_length) {
  11739. if (!content_provider(offset, content_length - offset, data_sink)) {
  11740. error = Error::Canceled;
  11741. output_error_log(error, &req);
  11742. return nullptr;
  11743. }
  11744. }
  11745. } else {
  11746. if (!compressor->compress(body, content_length, true,
  11747. [&](const char *data, size_t data_len) {
  11748. req.body.append(data, data_len);
  11749. return true;
  11750. })) {
  11751. error = Error::Compression;
  11752. output_error_log(error, &req);
  11753. return nullptr;
  11754. }
  11755. }
  11756. } else {
  11757. if (content_provider) {
  11758. req.content_length_ = content_length;
  11759. req.content_provider_ = std::move(content_provider);
  11760. req.is_chunked_content_provider_ = false;
  11761. } else if (content_provider_without_length) {
  11762. req.content_length_ = 0;
  11763. req.content_provider_ = detail::ContentProviderAdapter(
  11764. std::move(content_provider_without_length));
  11765. req.is_chunked_content_provider_ = true;
  11766. req.set_header("Transfer-Encoding", "chunked");
  11767. } else {
  11768. req.body.assign(body, content_length);
  11769. }
  11770. }
  11771. if (content_receiver) {
  11772. req.content_receiver =
  11773. [content_receiver](const char *data, size_t data_length,
  11774. size_t /*offset*/, size_t /*total_length*/) {
  11775. return content_receiver(data, data_length);
  11776. };
  11777. }
  11778. auto res = detail::make_unique<Response>();
  11779. return send(req, *res, error) ? std::move(res) : nullptr;
  11780. }
  11781. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11782. const std::string &method, const std::string &path, const Headers &headers,
  11783. const char *body, size_t content_length, ContentProvider content_provider,
  11784. ContentProviderWithoutLength content_provider_without_length,
  11785. const std::string &content_type, ContentReceiver content_receiver,
  11786. UploadProgress progress) {
  11787. Request req;
  11788. req.method = method;
  11789. req.headers = headers;
  11790. req.path = path;
  11791. req.upload_progress = std::move(progress);
  11792. if (max_timeout_msec_ > 0) {
  11793. req.start_time_ = std::chrono::steady_clock::now();
  11794. }
  11795. auto error = Error::Success;
  11796. auto res = send_with_content_provider_and_receiver(
  11797. req, body, content_length, std::move(content_provider),
  11798. std::move(content_provider_without_length), content_type,
  11799. std::move(content_receiver), error);
  11800. #ifdef CPPHTTPLIB_SSL_ENABLED
  11801. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11802. last_backend_error_};
  11803. #else
  11804. return Result{std::move(res), error, std::move(req.headers)};
  11805. #endif
  11806. }
  11807. inline void ClientImpl::output_log(const Request &req,
  11808. const Response &res) const {
  11809. if (logger_) {
  11810. std::lock_guard<std::mutex> guard(logger_mutex_);
  11811. logger_(req, res);
  11812. }
  11813. }
  11814. inline void ClientImpl::output_error_log(const Error &err,
  11815. const Request *req) const {
  11816. if (error_logger_) {
  11817. std::lock_guard<std::mutex> guard(logger_mutex_);
  11818. error_logger_(err, req);
  11819. }
  11820. }
  11821. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11822. Response &res, bool close_connection,
  11823. Error &error) {
  11824. // Auto-add Expect: 100-continue for large bodies
  11825. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11826. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11827. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11828. req.set_header("Expect", "100-continue");
  11829. }
  11830. }
  11831. // Check for Expect: 100-continue
  11832. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11833. // Send request (skip body if using Expect: 100-continue)
  11834. auto write_request_success =
  11835. write_request(strm, req, close_connection, error, expect_100_continue);
  11836. #ifdef CPPHTTPLIB_SSL_ENABLED
  11837. if (is_ssl() && !expect_100_continue) {
  11838. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  11839. if (!is_proxy_enabled) {
  11840. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11841. error = Error::SSLPeerCouldBeClosed_;
  11842. output_error_log(error, &req);
  11843. return false;
  11844. }
  11845. }
  11846. }
  11847. #endif
  11848. // Handle Expect: 100-continue.
  11849. //
  11850. // Wait for an interim/early response by attempting to read the status line
  11851. // under a short timeout, instead of trusting raw socket readability. Over
  11852. // TLS, post-handshake records (e.g. session tickets) make the socket
  11853. // readable without any HTTP response being available; relying on
  11854. // `select_read` there caused the body to be withheld forever and the
  11855. // request to fail with `Read` (#2458). If no status line arrives within the
  11856. // timeout, send the body anyway (matching curl's behavior).
  11857. auto status_line_read = false;
  11858. if (expect_100_continue && write_request_success) {
  11859. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11860. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11861. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11862. strm.set_read_timeout(sec, usec);
  11863. status_line_read = read_response_line(strm, req, res, false);
  11864. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11865. }
  11866. if (!status_line_read) {
  11867. // No interim response within the timeout: send the body and handle the
  11868. // response as usual.
  11869. if (!write_request_body(strm, req, error)) { return false; }
  11870. expect_100_continue = false; // Switch to normal response handling
  11871. }
  11872. }
  11873. // Receive response and headers
  11874. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11875. if ((!status_line_read &&
  11876. !read_response_line(strm, req, res, !expect_100_continue)) ||
  11877. !detail::read_headers(strm, res.headers)) {
  11878. if (write_request_success) { error = Error::Read; }
  11879. output_error_log(error, &req);
  11880. return false;
  11881. }
  11882. if (!write_request_success) { return false; }
  11883. // Handle Expect: 100-continue response
  11884. if (expect_100_continue) {
  11885. if (res.status == StatusCode::Continue_100) {
  11886. // Server accepted, send the body
  11887. if (!write_request_body(strm, req, error)) { return false; }
  11888. // Read the actual response
  11889. res.headers.clear();
  11890. res.body.clear();
  11891. if (!read_response_line(strm, req, res) ||
  11892. !detail::read_headers(strm, res.headers)) {
  11893. error = Error::Read;
  11894. output_error_log(error, &req);
  11895. return false;
  11896. }
  11897. }
  11898. // If not 100 Continue, server returned an error; proceed with that response
  11899. }
  11900. // Body
  11901. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11902. req.method != "CONNECT") {
  11903. auto redirect = 300 < res.status && res.status < 400 &&
  11904. res.status != StatusCode::NotModified_304 &&
  11905. follow_location_;
  11906. if (req.response_handler && !redirect) {
  11907. if (!req.response_handler(res)) {
  11908. error = Error::Canceled;
  11909. output_error_log(error, &req);
  11910. return false;
  11911. }
  11912. }
  11913. auto out =
  11914. req.content_receiver
  11915. ? static_cast<ContentReceiverWithProgress>(
  11916. [&](const char *buf, size_t n, size_t off, size_t len) {
  11917. if (redirect) { return true; }
  11918. auto ret = req.content_receiver(buf, n, off, len);
  11919. if (!ret) {
  11920. error = Error::Canceled;
  11921. output_error_log(error, &req);
  11922. }
  11923. return ret;
  11924. })
  11925. : static_cast<ContentReceiverWithProgress>(
  11926. [&](const char *buf, size_t n, size_t /*off*/,
  11927. size_t /*len*/) {
  11928. assert(res.body.size() + n <= res.body.max_size());
  11929. if (payload_max_length_ > 0 &&
  11930. (res.body.size() >= payload_max_length_ ||
  11931. n > payload_max_length_ - res.body.size())) {
  11932. return false;
  11933. }
  11934. res.body.append(buf, n);
  11935. return true;
  11936. });
  11937. auto progress = [&](size_t current, size_t total) {
  11938. if (!req.download_progress || redirect) { return true; }
  11939. auto ret = req.download_progress(current, total);
  11940. if (!ret) {
  11941. error = Error::Canceled;
  11942. output_error_log(error, &req);
  11943. }
  11944. return ret;
  11945. };
  11946. if (res.has_header("Content-Length")) {
  11947. if (!req.content_receiver) {
  11948. auto len = res.get_header_value_u64("Content-Length");
  11949. if (len > res.body.max_size()) {
  11950. error = Error::Read;
  11951. output_error_log(error, &req);
  11952. return false;
  11953. }
  11954. // Cap the reservation by payload_max_length_ to avoid OOM when a
  11955. // hostile or malformed server sends an enormous Content-Length.
  11956. // The actual body read below is bounded by payload_max_length_,
  11957. // so reserving more than that is never useful.
  11958. auto reserve_len = static_cast<size_t>(len);
  11959. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  11960. reserve_len = payload_max_length_;
  11961. }
  11962. res.body.reserve(reserve_len);
  11963. }
  11964. }
  11965. if (res.status != StatusCode::NotModified_304) {
  11966. int dummy_status;
  11967. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  11968. ? (std::numeric_limits<size_t>::max)()
  11969. : payload_max_length_;
  11970. if (!detail::read_content(strm, res, max_length, dummy_status,
  11971. std::move(progress), std::move(out),
  11972. decompress_)) {
  11973. if (error != Error::Canceled) { error = Error::Read; }
  11974. output_error_log(error, &req);
  11975. return false;
  11976. }
  11977. }
  11978. }
  11979. // Log
  11980. output_log(req, res);
  11981. return true;
  11982. }
  11983. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  11984. const std::string &boundary, const UploadFormDataItems &items,
  11985. const FormDataProviderItems &provider_items) const {
  11986. size_t cur_item = 0;
  11987. size_t cur_start = 0;
  11988. // cur_item and cur_start are copied to within the std::function and
  11989. // maintain state between successive calls
  11990. return [&, cur_item, cur_start](size_t offset,
  11991. DataSink &sink) mutable -> bool {
  11992. if (!offset && !items.empty()) {
  11993. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  11994. return true;
  11995. } else if (cur_item < provider_items.size()) {
  11996. if (!cur_start) {
  11997. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  11998. provider_items[cur_item], boundary);
  11999. offset += begin.size();
  12000. cur_start = offset;
  12001. sink.os << begin;
  12002. }
  12003. DataSink cur_sink;
  12004. auto has_data = true;
  12005. cur_sink.write = sink.write;
  12006. cur_sink.done = [&]() { has_data = false; };
  12007. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  12008. return false;
  12009. }
  12010. if (!has_data) {
  12011. sink.os << detail::serialize_multipart_formdata_item_end();
  12012. cur_item++;
  12013. cur_start = 0;
  12014. }
  12015. return true;
  12016. } else {
  12017. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12018. sink.done();
  12019. return true;
  12020. }
  12021. };
  12022. }
  12023. inline bool ClientImpl::process_socket(
  12024. const Socket &socket,
  12025. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12026. std::function<bool(Stream &strm)> callback) {
  12027. return detail::process_client_socket(
  12028. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12029. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12030. }
  12031. inline bool ClientImpl::is_ssl() const { return false; }
  12032. inline Result ClientImpl::Get(const std::string &path,
  12033. DownloadProgress progress) {
  12034. return Get(path, Headers(), std::move(progress));
  12035. }
  12036. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12037. const Headers &headers,
  12038. DownloadProgress progress) {
  12039. if (params.empty()) { return Get(path, headers); }
  12040. std::string path_with_query = append_query_params(path, params);
  12041. return Get(path_with_query, headers, std::move(progress));
  12042. }
  12043. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12044. DownloadProgress progress) {
  12045. Request req;
  12046. req.method = "GET";
  12047. req.path = path;
  12048. req.headers = headers;
  12049. req.download_progress = std::move(progress);
  12050. if (max_timeout_msec_ > 0) {
  12051. req.start_time_ = std::chrono::steady_clock::now();
  12052. }
  12053. return send_(std::move(req));
  12054. }
  12055. inline Result ClientImpl::Get(const std::string &path,
  12056. ContentReceiver content_receiver,
  12057. DownloadProgress progress) {
  12058. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12059. std::move(progress));
  12060. }
  12061. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12062. ContentReceiver content_receiver,
  12063. DownloadProgress progress) {
  12064. return Get(path, headers, nullptr, std::move(content_receiver),
  12065. std::move(progress));
  12066. }
  12067. inline Result ClientImpl::Get(const std::string &path,
  12068. ResponseHandler response_handler,
  12069. ContentReceiver content_receiver,
  12070. DownloadProgress progress) {
  12071. return Get(path, Headers(), std::move(response_handler),
  12072. std::move(content_receiver), std::move(progress));
  12073. }
  12074. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12075. ResponseHandler response_handler,
  12076. ContentReceiver content_receiver,
  12077. DownloadProgress progress) {
  12078. Request req;
  12079. req.method = "GET";
  12080. req.path = path;
  12081. req.headers = headers;
  12082. req.response_handler = std::move(response_handler);
  12083. req.content_receiver =
  12084. [content_receiver](const char *data, size_t data_length,
  12085. size_t /*offset*/, size_t /*total_length*/) {
  12086. return content_receiver(data, data_length);
  12087. };
  12088. req.download_progress = std::move(progress);
  12089. if (max_timeout_msec_ > 0) {
  12090. req.start_time_ = std::chrono::steady_clock::now();
  12091. }
  12092. return send_(std::move(req));
  12093. }
  12094. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12095. const Headers &headers,
  12096. ContentReceiver content_receiver,
  12097. DownloadProgress progress) {
  12098. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12099. std::move(progress));
  12100. }
  12101. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12102. const Headers &headers,
  12103. ResponseHandler response_handler,
  12104. ContentReceiver content_receiver,
  12105. DownloadProgress progress) {
  12106. if (params.empty()) {
  12107. return Get(path, headers, std::move(response_handler),
  12108. std::move(content_receiver), std::move(progress));
  12109. }
  12110. std::string path_with_query = append_query_params(path, params);
  12111. return Get(path_with_query, headers, std::move(response_handler),
  12112. std::move(content_receiver), std::move(progress));
  12113. }
  12114. inline Result ClientImpl::Head(const std::string &path) {
  12115. return Head(path, Headers());
  12116. }
  12117. inline Result ClientImpl::Head(const std::string &path,
  12118. const Headers &headers) {
  12119. Request req;
  12120. req.method = "HEAD";
  12121. req.headers = headers;
  12122. req.path = path;
  12123. if (max_timeout_msec_ > 0) {
  12124. req.start_time_ = std::chrono::steady_clock::now();
  12125. }
  12126. return send_(std::move(req));
  12127. }
  12128. inline Result ClientImpl::Post(const std::string &path) {
  12129. return Post(path, std::string(), std::string());
  12130. }
  12131. inline Result ClientImpl::Post(const std::string &path,
  12132. const Headers &headers) {
  12133. return Post(path, headers, nullptr, 0, std::string());
  12134. }
  12135. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12136. size_t content_length,
  12137. const std::string &content_type,
  12138. UploadProgress progress) {
  12139. return Post(path, Headers(), body, content_length, content_type, progress);
  12140. }
  12141. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12142. const std::string &content_type,
  12143. UploadProgress progress) {
  12144. return Post(path, Headers(), body, content_type, progress);
  12145. }
  12146. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12147. return Post(path, Headers(), params);
  12148. }
  12149. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12150. ContentProvider content_provider,
  12151. const std::string &content_type,
  12152. UploadProgress progress) {
  12153. return Post(path, Headers(), content_length, std::move(content_provider),
  12154. content_type, progress);
  12155. }
  12156. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12157. ContentProvider content_provider,
  12158. const std::string &content_type,
  12159. ContentReceiver content_receiver,
  12160. UploadProgress progress) {
  12161. return Post(path, Headers(), content_length, std::move(content_provider),
  12162. content_type, std::move(content_receiver), progress);
  12163. }
  12164. inline Result ClientImpl::Post(const std::string &path,
  12165. ContentProviderWithoutLength content_provider,
  12166. const std::string &content_type,
  12167. UploadProgress progress) {
  12168. return Post(path, Headers(), std::move(content_provider), content_type,
  12169. progress);
  12170. }
  12171. inline Result ClientImpl::Post(const std::string &path,
  12172. ContentProviderWithoutLength content_provider,
  12173. const std::string &content_type,
  12174. ContentReceiver content_receiver,
  12175. UploadProgress progress) {
  12176. return Post(path, Headers(), std::move(content_provider), content_type,
  12177. std::move(content_receiver), progress);
  12178. }
  12179. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12180. const Params &params) {
  12181. auto query = detail::params_to_query_str(params);
  12182. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12183. }
  12184. inline Result ClientImpl::Post(const std::string &path,
  12185. const UploadFormDataItems &items,
  12186. UploadProgress progress) {
  12187. return Post(path, Headers(), items, progress);
  12188. }
  12189. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12190. const UploadFormDataItems &items,
  12191. UploadProgress progress) {
  12192. const auto &boundary = detail::make_multipart_data_boundary();
  12193. const auto &content_type =
  12194. detail::serialize_multipart_formdata_get_content_type(boundary);
  12195. auto content_length = detail::get_multipart_content_length(items, boundary);
  12196. return Post(path, headers, content_length,
  12197. detail::make_multipart_content_provider(items, boundary),
  12198. content_type, progress);
  12199. }
  12200. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12201. const UploadFormDataItems &items,
  12202. const std::string &boundary,
  12203. UploadProgress progress) {
  12204. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12205. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12206. }
  12207. const auto &content_type =
  12208. detail::serialize_multipart_formdata_get_content_type(boundary);
  12209. auto content_length = detail::get_multipart_content_length(items, boundary);
  12210. return Post(path, headers, content_length,
  12211. detail::make_multipart_content_provider(items, boundary),
  12212. content_type, progress);
  12213. }
  12214. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12215. const char *body, size_t content_length,
  12216. const std::string &content_type,
  12217. UploadProgress progress) {
  12218. return send_with_content_provider_and_receiver(
  12219. "POST", path, headers, body, content_length, nullptr, nullptr,
  12220. content_type, nullptr, progress);
  12221. }
  12222. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12223. const std::string &body,
  12224. const std::string &content_type,
  12225. UploadProgress progress) {
  12226. return send_with_content_provider_and_receiver(
  12227. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12228. content_type, nullptr, progress);
  12229. }
  12230. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12231. size_t content_length,
  12232. ContentProvider content_provider,
  12233. const std::string &content_type,
  12234. UploadProgress progress) {
  12235. return send_with_content_provider_and_receiver(
  12236. "POST", path, headers, nullptr, content_length,
  12237. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12238. }
  12239. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12240. size_t content_length,
  12241. ContentProvider content_provider,
  12242. const std::string &content_type,
  12243. ContentReceiver content_receiver,
  12244. DownloadProgress progress) {
  12245. return send_with_content_provider_and_receiver(
  12246. "POST", path, headers, nullptr, content_length,
  12247. std::move(content_provider), nullptr, content_type,
  12248. std::move(content_receiver), std::move(progress));
  12249. }
  12250. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12251. ContentProviderWithoutLength content_provider,
  12252. const std::string &content_type,
  12253. UploadProgress progress) {
  12254. return send_with_content_provider_and_receiver(
  12255. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12256. content_type, nullptr, progress);
  12257. }
  12258. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12259. ContentProviderWithoutLength content_provider,
  12260. const std::string &content_type,
  12261. ContentReceiver content_receiver,
  12262. DownloadProgress progress) {
  12263. return send_with_content_provider_and_receiver(
  12264. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12265. content_type, std::move(content_receiver), std::move(progress));
  12266. }
  12267. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12268. const UploadFormDataItems &items,
  12269. const FormDataProviderItems &provider_items,
  12270. UploadProgress progress) {
  12271. const auto &boundary = detail::make_multipart_data_boundary();
  12272. const auto &content_type =
  12273. detail::serialize_multipart_formdata_get_content_type(boundary);
  12274. return send_with_content_provider_and_receiver(
  12275. "POST", path, headers, nullptr, 0, nullptr,
  12276. get_multipart_content_provider(boundary, items, provider_items),
  12277. content_type, nullptr, progress);
  12278. }
  12279. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12280. const std::string &body,
  12281. const std::string &content_type,
  12282. ContentReceiver content_receiver,
  12283. DownloadProgress progress) {
  12284. Request req;
  12285. req.method = "POST";
  12286. req.path = path;
  12287. req.headers = headers;
  12288. req.body = body;
  12289. req.content_receiver =
  12290. [content_receiver](const char *data, size_t data_length,
  12291. size_t /*offset*/, size_t /*total_length*/) {
  12292. return content_receiver(data, data_length);
  12293. };
  12294. req.download_progress = std::move(progress);
  12295. if (max_timeout_msec_ > 0) {
  12296. req.start_time_ = std::chrono::steady_clock::now();
  12297. }
  12298. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12299. return send_(std::move(req));
  12300. }
  12301. inline Result ClientImpl::Put(const std::string &path) {
  12302. return Put(path, std::string(), std::string());
  12303. }
  12304. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12305. return Put(path, headers, nullptr, 0, std::string());
  12306. }
  12307. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12308. size_t content_length,
  12309. const std::string &content_type,
  12310. UploadProgress progress) {
  12311. return Put(path, Headers(), body, content_length, content_type, progress);
  12312. }
  12313. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12314. const std::string &content_type,
  12315. UploadProgress progress) {
  12316. return Put(path, Headers(), body, content_type, progress);
  12317. }
  12318. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12319. return Put(path, Headers(), params);
  12320. }
  12321. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12322. ContentProvider content_provider,
  12323. const std::string &content_type,
  12324. UploadProgress progress) {
  12325. return Put(path, Headers(), content_length, std::move(content_provider),
  12326. content_type, progress);
  12327. }
  12328. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12329. ContentProvider content_provider,
  12330. const std::string &content_type,
  12331. ContentReceiver content_receiver,
  12332. UploadProgress progress) {
  12333. return Put(path, Headers(), content_length, std::move(content_provider),
  12334. content_type, std::move(content_receiver), progress);
  12335. }
  12336. inline Result ClientImpl::Put(const std::string &path,
  12337. ContentProviderWithoutLength content_provider,
  12338. const std::string &content_type,
  12339. UploadProgress progress) {
  12340. return Put(path, Headers(), std::move(content_provider), content_type,
  12341. progress);
  12342. }
  12343. inline Result ClientImpl::Put(const std::string &path,
  12344. ContentProviderWithoutLength content_provider,
  12345. const std::string &content_type,
  12346. ContentReceiver content_receiver,
  12347. UploadProgress progress) {
  12348. return Put(path, Headers(), std::move(content_provider), content_type,
  12349. std::move(content_receiver), progress);
  12350. }
  12351. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12352. const Params &params) {
  12353. auto query = detail::params_to_query_str(params);
  12354. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12355. }
  12356. inline Result ClientImpl::Put(const std::string &path,
  12357. const UploadFormDataItems &items,
  12358. UploadProgress progress) {
  12359. return Put(path, Headers(), items, progress);
  12360. }
  12361. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12362. const UploadFormDataItems &items,
  12363. UploadProgress progress) {
  12364. const auto &boundary = detail::make_multipart_data_boundary();
  12365. const auto &content_type =
  12366. detail::serialize_multipart_formdata_get_content_type(boundary);
  12367. auto content_length = detail::get_multipart_content_length(items, boundary);
  12368. return Put(path, headers, content_length,
  12369. detail::make_multipart_content_provider(items, boundary),
  12370. content_type, progress);
  12371. }
  12372. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12373. const UploadFormDataItems &items,
  12374. const std::string &boundary,
  12375. UploadProgress progress) {
  12376. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12377. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12378. }
  12379. const auto &content_type =
  12380. detail::serialize_multipart_formdata_get_content_type(boundary);
  12381. auto content_length = detail::get_multipart_content_length(items, boundary);
  12382. return Put(path, headers, content_length,
  12383. detail::make_multipart_content_provider(items, boundary),
  12384. content_type, progress);
  12385. }
  12386. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12387. const char *body, size_t content_length,
  12388. const std::string &content_type,
  12389. UploadProgress progress) {
  12390. return send_with_content_provider_and_receiver(
  12391. "PUT", path, headers, body, content_length, nullptr, nullptr,
  12392. content_type, nullptr, progress);
  12393. }
  12394. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12395. const std::string &body,
  12396. const std::string &content_type,
  12397. UploadProgress progress) {
  12398. return send_with_content_provider_and_receiver(
  12399. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12400. content_type, nullptr, progress);
  12401. }
  12402. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12403. size_t content_length,
  12404. ContentProvider content_provider,
  12405. const std::string &content_type,
  12406. UploadProgress progress) {
  12407. return send_with_content_provider_and_receiver(
  12408. "PUT", path, headers, nullptr, content_length,
  12409. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12410. }
  12411. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12412. size_t content_length,
  12413. ContentProvider content_provider,
  12414. const std::string &content_type,
  12415. ContentReceiver content_receiver,
  12416. UploadProgress progress) {
  12417. return send_with_content_provider_and_receiver(
  12418. "PUT", path, headers, nullptr, content_length,
  12419. std::move(content_provider), nullptr, content_type,
  12420. std::move(content_receiver), progress);
  12421. }
  12422. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12423. ContentProviderWithoutLength content_provider,
  12424. const std::string &content_type,
  12425. UploadProgress progress) {
  12426. return send_with_content_provider_and_receiver(
  12427. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12428. content_type, nullptr, progress);
  12429. }
  12430. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12431. ContentProviderWithoutLength content_provider,
  12432. const std::string &content_type,
  12433. ContentReceiver content_receiver,
  12434. UploadProgress progress) {
  12435. return send_with_content_provider_and_receiver(
  12436. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12437. content_type, std::move(content_receiver), progress);
  12438. }
  12439. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12440. const UploadFormDataItems &items,
  12441. const FormDataProviderItems &provider_items,
  12442. UploadProgress progress) {
  12443. const auto &boundary = detail::make_multipart_data_boundary();
  12444. const auto &content_type =
  12445. detail::serialize_multipart_formdata_get_content_type(boundary);
  12446. return send_with_content_provider_and_receiver(
  12447. "PUT", path, headers, nullptr, 0, nullptr,
  12448. get_multipart_content_provider(boundary, items, provider_items),
  12449. content_type, nullptr, progress);
  12450. }
  12451. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12452. const std::string &body,
  12453. const std::string &content_type,
  12454. ContentReceiver content_receiver,
  12455. DownloadProgress progress) {
  12456. Request req;
  12457. req.method = "PUT";
  12458. req.path = path;
  12459. req.headers = headers;
  12460. req.body = body;
  12461. req.content_receiver =
  12462. [content_receiver](const char *data, size_t data_length,
  12463. size_t /*offset*/, size_t /*total_length*/) {
  12464. return content_receiver(data, data_length);
  12465. };
  12466. req.download_progress = std::move(progress);
  12467. if (max_timeout_msec_ > 0) {
  12468. req.start_time_ = std::chrono::steady_clock::now();
  12469. }
  12470. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12471. return send_(std::move(req));
  12472. }
  12473. inline Result ClientImpl::Patch(const std::string &path) {
  12474. return Patch(path, std::string(), std::string());
  12475. }
  12476. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12477. UploadProgress progress) {
  12478. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12479. }
  12480. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12481. size_t content_length,
  12482. const std::string &content_type,
  12483. UploadProgress progress) {
  12484. return Patch(path, Headers(), body, content_length, content_type, progress);
  12485. }
  12486. inline Result ClientImpl::Patch(const std::string &path,
  12487. const std::string &body,
  12488. const std::string &content_type,
  12489. UploadProgress progress) {
  12490. return Patch(path, Headers(), body, content_type, progress);
  12491. }
  12492. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12493. return Patch(path, Headers(), params);
  12494. }
  12495. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12496. ContentProvider content_provider,
  12497. const std::string &content_type,
  12498. UploadProgress progress) {
  12499. return Patch(path, Headers(), content_length, std::move(content_provider),
  12500. content_type, progress);
  12501. }
  12502. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12503. ContentProvider content_provider,
  12504. const std::string &content_type,
  12505. ContentReceiver content_receiver,
  12506. UploadProgress progress) {
  12507. return Patch(path, Headers(), content_length, std::move(content_provider),
  12508. content_type, std::move(content_receiver), progress);
  12509. }
  12510. inline Result ClientImpl::Patch(const std::string &path,
  12511. ContentProviderWithoutLength content_provider,
  12512. const std::string &content_type,
  12513. UploadProgress progress) {
  12514. return Patch(path, Headers(), std::move(content_provider), content_type,
  12515. progress);
  12516. }
  12517. inline Result ClientImpl::Patch(const std::string &path,
  12518. ContentProviderWithoutLength content_provider,
  12519. const std::string &content_type,
  12520. ContentReceiver content_receiver,
  12521. UploadProgress progress) {
  12522. return Patch(path, Headers(), std::move(content_provider), content_type,
  12523. std::move(content_receiver), progress);
  12524. }
  12525. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12526. const Params &params) {
  12527. auto query = detail::params_to_query_str(params);
  12528. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12529. }
  12530. inline Result ClientImpl::Patch(const std::string &path,
  12531. const UploadFormDataItems &items,
  12532. UploadProgress progress) {
  12533. return Patch(path, Headers(), items, progress);
  12534. }
  12535. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12536. const UploadFormDataItems &items,
  12537. UploadProgress progress) {
  12538. const auto &boundary = detail::make_multipart_data_boundary();
  12539. const auto &content_type =
  12540. detail::serialize_multipart_formdata_get_content_type(boundary);
  12541. auto content_length = detail::get_multipart_content_length(items, boundary);
  12542. return Patch(path, headers, content_length,
  12543. detail::make_multipart_content_provider(items, boundary),
  12544. content_type, progress);
  12545. }
  12546. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12547. const UploadFormDataItems &items,
  12548. const std::string &boundary,
  12549. UploadProgress progress) {
  12550. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12551. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12552. }
  12553. const auto &content_type =
  12554. detail::serialize_multipart_formdata_get_content_type(boundary);
  12555. auto content_length = detail::get_multipart_content_length(items, boundary);
  12556. return Patch(path, headers, content_length,
  12557. detail::make_multipart_content_provider(items, boundary),
  12558. content_type, progress);
  12559. }
  12560. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12561. const char *body, size_t content_length,
  12562. const std::string &content_type,
  12563. UploadProgress progress) {
  12564. return send_with_content_provider_and_receiver(
  12565. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12566. content_type, nullptr, progress);
  12567. }
  12568. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12569. const std::string &body,
  12570. const std::string &content_type,
  12571. UploadProgress progress) {
  12572. return send_with_content_provider_and_receiver(
  12573. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12574. content_type, nullptr, progress);
  12575. }
  12576. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12577. size_t content_length,
  12578. ContentProvider content_provider,
  12579. const std::string &content_type,
  12580. UploadProgress progress) {
  12581. return send_with_content_provider_and_receiver(
  12582. "PATCH", path, headers, nullptr, content_length,
  12583. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12584. }
  12585. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12586. size_t content_length,
  12587. ContentProvider content_provider,
  12588. const std::string &content_type,
  12589. ContentReceiver content_receiver,
  12590. UploadProgress progress) {
  12591. return send_with_content_provider_and_receiver(
  12592. "PATCH", path, headers, nullptr, content_length,
  12593. std::move(content_provider), nullptr, content_type,
  12594. std::move(content_receiver), progress);
  12595. }
  12596. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12597. ContentProviderWithoutLength content_provider,
  12598. const std::string &content_type,
  12599. UploadProgress progress) {
  12600. return send_with_content_provider_and_receiver(
  12601. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12602. content_type, nullptr, progress);
  12603. }
  12604. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12605. ContentProviderWithoutLength content_provider,
  12606. const std::string &content_type,
  12607. ContentReceiver content_receiver,
  12608. UploadProgress progress) {
  12609. return send_with_content_provider_and_receiver(
  12610. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12611. content_type, std::move(content_receiver), progress);
  12612. }
  12613. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12614. const UploadFormDataItems &items,
  12615. const FormDataProviderItems &provider_items,
  12616. UploadProgress progress) {
  12617. const auto &boundary = detail::make_multipart_data_boundary();
  12618. const auto &content_type =
  12619. detail::serialize_multipart_formdata_get_content_type(boundary);
  12620. return send_with_content_provider_and_receiver(
  12621. "PATCH", path, headers, nullptr, 0, nullptr,
  12622. get_multipart_content_provider(boundary, items, provider_items),
  12623. content_type, nullptr, progress);
  12624. }
  12625. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12626. const std::string &body,
  12627. const std::string &content_type,
  12628. ContentReceiver content_receiver,
  12629. DownloadProgress progress) {
  12630. Request req;
  12631. req.method = "PATCH";
  12632. req.path = path;
  12633. req.headers = headers;
  12634. req.body = body;
  12635. req.content_receiver =
  12636. [content_receiver](const char *data, size_t data_length,
  12637. size_t /*offset*/, size_t /*total_length*/) {
  12638. return content_receiver(data, data_length);
  12639. };
  12640. req.download_progress = std::move(progress);
  12641. if (max_timeout_msec_ > 0) {
  12642. req.start_time_ = std::chrono::steady_clock::now();
  12643. }
  12644. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12645. return send_(std::move(req));
  12646. }
  12647. inline Result ClientImpl::Delete(const std::string &path,
  12648. DownloadProgress progress) {
  12649. return Delete(path, Headers(), std::string(), std::string(), progress);
  12650. }
  12651. inline Result ClientImpl::Delete(const std::string &path,
  12652. const Headers &headers,
  12653. DownloadProgress progress) {
  12654. return Delete(path, headers, std::string(), std::string(), progress);
  12655. }
  12656. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12657. size_t content_length,
  12658. const std::string &content_type,
  12659. DownloadProgress progress) {
  12660. return Delete(path, Headers(), body, content_length, content_type, progress);
  12661. }
  12662. inline Result ClientImpl::Delete(const std::string &path,
  12663. const std::string &body,
  12664. const std::string &content_type,
  12665. DownloadProgress progress) {
  12666. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12667. progress);
  12668. }
  12669. inline Result ClientImpl::Delete(const std::string &path,
  12670. const Headers &headers,
  12671. const std::string &body,
  12672. const std::string &content_type,
  12673. DownloadProgress progress) {
  12674. return Delete(path, headers, body.data(), body.size(), content_type,
  12675. progress);
  12676. }
  12677. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12678. DownloadProgress progress) {
  12679. return Delete(path, Headers(), params, progress);
  12680. }
  12681. inline Result ClientImpl::Delete(const std::string &path,
  12682. const Headers &headers, const Params &params,
  12683. DownloadProgress progress) {
  12684. auto query = detail::params_to_query_str(params);
  12685. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12686. progress);
  12687. }
  12688. inline Result ClientImpl::Delete(const std::string &path,
  12689. const Headers &headers, const char *body,
  12690. size_t content_length,
  12691. const std::string &content_type,
  12692. DownloadProgress progress) {
  12693. Request req;
  12694. req.method = "DELETE";
  12695. req.headers = headers;
  12696. req.path = path;
  12697. req.download_progress = std::move(progress);
  12698. if (max_timeout_msec_ > 0) {
  12699. req.start_time_ = std::chrono::steady_clock::now();
  12700. }
  12701. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12702. req.body.assign(body, content_length);
  12703. return send_(std::move(req));
  12704. }
  12705. inline Result ClientImpl::Options(const std::string &path) {
  12706. return Options(path, Headers());
  12707. }
  12708. inline Result ClientImpl::Options(const std::string &path,
  12709. const Headers &headers) {
  12710. Request req;
  12711. req.method = "OPTIONS";
  12712. req.headers = headers;
  12713. req.path = path;
  12714. if (max_timeout_msec_ > 0) {
  12715. req.start_time_ = std::chrono::steady_clock::now();
  12716. }
  12717. return send_(std::move(req));
  12718. }
  12719. inline void ClientImpl::stop() {
  12720. std::lock_guard<std::mutex> guard(socket_mutex_);
  12721. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12722. // do is to shutdown_socket, so that threads using this socket suddenly
  12723. // discover they can't read/write any more and error out. Everything else
  12724. // (closing the socket, shutting ssl down) is unsafe because these actions
  12725. // are not thread-safe.
  12726. if (socket_requests_in_flight_ > 0) {
  12727. shutdown_socket(socket_);
  12728. // Aside from that, we set a flag for the socket to be closed when we're
  12729. // done.
  12730. socket_should_be_closed_when_request_is_done_ = true;
  12731. return;
  12732. }
  12733. disconnect(/*gracefully=*/true);
  12734. }
  12735. inline std::string ClientImpl::host() const { return host_; }
  12736. inline int ClientImpl::port() const { return port_; }
  12737. inline size_t ClientImpl::is_socket_open() const {
  12738. std::lock_guard<std::mutex> guard(socket_mutex_);
  12739. return socket_.is_open();
  12740. }
  12741. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12742. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12743. connection_timeout_sec_ = sec;
  12744. connection_timeout_usec_ = usec;
  12745. }
  12746. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12747. read_timeout_sec_ = sec;
  12748. read_timeout_usec_ = usec;
  12749. }
  12750. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12751. write_timeout_sec_ = sec;
  12752. write_timeout_usec_ = usec;
  12753. }
  12754. inline void ClientImpl::set_max_timeout(time_t msec) {
  12755. max_timeout_msec_ = msec;
  12756. }
  12757. inline void ClientImpl::set_basic_auth(const std::string &username,
  12758. const std::string &password) {
  12759. basic_auth_username_ = username;
  12760. basic_auth_password_ = password;
  12761. }
  12762. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12763. bearer_token_auth_token_ = token;
  12764. }
  12765. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12766. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12767. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12768. inline void
  12769. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12770. addr_map_ = std::move(addr_map);
  12771. }
  12772. inline void ClientImpl::set_default_headers(Headers headers) {
  12773. default_headers_ = std::move(headers);
  12774. }
  12775. inline void ClientImpl::set_header_writer(
  12776. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12777. header_writer_ = writer;
  12778. }
  12779. inline void ClientImpl::set_address_family(int family) {
  12780. address_family_ = family;
  12781. }
  12782. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12783. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12784. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12785. socket_options_ = std::move(socket_options);
  12786. }
  12787. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12788. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12789. inline void ClientImpl::set_payload_max_length(size_t length) {
  12790. payload_max_length_ = length;
  12791. has_payload_max_length_ = true;
  12792. }
  12793. inline void ClientImpl::set_interface(const std::string &intf) {
  12794. interface_ = intf;
  12795. }
  12796. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12797. proxy_host_ = host;
  12798. proxy_port_ = port;
  12799. std::lock_guard<std::mutex> guard(socket_mutex_);
  12800. disconnect(/*gracefully=*/true);
  12801. }
  12802. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12803. const std::string &password) {
  12804. proxy_basic_auth_username_ = username;
  12805. proxy_basic_auth_password_ = password;
  12806. }
  12807. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12808. proxy_bearer_token_auth_token_ = token;
  12809. }
  12810. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12811. std::vector<detail::NoProxyEntry> parsed;
  12812. parsed.reserve(patterns.size());
  12813. for (const auto &p : patterns) {
  12814. auto trimmed = detail::trim_copy(p);
  12815. if (trimmed.empty()) { continue; }
  12816. detail::NoProxyEntry entry;
  12817. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  12818. parsed.push_back(std::move(entry));
  12819. }
  12820. }
  12821. no_proxy_entries_ = std::move(parsed);
  12822. std::lock_guard<std::mutex> guard(socket_mutex_);
  12823. disconnect(/*gracefully=*/true);
  12824. }
  12825. #ifdef CPPHTTPLIB_SSL_ENABLED
  12826. inline void ClientImpl::set_digest_auth(const std::string &username,
  12827. const std::string &password) {
  12828. digest_auth_username_ = username;
  12829. digest_auth_password_ = password;
  12830. }
  12831. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12832. const std::string &ca_cert_dir_path) {
  12833. ca_cert_file_path_ = ca_cert_file_path;
  12834. ca_cert_dir_path_ = ca_cert_dir_path;
  12835. }
  12836. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12837. const std::string &password) {
  12838. proxy_digest_auth_username_ = username;
  12839. proxy_digest_auth_password_ = password;
  12840. }
  12841. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12842. server_certificate_verification_ = enabled;
  12843. }
  12844. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12845. server_hostname_verification_ = enabled;
  12846. }
  12847. inline void ClientImpl::enable_system_ca(bool enabled) {
  12848. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  12849. }
  12850. #endif
  12851. inline void ClientImpl::set_logger(Logger logger) {
  12852. logger_ = std::move(logger);
  12853. }
  12854. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12855. error_logger_ = std::move(error_logger);
  12856. }
  12857. /*
  12858. * SSL/TLS Common Implementation
  12859. */
  12860. inline ClientConnection::~ClientConnection() {
  12861. #ifdef CPPHTTPLIB_SSL_ENABLED
  12862. if (session) {
  12863. tls::shutdown(session, true);
  12864. tls::free_session(session);
  12865. session = nullptr;
  12866. }
  12867. #endif
  12868. if (sock != INVALID_SOCKET) {
  12869. detail::close_socket(sock);
  12870. sock = INVALID_SOCKET;
  12871. }
  12872. }
  12873. // Universal client implementation
  12874. inline Client::Client(const std::string &scheme_host_port)
  12875. : Client(scheme_host_port, std::string(), std::string()) {}
  12876. inline Client::Client(const std::string &scheme_host_port,
  12877. const std::string &client_cert_path,
  12878. const std::string &client_key_path) {
  12879. detail::UrlComponents uc;
  12880. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12881. auto &scheme = uc.scheme;
  12882. #ifdef CPPHTTPLIB_SSL_ENABLED
  12883. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12884. #else
  12885. if (!scheme.empty() && scheme != "http") {
  12886. #endif
  12887. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12888. std::string msg = "'" + scheme + "' scheme is not supported.";
  12889. throw std::invalid_argument(msg);
  12890. #endif
  12891. return;
  12892. }
  12893. auto is_ssl = scheme == "https";
  12894. auto host = std::move(uc.host);
  12895. auto port = is_ssl ? 443 : 80;
  12896. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12897. if (is_ssl) {
  12898. #ifdef CPPHTTPLIB_SSL_ENABLED
  12899. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12900. client_key_path);
  12901. is_ssl_ = is_ssl;
  12902. #endif
  12903. } else {
  12904. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12905. client_key_path);
  12906. }
  12907. } else {
  12908. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12909. // if port param below changes.
  12910. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12911. client_cert_path, client_key_path);
  12912. }
  12913. }
  12914. inline Client::Client(const std::string &host, int port)
  12915. : Client(host, port, std::string(), std::string()) {}
  12916. inline Client::Client(const std::string &host, int port,
  12917. const std::string &client_cert_path,
  12918. const std::string &client_key_path)
  12919. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12920. client_key_path)) {}
  12921. inline Client::~Client() = default;
  12922. inline bool Client::is_valid() const {
  12923. return cli_ != nullptr && cli_->is_valid();
  12924. }
  12925. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12926. return cli_->Get(path, std::move(progress));
  12927. }
  12928. inline Result Client::Get(const std::string &path, const Headers &headers,
  12929. DownloadProgress progress) {
  12930. return cli_->Get(path, headers, std::move(progress));
  12931. }
  12932. inline Result Client::Get(const std::string &path,
  12933. ContentReceiver content_receiver,
  12934. DownloadProgress progress) {
  12935. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12936. }
  12937. inline Result Client::Get(const std::string &path, const Headers &headers,
  12938. ContentReceiver content_receiver,
  12939. DownloadProgress progress) {
  12940. return cli_->Get(path, headers, std::move(content_receiver),
  12941. std::move(progress));
  12942. }
  12943. inline Result Client::Get(const std::string &path,
  12944. ResponseHandler response_handler,
  12945. ContentReceiver content_receiver,
  12946. DownloadProgress progress) {
  12947. return cli_->Get(path, std::move(response_handler),
  12948. std::move(content_receiver), std::move(progress));
  12949. }
  12950. inline Result Client::Get(const std::string &path, const Headers &headers,
  12951. ResponseHandler response_handler,
  12952. ContentReceiver content_receiver,
  12953. DownloadProgress progress) {
  12954. return cli_->Get(path, headers, std::move(response_handler),
  12955. std::move(content_receiver), std::move(progress));
  12956. }
  12957. inline Result Client::Get(const std::string &path, const Params &params,
  12958. const Headers &headers, DownloadProgress progress) {
  12959. return cli_->Get(path, params, headers, std::move(progress));
  12960. }
  12961. inline Result Client::Get(const std::string &path, const Params &params,
  12962. const Headers &headers,
  12963. ContentReceiver content_receiver,
  12964. DownloadProgress progress) {
  12965. return cli_->Get(path, params, headers, std::move(content_receiver),
  12966. std::move(progress));
  12967. }
  12968. inline Result Client::Get(const std::string &path, const Params &params,
  12969. const Headers &headers,
  12970. ResponseHandler response_handler,
  12971. ContentReceiver content_receiver,
  12972. DownloadProgress progress) {
  12973. return cli_->Get(path, params, headers, std::move(response_handler),
  12974. std::move(content_receiver), std::move(progress));
  12975. }
  12976. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  12977. inline Result Client::Head(const std::string &path, const Headers &headers) {
  12978. return cli_->Head(path, headers);
  12979. }
  12980. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  12981. inline Result Client::Post(const std::string &path, const Headers &headers) {
  12982. return cli_->Post(path, headers);
  12983. }
  12984. inline Result Client::Post(const std::string &path, const char *body,
  12985. size_t content_length,
  12986. const std::string &content_type,
  12987. UploadProgress progress) {
  12988. return cli_->Post(path, body, content_length, content_type, progress);
  12989. }
  12990. inline Result Client::Post(const std::string &path, const Headers &headers,
  12991. const char *body, size_t content_length,
  12992. const std::string &content_type,
  12993. UploadProgress progress) {
  12994. return cli_->Post(path, headers, body, content_length, content_type,
  12995. progress);
  12996. }
  12997. inline Result Client::Post(const std::string &path, const std::string &body,
  12998. const std::string &content_type,
  12999. UploadProgress progress) {
  13000. return cli_->Post(path, body, content_type, progress);
  13001. }
  13002. inline Result Client::Post(const std::string &path, const Headers &headers,
  13003. const std::string &body,
  13004. const std::string &content_type,
  13005. UploadProgress progress) {
  13006. return cli_->Post(path, headers, body, content_type, progress);
  13007. }
  13008. inline Result Client::Post(const std::string &path, size_t content_length,
  13009. ContentProvider content_provider,
  13010. const std::string &content_type,
  13011. UploadProgress progress) {
  13012. return cli_->Post(path, content_length, std::move(content_provider),
  13013. content_type, progress);
  13014. }
  13015. inline Result Client::Post(const std::string &path, size_t content_length,
  13016. ContentProvider content_provider,
  13017. const std::string &content_type,
  13018. ContentReceiver content_receiver,
  13019. UploadProgress progress) {
  13020. return cli_->Post(path, content_length, std::move(content_provider),
  13021. content_type, std::move(content_receiver), progress);
  13022. }
  13023. inline Result Client::Post(const std::string &path,
  13024. ContentProviderWithoutLength content_provider,
  13025. const std::string &content_type,
  13026. UploadProgress progress) {
  13027. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13028. }
  13029. inline Result Client::Post(const std::string &path,
  13030. ContentProviderWithoutLength content_provider,
  13031. const std::string &content_type,
  13032. ContentReceiver content_receiver,
  13033. UploadProgress progress) {
  13034. return cli_->Post(path, std::move(content_provider), content_type,
  13035. std::move(content_receiver), progress);
  13036. }
  13037. inline Result Client::Post(const std::string &path, const Headers &headers,
  13038. size_t content_length,
  13039. ContentProvider content_provider,
  13040. const std::string &content_type,
  13041. UploadProgress progress) {
  13042. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13043. content_type, progress);
  13044. }
  13045. inline Result Client::Post(const std::string &path, const Headers &headers,
  13046. size_t content_length,
  13047. ContentProvider content_provider,
  13048. const std::string &content_type,
  13049. ContentReceiver content_receiver,
  13050. DownloadProgress progress) {
  13051. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13052. content_type, std::move(content_receiver), progress);
  13053. }
  13054. inline Result Client::Post(const std::string &path, const Headers &headers,
  13055. ContentProviderWithoutLength content_provider,
  13056. const std::string &content_type,
  13057. UploadProgress progress) {
  13058. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13059. progress);
  13060. }
  13061. inline Result Client::Post(const std::string &path, const Headers &headers,
  13062. ContentProviderWithoutLength content_provider,
  13063. const std::string &content_type,
  13064. ContentReceiver content_receiver,
  13065. DownloadProgress progress) {
  13066. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13067. std::move(content_receiver), progress);
  13068. }
  13069. inline Result Client::Post(const std::string &path, const Params &params) {
  13070. return cli_->Post(path, params);
  13071. }
  13072. inline Result Client::Post(const std::string &path, const Headers &headers,
  13073. const Params &params) {
  13074. return cli_->Post(path, headers, params);
  13075. }
  13076. inline Result Client::Post(const std::string &path,
  13077. const UploadFormDataItems &items,
  13078. UploadProgress progress) {
  13079. return cli_->Post(path, items, progress);
  13080. }
  13081. inline Result Client::Post(const std::string &path, const Headers &headers,
  13082. const UploadFormDataItems &items,
  13083. UploadProgress progress) {
  13084. return cli_->Post(path, headers, items, progress);
  13085. }
  13086. inline Result Client::Post(const std::string &path, const Headers &headers,
  13087. const UploadFormDataItems &items,
  13088. const std::string &boundary,
  13089. UploadProgress progress) {
  13090. return cli_->Post(path, headers, items, boundary, progress);
  13091. }
  13092. inline Result Client::Post(const std::string &path, const Headers &headers,
  13093. const UploadFormDataItems &items,
  13094. const FormDataProviderItems &provider_items,
  13095. UploadProgress progress) {
  13096. return cli_->Post(path, headers, items, provider_items, progress);
  13097. }
  13098. inline Result Client::Post(const std::string &path, const Headers &headers,
  13099. const std::string &body,
  13100. const std::string &content_type,
  13101. ContentReceiver content_receiver,
  13102. DownloadProgress progress) {
  13103. return cli_->Post(path, headers, body, content_type,
  13104. std::move(content_receiver), progress);
  13105. }
  13106. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13107. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13108. return cli_->Put(path, headers);
  13109. }
  13110. inline Result Client::Put(const std::string &path, const char *body,
  13111. size_t content_length,
  13112. const std::string &content_type,
  13113. UploadProgress progress) {
  13114. return cli_->Put(path, body, content_length, content_type, progress);
  13115. }
  13116. inline Result Client::Put(const std::string &path, const Headers &headers,
  13117. const char *body, size_t content_length,
  13118. const std::string &content_type,
  13119. UploadProgress progress) {
  13120. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13121. }
  13122. inline Result Client::Put(const std::string &path, const std::string &body,
  13123. const std::string &content_type,
  13124. UploadProgress progress) {
  13125. return cli_->Put(path, body, content_type, progress);
  13126. }
  13127. inline Result Client::Put(const std::string &path, const Headers &headers,
  13128. const std::string &body,
  13129. const std::string &content_type,
  13130. UploadProgress progress) {
  13131. return cli_->Put(path, headers, body, content_type, progress);
  13132. }
  13133. inline Result Client::Put(const std::string &path, size_t content_length,
  13134. ContentProvider content_provider,
  13135. const std::string &content_type,
  13136. UploadProgress progress) {
  13137. return cli_->Put(path, content_length, std::move(content_provider),
  13138. content_type, progress);
  13139. }
  13140. inline Result Client::Put(const std::string &path, size_t content_length,
  13141. ContentProvider content_provider,
  13142. const std::string &content_type,
  13143. ContentReceiver content_receiver,
  13144. UploadProgress progress) {
  13145. return cli_->Put(path, content_length, std::move(content_provider),
  13146. content_type, std::move(content_receiver), progress);
  13147. }
  13148. inline Result Client::Put(const std::string &path,
  13149. ContentProviderWithoutLength content_provider,
  13150. const std::string &content_type,
  13151. UploadProgress progress) {
  13152. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13153. }
  13154. inline Result Client::Put(const std::string &path,
  13155. ContentProviderWithoutLength content_provider,
  13156. const std::string &content_type,
  13157. ContentReceiver content_receiver,
  13158. UploadProgress progress) {
  13159. return cli_->Put(path, std::move(content_provider), content_type,
  13160. std::move(content_receiver), progress);
  13161. }
  13162. inline Result Client::Put(const std::string &path, const Headers &headers,
  13163. size_t content_length,
  13164. ContentProvider content_provider,
  13165. const std::string &content_type,
  13166. UploadProgress progress) {
  13167. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13168. content_type, progress);
  13169. }
  13170. inline Result Client::Put(const std::string &path, const Headers &headers,
  13171. size_t content_length,
  13172. ContentProvider content_provider,
  13173. const std::string &content_type,
  13174. ContentReceiver content_receiver,
  13175. UploadProgress progress) {
  13176. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13177. content_type, std::move(content_receiver), progress);
  13178. }
  13179. inline Result Client::Put(const std::string &path, const Headers &headers,
  13180. ContentProviderWithoutLength content_provider,
  13181. const std::string &content_type,
  13182. UploadProgress progress) {
  13183. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13184. progress);
  13185. }
  13186. inline Result Client::Put(const std::string &path, const Headers &headers,
  13187. ContentProviderWithoutLength content_provider,
  13188. const std::string &content_type,
  13189. ContentReceiver content_receiver,
  13190. UploadProgress progress) {
  13191. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13192. std::move(content_receiver), progress);
  13193. }
  13194. inline Result Client::Put(const std::string &path, const Params &params) {
  13195. return cli_->Put(path, params);
  13196. }
  13197. inline Result Client::Put(const std::string &path, const Headers &headers,
  13198. const Params &params) {
  13199. return cli_->Put(path, headers, params);
  13200. }
  13201. inline Result Client::Put(const std::string &path,
  13202. const UploadFormDataItems &items,
  13203. UploadProgress progress) {
  13204. return cli_->Put(path, items, progress);
  13205. }
  13206. inline Result Client::Put(const std::string &path, const Headers &headers,
  13207. const UploadFormDataItems &items,
  13208. UploadProgress progress) {
  13209. return cli_->Put(path, headers, items, progress);
  13210. }
  13211. inline Result Client::Put(const std::string &path, const Headers &headers,
  13212. const UploadFormDataItems &items,
  13213. const std::string &boundary,
  13214. UploadProgress progress) {
  13215. return cli_->Put(path, headers, items, boundary, progress);
  13216. }
  13217. inline Result Client::Put(const std::string &path, const Headers &headers,
  13218. const UploadFormDataItems &items,
  13219. const FormDataProviderItems &provider_items,
  13220. UploadProgress progress) {
  13221. return cli_->Put(path, headers, items, provider_items, progress);
  13222. }
  13223. inline Result Client::Put(const std::string &path, const Headers &headers,
  13224. const std::string &body,
  13225. const std::string &content_type,
  13226. ContentReceiver content_receiver,
  13227. DownloadProgress progress) {
  13228. return cli_->Put(path, headers, body, content_type, content_receiver,
  13229. progress);
  13230. }
  13231. inline Result Client::Patch(const std::string &path) {
  13232. return cli_->Patch(path);
  13233. }
  13234. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13235. return cli_->Patch(path, headers);
  13236. }
  13237. inline Result Client::Patch(const std::string &path, const char *body,
  13238. size_t content_length,
  13239. const std::string &content_type,
  13240. UploadProgress progress) {
  13241. return cli_->Patch(path, body, content_length, content_type, progress);
  13242. }
  13243. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13244. const char *body, size_t content_length,
  13245. const std::string &content_type,
  13246. UploadProgress progress) {
  13247. return cli_->Patch(path, headers, body, content_length, content_type,
  13248. progress);
  13249. }
  13250. inline Result Client::Patch(const std::string &path, const std::string &body,
  13251. const std::string &content_type,
  13252. UploadProgress progress) {
  13253. return cli_->Patch(path, body, content_type, progress);
  13254. }
  13255. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13256. const std::string &body,
  13257. const std::string &content_type,
  13258. UploadProgress progress) {
  13259. return cli_->Patch(path, headers, body, content_type, progress);
  13260. }
  13261. inline Result Client::Patch(const std::string &path, size_t content_length,
  13262. ContentProvider content_provider,
  13263. const std::string &content_type,
  13264. UploadProgress progress) {
  13265. return cli_->Patch(path, content_length, std::move(content_provider),
  13266. content_type, progress);
  13267. }
  13268. inline Result Client::Patch(const std::string &path, size_t content_length,
  13269. ContentProvider content_provider,
  13270. const std::string &content_type,
  13271. ContentReceiver content_receiver,
  13272. UploadProgress progress) {
  13273. return cli_->Patch(path, content_length, std::move(content_provider),
  13274. content_type, std::move(content_receiver), progress);
  13275. }
  13276. inline Result Client::Patch(const std::string &path,
  13277. ContentProviderWithoutLength content_provider,
  13278. const std::string &content_type,
  13279. UploadProgress progress) {
  13280. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13281. }
  13282. inline Result Client::Patch(const std::string &path,
  13283. ContentProviderWithoutLength content_provider,
  13284. const std::string &content_type,
  13285. ContentReceiver content_receiver,
  13286. UploadProgress progress) {
  13287. return cli_->Patch(path, std::move(content_provider), content_type,
  13288. std::move(content_receiver), progress);
  13289. }
  13290. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13291. size_t content_length,
  13292. ContentProvider content_provider,
  13293. const std::string &content_type,
  13294. UploadProgress progress) {
  13295. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13296. content_type, progress);
  13297. }
  13298. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13299. size_t content_length,
  13300. ContentProvider content_provider,
  13301. const std::string &content_type,
  13302. ContentReceiver content_receiver,
  13303. UploadProgress progress) {
  13304. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13305. content_type, std::move(content_receiver), progress);
  13306. }
  13307. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13308. ContentProviderWithoutLength content_provider,
  13309. const std::string &content_type,
  13310. UploadProgress progress) {
  13311. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13312. progress);
  13313. }
  13314. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13315. ContentProviderWithoutLength content_provider,
  13316. const std::string &content_type,
  13317. ContentReceiver content_receiver,
  13318. UploadProgress progress) {
  13319. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13320. std::move(content_receiver), progress);
  13321. }
  13322. inline Result Client::Patch(const std::string &path, const Params &params) {
  13323. return cli_->Patch(path, params);
  13324. }
  13325. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13326. const Params &params) {
  13327. return cli_->Patch(path, headers, params);
  13328. }
  13329. inline Result Client::Patch(const std::string &path,
  13330. const UploadFormDataItems &items,
  13331. UploadProgress progress) {
  13332. return cli_->Patch(path, items, progress);
  13333. }
  13334. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13335. const UploadFormDataItems &items,
  13336. UploadProgress progress) {
  13337. return cli_->Patch(path, headers, items, progress);
  13338. }
  13339. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13340. const UploadFormDataItems &items,
  13341. const std::string &boundary,
  13342. UploadProgress progress) {
  13343. return cli_->Patch(path, headers, items, boundary, progress);
  13344. }
  13345. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13346. const UploadFormDataItems &items,
  13347. const FormDataProviderItems &provider_items,
  13348. UploadProgress progress) {
  13349. return cli_->Patch(path, headers, items, provider_items, progress);
  13350. }
  13351. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13352. const std::string &body,
  13353. const std::string &content_type,
  13354. ContentReceiver content_receiver,
  13355. DownloadProgress progress) {
  13356. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13357. progress);
  13358. }
  13359. inline Result Client::Delete(const std::string &path,
  13360. DownloadProgress progress) {
  13361. return cli_->Delete(path, progress);
  13362. }
  13363. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13364. DownloadProgress progress) {
  13365. return cli_->Delete(path, headers, progress);
  13366. }
  13367. inline Result Client::Delete(const std::string &path, const char *body,
  13368. size_t content_length,
  13369. const std::string &content_type,
  13370. DownloadProgress progress) {
  13371. return cli_->Delete(path, body, content_length, content_type, progress);
  13372. }
  13373. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13374. const char *body, size_t content_length,
  13375. const std::string &content_type,
  13376. DownloadProgress progress) {
  13377. return cli_->Delete(path, headers, body, content_length, content_type,
  13378. progress);
  13379. }
  13380. inline Result Client::Delete(const std::string &path, const std::string &body,
  13381. const std::string &content_type,
  13382. DownloadProgress progress) {
  13383. return cli_->Delete(path, body, content_type, progress);
  13384. }
  13385. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13386. const std::string &body,
  13387. const std::string &content_type,
  13388. DownloadProgress progress) {
  13389. return cli_->Delete(path, headers, body, content_type, progress);
  13390. }
  13391. inline Result Client::Delete(const std::string &path, const Params &params,
  13392. DownloadProgress progress) {
  13393. return cli_->Delete(path, params, progress);
  13394. }
  13395. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13396. const Params &params, DownloadProgress progress) {
  13397. return cli_->Delete(path, headers, params, progress);
  13398. }
  13399. inline Result Client::Options(const std::string &path) {
  13400. return cli_->Options(path);
  13401. }
  13402. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13403. return cli_->Options(path, headers);
  13404. }
  13405. inline ClientImpl::StreamHandle
  13406. Client::open_stream(const std::string &method, const std::string &path,
  13407. const Params &params, const Headers &headers,
  13408. const std::string &body, const std::string &content_type) {
  13409. return cli_->open_stream(method, path, params, headers, body, content_type);
  13410. }
  13411. inline bool Client::send(Request &req, Response &res, Error &error) {
  13412. return cli_->send(req, res, error);
  13413. }
  13414. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13415. inline void Client::stop() { cli_->stop(); }
  13416. inline std::string Client::host() const { return cli_->host(); }
  13417. inline int Client::port() const { return cli_->port(); }
  13418. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13419. inline socket_t Client::socket() const { return cli_->socket(); }
  13420. inline void
  13421. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13422. cli_->set_hostname_addr_map(std::move(addr_map));
  13423. }
  13424. inline void Client::set_default_headers(Headers headers) {
  13425. cli_->set_default_headers(std::move(headers));
  13426. }
  13427. inline void Client::set_header_writer(
  13428. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13429. cli_->set_header_writer(writer);
  13430. }
  13431. inline void Client::set_address_family(int family) {
  13432. cli_->set_address_family(family);
  13433. }
  13434. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13435. inline void Client::set_socket_options(SocketOptions socket_options) {
  13436. cli_->set_socket_options(std::move(socket_options));
  13437. }
  13438. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13439. cli_->set_connection_timeout(sec, usec);
  13440. }
  13441. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13442. cli_->set_read_timeout(sec, usec);
  13443. }
  13444. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13445. cli_->set_write_timeout(sec, usec);
  13446. }
  13447. inline void Client::set_basic_auth(const std::string &username,
  13448. const std::string &password) {
  13449. cli_->set_basic_auth(username, password);
  13450. }
  13451. inline void Client::set_bearer_token_auth(const std::string &token) {
  13452. cli_->set_bearer_token_auth(token);
  13453. }
  13454. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13455. inline void Client::set_follow_location(bool on) {
  13456. cli_->set_follow_location(on);
  13457. }
  13458. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13459. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13460. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13461. inline void Client::set_payload_max_length(size_t length) {
  13462. cli_->set_payload_max_length(length);
  13463. }
  13464. inline void Client::set_interface(const std::string &intf) {
  13465. cli_->set_interface(intf);
  13466. }
  13467. inline void Client::set_proxy(const std::string &host, int port) {
  13468. cli_->set_proxy(host, port);
  13469. }
  13470. inline void Client::set_proxy_basic_auth(const std::string &username,
  13471. const std::string &password) {
  13472. cli_->set_proxy_basic_auth(username, password);
  13473. }
  13474. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13475. cli_->set_proxy_bearer_token_auth(token);
  13476. }
  13477. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13478. cli_->set_no_proxy(patterns);
  13479. }
  13480. inline void Client::set_logger(Logger logger) {
  13481. cli_->set_logger(std::move(logger));
  13482. }
  13483. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13484. cli_->set_error_logger(std::move(error_logger));
  13485. }
  13486. /*
  13487. * Group 6: SSL Server and Client implementation
  13488. */
  13489. #ifdef CPPHTTPLIB_SSL_ENABLED
  13490. // SSL HTTP server implementation
  13491. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13492. const char *client_ca_cert_file_path,
  13493. const char *client_ca_cert_dir_path,
  13494. const char *private_key_password) {
  13495. using namespace tls;
  13496. ctx_ = create_server_context();
  13497. if (!ctx_) { return; }
  13498. // Load server certificate and private key
  13499. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13500. private_key_password)) {
  13501. last_ssl_error_ = static_cast<int>(get_error());
  13502. free_context(ctx_);
  13503. ctx_ = nullptr;
  13504. return;
  13505. }
  13506. // Load client CA certificates for client authentication
  13507. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13508. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13509. client_ca_cert_dir_path)) {
  13510. last_ssl_error_ = static_cast<int>(get_error());
  13511. free_context(ctx_);
  13512. ctx_ = nullptr;
  13513. return;
  13514. }
  13515. // Enable client certificate verification
  13516. set_verify_client(ctx_, true);
  13517. }
  13518. }
  13519. inline SSLServer::SSLServer(const PemMemory &pem) {
  13520. using namespace tls;
  13521. ctx_ = create_server_context();
  13522. if (ctx_) {
  13523. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13524. pem.private_key_password)) {
  13525. last_ssl_error_ = static_cast<int>(get_error());
  13526. free_context(ctx_);
  13527. ctx_ = nullptr;
  13528. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13529. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13530. last_ssl_error_ = static_cast<int>(get_error());
  13531. free_context(ctx_);
  13532. ctx_ = nullptr;
  13533. } else {
  13534. set_verify_client(ctx_, true);
  13535. }
  13536. }
  13537. }
  13538. }
  13539. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13540. using namespace tls;
  13541. ctx_ = create_server_context();
  13542. if (ctx_) {
  13543. if (!setup_callback(ctx_)) {
  13544. free_context(ctx_);
  13545. ctx_ = nullptr;
  13546. }
  13547. }
  13548. }
  13549. inline SSLServer::~SSLServer() {
  13550. if (ctx_) { tls::free_context(ctx_); }
  13551. }
  13552. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13553. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13554. using namespace tls;
  13555. // Create TLS session with mutex protection
  13556. session_t session = nullptr;
  13557. {
  13558. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13559. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13560. }
  13561. if (!session) {
  13562. last_ssl_error_ = static_cast<int>(get_error());
  13563. detail::shutdown_socket(sock);
  13564. detail::close_socket(sock);
  13565. return false;
  13566. }
  13567. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13568. bool handshake_done = false;
  13569. bool ret = false;
  13570. bool websocket_upgraded = false;
  13571. auto cleanup = detail::scope_exit([&] {
  13572. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13573. free_session(session);
  13574. detail::shutdown_socket(sock);
  13575. detail::close_socket(sock);
  13576. });
  13577. // Perform TLS accept handshake with timeout
  13578. TlsError tls_err;
  13579. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13580. &tls_err)) {
  13581. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13582. // Map TlsError to legacy ssl_error for backward compatibility
  13583. if (tls_err.code == ErrorCode::WantRead) {
  13584. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13585. } else if (tls_err.code == ErrorCode::WantWrite) {
  13586. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13587. } else {
  13588. last_ssl_error_ = SSL_ERROR_SSL;
  13589. }
  13590. #else
  13591. last_ssl_error_ = static_cast<int>(get_error());
  13592. #endif
  13593. return false;
  13594. }
  13595. handshake_done = true;
  13596. std::string remote_addr;
  13597. int remote_port = 0;
  13598. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13599. std::string local_addr;
  13600. int local_port = 0;
  13601. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13602. ret = detail::process_server_socket_ssl(
  13603. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13604. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13605. write_timeout_usec_,
  13606. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13607. return process_request(
  13608. strm, remote_addr, remote_port, local_addr, local_port,
  13609. close_connection, connection_closed,
  13610. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13611. });
  13612. return ret;
  13613. }
  13614. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13615. const char *key_pem,
  13616. const char *client_ca_pem,
  13617. const char *password) {
  13618. if (!ctx_) { return false; }
  13619. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13620. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13621. return false;
  13622. }
  13623. if (client_ca_pem) {
  13624. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13625. }
  13626. return true;
  13627. }
  13628. // SSL HTTP client implementation
  13629. inline SSLClient::~SSLClient() {
  13630. if (ctx_) { tls::free_context(ctx_); }
  13631. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13632. // base function rather than the derived function once we get to the
  13633. // base class destructor, and won't free the SSL (causing a leak).
  13634. shutdown_ssl_impl(socket_, true);
  13635. }
  13636. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13637. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13638. shutdown_ssl_impl(socket, shutdown_gracefully);
  13639. }
  13640. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13641. bool shutdown_gracefully) {
  13642. if (socket.sock == INVALID_SOCKET) {
  13643. assert(socket.ssl == nullptr);
  13644. return;
  13645. }
  13646. if (socket.ssl) {
  13647. tls::shutdown(socket.ssl, shutdown_gracefully);
  13648. {
  13649. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13650. tls::free_session(socket.ssl);
  13651. }
  13652. socket.ssl = nullptr;
  13653. }
  13654. assert(socket.ssl == nullptr);
  13655. }
  13656. inline bool SSLClient::process_socket(
  13657. const Socket &socket,
  13658. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13659. std::function<bool(Stream &strm)> callback) {
  13660. assert(socket.ssl);
  13661. return detail::process_client_socket_ssl(
  13662. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13663. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13664. std::move(callback));
  13665. }
  13666. inline bool SSLClient::is_ssl() const { return true; }
  13667. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13668. if (!is_valid()) {
  13669. error = Error::SSLConnection;
  13670. return false;
  13671. }
  13672. return ClientImpl::create_and_connect_socket(socket, error);
  13673. }
  13674. inline bool SSLClient::setup_proxy_connection(
  13675. Socket &socket,
  13676. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13677. Response &res, bool &success, Error &error) {
  13678. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13679. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13680. return false;
  13681. }
  13682. if (!initialize_ssl(socket, error)) {
  13683. success = false;
  13684. return false;
  13685. }
  13686. return true;
  13687. }
  13688. // Assumes that socket_mutex_ is locked and that there are no requests in
  13689. // flight
  13690. inline bool SSLClient::connect_with_proxy(
  13691. Socket &socket,
  13692. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13693. Response &res, bool &success, Error &error) {
  13694. success = true;
  13695. Response proxy_res;
  13696. if (!detail::process_client_socket(
  13697. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13698. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13699. start_time, [&](Stream &strm) {
  13700. Request req2;
  13701. req2.method = "CONNECT";
  13702. req2.path =
  13703. detail::make_host_and_port_string_always_port(host_, port_);
  13704. if (max_timeout_msec_ > 0) {
  13705. req2.start_time_ = std::chrono::steady_clock::now();
  13706. }
  13707. return process_request(strm, req2, proxy_res, false, error);
  13708. })) {
  13709. // Thread-safe to close everything because we are assuming there are no
  13710. // requests in flight
  13711. shutdown_ssl(socket, true);
  13712. shutdown_socket(socket);
  13713. close_socket(socket);
  13714. success = false;
  13715. return false;
  13716. }
  13717. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13718. if (!proxy_digest_auth_username_.empty() &&
  13719. !proxy_digest_auth_password_.empty()) {
  13720. std::map<std::string, std::string> auth;
  13721. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13722. // Close the current socket and create a new one for the authenticated
  13723. // request
  13724. shutdown_ssl(socket, true);
  13725. shutdown_socket(socket);
  13726. close_socket(socket);
  13727. // Create a new socket for the authenticated CONNECT request
  13728. if (!ensure_socket_connection(socket, error)) {
  13729. success = false;
  13730. output_error_log(error, nullptr);
  13731. return false;
  13732. }
  13733. proxy_res = Response();
  13734. if (!detail::process_client_socket(
  13735. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13736. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13737. start_time, [&](Stream &strm) {
  13738. Request req3;
  13739. req3.method = "CONNECT";
  13740. req3.path = detail::make_host_and_port_string_always_port(
  13741. host_, port_);
  13742. req3.headers.insert(detail::make_digest_authentication_header(
  13743. req3, auth, 1, detail::random_string(10),
  13744. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13745. true));
  13746. if (max_timeout_msec_ > 0) {
  13747. req3.start_time_ = std::chrono::steady_clock::now();
  13748. }
  13749. return process_request(strm, req3, proxy_res, false, error);
  13750. })) {
  13751. // Thread-safe to close everything because we are assuming there are
  13752. // no requests in flight
  13753. shutdown_ssl(socket, true);
  13754. shutdown_socket(socket);
  13755. close_socket(socket);
  13756. success = false;
  13757. return false;
  13758. }
  13759. }
  13760. }
  13761. }
  13762. // If status code is not 200, proxy request is failed.
  13763. // Set error to ProxyConnection and return proxy response
  13764. // as the response of the request
  13765. if (proxy_res.status != StatusCode::OK_200) {
  13766. error = Error::ProxyConnection;
  13767. output_error_log(error, nullptr);
  13768. res = std::move(proxy_res);
  13769. // Thread-safe to close everything because we are assuming there are
  13770. // no requests in flight
  13771. shutdown_ssl(socket, true);
  13772. shutdown_socket(socket);
  13773. close_socket(socket);
  13774. return false;
  13775. }
  13776. return true;
  13777. }
  13778. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13779. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13780. if (is_proxy_enabled_for_host(host_)) { return true; }
  13781. if (!initialize_ssl(socket, error)) {
  13782. shutdown_socket(socket);
  13783. close_socket(socket);
  13784. return false;
  13785. }
  13786. return true;
  13787. }
  13788. // SSL HTTP client implementation
  13789. inline SSLClient::SSLClient(const std::string &host)
  13790. : SSLClient(host, 443, std::string(), std::string()) {}
  13791. inline SSLClient::SSLClient(const std::string &host, int port)
  13792. : SSLClient(host, port, std::string(), std::string()) {}
  13793. inline void SSLClient::init_ctx() {
  13794. ctx_ = tls::create_client_context();
  13795. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13796. }
  13797. inline void SSLClient::reset_ctx_on_error() {
  13798. last_backend_error_ = tls::get_error();
  13799. tls::free_context(ctx_);
  13800. ctx_ = nullptr;
  13801. }
  13802. inline SSLClient::SSLClient(const std::string &host, int port,
  13803. const std::string &client_cert_path,
  13804. const std::string &client_key_path,
  13805. const std::string &private_key_password)
  13806. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13807. init_ctx();
  13808. if (!ctx_) { return; }
  13809. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13810. const char *password =
  13811. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13812. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13813. client_key_path.c_str(), password)) {
  13814. reset_ctx_on_error();
  13815. }
  13816. }
  13817. }
  13818. inline SSLClient::SSLClient(const std::string &host, int port,
  13819. const PemMemory &pem)
  13820. : ClientImpl(host, port) {
  13821. init_ctx();
  13822. if (!ctx_) { return; }
  13823. if (pem.cert_pem && pem.key_pem) {
  13824. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13825. pem.private_key_password)) {
  13826. reset_ctx_on_error();
  13827. }
  13828. }
  13829. }
  13830. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13831. if (ca_cert_store && ctx_) {
  13832. // set_ca_store takes ownership of ca_cert_store
  13833. tls::set_ca_store(ctx_, ca_cert_store);
  13834. ca_cert_store_set_ = true;
  13835. } else if (ca_cert_store) {
  13836. tls::free_ca_store(ca_cert_store);
  13837. }
  13838. }
  13839. inline void
  13840. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13841. if (!ctx_) { return; }
  13842. tls::set_verify_callback(ctx_, verifier);
  13843. }
  13844. inline void SSLClient::set_session_verifier(
  13845. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13846. session_verifier_ = std::move(verifier);
  13847. }
  13848. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13849. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13850. enable_windows_cert_verification_ = enabled;
  13851. }
  13852. #endif
  13853. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13854. std::size_t size) {
  13855. if (ctx_ && ca_cert && size > 0) {
  13856. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13857. tls::load_ca_pem(ctx_, ca_cert, size);
  13858. }
  13859. }
  13860. inline bool SSLClient::load_certs() {
  13861. auto ret = true;
  13862. std::call_once(initialize_cert_, [&]() {
  13863. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13864. ret = detail::load_client_ca_config(
  13865. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  13866. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  13867. last_backend_error_);
  13868. });
  13869. return ret;
  13870. }
  13871. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13872. using namespace tls;
  13873. // Load CA certificates if server verification is enabled
  13874. if (server_certificate_verification_) {
  13875. if (!load_certs()) {
  13876. error = Error::SSLLoadingCerts;
  13877. output_error_log(error, nullptr);
  13878. return false;
  13879. }
  13880. }
  13881. bool is_ip = detail::is_ip_address(host_);
  13882. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13883. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13884. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13885. // Chain verification happens during the handshake even for IP hosts; the
  13886. // certificate identity is verified post-handshake via verify_hostname().
  13887. set_verify_client(ctx_, server_certificate_verification_);
  13888. #endif
  13889. // Create TLS session
  13890. session_t session = nullptr;
  13891. {
  13892. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13893. session = create_session(ctx_, socket.sock);
  13894. }
  13895. if (!session) {
  13896. error = Error::SSLConnection;
  13897. last_backend_error_ = get_error();
  13898. return false;
  13899. }
  13900. // Use scope_exit to ensure session is freed on error paths
  13901. bool success = false;
  13902. auto session_guard = detail::scope_exit([&] {
  13903. if (!success) { free_session(session); }
  13904. });
  13905. // Set SNI extension (skip for IP addresses per RFC 6066).
  13906. // On MbedTLS, set_sni also enables hostname verification internally.
  13907. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13908. if (!is_ip) {
  13909. if (!set_sni(session, host_.c_str())) {
  13910. error = Error::SSLConnection;
  13911. last_backend_error_ = get_error();
  13912. return false;
  13913. }
  13914. }
  13915. // Perform non-blocking TLS handshake with timeout
  13916. TlsError tls_err;
  13917. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13918. connection_timeout_usec_, &tls_err)) {
  13919. last_ssl_error_ = static_cast<int>(tls_err.code);
  13920. last_backend_error_ = tls_err.backend_code;
  13921. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13922. error = Error::SSLServerVerification;
  13923. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13924. error = Error::SSLServerHostnameVerification;
  13925. } else {
  13926. error = Error::SSLConnection;
  13927. }
  13928. output_error_log(error, nullptr);
  13929. return false;
  13930. }
  13931. // Post-handshake session verifier callback
  13932. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13933. if (session_verifier_) { verification_status = session_verifier_(session); }
  13934. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13935. last_backend_error_ = get_error();
  13936. error = Error::SSLServerVerification;
  13937. output_error_log(error, nullptr);
  13938. return false;
  13939. }
  13940. // Default server certificate verification
  13941. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  13942. server_certificate_verification_) {
  13943. verify_result_ = tls::get_verify_result(session);
  13944. if (verify_result_ != 0) {
  13945. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  13946. error = Error::SSLServerVerification;
  13947. output_error_log(error, nullptr);
  13948. return false;
  13949. }
  13950. auto server_cert = get_peer_cert(session);
  13951. if (!server_cert) {
  13952. last_backend_error_ = get_error();
  13953. error = Error::SSLServerVerification;
  13954. output_error_log(error, nullptr);
  13955. return false;
  13956. }
  13957. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  13958. // Hostname verification (post-handshake for all cases).
  13959. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  13960. // On MbedTLS, set_sni already enabled hostname verification during
  13961. // handshake for non-IP hosts, but this check is still needed for IP
  13962. // addresses where SNI is not set.
  13963. if (server_hostname_verification_) {
  13964. if (!verify_hostname(server_cert, host_.c_str())) {
  13965. last_backend_error_ = hostname_mismatch_code();
  13966. error = Error::SSLServerHostnameVerification;
  13967. output_error_log(error, nullptr);
  13968. return false;
  13969. }
  13970. }
  13971. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13972. // Additional Windows Schannel verification.
  13973. // This provides real-time certificate validation with Windows Update
  13974. // integration, working with both OpenSSL and MbedTLS backends.
  13975. // Skip when a custom CA cert is specified, as the Windows certificate
  13976. // store would not know about user-provided CA certificates. Also skip
  13977. // when system CA trust is explicitly disabled.
  13978. if (enable_windows_cert_verification_ &&
  13979. system_ca_mode_ != SystemCAMode::Disabled &&
  13980. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  13981. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  13982. std::vector<unsigned char> der;
  13983. if (get_cert_der(server_cert, der)) {
  13984. uint64_t wincrypt_error = 0;
  13985. if (!detail::verify_cert_with_windows_schannel(
  13986. der, host_, server_hostname_verification_, wincrypt_error)) {
  13987. last_backend_error_ = wincrypt_error;
  13988. error = Error::SSLServerVerification;
  13989. output_error_log(error, nullptr);
  13990. return false;
  13991. }
  13992. }
  13993. }
  13994. #endif
  13995. }
  13996. success = true;
  13997. socket.ssl = session;
  13998. return true;
  13999. }
  14000. inline void Client::set_digest_auth(const std::string &username,
  14001. const std::string &password) {
  14002. cli_->set_digest_auth(username, password);
  14003. }
  14004. inline void Client::set_proxy_digest_auth(const std::string &username,
  14005. const std::string &password) {
  14006. cli_->set_proxy_digest_auth(username, password);
  14007. }
  14008. inline void Client::enable_server_certificate_verification(bool enabled) {
  14009. cli_->enable_server_certificate_verification(enabled);
  14010. }
  14011. inline void Client::enable_server_hostname_verification(bool enabled) {
  14012. cli_->enable_server_hostname_verification(enabled);
  14013. }
  14014. inline void Client::enable_system_ca(bool enabled) {
  14015. cli_->enable_system_ca(enabled);
  14016. }
  14017. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14018. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14019. if (is_ssl_) {
  14020. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14021. enabled);
  14022. }
  14023. }
  14024. #endif
  14025. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14026. const std::string &ca_cert_dir_path) {
  14027. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14028. }
  14029. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14030. if (is_ssl_) {
  14031. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14032. } else if (ca_cert_store) {
  14033. tls::free_ca_store(ca_cert_store);
  14034. }
  14035. }
  14036. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14037. if (is_ssl_) {
  14038. // Use the PEM-based path so the CA data is retained for redirect transfer
  14039. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14040. }
  14041. }
  14042. inline void
  14043. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14044. if (is_ssl_) {
  14045. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14046. std::move(verifier));
  14047. }
  14048. }
  14049. inline void Client::set_session_verifier(
  14050. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14051. if (is_ssl_) {
  14052. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14053. }
  14054. }
  14055. inline tls::ctx_t Client::tls_context() const {
  14056. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14057. return nullptr;
  14058. }
  14059. #endif // CPPHTTPLIB_SSL_ENABLED
  14060. /*
  14061. * Group 7: TLS abstraction layer - Common API
  14062. */
  14063. #ifdef CPPHTTPLIB_SSL_ENABLED
  14064. namespace tls {
  14065. // Helper for PeerCert construction
  14066. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14067. return PeerCert(get_peer_cert(session));
  14068. }
  14069. namespace impl {
  14070. inline VerifyCallback &get_verify_callback() {
  14071. static thread_local VerifyCallback callback;
  14072. return callback;
  14073. }
  14074. inline VerifyCallback &get_mbedtls_verify_callback() {
  14075. static thread_local VerifyCallback callback;
  14076. return callback;
  14077. }
  14078. // Check if a string is an IPv4 address
  14079. inline bool is_ipv4_address(const std::string &str) {
  14080. int dots = 0;
  14081. for (char c : str) {
  14082. if (c == '.') {
  14083. dots++;
  14084. } else if (!isdigit(static_cast<unsigned char>(c))) {
  14085. return false;
  14086. }
  14087. }
  14088. return dots == 3;
  14089. }
  14090. // Parse IPv4 address string to bytes
  14091. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14092. const char *p = str.c_str();
  14093. for (int i = 0; i < 4; i++) {
  14094. if (i > 0) {
  14095. if (*p != '.') { return false; }
  14096. p++;
  14097. }
  14098. int val = 0;
  14099. int digits = 0;
  14100. while (*p >= '0' && *p <= '9') {
  14101. val = val * 10 + (*p - '0');
  14102. if (val > 255) { return false; }
  14103. p++;
  14104. digits++;
  14105. }
  14106. if (digits == 0) { return false; }
  14107. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14108. if (digits > 1 && *(p - digits) == '0') { return false; }
  14109. out[i] = static_cast<unsigned char>(val);
  14110. }
  14111. return *p == '\0';
  14112. }
  14113. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14114. // `out` must have room for at least 16 bytes. Returns the address length
  14115. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14116. // literal. Used to match a host against iPAddress SANs the same way the
  14117. // OpenSSL backend does via X509_check_ip.
  14118. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14119. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14120. struct in6_addr addr6 = {};
  14121. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14122. memcpy(out, &addr6, 16);
  14123. return 16;
  14124. }
  14125. return 0;
  14126. }
  14127. #ifdef _WIN32
  14128. // Enumerate Windows system certificates and call callback with DER data
  14129. template <typename Callback>
  14130. inline bool enumerate_windows_system_certs(Callback cb) {
  14131. bool loaded = false;
  14132. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14133. for (auto store_name : store_names) {
  14134. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14135. if (hStore) {
  14136. PCCERT_CONTEXT pContext = nullptr;
  14137. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14138. nullptr) {
  14139. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14140. loaded = true;
  14141. }
  14142. }
  14143. CertCloseStore(hStore, 0);
  14144. }
  14145. }
  14146. return loaded;
  14147. }
  14148. #endif
  14149. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14150. // Enumerate macOS Keychain certificates and call callback with DER data
  14151. template <typename Callback>
  14152. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14153. bool loaded = false;
  14154. const SecTrustSettingsDomain domains[] = {
  14155. kSecTrustSettingsDomainSystem,
  14156. kSecTrustSettingsDomainAdmin,
  14157. kSecTrustSettingsDomainUser,
  14158. };
  14159. for (auto domain : domains) {
  14160. CFArrayRef certs = nullptr;
  14161. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14162. if (status != errSecSuccess || !certs) {
  14163. if (certs) CFRelease(certs);
  14164. continue;
  14165. }
  14166. CFIndex count = CFArrayGetCount(certs);
  14167. for (CFIndex i = 0; i < count; i++) {
  14168. SecCertificateRef cert =
  14169. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14170. CFDataRef data = SecCertificateCopyData(cert);
  14171. if (data) {
  14172. if (cb(CFDataGetBytePtr(data),
  14173. static_cast<size_t>(CFDataGetLength(data)))) {
  14174. loaded = true;
  14175. }
  14176. CFRelease(data);
  14177. }
  14178. }
  14179. CFRelease(certs);
  14180. }
  14181. return loaded;
  14182. }
  14183. #endif
  14184. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14185. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14186. // Common CA certificate file paths on Linux/Unix
  14187. inline const char **system_ca_paths() {
  14188. static const char *paths[] = {
  14189. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14190. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14191. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14192. "/etc/pki/tls/cacert.pem", // OpenELEC
  14193. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14194. nullptr};
  14195. return paths;
  14196. }
  14197. // Common CA certificate directory paths on Linux/Unix
  14198. inline const char **system_ca_dirs() {
  14199. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14200. "/etc/pki/tls/certs", // RHEL/CentOS
  14201. "/usr/share/ca-certificates", // Other
  14202. nullptr};
  14203. return dirs;
  14204. }
  14205. #endif
  14206. } // namespace impl
  14207. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14208. const char *ca_dir) {
  14209. if (!ctx) { return false; }
  14210. bool success = true;
  14211. if (ca_file && *ca_file) {
  14212. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14213. }
  14214. if (ca_dir && *ca_dir) {
  14215. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14216. }
  14217. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14218. // Set CA list for client certificate request (CertificateRequest message)
  14219. if (ca_file && *ca_file) {
  14220. auto list = SSL_load_client_CA_file(ca_file);
  14221. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14222. }
  14223. #endif
  14224. return success;
  14225. }
  14226. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14227. const char *password) {
  14228. return set_client_cert_pem(ctx, cert, key, password);
  14229. }
  14230. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14231. const char *key_path, const char *password) {
  14232. return set_client_cert_file(ctx, cert_path, key_path, password);
  14233. }
  14234. // PeerCert implementation
  14235. inline PeerCert::PeerCert() = default;
  14236. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14237. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14238. other.cert_ = nullptr;
  14239. }
  14240. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14241. if (this != &other) {
  14242. if (cert_) { free_cert(cert_); }
  14243. cert_ = other.cert_;
  14244. other.cert_ = nullptr;
  14245. }
  14246. return *this;
  14247. }
  14248. inline PeerCert::~PeerCert() {
  14249. if (cert_) { free_cert(cert_); }
  14250. }
  14251. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14252. inline std::string PeerCert::subject_cn() const {
  14253. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14254. }
  14255. inline std::string PeerCert::issuer_name() const {
  14256. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14257. }
  14258. inline bool PeerCert::check_hostname(const char *hostname) const {
  14259. return cert_ ? verify_hostname(cert_, hostname) : false;
  14260. }
  14261. inline std::vector<SanEntry> PeerCert::sans() const {
  14262. std::vector<SanEntry> result;
  14263. if (cert_) { get_cert_sans(cert_, result); }
  14264. return result;
  14265. }
  14266. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14267. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14268. }
  14269. inline std::string PeerCert::serial() const {
  14270. return cert_ ? get_cert_serial(cert_) : std::string();
  14271. }
  14272. // VerifyContext method implementations
  14273. inline std::string VerifyContext::subject_cn() const {
  14274. return cert ? get_cert_subject_cn(cert) : std::string();
  14275. }
  14276. inline std::string VerifyContext::issuer_name() const {
  14277. return cert ? get_cert_issuer_name(cert) : std::string();
  14278. }
  14279. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14280. return cert ? verify_hostname(cert, hostname) : false;
  14281. }
  14282. inline std::vector<SanEntry> VerifyContext::sans() const {
  14283. std::vector<SanEntry> result;
  14284. if (cert) { get_cert_sans(cert, result); }
  14285. return result;
  14286. }
  14287. inline bool VerifyContext::validity(time_t &not_before,
  14288. time_t &not_after) const {
  14289. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14290. }
  14291. inline std::string VerifyContext::serial() const {
  14292. return cert ? get_cert_serial(cert) : std::string();
  14293. }
  14294. // TlsError static method implementation
  14295. inline std::string TlsError::verify_error_to_string(long error_code) {
  14296. return verify_error_string(error_code);
  14297. }
  14298. } // namespace tls
  14299. // Request::peer_cert() implementation
  14300. inline tls::PeerCert Request::peer_cert() const {
  14301. return tls::get_peer_cert_from_session(ssl);
  14302. }
  14303. // Request::sni() implementation
  14304. inline std::string Request::sni() const {
  14305. if (!ssl) { return std::string(); }
  14306. const char *s = tls::get_sni(ssl);
  14307. return s ? std::string(s) : std::string();
  14308. }
  14309. #endif // CPPHTTPLIB_SSL_ENABLED
  14310. /*
  14311. * Group 8: TLS abstraction layer - OpenSSL backend
  14312. */
  14313. /*
  14314. * OpenSSL Backend Implementation
  14315. */
  14316. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14317. namespace tls {
  14318. namespace impl {
  14319. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14320. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14321. switch (ssl_error) {
  14322. case SSL_ERROR_NONE: return ErrorCode::Success;
  14323. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14324. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14325. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14326. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14327. case SSL_ERROR_SSL:
  14328. default: return ErrorCode::Fatal;
  14329. }
  14330. }
  14331. // Helper: Create client CA list from PEM string
  14332. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14333. // Caller takes ownership of returned list
  14334. inline STACK_OF(X509_NAME) *
  14335. create_client_ca_list_from_pem(const char *ca_pem) {
  14336. if (!ca_pem) { return nullptr; }
  14337. auto ca_list = sk_X509_NAME_new_null();
  14338. if (!ca_list) { return nullptr; }
  14339. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14340. if (!bio) {
  14341. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14342. return nullptr;
  14343. }
  14344. X509 *cert = nullptr;
  14345. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14346. nullptr) {
  14347. const X509_NAME *name = X509_get_subject_name(cert);
  14348. if (name) {
  14349. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14350. }
  14351. X509_free(cert);
  14352. }
  14353. BIO_free(bio);
  14354. return ca_list;
  14355. }
  14356. // OpenSSL verify callback wrapper
  14357. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14358. auto &callback = get_verify_callback();
  14359. if (!callback) { return preverify_ok; }
  14360. // Get SSL object from X509_STORE_CTX
  14361. auto ssl = static_cast<SSL *>(
  14362. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14363. if (!ssl) { return preverify_ok; }
  14364. // Get current certificate and depth
  14365. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14366. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14367. int error = X509_STORE_CTX_get_error(ctx);
  14368. // Build context
  14369. VerifyContext verify_ctx;
  14370. verify_ctx.session = static_cast<session_t>(ssl);
  14371. verify_ctx.cert = static_cast<cert_t>(cert);
  14372. verify_ctx.depth = depth;
  14373. verify_ctx.preverify_ok = (preverify_ok != 0);
  14374. verify_ctx.error_code = error;
  14375. verify_ctx.error_string =
  14376. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14377. return callback(verify_ctx) ? 1 : 0;
  14378. }
  14379. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14380. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14381. // that must be released with release_store_objects
  14382. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14383. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14384. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14385. #endif
  14386. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14387. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14388. return X509_STORE_get1_objects(store);
  14389. #else
  14390. return X509_STORE_get0_objects(store);
  14391. #endif
  14392. }
  14393. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14394. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14395. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14396. #else
  14397. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14398. #endif
  14399. }
  14400. } // namespace impl
  14401. inline ctx_t create_client_context() {
  14402. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14403. if (ctx) {
  14404. // Disable auto-retry to properly handle non-blocking I/O
  14405. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14406. // Set minimum TLS version
  14407. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14408. }
  14409. return static_cast<ctx_t>(ctx);
  14410. }
  14411. inline void free_context(ctx_t ctx) {
  14412. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14413. }
  14414. inline bool set_min_version(ctx_t ctx, Version version) {
  14415. if (!ctx) return false;
  14416. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14417. static_cast<int>(version)) == 1;
  14418. }
  14419. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14420. if (!ctx || !pem || len == 0) return false;
  14421. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14422. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14423. if (!store) return false;
  14424. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14425. if (!bio) return false;
  14426. bool ok = true;
  14427. X509 *cert = nullptr;
  14428. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14429. nullptr) {
  14430. if (X509_STORE_add_cert(store, cert) != 1) {
  14431. // Ignore duplicate errors
  14432. auto err = ERR_peek_last_error();
  14433. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14434. ok = false;
  14435. }
  14436. }
  14437. X509_free(cert);
  14438. if (!ok) break;
  14439. }
  14440. BIO_free(bio);
  14441. // Clear any "no more certificates" errors
  14442. ERR_clear_error();
  14443. return ok;
  14444. }
  14445. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14446. if (!ctx || !file_path) return false;
  14447. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14448. nullptr) == 1;
  14449. }
  14450. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14451. if (!ctx || !dir_path) return false;
  14452. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14453. dir_path) == 1;
  14454. }
  14455. inline bool load_system_certs(ctx_t ctx) {
  14456. if (!ctx) return false;
  14457. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14458. #ifdef _WIN32
  14459. // Windows: Load from system certificate store (ROOT and CA)
  14460. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14461. if (!store) return false;
  14462. bool loaded_any = false;
  14463. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14464. for (auto store_name : store_names) {
  14465. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14466. if (!hStore) continue;
  14467. PCCERT_CONTEXT pContext = nullptr;
  14468. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14469. nullptr) {
  14470. const unsigned char *data = pContext->pbCertEncoded;
  14471. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14472. if (x509) {
  14473. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14474. X509_free(x509);
  14475. }
  14476. }
  14477. CertCloseStore(hStore, 0);
  14478. }
  14479. return loaded_any;
  14480. #elif defined(__APPLE__)
  14481. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14482. // macOS: Load from Keychain
  14483. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14484. if (!store) return false;
  14485. bool loaded_any = false;
  14486. const SecTrustSettingsDomain domains[] = {
  14487. kSecTrustSettingsDomainSystem,
  14488. kSecTrustSettingsDomainAdmin,
  14489. kSecTrustSettingsDomainUser,
  14490. };
  14491. for (auto domain : domains) {
  14492. CFArrayRef certs = nullptr;
  14493. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14494. !certs) {
  14495. if (certs) CFRelease(certs);
  14496. continue;
  14497. }
  14498. auto count = CFArrayGetCount(certs);
  14499. for (CFIndex i = 0; i < count; i++) {
  14500. auto cert = reinterpret_cast<SecCertificateRef>(
  14501. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14502. CFDataRef der = SecCertificateCopyData(cert);
  14503. if (der) {
  14504. const unsigned char *data = CFDataGetBytePtr(der);
  14505. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14506. if (x509) {
  14507. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14508. X509_free(x509);
  14509. }
  14510. CFRelease(der);
  14511. }
  14512. }
  14513. CFRelease(certs);
  14514. }
  14515. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14516. #else
  14517. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14518. #endif
  14519. #else
  14520. // Other Unix: use default verify paths
  14521. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14522. #endif
  14523. }
  14524. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14525. const char *password) {
  14526. if (!ctx || !cert || !key) return false;
  14527. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14528. // Load certificate
  14529. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14530. if (!cert_bio) return false;
  14531. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14532. BIO_free(cert_bio);
  14533. if (!x509) return false;
  14534. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14535. X509_free(x509);
  14536. if (!cert_ok) return false;
  14537. // Load private key
  14538. auto key_bio = BIO_new_mem_buf(key, -1);
  14539. if (!key_bio) return false;
  14540. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14541. password ? const_cast<char *>(password)
  14542. : nullptr);
  14543. BIO_free(key_bio);
  14544. if (!pkey) return false;
  14545. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14546. EVP_PKEY_free(pkey);
  14547. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14548. }
  14549. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14550. const char *key_path, const char *password) {
  14551. if (!ctx || !cert_path || !key_path) return false;
  14552. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14553. if (password && password[0] != '\0') {
  14554. SSL_CTX_set_default_passwd_cb_userdata(
  14555. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14556. }
  14557. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14558. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14559. }
  14560. inline ctx_t create_server_context() {
  14561. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14562. if (ctx) {
  14563. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14564. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14565. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14566. }
  14567. return static_cast<ctx_t>(ctx);
  14568. }
  14569. inline void set_verify_client(ctx_t ctx, bool require) {
  14570. if (!ctx) return;
  14571. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14572. require
  14573. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14574. : SSL_VERIFY_NONE,
  14575. nullptr);
  14576. }
  14577. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14578. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14579. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14580. SSL *ssl = SSL_new(ssl_ctx);
  14581. if (!ssl) return nullptr;
  14582. // Disable auto-retry for proper non-blocking I/O handling
  14583. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14584. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14585. if (!bio) {
  14586. SSL_free(ssl);
  14587. return nullptr;
  14588. }
  14589. SSL_set_bio(ssl, bio, bio);
  14590. return static_cast<session_t>(ssl);
  14591. }
  14592. inline void free_session(session_t session) {
  14593. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14594. }
  14595. inline bool set_sni(session_t session, const char *hostname) {
  14596. if (!session || !hostname) return false;
  14597. auto ssl = static_cast<SSL *>(session);
  14598. // Set SNI (Server Name Indication) only - does not enable verification
  14599. #if defined(OPENSSL_IS_BORINGSSL)
  14600. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14601. #else
  14602. // Direct call instead of macro to suppress -Wold-style-cast warning
  14603. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14604. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14605. #endif
  14606. }
  14607. inline bool set_hostname(session_t session, const char *hostname) {
  14608. if (!session || !hostname) return false;
  14609. auto ssl = static_cast<SSL *>(session);
  14610. // Enable hostname verification
  14611. auto param = SSL_get0_param(ssl);
  14612. if (!param) return false;
  14613. if (detail::is_ip_address(hostname)) {
  14614. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14615. // certificate's IP SANs instead of its DNS names
  14616. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14617. } else {
  14618. // Set SNI (Server Name Indication)
  14619. if (!set_sni(session, hostname)) { return false; }
  14620. X509_VERIFY_PARAM_set_hostflags(param,
  14621. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14622. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14623. }
  14624. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14625. return true;
  14626. }
  14627. inline TlsError connect(session_t session) {
  14628. if (!session) { return TlsError(); }
  14629. auto ssl = static_cast<SSL *>(session);
  14630. auto ret = SSL_connect(ssl);
  14631. TlsError err;
  14632. if (ret == 1) {
  14633. err.code = ErrorCode::Success;
  14634. } else {
  14635. auto ssl_err = SSL_get_error(ssl, ret);
  14636. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14637. err.backend_code = ERR_get_error();
  14638. }
  14639. return err;
  14640. }
  14641. inline TlsError accept(session_t session) {
  14642. if (!session) { return TlsError(); }
  14643. auto ssl = static_cast<SSL *>(session);
  14644. auto ret = SSL_accept(ssl);
  14645. TlsError err;
  14646. if (ret == 1) {
  14647. err.code = ErrorCode::Success;
  14648. } else {
  14649. auto ssl_err = SSL_get_error(ssl, ret);
  14650. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14651. err.backend_code = ERR_get_error();
  14652. }
  14653. return err;
  14654. }
  14655. inline bool connect_nonblocking(session_t session, socket_t sock,
  14656. time_t timeout_sec, time_t timeout_usec,
  14657. TlsError *err) {
  14658. if (!session) {
  14659. if (err) { err->code = ErrorCode::Fatal; }
  14660. return false;
  14661. }
  14662. auto ssl = static_cast<SSL *>(session);
  14663. auto bio = SSL_get_rbio(ssl);
  14664. // Set non-blocking mode for handshake
  14665. detail::set_nonblocking(sock, true);
  14666. if (bio) { BIO_set_nbio(bio, 1); }
  14667. auto cleanup = detail::scope_exit([&]() {
  14668. // Restore blocking mode after handshake
  14669. if (bio) { BIO_set_nbio(bio, 0); }
  14670. detail::set_nonblocking(sock, false);
  14671. });
  14672. auto res = 0;
  14673. while ((res = SSL_connect(ssl)) != 1) {
  14674. auto ssl_err = SSL_get_error(ssl, res);
  14675. switch (ssl_err) {
  14676. case SSL_ERROR_WANT_READ:
  14677. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14678. continue;
  14679. }
  14680. break;
  14681. case SSL_ERROR_WANT_WRITE:
  14682. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14683. continue;
  14684. }
  14685. break;
  14686. default: break;
  14687. }
  14688. if (err) {
  14689. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14690. err->backend_code = ERR_get_error();
  14691. }
  14692. return false;
  14693. }
  14694. if (err) { err->code = ErrorCode::Success; }
  14695. return true;
  14696. }
  14697. inline bool accept_nonblocking(session_t session, socket_t sock,
  14698. time_t timeout_sec, time_t timeout_usec,
  14699. TlsError *err) {
  14700. if (!session) {
  14701. if (err) { err->code = ErrorCode::Fatal; }
  14702. return false;
  14703. }
  14704. auto ssl = static_cast<SSL *>(session);
  14705. auto bio = SSL_get_rbio(ssl);
  14706. // Set non-blocking mode for handshake
  14707. detail::set_nonblocking(sock, true);
  14708. if (bio) { BIO_set_nbio(bio, 1); }
  14709. auto cleanup = detail::scope_exit([&]() {
  14710. // Restore blocking mode after handshake
  14711. if (bio) { BIO_set_nbio(bio, 0); }
  14712. detail::set_nonblocking(sock, false);
  14713. });
  14714. auto res = 0;
  14715. while ((res = SSL_accept(ssl)) != 1) {
  14716. auto ssl_err = SSL_get_error(ssl, res);
  14717. switch (ssl_err) {
  14718. case SSL_ERROR_WANT_READ:
  14719. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14720. continue;
  14721. }
  14722. break;
  14723. case SSL_ERROR_WANT_WRITE:
  14724. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14725. continue;
  14726. }
  14727. break;
  14728. default: break;
  14729. }
  14730. if (err) {
  14731. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14732. err->backend_code = ERR_get_error();
  14733. }
  14734. return false;
  14735. }
  14736. if (err) { err->code = ErrorCode::Success; }
  14737. return true;
  14738. }
  14739. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14740. if (!session || !buf) {
  14741. err.code = ErrorCode::Fatal;
  14742. return -1;
  14743. }
  14744. auto ssl = static_cast<SSL *>(session);
  14745. constexpr auto max_len =
  14746. static_cast<size_t>((std::numeric_limits<int>::max)());
  14747. if (len > max_len) { len = max_len; }
  14748. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14749. if (ret > 0) {
  14750. err.code = ErrorCode::Success;
  14751. return ret;
  14752. }
  14753. auto ssl_err = SSL_get_error(ssl, ret);
  14754. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14755. if (err.code == ErrorCode::PeerClosed) {
  14756. return 0;
  14757. } // Gracefully handle the peer closed state.
  14758. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14759. return -1;
  14760. }
  14761. inline ssize_t write(session_t session, const void *buf, size_t len,
  14762. TlsError &err) {
  14763. if (!session || !buf) {
  14764. err.code = ErrorCode::Fatal;
  14765. return -1;
  14766. }
  14767. auto ssl = static_cast<SSL *>(session);
  14768. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14769. if (ret > 0) {
  14770. err.code = ErrorCode::Success;
  14771. return ret;
  14772. }
  14773. auto ssl_err = SSL_get_error(ssl, ret);
  14774. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14775. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14776. return -1;
  14777. }
  14778. inline int pending(const_session_t session) {
  14779. if (!session) return 0;
  14780. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14781. }
  14782. inline void shutdown(session_t session, bool graceful) {
  14783. if (!session) return;
  14784. auto ssl = static_cast<SSL *>(session);
  14785. if (graceful) {
  14786. // First call sends close_notify
  14787. if (SSL_shutdown(ssl) == 0) {
  14788. // Second call waits for peer's close_notify
  14789. SSL_shutdown(ssl);
  14790. }
  14791. }
  14792. }
  14793. inline bool is_peer_closed(session_t session, socket_t sock) {
  14794. if (!session) return true;
  14795. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14796. detail::set_nonblocking(sock, true);
  14797. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14798. auto ssl = static_cast<SSL *>(session);
  14799. char buf;
  14800. auto ret = SSL_peek(ssl, &buf, 1);
  14801. if (ret > 0) return false;
  14802. auto err = SSL_get_error(ssl, ret);
  14803. return err == SSL_ERROR_ZERO_RETURN;
  14804. }
  14805. inline cert_t get_peer_cert(const_session_t session) {
  14806. if (!session) return nullptr;
  14807. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14808. static_cast<SSL *>(const_cast<void *>(session))));
  14809. }
  14810. inline void free_cert(cert_t cert) {
  14811. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14812. }
  14813. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14814. if (!cert || !hostname) return false;
  14815. auto x509 = static_cast<X509 *>(cert);
  14816. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14817. if (detail::is_ip_address(hostname)) {
  14818. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14819. }
  14820. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14821. }
  14822. inline uint64_t hostname_mismatch_code() {
  14823. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14824. }
  14825. inline long get_verify_result(const_session_t session) {
  14826. if (!session) return X509_V_ERR_UNSPECIFIED;
  14827. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14828. }
  14829. inline std::string get_cert_subject_cn(cert_t cert) {
  14830. if (!cert) return "";
  14831. auto x509 = static_cast<X509 *>(cert);
  14832. auto subject_name = X509_get_subject_name(x509);
  14833. if (!subject_name) return "";
  14834. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  14835. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  14836. if (idx < 0) return "";
  14837. auto entry = X509_NAME_get_entry(subject_name, idx);
  14838. if (!entry) return "";
  14839. auto data = X509_NAME_ENTRY_get_data(entry);
  14840. if (!data) return "";
  14841. return std::string(
  14842. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  14843. static_cast<size_t>(ASN1_STRING_length(data)));
  14844. }
  14845. inline std::string get_cert_issuer_name(cert_t cert) {
  14846. if (!cert) return "";
  14847. auto x509 = static_cast<X509 *>(cert);
  14848. auto issuer_name = X509_get_issuer_name(x509);
  14849. if (!issuer_name) return "";
  14850. char buf[256];
  14851. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14852. return std::string(buf);
  14853. }
  14854. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14855. sans.clear();
  14856. if (!cert) return false;
  14857. auto x509 = static_cast<X509 *>(cert);
  14858. auto names = static_cast<GENERAL_NAMES *>(
  14859. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14860. if (!names) return true; // No SANs is valid
  14861. auto count = sk_GENERAL_NAME_num(names);
  14862. for (decltype(count) i = 0; i < count; i++) {
  14863. auto gen = sk_GENERAL_NAME_value(names, i);
  14864. if (!gen) continue;
  14865. SanEntry entry;
  14866. switch (gen->type) {
  14867. case GEN_DNS:
  14868. entry.type = SanType::DNS;
  14869. if (gen->d.dNSName) {
  14870. entry.value = std::string(
  14871. reinterpret_cast<const char *>(
  14872. ASN1_STRING_get0_data(gen->d.dNSName)),
  14873. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14874. }
  14875. break;
  14876. case GEN_IPADD:
  14877. entry.type = SanType::IP;
  14878. if (gen->d.iPAddress) {
  14879. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14880. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14881. if (len == 4) {
  14882. // IPv4
  14883. char buf[INET_ADDRSTRLEN];
  14884. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14885. entry.value = buf;
  14886. } else if (len == 16) {
  14887. // IPv6
  14888. char buf[INET6_ADDRSTRLEN];
  14889. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14890. entry.value = buf;
  14891. }
  14892. }
  14893. break;
  14894. case GEN_EMAIL:
  14895. entry.type = SanType::EMAIL;
  14896. if (gen->d.rfc822Name) {
  14897. entry.value = std::string(
  14898. reinterpret_cast<const char *>(
  14899. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14900. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14901. }
  14902. break;
  14903. case GEN_URI:
  14904. entry.type = SanType::URI;
  14905. if (gen->d.uniformResourceIdentifier) {
  14906. entry.value = std::string(
  14907. reinterpret_cast<const char *>(
  14908. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14909. static_cast<size_t>(
  14910. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14911. }
  14912. break;
  14913. default: entry.type = SanType::OTHER; break;
  14914. }
  14915. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14916. }
  14917. GENERAL_NAMES_free(names);
  14918. return true;
  14919. }
  14920. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14921. time_t &not_after) {
  14922. if (!cert) return false;
  14923. auto x509 = static_cast<X509 *>(cert);
  14924. auto nb = X509_get0_notBefore(x509);
  14925. auto na = X509_get0_notAfter(x509);
  14926. if (!nb || !na) return false;
  14927. ASN1_TIME *epoch = ASN1_TIME_new();
  14928. if (!epoch) return false;
  14929. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14930. if (!ASN1_TIME_set(epoch, 0)) return false;
  14931. int pday, psec;
  14932. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14933. not_before = 86400 * (time_t)pday + psec;
  14934. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14935. not_after = 86400 * (time_t)pday + psec;
  14936. return true;
  14937. }
  14938. inline std::string get_cert_serial(cert_t cert) {
  14939. if (!cert) return "";
  14940. auto x509 = static_cast<X509 *>(cert);
  14941. auto serial = X509_get_serialNumber(x509);
  14942. if (!serial) return "";
  14943. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  14944. if (!bn) return "";
  14945. auto hex = BN_bn2hex(bn);
  14946. BN_free(bn);
  14947. if (!hex) return "";
  14948. std::string result(hex);
  14949. OPENSSL_free(hex);
  14950. return result;
  14951. }
  14952. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14953. if (!cert) return false;
  14954. auto x509 = static_cast<X509 *>(cert);
  14955. auto len = i2d_X509(x509, nullptr);
  14956. if (len < 0) return false;
  14957. der.resize(static_cast<size_t>(len));
  14958. auto p = der.data();
  14959. i2d_X509(x509, &p);
  14960. return true;
  14961. }
  14962. inline const char *get_sni(const_session_t session) {
  14963. if (!session) return nullptr;
  14964. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14965. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14966. }
  14967. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  14968. inline uint64_t get_error() { return ERR_get_error(); }
  14969. inline std::string error_string(uint64_t code) {
  14970. char buf[256];
  14971. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  14972. return std::string(buf);
  14973. }
  14974. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14975. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  14976. if (!mem) { return nullptr; }
  14977. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  14978. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  14979. if (!inf) { return nullptr; }
  14980. auto store = X509_STORE_new();
  14981. if (store) {
  14982. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  14983. auto itmp = sk_X509_INFO_value(inf, i);
  14984. if (!itmp) { continue; }
  14985. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  14986. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  14987. }
  14988. }
  14989. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  14990. return static_cast<ca_store_t>(store);
  14991. }
  14992. inline void free_ca_store(ca_store_t store) {
  14993. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  14994. }
  14995. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  14996. if (!ctx || !store) { return false; }
  14997. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14998. auto x509_store = static_cast<X509_STORE *>(store);
  14999. // Check if same store is already set
  15000. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  15001. // SSL_CTX_set_cert_store takes ownership and frees the old store
  15002. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  15003. return true;
  15004. }
  15005. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15006. certs.clear();
  15007. if (!ctx) { return 0; }
  15008. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15009. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15010. if (!store) { return 0; }
  15011. auto objs = impl::get_store_objects(store);
  15012. if (!objs) { return 0; }
  15013. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15014. auto count = sk_X509_OBJECT_num(objs);
  15015. for (decltype(count) i = 0; i < count; i++) {
  15016. auto obj = sk_X509_OBJECT_value(objs, i);
  15017. if (!obj) { continue; }
  15018. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15019. auto x509 = X509_OBJECT_get0_X509(obj);
  15020. if (x509) {
  15021. // Increment reference count so caller can free it
  15022. X509_up_ref(x509);
  15023. certs.push_back(static_cast<cert_t>(x509));
  15024. }
  15025. }
  15026. }
  15027. return certs.size();
  15028. }
  15029. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15030. std::vector<std::string> names;
  15031. if (!ctx) { return names; }
  15032. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15033. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15034. if (!store) { return names; }
  15035. auto objs = impl::get_store_objects(store);
  15036. if (!objs) { return names; }
  15037. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15038. auto count = sk_X509_OBJECT_num(objs);
  15039. for (decltype(count) i = 0; i < count; i++) {
  15040. auto obj = sk_X509_OBJECT_value(objs, i);
  15041. if (!obj) { continue; }
  15042. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15043. auto x509 = X509_OBJECT_get0_X509(obj);
  15044. if (x509) {
  15045. auto subject = X509_get_subject_name(x509);
  15046. if (subject) {
  15047. char buf[512];
  15048. X509_NAME_oneline(subject, buf, sizeof(buf));
  15049. names.push_back(buf);
  15050. }
  15051. }
  15052. }
  15053. }
  15054. return names;
  15055. }
  15056. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15057. const char *key_pem, const char *password) {
  15058. if (!ctx || !cert_pem || !key_pem) { return false; }
  15059. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15060. // Load certificate from PEM
  15061. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15062. if (!cert_bio) { return false; }
  15063. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15064. BIO_free(cert_bio);
  15065. if (!cert) { return false; }
  15066. // Load private key from PEM
  15067. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15068. if (!key_bio) {
  15069. X509_free(cert);
  15070. return false;
  15071. }
  15072. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15073. password ? const_cast<char *>(password)
  15074. : nullptr);
  15075. BIO_free(key_bio);
  15076. if (!key) {
  15077. X509_free(cert);
  15078. return false;
  15079. }
  15080. // Update certificate and key
  15081. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15082. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15083. X509_free(cert);
  15084. EVP_PKEY_free(key);
  15085. return ret;
  15086. }
  15087. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15088. if (!ctx || !ca_pem) { return false; }
  15089. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15090. // Create new X509_STORE from PEM
  15091. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15092. if (!store) { return false; }
  15093. // SSL_CTX_set_cert_store takes ownership
  15094. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15095. // Set client CA list for client certificate request
  15096. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15097. if (ca_list) {
  15098. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15099. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15100. }
  15101. return true;
  15102. }
  15103. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15104. if (!ctx) { return false; }
  15105. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15106. impl::get_verify_callback() = std::move(callback);
  15107. if (impl::get_verify_callback()) {
  15108. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15109. } else {
  15110. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15111. }
  15112. return true;
  15113. }
  15114. inline long get_verify_error(const_session_t session) {
  15115. if (!session) { return -1; }
  15116. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15117. return SSL_get_verify_result(ssl);
  15118. }
  15119. inline std::string verify_error_string(long error_code) {
  15120. if (error_code == X509_V_OK) { return ""; }
  15121. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15122. return str ? str : "unknown error";
  15123. }
  15124. } // namespace tls
  15125. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15126. /*
  15127. * Group 9: TLS abstraction layer - Mbed TLS backend
  15128. */
  15129. /*
  15130. * Mbed TLS Backend Implementation
  15131. */
  15132. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15133. namespace tls {
  15134. namespace impl {
  15135. // Mbed TLS session wrapper
  15136. struct MbedTlsSession {
  15137. mbedtls_ssl_context ssl;
  15138. socket_t sock = INVALID_SOCKET;
  15139. std::string hostname; // For client: set via set_sni
  15140. std::string sni_hostname; // For server: received from client via SNI callback
  15141. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15142. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15143. MbedTlsSession(const MbedTlsSession &) = delete;
  15144. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15145. };
  15146. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15147. // queue)
  15148. inline int &mbedtls_last_error() {
  15149. static thread_local int err = 0;
  15150. return err;
  15151. }
  15152. // Helper to map Mbed TLS error to ErrorCode
  15153. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15154. if (ret == 0) { return ErrorCode::Success; }
  15155. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15156. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15157. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15158. return ErrorCode::PeerClosed;
  15159. }
  15160. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15161. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15162. out_errno = errno;
  15163. return ErrorCode::SyscallError;
  15164. }
  15165. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15166. return ErrorCode::CertVerifyFailed;
  15167. }
  15168. return ErrorCode::Fatal;
  15169. }
  15170. // BIO-like send callback for Mbed TLS
  15171. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15172. size_t len) {
  15173. auto sock = *static_cast<socket_t *>(ctx);
  15174. #ifdef _WIN32
  15175. auto ret =
  15176. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15177. if (ret == SOCKET_ERROR) {
  15178. int err = WSAGetLastError();
  15179. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15180. return MBEDTLS_ERR_NET_SEND_FAILED;
  15181. }
  15182. #else
  15183. auto ret = send(sock, buf, len, 0);
  15184. if (ret < 0) {
  15185. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15186. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15187. }
  15188. return MBEDTLS_ERR_NET_SEND_FAILED;
  15189. }
  15190. #endif
  15191. return static_cast<int>(ret);
  15192. }
  15193. // BIO-like recv callback for Mbed TLS
  15194. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15195. auto sock = *static_cast<socket_t *>(ctx);
  15196. #ifdef _WIN32
  15197. auto ret =
  15198. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15199. if (ret == SOCKET_ERROR) {
  15200. int err = WSAGetLastError();
  15201. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15202. return MBEDTLS_ERR_NET_RECV_FAILED;
  15203. }
  15204. #else
  15205. auto ret = recv(sock, buf, len, 0);
  15206. if (ret < 0) {
  15207. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15208. return MBEDTLS_ERR_SSL_WANT_READ;
  15209. }
  15210. return MBEDTLS_ERR_NET_RECV_FAILED;
  15211. }
  15212. #endif
  15213. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15214. return static_cast<int>(ret);
  15215. }
  15216. // MbedTlsContext constructor/destructor implementations
  15217. inline MbedTlsContext::MbedTlsContext() {
  15218. mbedtls_ssl_config_init(&conf);
  15219. mbedtls_entropy_init(&entropy);
  15220. mbedtls_ctr_drbg_init(&ctr_drbg);
  15221. mbedtls_x509_crt_init(&ca_chain);
  15222. mbedtls_x509_crt_init(&own_cert);
  15223. mbedtls_pk_init(&own_key);
  15224. }
  15225. inline MbedTlsContext::~MbedTlsContext() {
  15226. mbedtls_pk_free(&own_key);
  15227. mbedtls_x509_crt_free(&own_cert);
  15228. mbedtls_x509_crt_free(&ca_chain);
  15229. mbedtls_ctr_drbg_free(&ctr_drbg);
  15230. mbedtls_entropy_free(&entropy);
  15231. mbedtls_ssl_config_free(&conf);
  15232. }
  15233. // Thread-local storage for SNI captured during handshake
  15234. // This is needed because the SNI callback doesn't have a way to pass
  15235. // session-specific data before the session is fully set up
  15236. inline std::string &mbedpending_sni() {
  15237. static thread_local std::string sni;
  15238. return sni;
  15239. }
  15240. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15241. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15242. const unsigned char *name, size_t name_len) {
  15243. (void)p_ctx;
  15244. (void)ssl;
  15245. // Store SNI name in thread-local storage
  15246. // It will be retrieved and stored in the session after handshake
  15247. if (name && name_len > 0) {
  15248. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15249. } else {
  15250. mbedpending_sni().clear();
  15251. }
  15252. return 0; // Accept any SNI
  15253. }
  15254. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15255. int cert_depth, uint32_t *flags);
  15256. // MbedTLS verify callback wrapper
  15257. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15258. int cert_depth, uint32_t *flags) {
  15259. auto &callback = get_verify_callback();
  15260. if (!callback) { return 0; } // Continue with default verification
  15261. // data points to the MbedTlsSession
  15262. auto *session = static_cast<MbedTlsSession *>(data);
  15263. // Build context
  15264. VerifyContext verify_ctx;
  15265. verify_ctx.session = static_cast<session_t>(session);
  15266. verify_ctx.cert = static_cast<cert_t>(crt);
  15267. verify_ctx.depth = cert_depth;
  15268. verify_ctx.preverify_ok = (*flags == 0);
  15269. verify_ctx.error_code = static_cast<long>(*flags);
  15270. // Convert Mbed TLS flags to error string
  15271. static thread_local char error_buf[256];
  15272. if (*flags != 0) {
  15273. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15274. verify_ctx.error_string = error_buf;
  15275. } else {
  15276. verify_ctx.error_string = nullptr;
  15277. }
  15278. bool accepted = callback(verify_ctx);
  15279. if (accepted) {
  15280. *flags = 0; // Clear all error flags
  15281. return 0;
  15282. }
  15283. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15284. }
  15285. } // namespace impl
  15286. inline ctx_t create_client_context() {
  15287. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15288. if (!ctx) { return nullptr; }
  15289. ctx->is_server = false;
  15290. // Seed the random number generator
  15291. const char *pers = "httplib_client";
  15292. int ret = mbedtls_ctr_drbg_seed(
  15293. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15294. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15295. if (ret != 0) {
  15296. impl::mbedtls_last_error() = ret;
  15297. delete ctx;
  15298. return nullptr;
  15299. }
  15300. // Set up SSL config for client
  15301. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15302. MBEDTLS_SSL_TRANSPORT_STREAM,
  15303. MBEDTLS_SSL_PRESET_DEFAULT);
  15304. if (ret != 0) {
  15305. impl::mbedtls_last_error() = ret;
  15306. delete ctx;
  15307. return nullptr;
  15308. }
  15309. // Set random number generator
  15310. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15311. // Default: verify peer certificate
  15312. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15313. // Set minimum TLS version to 1.2
  15314. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15315. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15316. #else
  15317. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15318. MBEDTLS_SSL_MINOR_VERSION_3);
  15319. #endif
  15320. return static_cast<ctx_t>(ctx);
  15321. }
  15322. inline ctx_t create_server_context() {
  15323. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15324. if (!ctx) { return nullptr; }
  15325. ctx->is_server = true;
  15326. // Seed the random number generator
  15327. const char *pers = "httplib_server";
  15328. int ret = mbedtls_ctr_drbg_seed(
  15329. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15330. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15331. if (ret != 0) {
  15332. impl::mbedtls_last_error() = ret;
  15333. delete ctx;
  15334. return nullptr;
  15335. }
  15336. // Set up SSL config for server
  15337. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15338. MBEDTLS_SSL_TRANSPORT_STREAM,
  15339. MBEDTLS_SSL_PRESET_DEFAULT);
  15340. if (ret != 0) {
  15341. impl::mbedtls_last_error() = ret;
  15342. delete ctx;
  15343. return nullptr;
  15344. }
  15345. // Set random number generator
  15346. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15347. // Default: don't verify client
  15348. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15349. // Set minimum TLS version to 1.2
  15350. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15351. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15352. #else
  15353. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15354. MBEDTLS_SSL_MINOR_VERSION_3);
  15355. #endif
  15356. // Set SNI callback to capture client's SNI hostname
  15357. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15358. return static_cast<ctx_t>(ctx);
  15359. }
  15360. inline void free_context(ctx_t ctx) {
  15361. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15362. }
  15363. inline bool set_min_version(ctx_t ctx, Version version) {
  15364. if (!ctx) { return false; }
  15365. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15366. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15367. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15368. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15369. if (version >= Version::TLS1_3) {
  15370. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15371. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15372. #endif
  15373. }
  15374. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15375. #else
  15376. // Mbed TLS 2.x uses major/minor version numbers
  15377. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15378. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15379. if (version >= Version::TLS1_3) {
  15380. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15381. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15382. #else
  15383. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15384. #endif
  15385. }
  15386. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15387. #endif
  15388. return true;
  15389. }
  15390. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15391. if (!ctx || !pem) { return false; }
  15392. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15393. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15394. // Add null terminator if not present
  15395. std::string pem_str(pem, len);
  15396. int ret = mbedtls_x509_crt_parse(
  15397. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15398. pem_str.size() + 1);
  15399. if (ret != 0) {
  15400. impl::mbedtls_last_error() = ret;
  15401. return false;
  15402. }
  15403. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15404. return true;
  15405. }
  15406. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15407. if (!ctx || !file_path) { return false; }
  15408. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15409. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15410. if (ret != 0) {
  15411. impl::mbedtls_last_error() = ret;
  15412. return false;
  15413. }
  15414. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15415. return true;
  15416. }
  15417. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15418. if (!ctx || !dir_path) { return false; }
  15419. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15420. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15421. if (ret < 0) { // Returns number of certs on success, negative on error
  15422. impl::mbedtls_last_error() = ret;
  15423. return false;
  15424. }
  15425. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15426. return true;
  15427. }
  15428. inline bool load_system_certs(ctx_t ctx) {
  15429. if (!ctx) { return false; }
  15430. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15431. bool loaded = false;
  15432. #ifdef _WIN32
  15433. loaded = impl::enumerate_windows_system_certs(
  15434. [&](const unsigned char *data, size_t len) {
  15435. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15436. });
  15437. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15438. loaded = impl::enumerate_macos_keychain_certs(
  15439. [&](const unsigned char *data, size_t len) {
  15440. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15441. });
  15442. #else
  15443. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15444. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15445. loaded = true;
  15446. break;
  15447. }
  15448. }
  15449. if (!loaded) {
  15450. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15451. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15452. loaded = true;
  15453. break;
  15454. }
  15455. }
  15456. }
  15457. #endif
  15458. if (loaded) {
  15459. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15460. }
  15461. return loaded;
  15462. }
  15463. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15464. const char *password) {
  15465. if (!ctx || !cert || !key) { return false; }
  15466. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15467. // Parse certificate
  15468. std::string cert_str(cert);
  15469. int ret = mbedtls_x509_crt_parse(
  15470. &mctx->own_cert,
  15471. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15472. cert_str.size() + 1);
  15473. if (ret != 0) {
  15474. impl::mbedtls_last_error() = ret;
  15475. return false;
  15476. }
  15477. // Parse private key
  15478. std::string key_str(key);
  15479. const unsigned char *pwd =
  15480. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15481. size_t pwd_len = password ? strlen(password) : 0;
  15482. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15483. ret = mbedtls_pk_parse_key(
  15484. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15485. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15486. &mctx->ctr_drbg);
  15487. #else
  15488. ret = mbedtls_pk_parse_key(
  15489. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15490. key_str.size() + 1, pwd, pwd_len);
  15491. #endif
  15492. if (ret != 0) {
  15493. impl::mbedtls_last_error() = ret;
  15494. return false;
  15495. }
  15496. // Verify that the certificate and private key match
  15497. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15498. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15499. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15500. #else
  15501. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15502. #endif
  15503. if (ret != 0) {
  15504. impl::mbedtls_last_error() = ret;
  15505. return false;
  15506. }
  15507. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15508. if (ret != 0) {
  15509. impl::mbedtls_last_error() = ret;
  15510. return false;
  15511. }
  15512. return true;
  15513. }
  15514. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15515. const char *key_path, const char *password) {
  15516. if (!ctx || !cert_path || !key_path) { return false; }
  15517. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15518. // Parse certificate file
  15519. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15520. if (ret != 0) {
  15521. impl::mbedtls_last_error() = ret;
  15522. return false;
  15523. }
  15524. // Parse private key file
  15525. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15526. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15527. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15528. #else
  15529. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15530. #endif
  15531. if (ret != 0) {
  15532. impl::mbedtls_last_error() = ret;
  15533. return false;
  15534. }
  15535. // Verify that the certificate and private key match
  15536. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15537. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15538. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15539. #else
  15540. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15541. #endif
  15542. if (ret != 0) {
  15543. impl::mbedtls_last_error() = ret;
  15544. return false;
  15545. }
  15546. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15547. if (ret != 0) {
  15548. impl::mbedtls_last_error() = ret;
  15549. return false;
  15550. }
  15551. return true;
  15552. }
  15553. inline void set_verify_client(ctx_t ctx, bool require) {
  15554. if (!ctx) { return; }
  15555. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15556. mctx->verify_client = require;
  15557. if (require) {
  15558. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15559. } else {
  15560. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15561. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15562. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15563. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15564. : MBEDTLS_SSL_VERIFY_NONE);
  15565. }
  15566. }
  15567. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15568. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15569. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15570. auto session = new (std::nothrow) impl::MbedTlsSession();
  15571. if (!session) { return nullptr; }
  15572. session->sock = sock;
  15573. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15574. if (ret != 0) {
  15575. impl::mbedtls_last_error() = ret;
  15576. delete session;
  15577. return nullptr;
  15578. }
  15579. // Explicitly opt out of in-handshake hostname verification by default;
  15580. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15581. // fails outright when no hostname was set. set_sni() installs the real
  15582. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15583. // caller verifies the certificate identity post-handshake via
  15584. // verify_hostname().
  15585. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15586. // Set BIO callbacks
  15587. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15588. impl::mbedtls_net_recv_cb, nullptr);
  15589. // Set per-session verify callback with session pointer if callback is
  15590. // registered
  15591. if (mctx->has_verify_callback) {
  15592. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15593. session);
  15594. }
  15595. return static_cast<session_t>(session);
  15596. }
  15597. inline void free_session(session_t session) {
  15598. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15599. }
  15600. inline bool set_sni(session_t session, const char *hostname) {
  15601. if (!session || !hostname) { return false; }
  15602. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15603. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15604. if (ret != 0) {
  15605. impl::mbedtls_last_error() = ret;
  15606. return false;
  15607. }
  15608. msession->hostname = hostname;
  15609. return true;
  15610. }
  15611. inline bool set_hostname(session_t session, const char *hostname) {
  15612. // In Mbed TLS, set_hostname also sets up hostname verification
  15613. return set_sni(session, hostname);
  15614. }
  15615. inline TlsError connect(session_t session) {
  15616. TlsError err;
  15617. if (!session) {
  15618. err.code = ErrorCode::Fatal;
  15619. return err;
  15620. }
  15621. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15622. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15623. if (ret == 0) {
  15624. err.code = ErrorCode::Success;
  15625. } else {
  15626. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15627. err.backend_code = static_cast<uint64_t>(-ret);
  15628. impl::mbedtls_last_error() = ret;
  15629. }
  15630. return err;
  15631. }
  15632. inline TlsError accept(session_t session) {
  15633. // Same as connect for Mbed TLS - handshake works for both client and server
  15634. auto result = connect(session);
  15635. // After successful handshake, capture SNI from thread-local storage
  15636. if (result.code == ErrorCode::Success && session) {
  15637. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15638. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15639. impl::mbedpending_sni().clear();
  15640. }
  15641. return result;
  15642. }
  15643. inline bool connect_nonblocking(session_t session, socket_t sock,
  15644. time_t timeout_sec, time_t timeout_usec,
  15645. TlsError *err) {
  15646. if (!session) {
  15647. if (err) { err->code = ErrorCode::Fatal; }
  15648. return false;
  15649. }
  15650. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15651. // Set socket to non-blocking mode
  15652. detail::set_nonblocking(sock, true);
  15653. auto cleanup =
  15654. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15655. int ret;
  15656. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15657. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15658. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15659. continue;
  15660. }
  15661. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15662. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15663. continue;
  15664. }
  15665. }
  15666. // TlsError or timeout
  15667. if (err) {
  15668. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15669. err->backend_code = static_cast<uint64_t>(-ret);
  15670. }
  15671. impl::mbedtls_last_error() = ret;
  15672. return false;
  15673. }
  15674. if (err) { err->code = ErrorCode::Success; }
  15675. return true;
  15676. }
  15677. inline bool accept_nonblocking(session_t session, socket_t sock,
  15678. time_t timeout_sec, time_t timeout_usec,
  15679. TlsError *err) {
  15680. // Same implementation as connect for Mbed TLS
  15681. bool result =
  15682. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15683. // After successful handshake, capture SNI from thread-local storage
  15684. if (result && session) {
  15685. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15686. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15687. impl::mbedpending_sni().clear();
  15688. }
  15689. return result;
  15690. }
  15691. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15692. if (!session || !buf) {
  15693. err.code = ErrorCode::Fatal;
  15694. return -1;
  15695. }
  15696. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15697. int ret =
  15698. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15699. if (ret > 0) {
  15700. err.code = ErrorCode::Success;
  15701. return static_cast<ssize_t>(ret);
  15702. }
  15703. if (ret == 0) {
  15704. err.code = ErrorCode::PeerClosed;
  15705. return 0;
  15706. }
  15707. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15708. err.backend_code = static_cast<uint64_t>(-ret);
  15709. impl::mbedtls_last_error() = ret;
  15710. // mbedTLS signals a clean close_notify via a negative error code rather
  15711. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15712. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15713. return -1;
  15714. }
  15715. inline ssize_t write(session_t session, const void *buf, size_t len,
  15716. TlsError &err) {
  15717. if (!session || !buf) {
  15718. err.code = ErrorCode::Fatal;
  15719. return -1;
  15720. }
  15721. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15722. int ret = mbedtls_ssl_write(&msession->ssl,
  15723. static_cast<const unsigned char *>(buf), len);
  15724. if (ret > 0) {
  15725. err.code = ErrorCode::Success;
  15726. return static_cast<ssize_t>(ret);
  15727. }
  15728. if (ret == 0) {
  15729. err.code = ErrorCode::PeerClosed;
  15730. return 0;
  15731. }
  15732. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15733. err.backend_code = static_cast<uint64_t>(-ret);
  15734. impl::mbedtls_last_error() = ret;
  15735. return -1;
  15736. }
  15737. inline int pending(const_session_t session) {
  15738. if (!session) { return 0; }
  15739. auto msession =
  15740. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15741. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15742. }
  15743. inline void shutdown(session_t session, bool graceful) {
  15744. if (!session) { return; }
  15745. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15746. if (graceful) {
  15747. // Try to send close_notify, but don't block forever
  15748. int ret;
  15749. int attempts = 0;
  15750. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15751. attempts < 3) {
  15752. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15753. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15754. break;
  15755. }
  15756. attempts++;
  15757. }
  15758. }
  15759. }
  15760. inline bool is_peer_closed(session_t session, socket_t sock) {
  15761. if (!session || sock == INVALID_SOCKET) { return true; }
  15762. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15763. // Check if there's already decrypted data available in the TLS buffer
  15764. // If so, the connection is definitely alive
  15765. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15766. // Set socket to non-blocking to avoid blocking on read
  15767. detail::set_nonblocking(sock, true);
  15768. auto cleanup =
  15769. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15770. // Try a 1-byte read to check connection status
  15771. // Note: This will consume the byte if data is available, but for the
  15772. // purpose of checking if peer is closed, this should be acceptable
  15773. // since we're only called when we expect the connection might be closing
  15774. unsigned char buf;
  15775. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15776. // If we got data or WANT_READ (would block), connection is alive
  15777. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15778. // If we get a peer close notify or a connection reset, the peer is closed
  15779. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15780. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15781. }
  15782. inline cert_t get_peer_cert(const_session_t session) {
  15783. if (!session) { return nullptr; }
  15784. auto msession =
  15785. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15786. // Mbed TLS returns a pointer to the internal peer cert chain.
  15787. // WARNING: This pointer is only valid while the session is active.
  15788. // Do not use the certificate after calling free_session().
  15789. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15790. return const_cast<mbedtls_x509_crt *>(cert);
  15791. }
  15792. inline void free_cert(cert_t cert) {
  15793. // Mbed TLS: peer certificate is owned by the SSL context.
  15794. // No-op here, but callers should still call this for cross-backend
  15795. // portability.
  15796. (void)cert;
  15797. }
  15798. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15799. if (!cert || !hostname) { return false; }
  15800. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15801. std::string host_str(hostname);
  15802. // Check if hostname is an IP address (IPv4 or IPv6)
  15803. unsigned char ip_bytes[16];
  15804. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  15805. auto is_ip = ip_len > 0;
  15806. // Check Subject Alternative Names (SAN)
  15807. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15808. // - DNS names: raw string bytes
  15809. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15810. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15811. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15812. const unsigned char *p = san->buf.p;
  15813. size_t len = san->buf.len;
  15814. if (is_ip) {
  15815. // For an IP host, only a matching iPAddress SAN of the same family
  15816. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  15817. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  15818. } else {
  15819. // Check if this SAN is a DNS name (printable ASCII string)
  15820. bool is_dns = len > 0;
  15821. for (size_t i = 0; i < len && is_dns; i++) {
  15822. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15823. }
  15824. if (is_dns) {
  15825. std::string san_name(reinterpret_cast<const char *>(p), len);
  15826. if (detail::match_hostname(san_name, host_str)) { return true; }
  15827. }
  15828. }
  15829. san = san->next;
  15830. }
  15831. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  15832. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  15833. // the OpenSSL backend's X509_check_ip behaves the same way).
  15834. if (!is_ip) {
  15835. char cn[256];
  15836. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15837. if (ret > 0) {
  15838. std::string cn_str(cn);
  15839. // Look for "CN=" in the DN string
  15840. size_t cn_pos = cn_str.find("CN=");
  15841. if (cn_pos != std::string::npos) {
  15842. size_t start = cn_pos + 3;
  15843. size_t end = cn_str.find(',', start);
  15844. std::string cn_value =
  15845. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15846. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15847. }
  15848. }
  15849. }
  15850. return false;
  15851. }
  15852. inline uint64_t hostname_mismatch_code() {
  15853. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15854. }
  15855. inline long get_verify_result(const_session_t session) {
  15856. if (!session) { return -1; }
  15857. auto msession =
  15858. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15859. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15860. // Return 0 (X509_V_OK equivalent) if verification passed
  15861. return flags == 0 ? 0 : static_cast<long>(flags);
  15862. }
  15863. inline std::string get_cert_subject_cn(cert_t cert) {
  15864. if (!cert) return "";
  15865. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15866. // Find the CN in the subject
  15867. const mbedtls_x509_name *name = &x509->subject;
  15868. while (name != nullptr) {
  15869. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15870. return std::string(reinterpret_cast<const char *>(name->val.p),
  15871. name->val.len);
  15872. }
  15873. name = name->next;
  15874. }
  15875. return "";
  15876. }
  15877. inline std::string get_cert_issuer_name(cert_t cert) {
  15878. if (!cert) return "";
  15879. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15880. // Build a human-readable issuer name string
  15881. char buf[512];
  15882. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15883. if (ret < 0) return "";
  15884. return std::string(buf);
  15885. }
  15886. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15887. sans.clear();
  15888. if (!cert) return false;
  15889. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15890. // Parse the Subject Alternative Name extension
  15891. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15892. while (cur != nullptr) {
  15893. if (cur->buf.len > 0) {
  15894. // Mbed TLS stores SAN as ASN.1 sequences
  15895. // The tag byte indicates the type
  15896. const unsigned char *p = cur->buf.p;
  15897. size_t len = cur->buf.len;
  15898. // First byte is the tag
  15899. unsigned char tag = *p;
  15900. p++;
  15901. len--;
  15902. // Parse length (simple single-byte length assumed)
  15903. if (len > 0 && *p < 0x80) {
  15904. size_t value_len = *p;
  15905. p++;
  15906. len--;
  15907. if (value_len <= len) {
  15908. SanEntry entry;
  15909. // ASN.1 context tags for GeneralName
  15910. switch (tag & 0x1F) {
  15911. case 2: // dNSName
  15912. entry.type = SanType::DNS;
  15913. entry.value =
  15914. std::string(reinterpret_cast<const char *>(p), value_len);
  15915. break;
  15916. case 7: // iPAddress
  15917. entry.type = SanType::IP;
  15918. if (value_len == 4) {
  15919. // IPv4
  15920. char buf[16];
  15921. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15922. entry.value = buf;
  15923. } else if (value_len == 16) {
  15924. // IPv6
  15925. char buf[64];
  15926. snprintf(buf, sizeof(buf),
  15927. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15928. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15929. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15930. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15931. entry.value = buf;
  15932. }
  15933. break;
  15934. case 1: // rfc822Name (email)
  15935. entry.type = SanType::EMAIL;
  15936. entry.value =
  15937. std::string(reinterpret_cast<const char *>(p), value_len);
  15938. break;
  15939. case 6: // uniformResourceIdentifier
  15940. entry.type = SanType::URI;
  15941. entry.value =
  15942. std::string(reinterpret_cast<const char *>(p), value_len);
  15943. break;
  15944. default: entry.type = SanType::OTHER; break;
  15945. }
  15946. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15947. }
  15948. }
  15949. }
  15950. cur = cur->next;
  15951. }
  15952. return true;
  15953. }
  15954. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15955. time_t &not_after) {
  15956. if (!cert) return false;
  15957. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15958. // Convert mbedtls_x509_time to time_t
  15959. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  15960. struct tm tm_time = {};
  15961. tm_time.tm_year = t.year - 1900;
  15962. tm_time.tm_mon = t.mon - 1;
  15963. tm_time.tm_mday = t.day;
  15964. tm_time.tm_hour = t.hour;
  15965. tm_time.tm_min = t.min;
  15966. tm_time.tm_sec = t.sec;
  15967. #ifdef _WIN32
  15968. return _mkgmtime(&tm_time);
  15969. #else
  15970. return timegm(&tm_time);
  15971. #endif
  15972. };
  15973. not_before = to_time_t(x509->valid_from);
  15974. not_after = to_time_t(x509->valid_to);
  15975. return true;
  15976. }
  15977. inline std::string get_cert_serial(cert_t cert) {
  15978. if (!cert) return "";
  15979. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15980. // Convert serial number to hex string
  15981. std::string result;
  15982. result.reserve(x509->serial.len * 2);
  15983. for (size_t i = 0; i < x509->serial.len; i++) {
  15984. char hex[3];
  15985. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  15986. result += hex;
  15987. }
  15988. return result;
  15989. }
  15990. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  15991. if (!cert) return false;
  15992. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  15993. if (!crt->raw.p || crt->raw.len == 0) return false;
  15994. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  15995. return true;
  15996. }
  15997. inline const char *get_sni(const_session_t session) {
  15998. if (!session) return nullptr;
  15999. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  16000. // For server: return SNI received from client during handshake
  16001. if (!msession->sni_hostname.empty()) {
  16002. return msession->sni_hostname.c_str();
  16003. }
  16004. // For client: return the hostname set via set_sni
  16005. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  16006. return nullptr;
  16007. }
  16008. inline uint64_t peek_error() {
  16009. // Mbed TLS doesn't have an error queue, return the last error
  16010. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  16011. }
  16012. inline uint64_t get_error() {
  16013. // Mbed TLS doesn't have an error queue, return and clear the last error
  16014. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  16015. impl::mbedtls_last_error() = 0;
  16016. return err;
  16017. }
  16018. inline std::string error_string(uint64_t code) {
  16019. char buf[256];
  16020. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16021. return std::string(buf);
  16022. }
  16023. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16024. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16025. if (!ca_chain) { return nullptr; }
  16026. mbedtls_x509_crt_init(ca_chain);
  16027. // mbedtls_x509_crt_parse expects null-terminated PEM
  16028. int ret = mbedtls_x509_crt_parse(ca_chain,
  16029. reinterpret_cast<const unsigned char *>(pem),
  16030. len + 1); // +1 for null terminator
  16031. if (ret != 0) {
  16032. // Try without +1 in case PEM is already null-terminated
  16033. ret = mbedtls_x509_crt_parse(
  16034. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16035. if (ret != 0) {
  16036. mbedtls_x509_crt_free(ca_chain);
  16037. delete ca_chain;
  16038. return nullptr;
  16039. }
  16040. }
  16041. return static_cast<ca_store_t>(ca_chain);
  16042. }
  16043. inline void free_ca_store(ca_store_t store) {
  16044. if (store) {
  16045. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16046. mbedtls_x509_crt_free(ca_chain);
  16047. delete ca_chain;
  16048. }
  16049. }
  16050. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16051. if (!ctx || !store) { return false; }
  16052. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16053. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16054. // Free existing CA chain
  16055. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16056. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16057. // Copy the CA chain (deep copy)
  16058. // Parse from the raw data of the source cert
  16059. mbedtls_x509_crt *src = ca_chain;
  16060. while (src != nullptr) {
  16061. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16062. src->raw.len);
  16063. if (ret != 0) {
  16064. free_ca_store(store);
  16065. return false;
  16066. }
  16067. src = src->next;
  16068. }
  16069. // This function takes ownership of the store; the chain was deep-copied
  16070. // above, so release the source
  16071. free_ca_store(store);
  16072. // Update the SSL config to use the new CA chain
  16073. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16074. return true;
  16075. }
  16076. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16077. certs.clear();
  16078. if (!ctx) { return 0; }
  16079. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16080. // Iterate through the CA chain
  16081. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16082. while (cert != nullptr && cert->raw.len > 0) {
  16083. // Create a copy of the certificate for the caller
  16084. auto *copy = new mbedtls_x509_crt;
  16085. mbedtls_x509_crt_init(copy);
  16086. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16087. if (ret == 0) {
  16088. certs.push_back(static_cast<cert_t>(copy));
  16089. } else {
  16090. mbedtls_x509_crt_free(copy);
  16091. delete copy;
  16092. }
  16093. cert = cert->next;
  16094. }
  16095. return certs.size();
  16096. }
  16097. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16098. std::vector<std::string> names;
  16099. if (!ctx) { return names; }
  16100. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16101. // Iterate through the CA chain
  16102. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16103. while (cert != nullptr && cert->raw.len > 0) {
  16104. char buf[512];
  16105. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16106. if (ret > 0) { names.push_back(buf); }
  16107. cert = cert->next;
  16108. }
  16109. return names;
  16110. }
  16111. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16112. const char *key_pem, const char *password) {
  16113. if (!ctx || !cert_pem || !key_pem) { return false; }
  16114. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16115. // Free existing certificate and key
  16116. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16117. mbedtls_pk_free(&mbed_ctx->own_key);
  16118. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16119. mbedtls_pk_init(&mbed_ctx->own_key);
  16120. // Parse certificate PEM
  16121. int ret = mbedtls_x509_crt_parse(
  16122. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16123. strlen(cert_pem) + 1);
  16124. if (ret != 0) {
  16125. impl::mbedtls_last_error() = ret;
  16126. return false;
  16127. }
  16128. // Parse private key PEM
  16129. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16130. ret = mbedtls_pk_parse_key(
  16131. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16132. strlen(key_pem) + 1,
  16133. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16134. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16135. &mbed_ctx->ctr_drbg);
  16136. #else
  16137. ret = mbedtls_pk_parse_key(
  16138. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16139. strlen(key_pem) + 1,
  16140. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16141. password ? strlen(password) : 0);
  16142. #endif
  16143. if (ret != 0) {
  16144. impl::mbedtls_last_error() = ret;
  16145. return false;
  16146. }
  16147. // Configure SSL to use the new certificate and key
  16148. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16149. &mbed_ctx->own_key);
  16150. if (ret != 0) {
  16151. impl::mbedtls_last_error() = ret;
  16152. return false;
  16153. }
  16154. return true;
  16155. }
  16156. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16157. if (!ctx || !ca_pem) { return false; }
  16158. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16159. // Free existing CA chain
  16160. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16161. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16162. // Parse CA PEM
  16163. int ret = mbedtls_x509_crt_parse(
  16164. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16165. strlen(ca_pem) + 1);
  16166. if (ret != 0) {
  16167. impl::mbedtls_last_error() = ret;
  16168. return false;
  16169. }
  16170. // Update SSL config to use new CA chain
  16171. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16172. return true;
  16173. }
  16174. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16175. if (!ctx) { return false; }
  16176. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16177. impl::get_verify_callback() = std::move(callback);
  16178. mbed_ctx->has_verify_callback =
  16179. static_cast<bool>(impl::get_verify_callback());
  16180. if (mbed_ctx->has_verify_callback) {
  16181. // Set OPTIONAL mode to ensure callback is called even when verification
  16182. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16183. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16184. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16185. nullptr);
  16186. } else {
  16187. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16188. }
  16189. return true;
  16190. }
  16191. inline long get_verify_error(const_session_t session) {
  16192. if (!session) { return -1; }
  16193. auto *msession =
  16194. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16195. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16196. }
  16197. inline std::string verify_error_string(long error_code) {
  16198. if (error_code == 0) { return ""; }
  16199. char buf[256];
  16200. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16201. static_cast<uint32_t>(error_code));
  16202. // Remove trailing newline if present
  16203. std::string result(buf);
  16204. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16205. result.pop_back();
  16206. }
  16207. return result;
  16208. }
  16209. } // namespace tls
  16210. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16211. /*
  16212. * Group 10: TLS abstraction layer - wolfSSL backend
  16213. */
  16214. /*
  16215. * wolfSSL Backend Implementation
  16216. */
  16217. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16218. namespace tls {
  16219. namespace impl {
  16220. // wolfSSL session wrapper
  16221. struct WolfSSLSession {
  16222. WOLFSSL *ssl = nullptr;
  16223. socket_t sock = INVALID_SOCKET;
  16224. std::string hostname; // For client: set via set_sni
  16225. std::string sni_hostname; // For server: received from client via SNI callback
  16226. WolfSSLSession() = default;
  16227. ~WolfSSLSession() {
  16228. if (ssl) { wolfSSL_free(ssl); }
  16229. }
  16230. WolfSSLSession(const WolfSSLSession &) = delete;
  16231. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16232. };
  16233. // Thread-local error code accessor for wolfSSL
  16234. inline uint64_t &wolfssl_last_error() {
  16235. static thread_local uint64_t err = 0;
  16236. return err;
  16237. }
  16238. // Helper to map wolfSSL error to ErrorCode.
  16239. // ssl_error is the value from wolfSSL_get_error().
  16240. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16241. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16242. int &out_errno) {
  16243. switch (ssl_error) {
  16244. case SSL_ERROR_NONE: return ErrorCode::Success;
  16245. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16246. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16247. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16248. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16249. default:
  16250. if (ssl) {
  16251. // wolfSSL stores the low-level error code as a negative value.
  16252. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16253. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16254. if (low_err == DOMAIN_NAME_MISMATCH) {
  16255. return ErrorCode::HostnameMismatch;
  16256. }
  16257. // Check verify result to distinguish cert verification from generic SSL
  16258. // errors.
  16259. long vr = wolfSSL_get_verify_result(ssl);
  16260. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16261. }
  16262. return ErrorCode::Fatal;
  16263. }
  16264. }
  16265. // WolfSSLContext constructor/destructor implementations
  16266. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16267. inline WolfSSLContext::~WolfSSLContext() {
  16268. if (ctx) { wolfSSL_CTX_free(ctx); }
  16269. }
  16270. // Thread-local storage for SNI captured during handshake
  16271. inline std::string &wolfssl_pending_sni() {
  16272. static thread_local std::string sni;
  16273. return sni;
  16274. }
  16275. // SNI callback for wolfSSL server to capture client's SNI hostname
  16276. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16277. (void)ret;
  16278. (void)exArg;
  16279. void *name_data = nullptr;
  16280. unsigned short name_len =
  16281. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16282. if (name_data && name_len > 0) {
  16283. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16284. name_len);
  16285. } else {
  16286. wolfssl_pending_sni().clear();
  16287. }
  16288. return 0; // Continue regardless
  16289. }
  16290. // wolfSSL verify callback wrapper
  16291. inline int wolfssl_verify_callback(int preverify_ok,
  16292. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16293. auto &callback = get_verify_callback();
  16294. if (!callback) { return preverify_ok; }
  16295. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16296. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16297. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16298. // Get the WOLFSSL object from the X509_STORE_CTX
  16299. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16300. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16301. VerifyContext verify_ctx;
  16302. verify_ctx.session = static_cast<session_t>(ssl);
  16303. verify_ctx.cert = static_cast<cert_t>(cert);
  16304. verify_ctx.depth = depth;
  16305. verify_ctx.preverify_ok = (preverify_ok != 0);
  16306. verify_ctx.error_code = static_cast<long>(err);
  16307. if (err != 0) {
  16308. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16309. } else {
  16310. verify_ctx.error_string = nullptr;
  16311. }
  16312. bool accepted = callback(verify_ctx);
  16313. return accepted ? 1 : 0;
  16314. }
  16315. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16316. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16317. wolfSSL_CTX_set_default_passwd_cb(
  16318. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16319. auto *pwd = static_cast<const char *>(userdata);
  16320. if (!pwd) return 0;
  16321. auto len = static_cast<int>(strlen(pwd));
  16322. if (len > size) len = size;
  16323. memcpy(buf, pwd, static_cast<size_t>(len));
  16324. return len;
  16325. });
  16326. }
  16327. } // namespace impl
  16328. inline ctx_t create_client_context() {
  16329. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16330. if (!ctx) { return nullptr; }
  16331. ctx->is_server = false;
  16332. WOLFSSL_METHOD *method = wolfTLSv1_2_client_method();
  16333. if (!method) {
  16334. delete ctx;
  16335. return nullptr;
  16336. }
  16337. ctx->ctx = wolfSSL_CTX_new(method);
  16338. if (!ctx->ctx) {
  16339. delete ctx;
  16340. return nullptr;
  16341. }
  16342. // Default: verify peer certificate
  16343. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16344. return static_cast<ctx_t>(ctx);
  16345. }
  16346. inline ctx_t create_server_context() {
  16347. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16348. if (!ctx) { return nullptr; }
  16349. ctx->is_server = true;
  16350. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16351. if (!method) {
  16352. delete ctx;
  16353. return nullptr;
  16354. }
  16355. ctx->ctx = wolfSSL_CTX_new(method);
  16356. if (!ctx->ctx) {
  16357. delete ctx;
  16358. return nullptr;
  16359. }
  16360. // Default: don't verify client
  16361. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16362. // Enable SNI on server
  16363. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16364. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16365. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16366. return static_cast<ctx_t>(ctx);
  16367. }
  16368. inline void free_context(ctx_t ctx) {
  16369. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16370. }
  16371. inline bool set_min_version(ctx_t ctx, Version version) {
  16372. if (!ctx) { return false; }
  16373. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16374. int min_ver = WOLFSSL_TLSV1_2;
  16375. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16376. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16377. }
  16378. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16379. if (!ctx || !pem) { return false; }
  16380. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16381. int ret = wolfSSL_CTX_load_verify_buffer(
  16382. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16383. static_cast<long>(len), SSL_FILETYPE_PEM);
  16384. if (ret != SSL_SUCCESS) {
  16385. impl::wolfssl_last_error() =
  16386. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16387. return false;
  16388. }
  16389. wctx->ca_pem_data_.append(pem, len);
  16390. return true;
  16391. }
  16392. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16393. if (!ctx || !file_path) { return false; }
  16394. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16395. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16396. if (ret != SSL_SUCCESS) {
  16397. impl::wolfssl_last_error() =
  16398. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16399. return false;
  16400. }
  16401. return true;
  16402. }
  16403. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16404. if (!ctx || !dir_path) { return false; }
  16405. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16406. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16407. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16408. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16409. // immediately. Return true even on failure since the CA file may have
  16410. // already been loaded, matching OpenSSL's lenient behavior.
  16411. (void)ret;
  16412. return true;
  16413. }
  16414. inline bool load_system_certs(ctx_t ctx) {
  16415. if (!ctx) { return false; }
  16416. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16417. bool loaded = false;
  16418. #ifdef _WIN32
  16419. loaded = impl::enumerate_windows_system_certs(
  16420. [&](const unsigned char *data, size_t len) {
  16421. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16422. static_cast<long>(len),
  16423. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16424. });
  16425. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16426. loaded = impl::enumerate_macos_keychain_certs(
  16427. [&](const unsigned char *data, size_t len) {
  16428. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16429. static_cast<long>(len),
  16430. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16431. });
  16432. #else
  16433. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16434. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16435. SSL_SUCCESS) {
  16436. loaded = true;
  16437. break;
  16438. }
  16439. }
  16440. if (!loaded) {
  16441. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16442. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16443. SSL_SUCCESS) {
  16444. loaded = true;
  16445. break;
  16446. }
  16447. }
  16448. }
  16449. #endif
  16450. return loaded;
  16451. }
  16452. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16453. const char *password) {
  16454. if (!ctx || !cert || !key) { return false; }
  16455. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16456. // Load certificate
  16457. int ret = wolfSSL_CTX_use_certificate_buffer(
  16458. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16459. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16460. if (ret != SSL_SUCCESS) {
  16461. impl::wolfssl_last_error() =
  16462. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16463. return false;
  16464. }
  16465. // Set password callback if password is provided
  16466. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16467. // Load private key
  16468. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16469. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16470. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16471. if (ret != SSL_SUCCESS) {
  16472. impl::wolfssl_last_error() =
  16473. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16474. return false;
  16475. }
  16476. // Verify that the certificate and private key match
  16477. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16478. }
  16479. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16480. const char *key_path, const char *password) {
  16481. if (!ctx || !cert_path || !key_path) { return false; }
  16482. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16483. // Load certificate file
  16484. int ret =
  16485. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16486. if (ret != SSL_SUCCESS) {
  16487. impl::wolfssl_last_error() =
  16488. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16489. return false;
  16490. }
  16491. // Set password callback if password is provided
  16492. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16493. // Load private key file
  16494. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16495. if (ret != SSL_SUCCESS) {
  16496. impl::wolfssl_last_error() =
  16497. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16498. return false;
  16499. }
  16500. // Verify that the certificate and private key match
  16501. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16502. }
  16503. inline void set_verify_client(ctx_t ctx, bool require) {
  16504. if (!ctx) { return; }
  16505. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16506. wctx->verify_client = require;
  16507. if (require) {
  16508. wolfSSL_CTX_set_verify(
  16509. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16510. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16511. } else {
  16512. if (wctx->has_verify_callback) {
  16513. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16514. impl::wolfssl_verify_callback);
  16515. } else {
  16516. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16517. }
  16518. }
  16519. }
  16520. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16521. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16522. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16523. auto session = new (std::nothrow) impl::WolfSSLSession();
  16524. if (!session) { return nullptr; }
  16525. session->sock = sock;
  16526. session->ssl = wolfSSL_new(wctx->ctx);
  16527. if (!session->ssl) {
  16528. impl::wolfssl_last_error() =
  16529. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16530. delete session;
  16531. return nullptr;
  16532. }
  16533. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16534. return static_cast<session_t>(session);
  16535. }
  16536. inline void free_session(session_t session) {
  16537. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16538. }
  16539. inline bool set_sni(session_t session, const char *hostname) {
  16540. if (!session || !hostname) { return false; }
  16541. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16542. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16543. static_cast<word16>(strlen(hostname)));
  16544. if (ret != WOLFSSL_SUCCESS) {
  16545. impl::wolfssl_last_error() =
  16546. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16547. return false;
  16548. }
  16549. // Also set hostname for verification
  16550. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16551. wsession->hostname = hostname;
  16552. return true;
  16553. }
  16554. inline bool set_hostname(session_t session, const char *hostname) {
  16555. // In wolfSSL, set_hostname also sets up hostname verification
  16556. return set_sni(session, hostname);
  16557. }
  16558. inline TlsError connect(session_t session) {
  16559. TlsError err;
  16560. if (!session) {
  16561. err.code = ErrorCode::Fatal;
  16562. return err;
  16563. }
  16564. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16565. int ret = wolfSSL_connect(wsession->ssl);
  16566. if (ret == SSL_SUCCESS) {
  16567. err.code = ErrorCode::Success;
  16568. } else {
  16569. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16570. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16571. err.backend_code = static_cast<uint64_t>(ssl_error);
  16572. impl::wolfssl_last_error() = err.backend_code;
  16573. }
  16574. return err;
  16575. }
  16576. inline TlsError accept(session_t session) {
  16577. TlsError err;
  16578. if (!session) {
  16579. err.code = ErrorCode::Fatal;
  16580. return err;
  16581. }
  16582. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16583. int ret = wolfSSL_accept(wsession->ssl);
  16584. if (ret == SSL_SUCCESS) {
  16585. err.code = ErrorCode::Success;
  16586. // Capture SNI from thread-local storage after successful handshake
  16587. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16588. impl::wolfssl_pending_sni().clear();
  16589. } else {
  16590. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16591. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16592. err.backend_code = static_cast<uint64_t>(ssl_error);
  16593. impl::wolfssl_last_error() = err.backend_code;
  16594. }
  16595. return err;
  16596. }
  16597. inline bool connect_nonblocking(session_t session, socket_t sock,
  16598. time_t timeout_sec, time_t timeout_usec,
  16599. TlsError *err) {
  16600. if (!session) {
  16601. if (err) { err->code = ErrorCode::Fatal; }
  16602. return false;
  16603. }
  16604. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16605. // Set socket to non-blocking mode
  16606. detail::set_nonblocking(sock, true);
  16607. auto cleanup =
  16608. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16609. int ret;
  16610. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16611. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16612. if (ssl_error == SSL_ERROR_WANT_READ) {
  16613. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16614. continue;
  16615. }
  16616. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16617. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16618. continue;
  16619. }
  16620. }
  16621. // Error or timeout
  16622. if (err) {
  16623. err->code =
  16624. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16625. err->backend_code = static_cast<uint64_t>(ssl_error);
  16626. }
  16627. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16628. return false;
  16629. }
  16630. if (err) { err->code = ErrorCode::Success; }
  16631. return true;
  16632. }
  16633. inline bool accept_nonblocking(session_t session, socket_t sock,
  16634. time_t timeout_sec, time_t timeout_usec,
  16635. TlsError *err) {
  16636. if (!session) {
  16637. if (err) { err->code = ErrorCode::Fatal; }
  16638. return false;
  16639. }
  16640. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16641. // Set socket to non-blocking mode
  16642. detail::set_nonblocking(sock, true);
  16643. auto cleanup =
  16644. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16645. int ret;
  16646. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16647. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16648. if (ssl_error == SSL_ERROR_WANT_READ) {
  16649. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16650. continue;
  16651. }
  16652. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16653. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16654. continue;
  16655. }
  16656. }
  16657. // Error or timeout
  16658. if (err) {
  16659. err->code =
  16660. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16661. err->backend_code = static_cast<uint64_t>(ssl_error);
  16662. }
  16663. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16664. return false;
  16665. }
  16666. if (err) { err->code = ErrorCode::Success; }
  16667. // Capture SNI from thread-local storage after successful handshake
  16668. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16669. impl::wolfssl_pending_sni().clear();
  16670. return true;
  16671. }
  16672. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16673. if (!session || !buf) {
  16674. err.code = ErrorCode::Fatal;
  16675. return -1;
  16676. }
  16677. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16678. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16679. if (ret > 0) {
  16680. err.code = ErrorCode::Success;
  16681. return static_cast<ssize_t>(ret);
  16682. }
  16683. if (ret == 0) {
  16684. err.code = ErrorCode::PeerClosed;
  16685. return 0;
  16686. }
  16687. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16688. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16689. err.backend_code = static_cast<uint64_t>(ssl_error);
  16690. impl::wolfssl_last_error() = err.backend_code;
  16691. return -1;
  16692. }
  16693. inline ssize_t write(session_t session, const void *buf, size_t len,
  16694. TlsError &err) {
  16695. if (!session || !buf) {
  16696. err.code = ErrorCode::Fatal;
  16697. return -1;
  16698. }
  16699. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16700. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16701. if (ret > 0) {
  16702. err.code = ErrorCode::Success;
  16703. return static_cast<ssize_t>(ret);
  16704. }
  16705. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16706. // Treat this as an error (return -1) so callers don't spin in a
  16707. // write loop adding zero to the offset.
  16708. if (ret == 0) {
  16709. err.code = ErrorCode::PeerClosed;
  16710. return -1;
  16711. }
  16712. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16713. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16714. err.backend_code = static_cast<uint64_t>(ssl_error);
  16715. impl::wolfssl_last_error() = err.backend_code;
  16716. return -1;
  16717. }
  16718. inline int pending(const_session_t session) {
  16719. if (!session) { return 0; }
  16720. auto wsession =
  16721. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16722. return wolfSSL_pending(wsession->ssl);
  16723. }
  16724. inline void shutdown(session_t session, bool graceful) {
  16725. if (!session) { return; }
  16726. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16727. if (graceful) {
  16728. int ret;
  16729. int attempts = 0;
  16730. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16731. attempts < 3) {
  16732. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16733. if (ssl_error != SSL_ERROR_WANT_READ &&
  16734. ssl_error != SSL_ERROR_WANT_WRITE) {
  16735. break;
  16736. }
  16737. attempts++;
  16738. }
  16739. } else {
  16740. wolfSSL_shutdown(wsession->ssl);
  16741. }
  16742. }
  16743. inline bool is_peer_closed(session_t session, socket_t sock) {
  16744. if (!session || sock == INVALID_SOCKET) { return true; }
  16745. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16746. // Check if there's already decrypted data available
  16747. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16748. // Set socket to non-blocking to avoid blocking on read
  16749. detail::set_nonblocking(sock, true);
  16750. auto cleanup =
  16751. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16752. // Peek 1 byte to check connection status without consuming data
  16753. unsigned char buf;
  16754. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16755. // If we got data or WANT_READ (would block), connection is alive
  16756. if (ret > 0) { return false; }
  16757. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16758. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16759. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16760. ret == 0;
  16761. }
  16762. inline cert_t get_peer_cert(const_session_t session) {
  16763. if (!session) { return nullptr; }
  16764. auto wsession =
  16765. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16766. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16767. return static_cast<cert_t>(cert);
  16768. }
  16769. inline void free_cert(cert_t cert) {
  16770. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16771. }
  16772. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16773. if (!cert || !hostname) { return false; }
  16774. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16775. std::string host_str(hostname);
  16776. // Check if hostname is an IP address (IPv4 or IPv6)
  16777. unsigned char ip_bytes[16];
  16778. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16779. auto is_ip = ip_len > 0;
  16780. // Check Subject Alternative Names
  16781. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16782. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16783. if (san_names) {
  16784. int san_count = wolfSSL_sk_num(san_names);
  16785. for (int i = 0; i < san_count; i++) {
  16786. auto *names =
  16787. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16788. if (!names) continue;
  16789. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16790. // DNS name
  16791. unsigned char *dns_name = nullptr;
  16792. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16793. if (dns_name && dns_len > 0) {
  16794. std::string san_name(reinterpret_cast<char *>(dns_name),
  16795. static_cast<size_t>(dns_len));
  16796. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16797. if (detail::match_hostname(san_name, host_str)) {
  16798. wolfSSL_sk_free(san_names);
  16799. return true;
  16800. }
  16801. }
  16802. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16803. // IP address: only an iPAddress SAN of the same family (4 bytes for
  16804. // IPv4, 16 bytes for IPv6) may authenticate the host.
  16805. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16806. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16807. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  16808. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  16809. wolfSSL_sk_free(san_names);
  16810. return true;
  16811. }
  16812. }
  16813. }
  16814. wolfSSL_sk_free(san_names);
  16815. }
  16816. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16817. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16818. // the OpenSSL backend's X509_check_ip behaves the same way).
  16819. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  16820. if (subject) {
  16821. char cn[256] = {};
  16822. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16823. sizeof(cn));
  16824. if (cn_len > 0) {
  16825. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16826. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16827. }
  16828. }
  16829. return false;
  16830. }
  16831. inline uint64_t hostname_mismatch_code() {
  16832. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16833. }
  16834. inline long get_verify_result(const_session_t session) {
  16835. if (!session) { return -1; }
  16836. auto wsession =
  16837. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16838. long result = wolfSSL_get_verify_result(wsession->ssl);
  16839. return result;
  16840. }
  16841. inline std::string get_cert_subject_cn(cert_t cert) {
  16842. if (!cert) return "";
  16843. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16844. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16845. if (!subject) return "";
  16846. char cn[256] = {};
  16847. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16848. sizeof(cn));
  16849. if (cn_len <= 0) return "";
  16850. return std::string(cn, static_cast<size_t>(cn_len));
  16851. }
  16852. inline std::string get_cert_issuer_name(cert_t cert) {
  16853. if (!cert) return "";
  16854. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16855. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16856. if (!issuer) return "";
  16857. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16858. if (!name_str) return "";
  16859. std::string result(name_str);
  16860. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16861. return result;
  16862. }
  16863. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16864. sans.clear();
  16865. if (!cert) return false;
  16866. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16867. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16868. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16869. if (!san_names) return true; // No SANs is not an error
  16870. int count = wolfSSL_sk_num(san_names);
  16871. for (int i = 0; i < count; i++) {
  16872. auto *name =
  16873. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16874. if (!name) continue;
  16875. SanEntry entry;
  16876. switch (name->type) {
  16877. case WOLFSSL_GEN_DNS: {
  16878. entry.type = SanType::DNS;
  16879. unsigned char *dns_name = nullptr;
  16880. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16881. if (dns_name && dns_len > 0) {
  16882. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16883. static_cast<size_t>(dns_len));
  16884. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16885. }
  16886. break;
  16887. }
  16888. case WOLFSSL_GEN_IPADD: {
  16889. entry.type = SanType::IP;
  16890. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16891. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16892. if (ip_data && ip_len == 4) {
  16893. char buf[16];
  16894. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16895. ip_data[2], ip_data[3]);
  16896. entry.value = buf;
  16897. } else if (ip_data && ip_len == 16) {
  16898. char buf[64];
  16899. snprintf(buf, sizeof(buf),
  16900. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16901. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16902. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16903. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16904. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16905. ip_data[14], ip_data[15]);
  16906. entry.value = buf;
  16907. }
  16908. break;
  16909. }
  16910. case WOLFSSL_GEN_EMAIL:
  16911. entry.type = SanType::EMAIL;
  16912. {
  16913. unsigned char *email = nullptr;
  16914. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16915. if (email && email_len > 0) {
  16916. entry.value = std::string(reinterpret_cast<char *>(email),
  16917. static_cast<size_t>(email_len));
  16918. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16919. }
  16920. }
  16921. break;
  16922. case WOLFSSL_GEN_URI:
  16923. entry.type = SanType::URI;
  16924. {
  16925. unsigned char *uri = nullptr;
  16926. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16927. &uri, name->d.uniformResourceIdentifier);
  16928. if (uri && uri_len > 0) {
  16929. entry.value = std::string(reinterpret_cast<char *>(uri),
  16930. static_cast<size_t>(uri_len));
  16931. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16932. }
  16933. }
  16934. break;
  16935. default: entry.type = SanType::OTHER; break;
  16936. }
  16937. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16938. }
  16939. wolfSSL_sk_free(san_names);
  16940. return true;
  16941. }
  16942. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16943. time_t &not_after) {
  16944. if (!cert) return false;
  16945. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16946. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  16947. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  16948. if (!nb || !na) return false;
  16949. // wolfSSL_ASN1_TIME_to_tm is available
  16950. struct tm tm_nb = {}, tm_na = {};
  16951. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  16952. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  16953. #ifdef _WIN32
  16954. not_before = _mkgmtime(&tm_nb);
  16955. not_after = _mkgmtime(&tm_na);
  16956. #else
  16957. not_before = timegm(&tm_nb);
  16958. not_after = timegm(&tm_na);
  16959. #endif
  16960. return true;
  16961. }
  16962. inline std::string get_cert_serial(cert_t cert) {
  16963. if (!cert) return "";
  16964. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16965. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  16966. if (!serial_asn1) return "";
  16967. // Get the serial number data
  16968. int len = serial_asn1->length;
  16969. unsigned char *data = serial_asn1->data;
  16970. if (!data || len <= 0) return "";
  16971. std::string result;
  16972. result.reserve(static_cast<size_t>(len) * 2);
  16973. for (int i = 0; i < len; i++) {
  16974. char hex[3];
  16975. snprintf(hex, sizeof(hex), "%02X", data[i]);
  16976. result += hex;
  16977. }
  16978. return result;
  16979. }
  16980. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16981. if (!cert) return false;
  16982. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16983. int der_len = 0;
  16984. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  16985. if (!der_data || der_len <= 0) return false;
  16986. der.assign(der_data, der_data + der_len);
  16987. return true;
  16988. }
  16989. inline const char *get_sni(const_session_t session) {
  16990. if (!session) return nullptr;
  16991. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  16992. // For server: return SNI received from client during handshake
  16993. if (!wsession->sni_hostname.empty()) {
  16994. return wsession->sni_hostname.c_str();
  16995. }
  16996. // For client: return the hostname set via set_sni
  16997. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  16998. return nullptr;
  16999. }
  17000. inline uint64_t peek_error() {
  17001. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17002. }
  17003. inline uint64_t get_error() {
  17004. uint64_t err = impl::wolfssl_last_error();
  17005. impl::wolfssl_last_error() = 0;
  17006. return err;
  17007. }
  17008. inline std::string error_string(uint64_t code) {
  17009. char buf[256];
  17010. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  17011. return std::string(buf);
  17012. }
  17013. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17014. if (!pem || len == 0) { return nullptr; }
  17015. // Validate by attempting to load into a temporary ctx
  17016. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  17017. if (!tmp_ctx) { return nullptr; }
  17018. int ret = wolfSSL_CTX_load_verify_buffer(
  17019. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17020. static_cast<long>(len), SSL_FILETYPE_PEM);
  17021. wolfSSL_CTX_free(tmp_ctx);
  17022. if (ret != SSL_SUCCESS) { return nullptr; }
  17023. return static_cast<ca_store_t>(
  17024. new impl::WolfSSLCAStore{std::string(pem, len)});
  17025. }
  17026. inline void free_ca_store(ca_store_t store) {
  17027. delete static_cast<impl::WolfSSLCAStore *>(store);
  17028. }
  17029. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17030. if (!ctx || !store) { return false; }
  17031. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17032. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17033. int ret = wolfSSL_CTX_load_verify_buffer(
  17034. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17035. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17036. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17037. // This function takes ownership of the store; the PEM data was copied into
  17038. // the context, so release the source
  17039. free_ca_store(store);
  17040. return ret == SSL_SUCCESS;
  17041. }
  17042. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17043. certs.clear();
  17044. if (!ctx) { return 0; }
  17045. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17046. if (wctx->ca_pem_data_.empty()) { return 0; }
  17047. const std::string &pem = wctx->ca_pem_data_;
  17048. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17049. const std::string end_marker = "-----END CERTIFICATE-----";
  17050. size_t pos = 0;
  17051. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17052. size_t end_pos = pem.find(end_marker, pos);
  17053. if (end_pos == std::string::npos) { break; }
  17054. end_pos += end_marker.size();
  17055. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17056. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17057. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17058. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17059. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17060. pos = end_pos;
  17061. }
  17062. return certs.size();
  17063. }
  17064. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17065. std::vector<std::string> names;
  17066. if (!ctx) { return names; }
  17067. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17068. if (wctx->ca_pem_data_.empty()) { return names; }
  17069. const std::string &pem = wctx->ca_pem_data_;
  17070. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17071. const std::string end_marker = "-----END CERTIFICATE-----";
  17072. size_t pos = 0;
  17073. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17074. size_t end_pos = pem.find(end_marker, pos);
  17075. if (end_pos == std::string::npos) { break; }
  17076. end_pos += end_marker.size();
  17077. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17078. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17079. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17080. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17081. if (x509) {
  17082. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17083. if (subject) {
  17084. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17085. if (name_str) {
  17086. names.push_back(name_str);
  17087. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17088. }
  17089. }
  17090. wolfSSL_X509_free(x509);
  17091. }
  17092. pos = end_pos;
  17093. }
  17094. return names;
  17095. }
  17096. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17097. const char *key_pem, const char *password) {
  17098. if (!ctx || !cert_pem || !key_pem) { return false; }
  17099. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17100. // Load new certificate
  17101. int ret = wolfSSL_CTX_use_certificate_buffer(
  17102. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17103. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17104. if (ret != SSL_SUCCESS) {
  17105. impl::wolfssl_last_error() =
  17106. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17107. return false;
  17108. }
  17109. // Set password if provided
  17110. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17111. // Load new private key
  17112. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17113. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17114. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17115. if (ret != SSL_SUCCESS) {
  17116. impl::wolfssl_last_error() =
  17117. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17118. return false;
  17119. }
  17120. return true;
  17121. }
  17122. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17123. if (!ctx || !ca_pem) { return false; }
  17124. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17125. int ret = wolfSSL_CTX_load_verify_buffer(
  17126. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17127. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  17128. if (ret != SSL_SUCCESS) {
  17129. impl::wolfssl_last_error() =
  17130. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17131. return false;
  17132. }
  17133. return true;
  17134. }
  17135. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17136. if (!ctx) { return false; }
  17137. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17138. impl::get_verify_callback() = std::move(callback);
  17139. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17140. if (wctx->has_verify_callback) {
  17141. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17142. impl::wolfssl_verify_callback);
  17143. } else {
  17144. wolfSSL_CTX_set_verify(
  17145. wctx->ctx,
  17146. wctx->verify_client
  17147. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17148. : SSL_VERIFY_NONE,
  17149. nullptr);
  17150. }
  17151. return true;
  17152. }
  17153. inline long get_verify_error(const_session_t session) {
  17154. if (!session) { return -1; }
  17155. auto *wsession =
  17156. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17157. return wolfSSL_get_verify_result(wsession->ssl);
  17158. }
  17159. inline std::string verify_error_string(long error_code) {
  17160. if (error_code == 0) { return ""; }
  17161. const char *str =
  17162. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17163. return str ? std::string(str) : std::string();
  17164. }
  17165. } // namespace tls
  17166. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17167. // WebSocket implementation
  17168. namespace ws {
  17169. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17170. bool fin) {
  17171. std::lock_guard<std::mutex> lock(write_mutex_);
  17172. if (closed_) { return false; }
  17173. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17174. }
  17175. inline ReadResult WebSocket::read(std::string &msg) {
  17176. while (!closed_) {
  17177. Opcode opcode;
  17178. std::string payload;
  17179. bool fin;
  17180. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17181. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17182. closed_ = true;
  17183. return Fail;
  17184. }
  17185. switch (opcode) {
  17186. case Opcode::Ping: {
  17187. std::lock_guard<std::mutex> lock(write_mutex_);
  17188. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17189. payload.size(), true, !is_server_);
  17190. continue;
  17191. }
  17192. case Opcode::Pong: {
  17193. std::lock_guard<std::mutex> lock(ping_mutex_);
  17194. unacked_pings_ = 0;
  17195. continue;
  17196. }
  17197. case Opcode::Close: {
  17198. if (!closed_.exchange(true)) {
  17199. // Echo close frame back
  17200. std::lock_guard<std::mutex> lock(write_mutex_);
  17201. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17202. payload.size(), true, !is_server_);
  17203. }
  17204. return Fail;
  17205. }
  17206. case Opcode::Text:
  17207. case Opcode::Binary: {
  17208. auto result = opcode == Opcode::Text ? Text : Binary;
  17209. msg = std::move(payload);
  17210. // Handle fragmentation
  17211. if (!fin) {
  17212. while (true) {
  17213. Opcode cont_opcode;
  17214. std::string cont_payload;
  17215. bool cont_fin;
  17216. if (!impl::read_websocket_frame(
  17217. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17218. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17219. closed_ = true;
  17220. return Fail;
  17221. }
  17222. if (cont_opcode == Opcode::Ping) {
  17223. std::lock_guard<std::mutex> lock(write_mutex_);
  17224. detail::write_websocket_frame(
  17225. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17226. true, !is_server_);
  17227. continue;
  17228. }
  17229. if (cont_opcode == Opcode::Pong) {
  17230. std::lock_guard<std::mutex> lock(ping_mutex_);
  17231. unacked_pings_ = 0;
  17232. continue;
  17233. }
  17234. if (cont_opcode == Opcode::Close) {
  17235. if (!closed_.exchange(true)) {
  17236. std::lock_guard<std::mutex> lock(write_mutex_);
  17237. detail::write_websocket_frame(
  17238. strm_, Opcode::Close, cont_payload.data(),
  17239. cont_payload.size(), true, !is_server_);
  17240. }
  17241. return Fail;
  17242. }
  17243. // RFC 6455: continuation frames must use opcode 0x0
  17244. if (cont_opcode != Opcode::Continuation) {
  17245. closed_ = true;
  17246. return Fail;
  17247. }
  17248. msg += cont_payload;
  17249. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17250. closed_ = true;
  17251. return Fail;
  17252. }
  17253. if (cont_fin) { break; }
  17254. }
  17255. }
  17256. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17257. if (result == Text && !impl::is_valid_utf8(msg)) {
  17258. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17259. return Fail;
  17260. }
  17261. return result;
  17262. }
  17263. default: closed_ = true; return Fail;
  17264. }
  17265. }
  17266. return Fail;
  17267. }
  17268. inline bool WebSocket::send(const std::string &data) {
  17269. return send_frame(Opcode::Text, data.data(), data.size());
  17270. }
  17271. inline bool WebSocket::send(const char *data, size_t len) {
  17272. return send_frame(Opcode::Binary, data, len);
  17273. }
  17274. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17275. if (closed_.exchange(true)) { return; }
  17276. ping_cv_.notify_all();
  17277. std::string payload;
  17278. auto code = static_cast<uint16_t>(status);
  17279. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17280. payload.push_back(static_cast<char>(code & 0xFF));
  17281. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17282. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17283. payload += reason.substr(0, 123);
  17284. {
  17285. std::lock_guard<std::mutex> lock(write_mutex_);
  17286. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17287. payload.size(), true, !is_server_);
  17288. }
  17289. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17290. // Close response before closing the TCP connection. Use a short timeout to
  17291. // avoid hanging if the peer doesn't respond.
  17292. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17293. Opcode op;
  17294. std::string resp;
  17295. bool fin;
  17296. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17297. if (op == Opcode::Close) { break; }
  17298. }
  17299. }
  17300. inline WebSocket::~WebSocket() {
  17301. {
  17302. std::lock_guard<std::mutex> lock(ping_mutex_);
  17303. closed_ = true;
  17304. }
  17305. ping_cv_.notify_all();
  17306. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17307. }
  17308. inline void WebSocket::start_heartbeat() {
  17309. if (ping_interval_sec_ == 0) { return; }
  17310. ping_thread_ = std::thread([this]() {
  17311. std::unique_lock<std::mutex> lock(ping_mutex_);
  17312. while (!closed_) {
  17313. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17314. if (closed_) { break; }
  17315. // If the peer has failed to respond to the previous pings, give up.
  17316. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17317. // opt-in liveness check controlled by max_missed_pongs_.
  17318. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17319. lock.unlock();
  17320. close(CloseStatus::GoingAway, "pong timeout");
  17321. return;
  17322. }
  17323. lock.unlock();
  17324. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17325. lock.lock();
  17326. closed_ = true;
  17327. break;
  17328. }
  17329. lock.lock();
  17330. unacked_pings_++;
  17331. }
  17332. });
  17333. }
  17334. inline const Request &WebSocket::request() const { return req_; }
  17335. inline bool WebSocket::is_open() const { return !closed_; }
  17336. // WebSocketClient implementation
  17337. inline WebSocketClient::WebSocketClient(
  17338. const std::string &scheme_host_port_path, const Headers &headers)
  17339. : headers_(headers) {
  17340. detail::UrlComponents uc;
  17341. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17342. !uc.host.empty() && !uc.path.empty()) {
  17343. auto &scheme = uc.scheme;
  17344. #ifdef CPPHTTPLIB_SSL_ENABLED
  17345. if (scheme != "ws" && scheme != "wss") {
  17346. #else
  17347. if (scheme != "ws") {
  17348. #endif
  17349. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17350. std::string msg = "'" + scheme + "' scheme is not supported.";
  17351. throw std::invalid_argument(msg);
  17352. #endif
  17353. return;
  17354. }
  17355. auto is_ssl = scheme == "wss";
  17356. host_ = std::move(uc.host);
  17357. port_ = is_ssl ? 443 : 80;
  17358. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17359. path_ = std::move(uc.path);
  17360. if (!uc.query.empty()) { path_ += uc.query; }
  17361. #ifdef CPPHTTPLIB_SSL_ENABLED
  17362. is_ssl_ = is_ssl;
  17363. if (is_ssl_) {
  17364. // The context lives as long as the client so that CA configuration
  17365. // survives reconnects; sessions are created per connection.
  17366. tls_ctx_ = tls::create_client_context();
  17367. if (!tls_ctx_) { return; }
  17368. }
  17369. #else
  17370. if (is_ssl) { return; }
  17371. #endif
  17372. is_valid_ = true;
  17373. }
  17374. }
  17375. inline WebSocketClient::~WebSocketClient() {
  17376. shutdown_and_close();
  17377. #ifdef CPPHTTPLIB_SSL_ENABLED
  17378. if (tls_ctx_) {
  17379. tls::free_context(tls_ctx_);
  17380. tls_ctx_ = nullptr;
  17381. }
  17382. #endif
  17383. }
  17384. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17385. inline void WebSocketClient::shutdown_and_close() {
  17386. #ifdef CPPHTTPLIB_SSL_ENABLED
  17387. if (is_ssl_) {
  17388. if (tls_session_) {
  17389. tls::shutdown(tls_session_, true);
  17390. tls::free_session(tls_session_);
  17391. tls_session_ = nullptr;
  17392. }
  17393. }
  17394. #endif
  17395. if (ws_ && ws_->is_open()) { ws_->close(); }
  17396. ws_.reset();
  17397. if (sock_ != INVALID_SOCKET) {
  17398. detail::shutdown_socket(sock_);
  17399. detail::close_socket(sock_);
  17400. sock_ = INVALID_SOCKET;
  17401. }
  17402. }
  17403. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17404. #ifdef CPPHTTPLIB_SSL_ENABLED
  17405. if (is_ssl_) {
  17406. if (server_certificate_verification_ && !certs_loaded_) {
  17407. uint64_t backend_error = 0;
  17408. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17409. custom_ca_loaded_, system_ca_mode_,
  17410. backend_error);
  17411. certs_loaded_ = true;
  17412. }
  17413. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17414. server_certificate_verification_,
  17415. read_timeout_sec_,
  17416. read_timeout_usec_)) {
  17417. return false;
  17418. }
  17419. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17420. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17421. write_timeout_sec_, write_timeout_usec_));
  17422. return true;
  17423. }
  17424. #endif
  17425. strm = std::unique_ptr<Stream>(
  17426. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17427. write_timeout_sec_, write_timeout_usec_));
  17428. return true;
  17429. }
  17430. inline bool WebSocketClient::connect() {
  17431. if (!is_valid_) { return false; }
  17432. shutdown_and_close();
  17433. // Check is custom IP specified for host_
  17434. std::string ip;
  17435. auto it = addr_map_.find(host_);
  17436. if (it != addr_map_.end()) { ip = it->second; }
  17437. Error error;
  17438. sock_ = detail::create_client_socket(
  17439. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17440. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17441. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17442. write_timeout_usec_, interface_, error);
  17443. if (sock_ == INVALID_SOCKET) { return false; }
  17444. std::unique_ptr<Stream> strm;
  17445. if (!create_stream(strm)) {
  17446. shutdown_and_close();
  17447. return false;
  17448. }
  17449. #ifdef CPPHTTPLIB_SSL_ENABLED
  17450. auto is_ssl = is_ssl_;
  17451. #else
  17452. auto is_ssl = false;
  17453. #endif
  17454. std::string selected_subprotocol;
  17455. if (!detail::perform_websocket_handshake(*strm, host_, port_, is_ssl, path_,
  17456. headers_, selected_subprotocol)) {
  17457. shutdown_and_close();
  17458. return false;
  17459. }
  17460. subprotocol_ = std::move(selected_subprotocol);
  17461. Request req;
  17462. req.method = "GET";
  17463. req.path = path_;
  17464. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17465. websocket_ping_interval_sec_,
  17466. websocket_max_missed_pongs_));
  17467. return true;
  17468. }
  17469. inline ReadResult WebSocketClient::read(std::string &msg) {
  17470. if (!ws_) { return Fail; }
  17471. return ws_->read(msg);
  17472. }
  17473. inline bool WebSocketClient::send(const std::string &data) {
  17474. if (!ws_) { return false; }
  17475. return ws_->send(data);
  17476. }
  17477. inline bool WebSocketClient::send(const char *data, size_t len) {
  17478. if (!ws_) { return false; }
  17479. return ws_->send(data, len);
  17480. }
  17481. inline void WebSocketClient::close(CloseStatus status,
  17482. const std::string &reason) {
  17483. if (ws_) { ws_->close(status, reason); }
  17484. }
  17485. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17486. inline const std::string &WebSocketClient::subprotocol() const {
  17487. return subprotocol_;
  17488. }
  17489. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17490. read_timeout_sec_ = sec;
  17491. read_timeout_usec_ = usec;
  17492. }
  17493. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17494. write_timeout_sec_ = sec;
  17495. write_timeout_usec_ = usec;
  17496. }
  17497. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17498. websocket_ping_interval_sec_ = sec;
  17499. }
  17500. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17501. websocket_max_missed_pongs_ = count;
  17502. }
  17503. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17504. inline void WebSocketClient::set_address_family(int family) {
  17505. address_family_ = family;
  17506. }
  17507. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17508. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17509. socket_options_ = std::move(socket_options);
  17510. }
  17511. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17512. connection_timeout_sec_ = sec;
  17513. connection_timeout_usec_ = usec;
  17514. }
  17515. inline void WebSocketClient::set_interface(const std::string &intf) {
  17516. interface_ = intf;
  17517. }
  17518. inline void WebSocketClient::set_hostname_addr_map(
  17519. std::map<std::string, std::string> addr_map) {
  17520. addr_map_ = std::move(addr_map);
  17521. }
  17522. #ifdef CPPHTTPLIB_SSL_ENABLED
  17523. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17524. ca_cert_file_path_ = path;
  17525. }
  17526. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17527. if (store && tls_ctx_) {
  17528. // set_ca_store takes ownership of store
  17529. tls::set_ca_store(tls_ctx_, store);
  17530. custom_ca_loaded_ = true;
  17531. } else if (store) {
  17532. tls::free_ca_store(store);
  17533. }
  17534. }
  17535. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17536. std::size_t size) {
  17537. if (tls_ctx_ && ca_cert && size > 0) {
  17538. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17539. custom_ca_loaded_ = true;
  17540. }
  17541. }
  17542. inline void
  17543. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17544. server_certificate_verification_ = enabled;
  17545. }
  17546. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17547. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17548. }
  17549. #endif // CPPHTTPLIB_SSL_ENABLED
  17550. } // namespace ws
  17551. // ----------------------------------------------------------------------------
  17552. } // namespace httplib
  17553. #endif // CPPHTTPLIB_HTTPLIB_H