1
0

httplib.h 685 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735
  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.49.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x003100"
  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 <chrono>
  246. #include <climits>
  247. #include <condition_variable>
  248. #include <cstdlib>
  249. #include <cstring>
  250. #include <errno.h>
  251. #include <exception>
  252. #include <fcntl.h>
  253. #include <fstream>
  254. #include <functional>
  255. #include <iomanip>
  256. #include <iostream>
  257. #include <list>
  258. #include <map>
  259. #include <memory>
  260. #include <mutex>
  261. #include <random>
  262. #include <regex>
  263. #include <set>
  264. #include <sstream>
  265. #include <string>
  266. #include <sys/stat.h>
  267. #include <system_error>
  268. #include <thread>
  269. #include <unordered_map>
  270. #include <unordered_set>
  271. #include <utility>
  272. // On macOS with a TLS backend, enable Keychain root certificates by default
  273. // unless the user explicitly opts out. Not enabled on iOS/tvOS/watchOS since
  274. // the SecTrustSettings APIs used to enumerate anchor certificates are macOS
  275. // only; on those platforms the user must provide a CA bundle explicitly.
  276. #if defined(__APPLE__) && defined(__clang__) && \
  277. !defined(CPPHTTPLIB_DISABLE_MACOSX_AUTOMATIC_ROOT_CERTIFICATES) && \
  278. (defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  279. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || \
  280. defined(CPPHTTPLIB_WOLFSSL_SUPPORT))
  281. #if TARGET_OS_OSX
  282. #ifndef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  283. #define CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  284. #endif
  285. #endif
  286. #endif
  287. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  288. defined(__APPLE__) && !TARGET_OS_OSX
  289. #error \
  290. "CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN is only supported on macOS. On iOS/tvOS/watchOS, supply a CA bundle via set_ca_cert_path()."
  291. #endif
  292. // On Windows, enable Schannel certificate verification by default
  293. // unless the user explicitly opts out.
  294. #if defined(_WIN32) && \
  295. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  296. #define CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  297. #endif
  298. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  299. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  300. #if TARGET_OS_MAC && defined(__clang__)
  301. #include <CFNetwork/CFHost.h>
  302. #include <CoreFoundation/CoreFoundation.h>
  303. #endif
  304. #endif
  305. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  306. #ifdef _WIN32
  307. #include <wincrypt.h>
  308. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  309. // used
  310. #undef X509_NAME
  311. #undef X509_CERT_PAIR
  312. #undef X509_EXTENSIONS
  313. #undef PKCS7_SIGNER_INFO
  314. #ifdef _MSC_VER
  315. #pragma comment(lib, "crypt32.lib")
  316. #endif
  317. #endif // _WIN32
  318. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  319. #if TARGET_OS_OSX
  320. #include <Security/Security.h>
  321. #endif
  322. #endif
  323. #include <openssl/err.h>
  324. #include <openssl/evp.h>
  325. #include <openssl/ssl.h>
  326. #include <openssl/x509v3.h>
  327. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  328. #include <openssl/applink.c>
  329. #endif
  330. #include <iostream>
  331. #include <sstream>
  332. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  333. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  334. #error Please use OpenSSL or a current version of BoringSSL
  335. #endif
  336. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  337. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  338. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  339. #endif
  340. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  341. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  342. #include <mbedtls/ctr_drbg.h>
  343. #include <mbedtls/entropy.h>
  344. #include <mbedtls/error.h>
  345. #include <mbedtls/md5.h>
  346. #include <mbedtls/net_sockets.h>
  347. #include <mbedtls/oid.h>
  348. #include <mbedtls/pk.h>
  349. #include <mbedtls/sha1.h>
  350. #include <mbedtls/sha256.h>
  351. #include <mbedtls/sha512.h>
  352. #include <mbedtls/ssl.h>
  353. #include <mbedtls/x509_crt.h>
  354. #ifdef _WIN32
  355. #include <wincrypt.h>
  356. #ifdef _MSC_VER
  357. #pragma comment(lib, "crypt32.lib")
  358. #endif
  359. #endif // _WIN32
  360. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  361. #if TARGET_OS_OSX
  362. #include <Security/Security.h>
  363. #endif
  364. #endif
  365. // Mbed TLS 3.x API compatibility
  366. #if MBEDTLS_VERSION_MAJOR >= 3
  367. #define CPPHTTPLIB_MBEDTLS_V3
  368. #endif
  369. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  370. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  371. #include <wolfssl/options.h>
  372. #include <wolfssl/openssl/x509v3.h>
  373. // Fallback definitions for older wolfSSL versions (e.g., 5.6.6)
  374. #ifndef WOLFSSL_GEN_EMAIL
  375. #define WOLFSSL_GEN_EMAIL 1
  376. #endif
  377. #ifndef WOLFSSL_GEN_DNS
  378. #define WOLFSSL_GEN_DNS 2
  379. #endif
  380. #ifndef WOLFSSL_GEN_URI
  381. #define WOLFSSL_GEN_URI 6
  382. #endif
  383. #ifndef WOLFSSL_GEN_IPADD
  384. #define WOLFSSL_GEN_IPADD 7
  385. #endif
  386. #include <wolfssl/ssl.h>
  387. #include <wolfssl/wolfcrypt/hash.h>
  388. #include <wolfssl/wolfcrypt/md5.h>
  389. #include <wolfssl/wolfcrypt/sha256.h>
  390. #include <wolfssl/wolfcrypt/sha512.h>
  391. #ifdef _WIN32
  392. #include <wincrypt.h>
  393. #ifdef _MSC_VER
  394. #pragma comment(lib, "crypt32.lib")
  395. #endif
  396. #endif // _WIN32
  397. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  398. #if TARGET_OS_OSX
  399. #include <Security/Security.h>
  400. #endif
  401. #endif
  402. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  403. // Define CPPHTTPLIB_SSL_ENABLED if any SSL backend is available
  404. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) || \
  405. defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  406. #define CPPHTTPLIB_SSL_ENABLED
  407. #endif
  408. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  409. #include <zlib.h>
  410. #endif
  411. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  412. #include <brotli/decode.h>
  413. #include <brotli/encode.h>
  414. #endif
  415. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  416. #include <zstd.h>
  417. #endif
  418. /*
  419. * Declaration
  420. */
  421. namespace httplib {
  422. namespace ws {
  423. class WebSocket;
  424. } // namespace ws
  425. namespace detail {
  426. /*
  427. * Backport std::make_unique from C++14.
  428. *
  429. * NOTE: This code came up with the following stackoverflow post:
  430. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  431. *
  432. */
  433. template <class T, class... Args>
  434. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  435. make_unique(Args &&...args) {
  436. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  437. }
  438. template <class T>
  439. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  440. make_unique(std::size_t n) {
  441. typedef typename std::remove_extent<T>::type RT;
  442. return std::unique_ptr<T>(new RT[n]);
  443. }
  444. // Locale-independent ASCII character classification. The <cctype>
  445. // counterparts (std::isalnum, std::isdigit, ...) consult the global C locale,
  446. // so e.g. std::isalnum(0xC5) can return true once an embedder calls
  447. // setlocale(). HTTP grammars are defined over ASCII, so raw bytes must be
  448. // classified without regard to the locale.
  449. inline bool is_ascii_digit(char c) { return '0' <= c && c <= '9'; }
  450. inline bool is_ascii_alpha(char c) {
  451. return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
  452. }
  453. inline bool is_ascii_alnum(char c) {
  454. return is_ascii_digit(c) || is_ascii_alpha(c);
  455. }
  456. namespace case_ignore {
  457. inline unsigned char to_lower(int c) {
  458. const static unsigned char table[256] = {
  459. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  460. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  461. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  462. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  463. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  464. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  465. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  466. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  467. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  468. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  469. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  470. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  471. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  472. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  473. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  474. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  475. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  476. 255,
  477. };
  478. return table[(unsigned char)(char)c];
  479. }
  480. inline std::string to_lower(const std::string &s) {
  481. std::string result = s;
  482. std::transform(
  483. result.begin(), result.end(), result.begin(),
  484. [](unsigned char c) { return static_cast<char>(to_lower(c)); });
  485. return result;
  486. }
  487. inline bool equal(const std::string &a, const std::string &b) {
  488. return a.size() == b.size() &&
  489. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  490. return to_lower(ca) == to_lower(cb);
  491. });
  492. }
  493. struct equal_to {
  494. bool operator()(const std::string &a, const std::string &b) const {
  495. return equal(a, b);
  496. }
  497. };
  498. struct hash {
  499. size_t operator()(const std::string &key) const {
  500. return hash_core(key.data(), key.size(), 0);
  501. }
  502. size_t hash_core(const char *s, size_t l, size_t h) const {
  503. return (l == 0) ? h
  504. : hash_core(s + 1, l - 1,
  505. // Unsets the 6 high bits of h, therefore no
  506. // overflow happens
  507. (((std::numeric_limits<size_t>::max)() >> 6) &
  508. h * 33) ^
  509. static_cast<unsigned char>(to_lower(*s)));
  510. }
  511. };
  512. template <typename T>
  513. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  514. detail::case_ignore::equal_to>;
  515. } // namespace case_ignore
  516. // This is based on
  517. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  518. struct scope_exit {
  519. explicit scope_exit(std::function<void(void)> &&f)
  520. : exit_function(std::move(f)), execute_on_destruction{true} {}
  521. scope_exit(scope_exit &&rhs) noexcept
  522. : exit_function(std::move(rhs.exit_function)),
  523. execute_on_destruction{rhs.execute_on_destruction} {
  524. rhs.release();
  525. }
  526. ~scope_exit() {
  527. if (execute_on_destruction) { this->exit_function(); }
  528. }
  529. void release() { this->execute_on_destruction = false; }
  530. private:
  531. scope_exit(const scope_exit &) = delete;
  532. void operator=(const scope_exit &) = delete;
  533. scope_exit &operator=(scope_exit &&) = delete;
  534. std::function<void(void)> exit_function;
  535. bool execute_on_destruction;
  536. };
  537. // Simple from_chars implementation for integer and double types (C++17
  538. // substitute)
  539. template <typename T> struct from_chars_result {
  540. const char *ptr;
  541. std::errc ec;
  542. };
  543. template <typename T>
  544. inline from_chars_result<T> from_chars(const char *first, const char *last,
  545. T &value, int base = 10) {
  546. value = 0;
  547. const char *p = first;
  548. bool negative = false;
  549. if (p != last && *p == '-') {
  550. negative = true;
  551. ++p;
  552. }
  553. if (p == last) { return {first, std::errc::invalid_argument}; }
  554. T result = 0;
  555. for (; p != last; ++p) {
  556. char c = *p;
  557. int digit = -1;
  558. if (is_ascii_digit(c)) {
  559. digit = c - '0';
  560. } else if ('a' <= c && c <= 'z') {
  561. digit = c - 'a' + 10;
  562. } else if ('A' <= c && c <= 'Z') {
  563. digit = c - 'A' + 10;
  564. } else {
  565. break;
  566. }
  567. if (digit < 0 || digit >= base) { break; }
  568. if (result > ((std::numeric_limits<T>::max)() - digit) / base) {
  569. return {p, std::errc::result_out_of_range};
  570. }
  571. result = result * base + digit;
  572. }
  573. if (p == first || (negative && p == first + 1)) {
  574. return {first, std::errc::invalid_argument};
  575. }
  576. value = negative ? -result : result;
  577. return {p, std::errc{}};
  578. }
  579. // from_chars for double (hand-written, locale-independent)
  580. //
  581. // The only double consumed by this library is the HTTP quality value, whose
  582. // grammar is (RFC 9110 12.4.2):
  583. // qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
  584. // i.e. a non-negative decimal with no sign, exponent, "inf"/"nan", or wide
  585. // magnitude. So this parser recognizes exactly 1*DIGIT [ "." *DIGIT ] with
  586. // '.' always the decimal separator (std::strtod would instead read it from the
  587. // global C locale, mis-parsing q-values once an embedder calls
  588. // setlocale(LC_ALL, "") into a comma-decimal locale). The caller range-checks
  589. // the result to [0, 1], so inputs outside that range need not be distinguished
  590. // here. Allocation-free, single pass, and free of the overflow/rounding edge
  591. // cases that exponent and wide-range handling would introduce.
  592. inline from_chars_result<double> from_chars(const char *first, const char *last,
  593. double &value) {
  594. value = 0.0;
  595. const char *p = first;
  596. // Each 1eN is exactly representable, so a single final division by the
  597. // matching entry yields a correctly-rounded result.
  598. static const double powers_of_ten[] = {
  599. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  600. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18};
  601. const int max_frac_digits =
  602. static_cast<int>(sizeof(powers_of_ten) / sizeof(powers_of_ten[0])) - 1;
  603. // Accumulate digits into a 64-bit integer and remember how many were
  604. // fractional. Two independent caps keep this bounded and safe:
  605. // * accumulation saturates before mantissa could overflow uint64_t, and
  606. // * frac_digits is capped at max_frac_digits so it is always a valid index
  607. // into powers_of_ten (without this an input like "0.000...0" would never
  608. // grow mantissa, so the saturation cap alone would not bound it).
  609. // Both caps only drop digits far beyond the precision a q-value needs; any
  610. // value they would change is well outside [0, 1] and rejected by the caller.
  611. uint64_t mantissa = 0;
  612. int frac_digits = 0;
  613. bool seen_digit = false;
  614. const uint64_t limit = ((std::numeric_limits<uint64_t>::max)() - 9) / 10;
  615. auto accumulate = [&](char c) {
  616. if (mantissa <= limit) {
  617. mantissa = mantissa * 10 + static_cast<uint64_t>(c - '0');
  618. return true;
  619. }
  620. return false;
  621. };
  622. for (; p != last && is_ascii_digit(*p); ++p) {
  623. seen_digit = true;
  624. accumulate(*p);
  625. }
  626. if (p != last && *p == '.') {
  627. ++p;
  628. for (; p != last && is_ascii_digit(*p); ++p) {
  629. seen_digit = true;
  630. if (frac_digits < max_frac_digits && accumulate(*p)) { ++frac_digits; }
  631. }
  632. }
  633. if (!seen_digit) { return {first, std::errc::invalid_argument}; }
  634. value = static_cast<double>(mantissa) / powers_of_ten[frac_digits];
  635. return {p, std::errc{}};
  636. }
  637. inline bool parse_port(const char *s, size_t len, int &port) {
  638. int val = 0;
  639. auto r = from_chars(s, s + len, val);
  640. if (r.ec != std::errc{} || val < 1 || val > 65535) { return false; }
  641. port = val;
  642. return true;
  643. }
  644. inline bool parse_port(const std::string &s, int &port) {
  645. return parse_port(s.data(), s.size(), port);
  646. }
  647. struct UrlComponents {
  648. std::string scheme;
  649. std::string host;
  650. std::string port;
  651. std::string path;
  652. std::string query;
  653. };
  654. inline bool parse_url(const std::string &url, UrlComponents &uc) {
  655. uc = {};
  656. size_t pos = 0;
  657. auto sep = url.find("://");
  658. if (sep != std::string::npos) {
  659. uc.scheme = url.substr(0, sep);
  660. // Scheme must be [a-z]+ only
  661. if (uc.scheme.empty()) { return false; }
  662. for (auto c : uc.scheme) {
  663. if (c < 'a' || c > 'z') { return false; }
  664. }
  665. pos = sep + 3;
  666. } else if (url.compare(0, 2, "//") == 0) {
  667. pos = 2;
  668. }
  669. auto has_authority_prefix = pos > 0;
  670. auto has_authority = has_authority_prefix || (!url.empty() && url[0] != '/' &&
  671. url[0] != '?' && url[0] != '#');
  672. if (has_authority) {
  673. if (pos < url.size() && url[pos] == '[') {
  674. auto close = url.find(']', pos);
  675. if (close == std::string::npos) { return false; }
  676. uc.host = url.substr(pos + 1, close - pos - 1);
  677. // IPv6 host must be [a-fA-F0-9:]+ only
  678. if (uc.host.empty()) { return false; }
  679. for (auto c : uc.host) {
  680. if (!(is_ascii_digit(c) || (c >= 'a' && c <= 'f') ||
  681. (c >= 'A' && c <= 'F') || c == ':')) {
  682. return false;
  683. }
  684. }
  685. pos = close + 1;
  686. } else {
  687. auto end = url.find_first_of(":/?#", pos);
  688. if (end == std::string::npos) { end = url.size(); }
  689. uc.host = url.substr(pos, end - pos);
  690. pos = end;
  691. }
  692. if (pos < url.size() && url[pos] == ':') {
  693. ++pos;
  694. auto end = url.find_first_of("/?#", pos);
  695. if (end == std::string::npos) { end = url.size(); }
  696. uc.port = url.substr(pos, end - pos);
  697. pos = end;
  698. }
  699. // Without :// or //, the entire input must be consumed as host[:port].
  700. // If there is leftover (path, query, etc.), this is not a valid
  701. // host[:port] string — clear and reparse as a plain path.
  702. if (!has_authority_prefix && pos < url.size()) {
  703. uc.host.clear();
  704. uc.port.clear();
  705. pos = 0;
  706. }
  707. }
  708. if (pos < url.size() && url[pos] != '?' && url[pos] != '#') {
  709. auto end = url.find_first_of("?#", pos);
  710. if (end == std::string::npos) { end = url.size(); }
  711. uc.path = url.substr(pos, end - pos);
  712. pos = end;
  713. }
  714. if (pos < url.size() && url[pos] == '?') {
  715. auto end = url.find('#', pos);
  716. if (end == std::string::npos) { end = url.size(); }
  717. uc.query = url.substr(pos, end - pos);
  718. }
  719. return true;
  720. }
  721. } // namespace detail
  722. enum class SSLVerifierResponse {
  723. // no decision has been made, use the built-in certificate verifier
  724. NoDecisionMade,
  725. // connection certificate is verified and accepted
  726. CertificateAccepted,
  727. // connection certificate was processed but is rejected
  728. CertificateRejected
  729. };
  730. // System CA loading policy for SSL clients. Auto (the default) loads system
  731. // CA certs only when no custom CA is configured; enable_system_ca() switches
  732. // to an explicit policy.
  733. enum class SystemCAMode { Auto, Enabled, Disabled };
  734. enum StatusCode {
  735. // Information responses
  736. Continue_100 = 100,
  737. SwitchingProtocol_101 = 101,
  738. Processing_102 = 102,
  739. EarlyHints_103 = 103,
  740. // Successful responses
  741. OK_200 = 200,
  742. Created_201 = 201,
  743. Accepted_202 = 202,
  744. NonAuthoritativeInformation_203 = 203,
  745. NoContent_204 = 204,
  746. ResetContent_205 = 205,
  747. PartialContent_206 = 206,
  748. MultiStatus_207 = 207,
  749. AlreadyReported_208 = 208,
  750. IMUsed_226 = 226,
  751. // Redirection messages
  752. MultipleChoices_300 = 300,
  753. MovedPermanently_301 = 301,
  754. Found_302 = 302,
  755. SeeOther_303 = 303,
  756. NotModified_304 = 304,
  757. UseProxy_305 = 305,
  758. unused_306 = 306,
  759. TemporaryRedirect_307 = 307,
  760. PermanentRedirect_308 = 308,
  761. // Client error responses
  762. BadRequest_400 = 400,
  763. Unauthorized_401 = 401,
  764. PaymentRequired_402 = 402,
  765. Forbidden_403 = 403,
  766. NotFound_404 = 404,
  767. MethodNotAllowed_405 = 405,
  768. NotAcceptable_406 = 406,
  769. ProxyAuthenticationRequired_407 = 407,
  770. RequestTimeout_408 = 408,
  771. Conflict_409 = 409,
  772. Gone_410 = 410,
  773. LengthRequired_411 = 411,
  774. PreconditionFailed_412 = 412,
  775. PayloadTooLarge_413 = 413,
  776. UriTooLong_414 = 414,
  777. UnsupportedMediaType_415 = 415,
  778. RangeNotSatisfiable_416 = 416,
  779. ExpectationFailed_417 = 417,
  780. ImATeapot_418 = 418,
  781. MisdirectedRequest_421 = 421,
  782. UnprocessableContent_422 = 422,
  783. Locked_423 = 423,
  784. FailedDependency_424 = 424,
  785. TooEarly_425 = 425,
  786. UpgradeRequired_426 = 426,
  787. PreconditionRequired_428 = 428,
  788. TooManyRequests_429 = 429,
  789. RequestHeaderFieldsTooLarge_431 = 431,
  790. UnavailableForLegalReasons_451 = 451,
  791. // Server error responses
  792. InternalServerError_500 = 500,
  793. NotImplemented_501 = 501,
  794. BadGateway_502 = 502,
  795. ServiceUnavailable_503 = 503,
  796. GatewayTimeout_504 = 504,
  797. HttpVersionNotSupported_505 = 505,
  798. VariantAlsoNegotiates_506 = 506,
  799. InsufficientStorage_507 = 507,
  800. LoopDetected_508 = 508,
  801. NotExtended_510 = 510,
  802. NetworkAuthenticationRequired_511 = 511,
  803. };
  804. using Headers =
  805. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  806. detail::case_ignore::equal_to>;
  807. using Params = std::multimap<std::string, std::string>;
  808. using Match = std::smatch;
  809. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  810. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  811. /*
  812. * detail: type-erased storage used by UserData.
  813. * ABI-stable regardless of C++ standard — always uses this custom
  814. * implementation instead of std::any.
  815. */
  816. namespace detail {
  817. using any_type_id = const void *;
  818. template <typename T> any_type_id any_typeid() noexcept {
  819. static const char id = 0;
  820. return &id;
  821. }
  822. struct any_storage {
  823. virtual ~any_storage() = default;
  824. virtual std::unique_ptr<any_storage> clone() const = 0;
  825. virtual any_type_id type_id() const noexcept = 0;
  826. };
  827. template <typename T> struct any_value final : any_storage {
  828. T value;
  829. template <typename U> explicit any_value(U &&v) : value(std::forward<U>(v)) {}
  830. std::unique_ptr<any_storage> clone() const override {
  831. return std::unique_ptr<any_storage>(new any_value<T>(value));
  832. }
  833. any_type_id type_id() const noexcept override { return any_typeid<T>(); }
  834. };
  835. } // namespace detail
  836. class UserData {
  837. public:
  838. UserData() = default;
  839. UserData(UserData &&) noexcept = default;
  840. UserData &operator=(UserData &&) noexcept = default;
  841. UserData(const UserData &o) {
  842. for (const auto &e : o.entries_) {
  843. if (e.second) { entries_[e.first] = e.second->clone(); }
  844. }
  845. }
  846. UserData &operator=(const UserData &o) {
  847. if (this != &o) {
  848. entries_.clear();
  849. for (const auto &e : o.entries_) {
  850. if (e.second) { entries_[e.first] = e.second->clone(); }
  851. }
  852. }
  853. return *this;
  854. }
  855. template <typename T> void set(const std::string &key, T &&value) {
  856. using D = typename std::decay<T>::type;
  857. entries_[key].reset(new detail::any_value<D>(std::forward<T>(value)));
  858. }
  859. template <typename T> T *get(const std::string &key) noexcept {
  860. auto it = entries_.find(key);
  861. if (it == entries_.end() || !it->second) { return nullptr; }
  862. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  863. return &static_cast<detail::any_value<T> *>(it->second.get())->value;
  864. }
  865. template <typename T> const T *get(const std::string &key) const noexcept {
  866. auto it = entries_.find(key);
  867. if (it == entries_.end() || !it->second) { return nullptr; }
  868. if (it->second->type_id() != detail::any_typeid<T>()) { return nullptr; }
  869. return &static_cast<const detail::any_value<T> *>(it->second.get())->value;
  870. }
  871. bool has(const std::string &key) const noexcept {
  872. return entries_.find(key) != entries_.end();
  873. }
  874. void erase(const std::string &key) { entries_.erase(key); }
  875. void clear() noexcept { entries_.clear(); }
  876. private:
  877. std::unordered_map<std::string, std::unique_ptr<detail::any_storage>>
  878. entries_;
  879. };
  880. struct Response;
  881. using ResponseHandler = std::function<bool(const Response &response)>;
  882. struct FormData {
  883. std::string name;
  884. std::string content;
  885. std::string filename;
  886. std::string content_type;
  887. Headers headers;
  888. };
  889. struct FormField {
  890. std::string name;
  891. std::string content;
  892. Headers headers;
  893. };
  894. using FormFields = std::multimap<std::string, FormField>;
  895. using FormFiles = std::multimap<std::string, FormData>;
  896. struct MultipartFormData {
  897. FormFields fields; // Text fields from multipart
  898. FormFiles files; // Files from multipart
  899. // Text field access
  900. std::string get_field(const std::string &key, size_t id = 0) const;
  901. std::vector<std::string> get_fields(const std::string &key) const;
  902. bool has_field(const std::string &key) const;
  903. size_t get_field_count(const std::string &key) const;
  904. // File access
  905. FormData get_file(const std::string &key, size_t id = 0) const;
  906. std::vector<FormData> get_files(const std::string &key) const;
  907. bool has_file(const std::string &key) const;
  908. size_t get_file_count(const std::string &key) const;
  909. };
  910. struct UploadFormData {
  911. std::string name;
  912. std::string content;
  913. std::string filename;
  914. std::string content_type;
  915. };
  916. using UploadFormDataItems = std::vector<UploadFormData>;
  917. class DataSink {
  918. public:
  919. DataSink() : os(&sb_), sb_(*this) {}
  920. DataSink(const DataSink &) = delete;
  921. DataSink &operator=(const DataSink &) = delete;
  922. DataSink(DataSink &&) = delete;
  923. DataSink &operator=(DataSink &&) = delete;
  924. std::function<bool(const char *data, size_t data_len)> write;
  925. std::function<bool()> is_writable;
  926. std::function<void()> done;
  927. std::function<void(const Headers &trailer)> done_with_trailer;
  928. std::ostream os;
  929. private:
  930. class data_sink_streambuf final : public std::streambuf {
  931. public:
  932. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  933. protected:
  934. std::streamsize xsputn(const char *s, std::streamsize n) override {
  935. if (sink_.write(s, static_cast<size_t>(n))) { return n; }
  936. return 0;
  937. }
  938. private:
  939. DataSink &sink_;
  940. };
  941. data_sink_streambuf sb_;
  942. };
  943. using ContentProvider =
  944. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  945. using ContentProviderWithoutLength =
  946. std::function<bool(size_t offset, DataSink &sink)>;
  947. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  948. struct FormDataProvider {
  949. std::string name;
  950. ContentProviderWithoutLength provider;
  951. std::string filename;
  952. std::string content_type;
  953. };
  954. using FormDataProviderItems = std::vector<FormDataProvider>;
  955. inline FormDataProvider
  956. make_file_provider(const std::string &name, const std::string &filepath,
  957. const std::string &filename = std::string(),
  958. const std::string &content_type = std::string()) {
  959. FormDataProvider fdp;
  960. fdp.name = name;
  961. fdp.filename = filename.empty() ? filepath : filename;
  962. fdp.content_type = content_type;
  963. fdp.provider = [filepath](size_t offset, DataSink &sink) -> bool {
  964. std::ifstream f(filepath, std::ios::binary);
  965. if (!f) { return false; }
  966. if (offset > 0) {
  967. f.seekg(static_cast<std::streamoff>(offset));
  968. if (!f.good()) {
  969. sink.done();
  970. return true;
  971. }
  972. }
  973. char buf[8192];
  974. f.read(buf, sizeof(buf));
  975. auto n = static_cast<size_t>(f.gcount());
  976. if (n > 0) { return sink.write(buf, n); }
  977. sink.done(); // EOF
  978. return true;
  979. };
  980. return fdp;
  981. }
  982. inline std::pair<size_t, ContentProvider>
  983. make_file_body(const std::string &filepath) {
  984. size_t size = 0;
  985. {
  986. std::ifstream f(filepath, std::ios::binary | std::ios::ate);
  987. if (!f) { return {0, ContentProvider{}}; }
  988. size = static_cast<size_t>(f.tellg());
  989. }
  990. ContentProvider provider = [filepath](size_t offset, size_t length,
  991. DataSink &sink) -> bool {
  992. std::ifstream f(filepath, std::ios::binary);
  993. if (!f) { return false; }
  994. f.seekg(static_cast<std::streamoff>(offset));
  995. if (!f.good()) { return false; }
  996. char buf[8192];
  997. while (length > 0) {
  998. auto to_read = (std::min)(sizeof(buf), length);
  999. f.read(buf, static_cast<std::streamsize>(to_read));
  1000. auto n = static_cast<size_t>(f.gcount());
  1001. if (n == 0) { break; }
  1002. if (!sink.write(buf, n)) { return false; }
  1003. length -= n;
  1004. }
  1005. return true;
  1006. };
  1007. return {size, std::move(provider)};
  1008. }
  1009. using ContentReceiverWithProgress = std::function<bool(
  1010. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  1011. using ContentReceiver =
  1012. std::function<bool(const char *data, size_t data_length)>;
  1013. using FormDataHeader = std::function<bool(const FormData &file)>;
  1014. class ContentReader {
  1015. public:
  1016. using Reader = std::function<bool(ContentReceiver receiver)>;
  1017. using FormDataReader =
  1018. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  1019. ContentReader(Reader reader, FormDataReader multipart_reader)
  1020. : reader_(std::move(reader)),
  1021. formdata_reader_(std::move(multipart_reader)) {}
  1022. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  1023. return formdata_reader_(std::move(header), std::move(receiver));
  1024. }
  1025. bool operator()(ContentReceiver receiver) const {
  1026. return reader_(std::move(receiver));
  1027. }
  1028. Reader reader_;
  1029. FormDataReader formdata_reader_;
  1030. };
  1031. using Range = std::pair<ssize_t, ssize_t>;
  1032. using Ranges = std::vector<Range>;
  1033. #ifdef CPPHTTPLIB_SSL_ENABLED
  1034. // TLS abstraction layer - public type definitions and API
  1035. namespace tls {
  1036. // Opaque handles (defined as void* for abstraction)
  1037. using ctx_t = void *;
  1038. using session_t = void *;
  1039. using const_session_t = const void *; // For read-only session access
  1040. using cert_t = void *;
  1041. using ca_store_t = void *;
  1042. // TLS versions
  1043. enum class Version {
  1044. TLS1_2 = 0x0303,
  1045. TLS1_3 = 0x0304,
  1046. };
  1047. // Subject Alternative Names (SAN) entry types
  1048. enum class SanType { DNS, IP, EMAIL, URI, OTHER };
  1049. // SAN entry structure
  1050. struct SanEntry {
  1051. SanType type;
  1052. std::string value;
  1053. };
  1054. // Verification context for certificate verification callback
  1055. struct VerifyContext {
  1056. session_t session; // TLS session handle
  1057. cert_t cert; // Current certificate being verified
  1058. int depth; // Certificate chain depth (0 = leaf)
  1059. bool preverify_ok; // OpenSSL/Mbed TLS pre-verification result
  1060. long error_code; // Backend-specific error code (0 = no error)
  1061. const char *error_string; // Human-readable error description
  1062. // Certificate introspection methods
  1063. std::string subject_cn() const;
  1064. std::string issuer_name() const;
  1065. bool check_hostname(const char *hostname) const;
  1066. std::vector<SanEntry> sans() const;
  1067. bool validity(time_t &not_before, time_t &not_after) const;
  1068. std::string serial() const;
  1069. };
  1070. using VerifyCallback = std::function<bool(const VerifyContext &ctx)>;
  1071. // TlsError codes for TLS operations (backend-independent)
  1072. enum class ErrorCode : int {
  1073. Success = 0,
  1074. WantRead, // Non-blocking: need to wait for read
  1075. WantWrite, // Non-blocking: need to wait for write
  1076. PeerClosed, // Peer closed the connection
  1077. Fatal, // Unrecoverable error
  1078. SyscallError, // System call error (check sys_errno)
  1079. CertVerifyFailed, // Certificate verification failed
  1080. HostnameMismatch, // Hostname verification failed
  1081. };
  1082. // TLS error information
  1083. struct TlsError {
  1084. ErrorCode code = ErrorCode::Fatal;
  1085. uint64_t backend_code = 0; // OpenSSL: ERR_get_error(), mbedTLS: return value
  1086. int sys_errno = 0; // errno when SyscallError
  1087. // Convert verification error code to human-readable string
  1088. static std::string verify_error_to_string(long error_code);
  1089. };
  1090. // RAII wrapper for peer certificate
  1091. class PeerCert {
  1092. public:
  1093. PeerCert();
  1094. PeerCert(PeerCert &&other) noexcept;
  1095. PeerCert &operator=(PeerCert &&other) noexcept;
  1096. ~PeerCert();
  1097. PeerCert(const PeerCert &) = delete;
  1098. PeerCert &operator=(const PeerCert &) = delete;
  1099. explicit operator bool() const;
  1100. std::string subject_cn() const;
  1101. std::string issuer_name() const;
  1102. bool check_hostname(const char *hostname) const;
  1103. std::vector<SanEntry> sans() const;
  1104. bool validity(time_t &not_before, time_t &not_after) const;
  1105. std::string serial() const;
  1106. private:
  1107. explicit PeerCert(cert_t cert);
  1108. cert_t cert_ = nullptr;
  1109. friend PeerCert get_peer_cert_from_session(const_session_t session);
  1110. };
  1111. // Callback for TLS context setup (used by SSLServer constructor)
  1112. using ContextSetupCallback = std::function<bool(ctx_t ctx)>;
  1113. } // namespace tls
  1114. #endif
  1115. struct Request {
  1116. std::string method;
  1117. std::string path;
  1118. std::string matched_route;
  1119. Params params;
  1120. Headers headers;
  1121. Headers trailers;
  1122. std::string body;
  1123. std::string remote_addr;
  1124. int remote_port = -1;
  1125. std::string local_addr;
  1126. int local_port = -1;
  1127. // for server
  1128. std::string version;
  1129. std::string target;
  1130. MultipartFormData form;
  1131. Ranges ranges;
  1132. Match matches;
  1133. std::unordered_map<std::string, std::string> path_params;
  1134. std::function<bool()> is_connection_closed = []() { return true; };
  1135. // for client
  1136. std::vector<std::string> accept_content_types;
  1137. ResponseHandler response_handler;
  1138. ContentReceiverWithProgress content_receiver;
  1139. DownloadProgress download_progress;
  1140. UploadProgress upload_progress;
  1141. bool has_header(const std::string &key) const;
  1142. std::string get_header_value(const std::string &key, const char *def = "",
  1143. size_t id = 0) const;
  1144. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1145. size_t id = 0) const;
  1146. size_t get_header_value_count(const std::string &key) const;
  1147. void set_header(const std::string &key, const std::string &val);
  1148. bool has_trailer(const std::string &key) const;
  1149. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1150. size_t get_trailer_value_count(const std::string &key) const;
  1151. bool has_param(const std::string &key) const;
  1152. std::string get_param_value(const std::string &key, size_t id = 0) const;
  1153. std::vector<std::string> get_param_values(const std::string &key) const;
  1154. size_t get_param_value_count(const std::string &key) const;
  1155. bool is_multipart_form_data() const;
  1156. // private members...
  1157. bool body_consumed_ = false;
  1158. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  1159. size_t content_length_ = 0;
  1160. ContentProvider content_provider_;
  1161. bool is_chunked_content_provider_ = false;
  1162. size_t authorization_count_ = 0;
  1163. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  1164. (std::chrono::steady_clock::time_point::min)();
  1165. #ifdef CPPHTTPLIB_SSL_ENABLED
  1166. tls::const_session_t ssl = nullptr;
  1167. tls::PeerCert peer_cert() const;
  1168. std::string sni() const;
  1169. #endif
  1170. };
  1171. struct Response {
  1172. std::string version;
  1173. int status = -1;
  1174. std::string reason;
  1175. Headers headers;
  1176. Headers trailers;
  1177. std::string body;
  1178. std::string location; // Redirect location
  1179. // User-defined context — set by pre-routing/pre-request handlers and read
  1180. // by route handlers to pass arbitrary data (e.g. decoded auth tokens).
  1181. UserData user_data;
  1182. bool has_header(const std::string &key) const;
  1183. std::string get_header_value(const std::string &key, const char *def = "",
  1184. size_t id = 0) const;
  1185. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  1186. size_t id = 0) const;
  1187. size_t get_header_value_count(const std::string &key) const;
  1188. void set_header(const std::string &key, const std::string &val);
  1189. bool has_trailer(const std::string &key) const;
  1190. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  1191. size_t get_trailer_value_count(const std::string &key) const;
  1192. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  1193. void set_content(const char *s, size_t n, const std::string &content_type);
  1194. void set_content(const std::string &s, const std::string &content_type);
  1195. void set_content(std::string &&s, const std::string &content_type);
  1196. void set_content_provider(
  1197. size_t length, const std::string &content_type, ContentProvider provider,
  1198. ContentProviderResourceReleaser resource_releaser = nullptr);
  1199. void set_content_provider(
  1200. const std::string &content_type, ContentProviderWithoutLength provider,
  1201. ContentProviderResourceReleaser resource_releaser = nullptr);
  1202. void set_chunked_content_provider(
  1203. const std::string &content_type, ContentProviderWithoutLength provider,
  1204. ContentProviderResourceReleaser resource_releaser = nullptr);
  1205. void set_file_content(const std::string &path,
  1206. const std::string &content_type);
  1207. void set_file_content(const std::string &path);
  1208. Response() = default;
  1209. Response(const Response &) = default;
  1210. Response &operator=(const Response &) = default;
  1211. Response(Response &&) = default;
  1212. Response &operator=(Response &&) = default;
  1213. ~Response() {
  1214. if (content_provider_resource_releaser_) {
  1215. content_provider_resource_releaser_(content_provider_success_);
  1216. }
  1217. }
  1218. // private members...
  1219. size_t content_length_ = 0;
  1220. ContentProvider content_provider_;
  1221. ContentProviderResourceReleaser content_provider_resource_releaser_;
  1222. bool is_chunked_content_provider_ = false;
  1223. bool content_provider_success_ = false;
  1224. std::string file_content_path_;
  1225. std::string file_content_content_type_;
  1226. };
  1227. enum class Error {
  1228. Success = 0,
  1229. Unknown,
  1230. Connection,
  1231. BindIPAddress,
  1232. Read,
  1233. Write,
  1234. ExceedRedirectCount,
  1235. Canceled,
  1236. SSLConnection,
  1237. SSLLoadingCerts,
  1238. SSLServerVerification,
  1239. SSLServerHostnameVerification,
  1240. UnsupportedMultipartBoundaryChars,
  1241. Compression,
  1242. ConnectionTimeout,
  1243. ProxyConnection,
  1244. ConnectionClosed,
  1245. Timeout,
  1246. ResourceExhaustion,
  1247. TooManyFormDataFiles,
  1248. ExceedMaxPayloadSize,
  1249. ExceedUriMaxLength,
  1250. ExceedMaxSocketDescriptorCount,
  1251. InvalidRequestLine,
  1252. InvalidHTTPMethod,
  1253. InvalidHTTPVersion,
  1254. InvalidHeaders,
  1255. MultipartParsing,
  1256. OpenFile,
  1257. Listen,
  1258. GetSockName,
  1259. UnsupportedAddressFamily,
  1260. HTTPParsing,
  1261. InvalidRangeHeader,
  1262. // For internal use only
  1263. SSLPeerCouldBeClosed_,
  1264. };
  1265. std::string to_string(Error error);
  1266. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1267. class Stream {
  1268. public:
  1269. virtual ~Stream() = default;
  1270. virtual bool is_readable() const = 0;
  1271. virtual bool wait_readable() const = 0;
  1272. virtual bool wait_writable() const = 0;
  1273. virtual bool is_peer_alive() const { return wait_writable(); }
  1274. virtual ssize_t read(char *ptr, size_t size) = 0;
  1275. virtual ssize_t write(const char *ptr, size_t size) = 0;
  1276. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  1277. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  1278. virtual socket_t socket() const = 0;
  1279. virtual time_t duration() const = 0;
  1280. virtual void set_read_timeout(time_t sec, time_t usec = 0) {
  1281. (void)sec;
  1282. (void)usec;
  1283. }
  1284. ssize_t write(const char *ptr);
  1285. ssize_t write(const std::string &s);
  1286. Error get_error() const { return error_; }
  1287. protected:
  1288. Error error_ = Error::Success;
  1289. };
  1290. class TaskQueue {
  1291. public:
  1292. TaskQueue() = default;
  1293. virtual ~TaskQueue() = default;
  1294. virtual bool enqueue(std::function<void()> fn) = 0;
  1295. virtual void shutdown() = 0;
  1296. virtual void on_idle() {}
  1297. };
  1298. class ThreadPool final : public TaskQueue {
  1299. public:
  1300. explicit ThreadPool(
  1301. size_t n, size_t max_n = 0, size_t mqr = 0,
  1302. time_t idle_timeout_sec = CPPHTTPLIB_THREAD_POOL_IDLE_TIMEOUT);
  1303. ThreadPool(const ThreadPool &) = delete;
  1304. ~ThreadPool() override = default;
  1305. bool enqueue(std::function<void()> fn) override;
  1306. void shutdown() override;
  1307. private:
  1308. void worker(bool is_dynamic);
  1309. void move_to_finished(std::thread::id id);
  1310. void cleanup_finished_threads();
  1311. size_t base_thread_count_;
  1312. size_t max_thread_count_;
  1313. size_t max_queued_requests_;
  1314. time_t idle_timeout_sec_;
  1315. size_t idle_thread_count_;
  1316. bool shutdown_;
  1317. std::list<std::function<void()>> jobs_;
  1318. std::vector<std::thread> threads_; // base threads
  1319. std::list<std::thread> dynamic_threads_; // dynamic threads
  1320. std::vector<std::thread>
  1321. finished_threads_; // exited dynamic threads awaiting join
  1322. std::condition_variable cond_;
  1323. std::mutex mutex_;
  1324. };
  1325. using Logger = std::function<void(const Request &, const Response &)>;
  1326. // Forward declaration for Error type
  1327. enum class Error;
  1328. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  1329. using SocketOptions = std::function<void(socket_t sock)>;
  1330. void default_socket_options(socket_t sock);
  1331. bool set_socket_opt(socket_t sock, int level, int optname, int optval);
  1332. const char *status_message(int status);
  1333. std::string to_string(Error error);
  1334. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1335. std::string get_bearer_token_auth(const Request &req);
  1336. namespace detail {
  1337. class MatcherBase {
  1338. public:
  1339. MatcherBase(std::string pattern) : pattern_(std::move(pattern)) {}
  1340. virtual ~MatcherBase() = default;
  1341. const std::string &pattern() const { return pattern_; }
  1342. // Match request path and populate its matches and
  1343. virtual bool match(Request &request) const = 0;
  1344. private:
  1345. std::string pattern_;
  1346. };
  1347. /**
  1348. * Captures parameters in request path and stores them in Request::path_params
  1349. *
  1350. * Capture name is a substring of a pattern from : to /.
  1351. * The rest of the pattern is matched against the request path directly
  1352. * Parameters are captured starting from the next character after
  1353. * the end of the last matched static pattern fragment until the next /.
  1354. *
  1355. * Example pattern:
  1356. * "/path/fragments/:capture/more/fragments/:second_capture"
  1357. * Static fragments:
  1358. * "/path/fragments/", "more/fragments/"
  1359. *
  1360. * Given the following request path:
  1361. * "/path/fragments/:1/more/fragments/:2"
  1362. * the resulting capture will be
  1363. * {{"capture", "1"}, {"second_capture", "2"}}
  1364. */
  1365. class PathParamsMatcher final : public MatcherBase {
  1366. public:
  1367. PathParamsMatcher(const std::string &pattern);
  1368. bool match(Request &request) const override;
  1369. private:
  1370. // Treat segment separators as the end of path parameter capture
  1371. // Does not need to handle query parameters as they are parsed before path
  1372. // matching
  1373. static constexpr char separator = '/';
  1374. // Contains static path fragments to match against, excluding the '/' after
  1375. // path params
  1376. // Fragments are separated by path params
  1377. std::vector<std::string> static_fragments_;
  1378. // Stores the names of the path parameters to be used as keys in the
  1379. // Request::path_params map
  1380. std::vector<std::string> param_names_;
  1381. };
  1382. /**
  1383. * Performs std::regex_match on request path
  1384. * and stores the result in Request::matches
  1385. *
  1386. * Note that regex match is performed directly on the whole request.
  1387. * This means that wildcard patterns may match multiple path segments with /:
  1388. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  1389. */
  1390. class RegexMatcher final : public MatcherBase {
  1391. public:
  1392. RegexMatcher(const std::string &pattern)
  1393. : MatcherBase(pattern), regex_(pattern) {}
  1394. bool match(Request &request) const override;
  1395. private:
  1396. std::regex regex_;
  1397. };
  1398. int close_socket(socket_t sock) noexcept;
  1399. ssize_t write_headers(Stream &strm, const Headers &headers);
  1400. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  1401. time_t usec);
  1402. size_t get_multipart_content_length(const UploadFormDataItems &items,
  1403. const std::string &boundary);
  1404. ContentProvider
  1405. make_multipart_content_provider(const UploadFormDataItems &items,
  1406. const std::string &boundary);
  1407. } // namespace detail
  1408. bool is_valid_multipart_boundary(const std::string &boundary);
  1409. // Serializer for multipart/form-data request bodies. The boundary is owned
  1410. // by the writer so that per-part framing and the final terminator always
  1411. // agree. Field names and filenames are escaped following the WHATWG HTML
  1412. // standard ('"' -> %22, CR -> %0D, LF -> %0A); CR and LF are also escaped
  1413. // in content types.
  1414. class MultipartFormDataWriter {
  1415. public:
  1416. MultipartFormDataWriter();
  1417. // precondition: is_valid_multipart_boundary(boundary)
  1418. explicit MultipartFormDataWriter(std::string boundary);
  1419. const std::string &boundary() const;
  1420. std::string content_type() const;
  1421. // In-memory items -> whole body (known length)
  1422. std::string serialize(const UploadFormDataItems &items) const;
  1423. size_t content_length(const UploadFormDataItems &items) const;
  1424. // Per-part framing for streaming via a content provider
  1425. std::string item_begin(const UploadFormData &item) const;
  1426. static std::string item_end();
  1427. std::string finish() const;
  1428. private:
  1429. std::string boundary_;
  1430. };
  1431. class Server {
  1432. public:
  1433. using Handler = std::function<void(const Request &, Response &)>;
  1434. using ExceptionHandler =
  1435. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  1436. enum class HandlerResponse {
  1437. Handled,
  1438. Unhandled,
  1439. };
  1440. using HandlerWithResponse =
  1441. std::function<HandlerResponse(const Request &, Response &)>;
  1442. using HandlerWithContentReader = std::function<void(
  1443. const Request &, Response &, const ContentReader &content_reader)>;
  1444. using Expect100ContinueHandler =
  1445. std::function<int(const Request &, Response &)>;
  1446. using StartHandler = std::function<void()>;
  1447. using WebSocketHandler =
  1448. std::function<void(const Request &, ws::WebSocket &)>;
  1449. using SubProtocolSelector =
  1450. std::function<std::string(const std::vector<std::string> &protocols)>;
  1451. Server();
  1452. virtual ~Server();
  1453. virtual bool is_valid() const;
  1454. Server &Get(const std::string &pattern, Handler handler);
  1455. Server &Post(const std::string &pattern, Handler handler);
  1456. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  1457. Server &Put(const std::string &pattern, Handler handler);
  1458. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  1459. Server &Patch(const std::string &pattern, Handler handler);
  1460. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  1461. Server &Delete(const std::string &pattern, Handler handler);
  1462. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  1463. Server &Options(const std::string &pattern, Handler handler);
  1464. Server &WebSocket(const std::string &pattern, WebSocketHandler handler);
  1465. Server &WebSocket(const std::string &pattern, WebSocketHandler handler,
  1466. SubProtocolSelector sub_protocol_selector);
  1467. bool set_base_dir(const std::string &dir,
  1468. const std::string &mount_point = std::string());
  1469. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  1470. Headers headers = Headers());
  1471. bool remove_mount_point(const std::string &mount_point);
  1472. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  1473. const std::string &mime);
  1474. Server &set_default_file_mimetype(const std::string &mime);
  1475. Server &set_file_request_handler(Handler handler);
  1476. template <class ErrorHandlerFunc>
  1477. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  1478. return set_error_handler_core(
  1479. std::forward<ErrorHandlerFunc>(handler),
  1480. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  1481. }
  1482. Server &set_exception_handler(ExceptionHandler handler);
  1483. Server &set_pre_routing_handler(HandlerWithResponse handler);
  1484. Server &set_post_routing_handler(Handler handler);
  1485. Server &set_pre_request_handler(HandlerWithResponse handler);
  1486. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  1487. Server &set_start_handler(StartHandler handler);
  1488. Server &set_logger(Logger logger);
  1489. Server &set_pre_compression_logger(Logger logger);
  1490. Server &set_error_logger(ErrorLogger error_logger);
  1491. Server &set_address_family(int family);
  1492. Server &set_tcp_nodelay(bool on);
  1493. Server &set_ipv6_v6only(bool on);
  1494. Server &set_socket_options(SocketOptions socket_options);
  1495. Server &set_default_headers(Headers headers);
  1496. Server &
  1497. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1498. Server &set_trusted_proxies(const std::vector<std::string> &proxies);
  1499. Server &set_keep_alive_max_count(size_t count);
  1500. Server &set_keep_alive_timeout(time_t sec);
  1501. template <class Rep, class Period>
  1502. Server &
  1503. set_keep_alive_timeout(const std::chrono::duration<Rep, Period> &duration);
  1504. Server &set_read_timeout(time_t sec, time_t usec = 0);
  1505. template <class Rep, class Period>
  1506. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1507. Server &set_write_timeout(time_t sec, time_t usec = 0);
  1508. template <class Rep, class Period>
  1509. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1510. Server &set_idle_interval(time_t sec, time_t usec = 0);
  1511. template <class Rep, class Period>
  1512. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  1513. Server &set_payload_max_length(size_t length);
  1514. Server &set_websocket_ping_interval(time_t sec);
  1515. template <class Rep, class Period>
  1516. Server &set_websocket_ping_interval(
  1517. const std::chrono::duration<Rep, Period> &duration);
  1518. Server &set_websocket_max_missed_pongs(int count);
  1519. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  1520. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  1521. bool listen_after_bind();
  1522. bool listen(const std::string &host, int port, int socket_flags = 0);
  1523. bool is_running() const;
  1524. void wait_until_ready() const;
  1525. void stop() noexcept;
  1526. void decommission();
  1527. std::function<TaskQueue *(void)> new_task_queue;
  1528. protected:
  1529. bool process_request(Stream &strm, const std::string &remote_addr,
  1530. int remote_port, const std::string &local_addr,
  1531. int local_port, bool close_connection,
  1532. bool &connection_closed,
  1533. const std::function<void(Request &)> &setup_request,
  1534. bool *websocket_upgraded = nullptr);
  1535. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  1536. std::vector<std::string> trusted_proxies_;
  1537. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  1538. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  1539. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  1540. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  1541. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  1542. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  1543. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  1544. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  1545. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1546. time_t websocket_ping_interval_sec_ =
  1547. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  1548. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  1549. private:
  1550. using Handlers =
  1551. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  1552. using HandlersForContentReader =
  1553. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  1554. HandlerWithContentReader>>;
  1555. static std::unique_ptr<detail::MatcherBase>
  1556. make_matcher(const std::string &pattern);
  1557. template <typename H>
  1558. Server &add_handler(
  1559. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, H>> &handlers,
  1560. const std::string &pattern, H handler) {
  1561. handlers.emplace_back(make_matcher(pattern), std::move(handler));
  1562. return *this;
  1563. }
  1564. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  1565. Server &set_error_handler_core(Handler handler, std::false_type);
  1566. socket_t create_server_socket(const std::string &host, int port,
  1567. int socket_flags,
  1568. SocketOptions socket_options) const;
  1569. int bind_internal(const std::string &host, int port, int socket_flags);
  1570. bool listen_internal();
  1571. bool routing(Request &req, Response &res, Stream &strm);
  1572. bool handle_file_request(Request &req, Response &res);
  1573. bool check_if_not_modified(const Request &req, Response &res,
  1574. const std::string &etag, time_t mtime) const;
  1575. bool check_if_range(Request &req, const std::string &etag,
  1576. time_t mtime) const;
  1577. bool dispatch_request(Request &req, Response &res, const Handlers &handlers,
  1578. Stream &strm);
  1579. bool dispatch_request_for_content_reader(
  1580. Request &req, Response &res, ContentReader content_reader,
  1581. const HandlersForContentReader &handlers) const;
  1582. bool parse_request_line(const char *s, Request &req) const;
  1583. void apply_ranges(const Request &req, Response &res,
  1584. std::string &content_type, std::string &boundary) const;
  1585. bool write_response(Stream &strm, bool close_connection, Request &req,
  1586. Response &res);
  1587. bool write_response_with_content(Stream &strm, bool close_connection,
  1588. const Request &req, Response &res);
  1589. bool write_response_core(Stream &strm, bool close_connection,
  1590. const Request &req, Response &res,
  1591. bool need_apply_ranges);
  1592. bool write_content_with_provider(Stream &strm, const Request &req,
  1593. Response &res, const std::string &boundary,
  1594. const std::string &content_type);
  1595. bool read_content(Stream &strm, Request &req, Response &res);
  1596. bool read_content_with_content_receiver(Stream &strm, Request &req,
  1597. Response &res,
  1598. ContentReceiver receiver,
  1599. FormDataHeader multipart_header,
  1600. ContentReceiver multipart_receiver);
  1601. bool read_content_core(Stream &strm, Request &req, Response &res,
  1602. ContentReceiver receiver,
  1603. FormDataHeader multipart_header,
  1604. ContentReceiver multipart_receiver) const;
  1605. virtual bool process_and_close_socket(socket_t sock);
  1606. void output_log(const Request &req, const Response &res) const;
  1607. void output_pre_compression_log(const Request &req,
  1608. const Response &res) const;
  1609. void output_error_log(const Error &err, const Request *req) const;
  1610. std::atomic<bool> is_running_{false};
  1611. std::atomic<bool> is_decommissioned{false};
  1612. struct MountPointEntry {
  1613. std::string mount_point;
  1614. std::string base_dir;
  1615. std::string resolved_base_dir;
  1616. Headers headers;
  1617. };
  1618. std::vector<MountPointEntry> base_dirs_;
  1619. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1620. std::string default_file_mimetype_ = "application/octet-stream";
  1621. Handler file_request_handler_;
  1622. Handlers get_handlers_;
  1623. Handlers post_handlers_;
  1624. HandlersForContentReader post_handlers_for_content_reader_;
  1625. Handlers put_handlers_;
  1626. HandlersForContentReader put_handlers_for_content_reader_;
  1627. Handlers patch_handlers_;
  1628. HandlersForContentReader patch_handlers_for_content_reader_;
  1629. Handlers delete_handlers_;
  1630. HandlersForContentReader delete_handlers_for_content_reader_;
  1631. Handlers options_handlers_;
  1632. struct WebSocketHandlerEntry {
  1633. std::unique_ptr<detail::MatcherBase> matcher;
  1634. WebSocketHandler handler;
  1635. SubProtocolSelector sub_protocol_selector;
  1636. };
  1637. using WebSocketHandlers = std::vector<WebSocketHandlerEntry>;
  1638. WebSocketHandlers websocket_handlers_;
  1639. HandlerWithResponse error_handler_;
  1640. ExceptionHandler exception_handler_;
  1641. HandlerWithResponse pre_routing_handler_;
  1642. Handler post_routing_handler_;
  1643. HandlerWithResponse pre_request_handler_;
  1644. Expect100ContinueHandler expect_100_continue_handler_;
  1645. StartHandler start_handler_;
  1646. mutable std::mutex logger_mutex_;
  1647. Logger logger_;
  1648. Logger pre_compression_logger_;
  1649. ErrorLogger error_logger_;
  1650. int address_family_ = AF_UNSPEC;
  1651. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1652. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1653. SocketOptions socket_options_ = default_socket_options;
  1654. Headers default_headers_;
  1655. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1656. detail::write_headers;
  1657. };
  1658. class Result {
  1659. public:
  1660. Result() = default;
  1661. Result(std::unique_ptr<Response> &&res, Error err,
  1662. Headers &&request_headers = Headers{})
  1663. : res_(std::move(res)), err_(err),
  1664. request_headers_(std::move(request_headers)) {}
  1665. // Response
  1666. operator bool() const { return res_ != nullptr; }
  1667. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1668. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1669. const Response &value() const { return *res_; }
  1670. Response &value() { return *res_; }
  1671. const Response &operator*() const { return *res_; }
  1672. Response &operator*() { return *res_; }
  1673. const Response *operator->() const { return res_.get(); }
  1674. Response *operator->() { return res_.get(); }
  1675. // Error
  1676. Error error() const { return err_; }
  1677. // Request Headers
  1678. bool has_request_header(const std::string &key) const;
  1679. std::string get_request_header_value(const std::string &key,
  1680. const char *def = "",
  1681. size_t id = 0) const;
  1682. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1683. size_t id = 0) const;
  1684. size_t get_request_header_value_count(const std::string &key) const;
  1685. private:
  1686. std::unique_ptr<Response> res_;
  1687. Error err_ = Error::Unknown;
  1688. Headers request_headers_;
  1689. #ifdef CPPHTTPLIB_SSL_ENABLED
  1690. public:
  1691. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1692. int ssl_error)
  1693. : res_(std::move(res)), err_(err),
  1694. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1695. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1696. int ssl_error, uint64_t ssl_backend_error)
  1697. : res_(std::move(res)), err_(err),
  1698. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1699. ssl_backend_error_(ssl_backend_error) {}
  1700. int ssl_error() const { return ssl_error_; }
  1701. uint64_t ssl_backend_error() const { return ssl_backend_error_; }
  1702. private:
  1703. int ssl_error_ = 0;
  1704. uint64_t ssl_backend_error_ = 0;
  1705. #endif
  1706. };
  1707. struct ClientConnection {
  1708. socket_t sock = INVALID_SOCKET;
  1709. bool is_open() const { return sock != INVALID_SOCKET; }
  1710. ClientConnection() = default;
  1711. ~ClientConnection();
  1712. ClientConnection(const ClientConnection &) = delete;
  1713. ClientConnection &operator=(const ClientConnection &) = delete;
  1714. ClientConnection(ClientConnection &&other) noexcept
  1715. : sock(other.sock)
  1716. #ifdef CPPHTTPLIB_SSL_ENABLED
  1717. ,
  1718. session(other.session)
  1719. #endif
  1720. {
  1721. other.sock = INVALID_SOCKET;
  1722. #ifdef CPPHTTPLIB_SSL_ENABLED
  1723. other.session = nullptr;
  1724. #endif
  1725. }
  1726. ClientConnection &operator=(ClientConnection &&other) noexcept {
  1727. if (this != &other) {
  1728. sock = other.sock;
  1729. other.sock = INVALID_SOCKET;
  1730. #ifdef CPPHTTPLIB_SSL_ENABLED
  1731. session = other.session;
  1732. other.session = nullptr;
  1733. #endif
  1734. }
  1735. return *this;
  1736. }
  1737. #ifdef CPPHTTPLIB_SSL_ENABLED
  1738. tls::session_t session = nullptr;
  1739. #endif
  1740. };
  1741. namespace detail {
  1742. struct ChunkedDecoder;
  1743. struct BodyReader {
  1744. Stream *stream = nullptr;
  1745. bool has_content_length = false;
  1746. size_t content_length = 0;
  1747. size_t payload_max_length = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  1748. size_t bytes_read = 0;
  1749. bool chunked = false;
  1750. bool eof = false;
  1751. std::unique_ptr<ChunkedDecoder> chunked_decoder;
  1752. Error last_error = Error::Success;
  1753. ssize_t read(char *buf, size_t len);
  1754. bool has_error() const { return last_error != Error::Success; }
  1755. };
  1756. inline ssize_t read_body_content(Stream *stream, BodyReader &br, char *buf,
  1757. size_t len) {
  1758. (void)stream;
  1759. return br.read(buf, len);
  1760. }
  1761. class decompressor;
  1762. enum class NoProxyKind {
  1763. Wildcard, // "*"
  1764. HostnameSuffix, // "example.com" or ".example.com"
  1765. IPv4Cidr, // "10.0.0.0/8" (or single IP, treated as /32)
  1766. IPv6Cidr, // "fe80::/10" (or single IP, treated as /128)
  1767. };
  1768. // Unified 16-byte buffer holding either a v4 (first 4 bytes) or v6 address.
  1769. // Lets one CIDR matcher cover both families.
  1770. using IPBytes = std::array<uint8_t, 16>;
  1771. struct NoProxyEntry {
  1772. NoProxyKind kind = NoProxyKind::Wildcard;
  1773. std::string hostname_pattern; // lowercased, leading/trailing dot stripped
  1774. IPBytes net{};
  1775. int prefix_bits = 0;
  1776. };
  1777. struct NormalizedTarget {
  1778. std::string hostname; // lowercase; brackets and trailing dot removed
  1779. bool is_ipv4 = false;
  1780. bool is_ipv6 = false;
  1781. IPBytes ip{};
  1782. };
  1783. } // namespace detail
  1784. class ClientImpl {
  1785. public:
  1786. explicit ClientImpl(const std::string &host);
  1787. explicit ClientImpl(const std::string &host, int port);
  1788. explicit ClientImpl(const std::string &host, int port,
  1789. const std::string &client_cert_path,
  1790. const std::string &client_key_path);
  1791. virtual ~ClientImpl();
  1792. virtual bool is_valid() const;
  1793. struct StreamHandle {
  1794. std::unique_ptr<Response> response;
  1795. Error error = Error::Success;
  1796. StreamHandle() = default;
  1797. StreamHandle(const StreamHandle &) = delete;
  1798. StreamHandle &operator=(const StreamHandle &) = delete;
  1799. StreamHandle(StreamHandle &&) = default;
  1800. StreamHandle &operator=(StreamHandle &&) = default;
  1801. ~StreamHandle() = default;
  1802. bool is_valid() const {
  1803. return response != nullptr && error == Error::Success;
  1804. }
  1805. ssize_t read(char *buf, size_t len);
  1806. void parse_trailers_if_needed();
  1807. Error get_read_error() const { return body_reader_.last_error; }
  1808. bool has_read_error() const { return body_reader_.has_error(); }
  1809. bool trailers_parsed_ = false;
  1810. private:
  1811. friend class ClientImpl;
  1812. ssize_t read_with_decompression(char *buf, size_t len);
  1813. std::unique_ptr<ClientConnection> connection_;
  1814. std::unique_ptr<Stream> socket_stream_;
  1815. Stream *stream_ = nullptr;
  1816. detail::BodyReader body_reader_;
  1817. std::unique_ptr<detail::decompressor> decompressor_;
  1818. std::string decompress_buffer_;
  1819. size_t decompress_offset_ = 0;
  1820. size_t decompressed_bytes_read_ = 0;
  1821. };
  1822. // clang-format off
  1823. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1824. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1825. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1826. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1827. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1828. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1829. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1830. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1831. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1832. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1833. Result Head(const std::string &path);
  1834. Result Head(const std::string &path, const Headers &headers);
  1835. Result Post(const std::string &path);
  1836. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1837. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1838. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1839. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1840. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1841. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1842. Result Post(const std::string &path, const Params &params);
  1843. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1844. Result Post(const std::string &path, const Headers &headers);
  1845. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1846. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1847. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1848. 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);
  1849. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1850. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1851. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1852. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1853. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1854. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1855. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1856. Result Put(const std::string &path);
  1857. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1858. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1859. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1860. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1861. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1862. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1863. Result Put(const std::string &path, const Params &params);
  1864. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1865. Result Put(const std::string &path, const Headers &headers);
  1866. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1867. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1868. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1869. 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);
  1870. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1871. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1872. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1873. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1874. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1875. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1876. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1877. Result Patch(const std::string &path);
  1878. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1879. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1880. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1881. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1882. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1883. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1884. Result Patch(const std::string &path, const Params &params);
  1885. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1886. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1887. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1888. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1889. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1890. 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);
  1891. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1892. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  1893. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1894. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1895. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1896. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1897. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1898. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1899. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1900. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1901. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1902. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1903. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1904. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1905. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1906. Result Options(const std::string &path);
  1907. Result Options(const std::string &path, const Headers &headers);
  1908. // clang-format on
  1909. // Streaming API: Open a stream for reading response body incrementally
  1910. // Socket ownership is transferred to StreamHandle for true streaming
  1911. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  1912. StreamHandle open_stream(const std::string &method, const std::string &path,
  1913. const Params &params = {},
  1914. const Headers &headers = {},
  1915. const std::string &body = {},
  1916. const std::string &content_type = {});
  1917. bool send(Request &req, Response &res, Error &error);
  1918. Result send(const Request &req);
  1919. void stop();
  1920. std::string host() const;
  1921. int port() const;
  1922. size_t is_socket_open() const;
  1923. socket_t socket() const;
  1924. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1925. void set_default_headers(Headers headers);
  1926. void
  1927. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1928. void set_address_family(int family);
  1929. void set_tcp_nodelay(bool on);
  1930. void set_ipv6_v6only(bool on);
  1931. void set_socket_options(SocketOptions socket_options);
  1932. void set_connection_timeout(time_t sec, time_t usec = 0);
  1933. template <class Rep, class Period>
  1934. void
  1935. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1936. void set_read_timeout(time_t sec, time_t usec = 0);
  1937. template <class Rep, class Period>
  1938. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1939. void set_write_timeout(time_t sec, time_t usec = 0);
  1940. template <class Rep, class Period>
  1941. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1942. void set_max_timeout(time_t msec);
  1943. template <class Rep, class Period>
  1944. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1945. void set_basic_auth(const std::string &username, const std::string &password);
  1946. void set_bearer_token_auth(const std::string &token);
  1947. void set_keep_alive(bool on);
  1948. void set_follow_location(bool on);
  1949. void set_path_encode(bool on);
  1950. void set_compress(bool on);
  1951. void set_decompress(bool on);
  1952. void set_payload_max_length(size_t length);
  1953. void set_interface(const std::string &intf);
  1954. void set_proxy(const std::string &host, int port);
  1955. void set_proxy_basic_auth(const std::string &username,
  1956. const std::string &password);
  1957. void set_proxy_bearer_token_auth(const std::string &token);
  1958. void set_no_proxy(const std::vector<std::string> &patterns);
  1959. void set_logger(Logger logger);
  1960. void set_error_logger(ErrorLogger error_logger);
  1961. protected:
  1962. struct Socket {
  1963. socket_t sock = INVALID_SOCKET;
  1964. // For Mbed TLS compatibility: start_time for request timeout tracking
  1965. std::chrono::time_point<std::chrono::steady_clock> start_time_;
  1966. bool is_open() const { return sock != INVALID_SOCKET; }
  1967. #ifdef CPPHTTPLIB_SSL_ENABLED
  1968. tls::session_t ssl = nullptr;
  1969. #endif
  1970. };
  1971. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1972. virtual bool ensure_socket_connection(Socket &socket, Error &error);
  1973. virtual bool setup_proxy_connection(
  1974. Socket &socket,
  1975. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1976. Response &res, bool &success, Error &error);
  1977. bool is_proxy_enabled_for_host(const std::string &host) const;
  1978. // All of:
  1979. // shutdown_ssl
  1980. // shutdown_socket
  1981. // close_socket
  1982. // disconnect
  1983. // should ONLY be called when socket_mutex_ is locked, and only when
  1984. // no other thread is using the socket.
  1985. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1986. void shutdown_socket(Socket &socket) const;
  1987. void close_socket(Socket &socket);
  1988. void disconnect(bool gracefully);
  1989. bool process_request(Stream &strm, Request &req, Response &res,
  1990. bool close_connection, Error &error);
  1991. bool write_content_with_provider(Stream &strm, const Request &req,
  1992. Error &error) const;
  1993. void copy_settings(const ClientImpl &rhs);
  1994. void output_log(const Request &req, const Response &res) const;
  1995. void output_error_log(const Error &err, const Request *req) const;
  1996. // Socket endpoint information
  1997. const std::string host_;
  1998. const int port_;
  1999. // Current open socket
  2000. Socket socket_;
  2001. mutable std::mutex socket_mutex_;
  2002. std::recursive_mutex request_mutex_;
  2003. // These are all protected under socket_mutex
  2004. size_t socket_requests_in_flight_ = 0;
  2005. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  2006. bool socket_should_be_closed_when_request_is_done_ = false;
  2007. // Hostname-IP map
  2008. std::map<std::string, std::string> addr_map_;
  2009. // Default headers
  2010. Headers default_headers_;
  2011. // Header writer
  2012. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  2013. detail::write_headers;
  2014. // Settings
  2015. std::string client_cert_path_;
  2016. std::string client_key_path_;
  2017. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  2018. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  2019. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  2020. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  2021. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  2022. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  2023. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  2024. std::string basic_auth_username_;
  2025. std::string basic_auth_password_;
  2026. std::string bearer_token_auth_token_;
  2027. bool keep_alive_ = false;
  2028. bool follow_location_ = false;
  2029. bool path_encode_ = true;
  2030. int address_family_ = AF_UNSPEC;
  2031. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  2032. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  2033. SocketOptions socket_options_ = nullptr;
  2034. bool compress_ = false;
  2035. bool decompress_ = true;
  2036. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  2037. bool has_payload_max_length_ = false;
  2038. std::string interface_;
  2039. std::string proxy_host_;
  2040. int proxy_port_ = -1;
  2041. std::string proxy_basic_auth_username_;
  2042. std::string proxy_basic_auth_password_;
  2043. std::string proxy_bearer_token_auth_token_;
  2044. std::vector<detail::NoProxyEntry> no_proxy_entries_;
  2045. mutable detail::NormalizedTarget host_normalized_;
  2046. mutable bool host_normalized_valid_ = false;
  2047. mutable std::mutex logger_mutex_;
  2048. Logger logger_;
  2049. ErrorLogger error_logger_;
  2050. private:
  2051. bool send_(Request &req, Response &res, Error &error);
  2052. Result send_(Request &&req);
  2053. socket_t create_client_socket(Error &error) const;
  2054. bool read_response_line(Stream &strm, const Request &req, Response &res,
  2055. bool skip_100_continue = true) const;
  2056. bool write_request(Stream &strm, Request &req, bool close_connection,
  2057. Error &error, bool skip_body = false);
  2058. bool write_request_body(Stream &strm, Request &req, Error &error);
  2059. void prepare_default_headers(Request &r, bool for_stream,
  2060. const std::string &ct);
  2061. bool redirect(Request &req, Response &res, Error &error);
  2062. bool create_redirect_client(const std::string &scheme,
  2063. const std::string &host, int port, Request &req,
  2064. Response &res, const std::string &path,
  2065. const std::string &location, Error &error);
  2066. template <typename ClientType> void setup_redirect_client(ClientType &client);
  2067. bool handle_request(Stream &strm, Request &req, Response &res,
  2068. bool close_connection, Error &error);
  2069. std::unique_ptr<Response> send_with_content_provider_and_receiver(
  2070. Request &req, const char *body, size_t content_length,
  2071. ContentProvider content_provider,
  2072. ContentProviderWithoutLength content_provider_without_length,
  2073. const std::string &content_type, ContentReceiver content_receiver,
  2074. Error &error);
  2075. Result send_with_content_provider_and_receiver(
  2076. const std::string &method, const std::string &path,
  2077. const Headers &headers, const char *body, size_t content_length,
  2078. ContentProvider content_provider,
  2079. ContentProviderWithoutLength content_provider_without_length,
  2080. const std::string &content_type, ContentReceiver content_receiver,
  2081. UploadProgress progress);
  2082. ContentProviderWithoutLength get_multipart_content_provider(
  2083. const std::string &boundary, const UploadFormDataItems &items,
  2084. const FormDataProviderItems &provider_items) const;
  2085. virtual bool
  2086. process_socket(const Socket &socket,
  2087. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2088. std::function<bool(Stream &strm)> callback);
  2089. virtual bool is_ssl() const;
  2090. void transfer_socket_ownership_to_handle(StreamHandle &handle);
  2091. #ifdef CPPHTTPLIB_SSL_ENABLED
  2092. public:
  2093. void set_digest_auth(const std::string &username,
  2094. const std::string &password);
  2095. void set_proxy_digest_auth(const std::string &username,
  2096. const std::string &password);
  2097. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2098. const std::string &ca_cert_dir_path = std::string());
  2099. void enable_server_certificate_verification(bool enabled);
  2100. void enable_server_hostname_verification(bool enabled);
  2101. void enable_system_ca(bool enabled);
  2102. protected:
  2103. std::string digest_auth_username_;
  2104. std::string digest_auth_password_;
  2105. std::string proxy_digest_auth_username_;
  2106. std::string proxy_digest_auth_password_;
  2107. std::string ca_cert_file_path_;
  2108. std::string ca_cert_dir_path_;
  2109. bool server_certificate_verification_ = true;
  2110. bool server_hostname_verification_ = true;
  2111. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  2112. std::string ca_cert_pem_; // Store CA cert PEM for redirect transfer
  2113. int last_ssl_error_ = 0;
  2114. uint64_t last_backend_error_ = 0;
  2115. #endif
  2116. };
  2117. class Client {
  2118. public:
  2119. // Universal interface
  2120. explicit Client(const std::string &scheme_host_port);
  2121. explicit Client(const std::string &scheme_host_port,
  2122. const std::string &client_cert_path,
  2123. const std::string &client_key_path);
  2124. // HTTP only interface
  2125. explicit Client(const std::string &host, int port);
  2126. explicit Client(const std::string &host, int port,
  2127. const std::string &client_cert_path,
  2128. const std::string &client_key_path);
  2129. Client(Client &&) = default;
  2130. Client &operator=(Client &&) = default;
  2131. ~Client();
  2132. bool is_valid() const;
  2133. // clang-format off
  2134. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  2135. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2136. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2137. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2138. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2139. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2140. Result Get(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2141. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  2142. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2143. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2144. Result Head(const std::string &path);
  2145. Result Head(const std::string &path, const Headers &headers);
  2146. Result Post(const std::string &path);
  2147. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2148. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2149. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2150. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2151. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2152. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2153. Result Post(const std::string &path, const Params &params);
  2154. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2155. Result Post(const std::string &path, const Headers &headers);
  2156. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2157. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2158. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2159. 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);
  2160. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2161. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2162. Result Post(const std::string &path, const Headers &headers, const Params &params);
  2163. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2164. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2165. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2166. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2167. Result Put(const std::string &path);
  2168. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2169. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2170. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2171. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2172. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2173. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2174. Result Put(const std::string &path, const Params &params);
  2175. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2176. Result Put(const std::string &path, const Headers &headers);
  2177. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2178. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2179. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2180. 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);
  2181. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2182. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2183. Result Put(const std::string &path, const Headers &headers, const Params &params);
  2184. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2185. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2186. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2187. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2188. Result Patch(const std::string &path);
  2189. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2190. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2191. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2192. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2193. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2194. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2195. Result Patch(const std::string &path, const Params &params);
  2196. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2197. Result Patch(const std::string &path, const Headers &headers);
  2198. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  2199. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  2200. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2201. 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);
  2202. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  2203. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, ContentReceiver content_receiver, UploadProgress progress = nullptr);
  2204. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  2205. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  2206. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  2207. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  2208. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  2209. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  2210. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2211. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2212. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  2213. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  2214. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  2215. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  2216. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  2217. Result Options(const std::string &path);
  2218. Result Options(const std::string &path, const Headers &headers);
  2219. // clang-format on
  2220. // Streaming API: Open a stream for reading response body incrementally
  2221. // Socket ownership is transferred to StreamHandle for true streaming
  2222. // Supports all HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  2223. ClientImpl::StreamHandle open_stream(const std::string &method,
  2224. const std::string &path,
  2225. const Params &params = {},
  2226. const Headers &headers = {},
  2227. const std::string &body = {},
  2228. const std::string &content_type = {});
  2229. bool send(Request &req, Response &res, Error &error);
  2230. Result send(const Request &req);
  2231. void stop();
  2232. std::string host() const;
  2233. int port() const;
  2234. size_t is_socket_open() const;
  2235. socket_t socket() const;
  2236. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  2237. void set_default_headers(Headers headers);
  2238. void
  2239. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  2240. void set_address_family(int family);
  2241. void set_tcp_nodelay(bool on);
  2242. void set_socket_options(SocketOptions socket_options);
  2243. void set_connection_timeout(time_t sec, time_t usec = 0);
  2244. template <class Rep, class Period>
  2245. void
  2246. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  2247. void set_read_timeout(time_t sec, time_t usec = 0);
  2248. template <class Rep, class Period>
  2249. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  2250. void set_write_timeout(time_t sec, time_t usec = 0);
  2251. template <class Rep, class Period>
  2252. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  2253. void set_max_timeout(time_t msec);
  2254. template <class Rep, class Period>
  2255. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  2256. void set_basic_auth(const std::string &username, const std::string &password);
  2257. void set_bearer_token_auth(const std::string &token);
  2258. void set_keep_alive(bool on);
  2259. void set_follow_location(bool on);
  2260. void set_path_encode(bool on);
  2261. void set_compress(bool on);
  2262. void set_decompress(bool on);
  2263. void set_payload_max_length(size_t length);
  2264. void set_interface(const std::string &intf);
  2265. void set_proxy(const std::string &host, int port);
  2266. void set_proxy_basic_auth(const std::string &username,
  2267. const std::string &password);
  2268. void set_proxy_bearer_token_auth(const std::string &token);
  2269. void set_no_proxy(const std::vector<std::string> &patterns);
  2270. void set_logger(Logger logger);
  2271. void set_error_logger(ErrorLogger error_logger);
  2272. private:
  2273. std::unique_ptr<ClientImpl> cli_;
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. public:
  2276. void set_digest_auth(const std::string &username,
  2277. const std::string &password);
  2278. void set_proxy_digest_auth(const std::string &username,
  2279. const std::string &password);
  2280. void enable_server_certificate_verification(bool enabled);
  2281. void enable_server_hostname_verification(bool enabled);
  2282. void enable_system_ca(bool enabled);
  2283. void set_ca_cert_path(const std::string &ca_cert_file_path,
  2284. const std::string &ca_cert_dir_path = std::string());
  2285. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2286. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2287. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2288. void set_session_verifier(
  2289. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2290. tls::ctx_t tls_context() const;
  2291. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2292. void enable_windows_certificate_verification(bool enabled);
  2293. #endif
  2294. private:
  2295. bool is_ssl_ = false;
  2296. #endif
  2297. };
  2298. #ifdef CPPHTTPLIB_SSL_ENABLED
  2299. class SSLServer : public Server {
  2300. public:
  2301. SSLServer(const char *cert_path, const char *private_key_path,
  2302. const char *client_ca_cert_file_path = nullptr,
  2303. const char *client_ca_cert_dir_path = nullptr,
  2304. const char *private_key_password = nullptr);
  2305. struct PemMemory {
  2306. const char *cert_pem;
  2307. size_t cert_pem_len;
  2308. const char *key_pem;
  2309. size_t key_pem_len;
  2310. const char *client_ca_pem;
  2311. size_t client_ca_pem_len;
  2312. const char *private_key_password;
  2313. };
  2314. explicit SSLServer(const PemMemory &pem);
  2315. // The callback receives the ctx_t handle which can be cast to the
  2316. // appropriate backend type (SSL_CTX* for OpenSSL,
  2317. // tls::impl::MbedTlsContext* for Mbed TLS)
  2318. explicit SSLServer(const tls::ContextSetupCallback &setup_callback);
  2319. ~SSLServer() override;
  2320. bool is_valid() const override;
  2321. bool update_certs_pem(const char *cert_pem, const char *key_pem,
  2322. const char *client_ca_pem = nullptr,
  2323. const char *password = nullptr);
  2324. tls::ctx_t tls_context() const { return ctx_; }
  2325. int ssl_last_error() const { return last_ssl_error_; }
  2326. private:
  2327. bool process_and_close_socket(socket_t sock) override;
  2328. tls::ctx_t ctx_ = nullptr;
  2329. std::mutex ctx_mutex_;
  2330. int last_ssl_error_ = 0;
  2331. };
  2332. class SSLClient final : public ClientImpl {
  2333. public:
  2334. explicit SSLClient(const std::string &host);
  2335. explicit SSLClient(const std::string &host, int port);
  2336. explicit SSLClient(const std::string &host, int port,
  2337. const std::string &client_cert_path,
  2338. const std::string &client_key_path,
  2339. const std::string &private_key_password = std::string());
  2340. struct PemMemory {
  2341. const char *cert_pem;
  2342. size_t cert_pem_len;
  2343. const char *key_pem;
  2344. size_t key_pem_len;
  2345. const char *private_key_password;
  2346. };
  2347. explicit SSLClient(const std::string &host, int port, const PemMemory &pem);
  2348. ~SSLClient() override;
  2349. bool is_valid() const override;
  2350. void set_ca_cert_store(tls::ca_store_t ca_cert_store);
  2351. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  2352. void set_server_certificate_verifier(tls::VerifyCallback verifier);
  2353. // Post-handshake session verifier (backend-independent)
  2354. void set_session_verifier(
  2355. std::function<SSLVerifierResponse(tls::session_t)> verifier);
  2356. tls::ctx_t tls_context() const { return ctx_; }
  2357. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2358. void enable_windows_certificate_verification(bool enabled);
  2359. #endif
  2360. private:
  2361. bool create_and_connect_socket(Socket &socket, Error &error) override;
  2362. bool ensure_socket_connection(Socket &socket, Error &error) override;
  2363. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  2364. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  2365. bool
  2366. process_socket(const Socket &socket,
  2367. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2368. std::function<bool(Stream &strm)> callback) override;
  2369. bool is_ssl() const override;
  2370. bool setup_proxy_connection(
  2371. Socket &socket,
  2372. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2373. Response &res, bool &success, Error &error) override;
  2374. bool connect_with_proxy(
  2375. Socket &sock,
  2376. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2377. Response &res, bool &success, Error &error);
  2378. bool initialize_ssl(Socket &socket, Error &error);
  2379. void init_ctx();
  2380. void reset_ctx_on_error();
  2381. bool load_certs();
  2382. tls::ctx_t ctx_ = nullptr;
  2383. std::mutex ctx_mutex_;
  2384. std::once_flag initialize_cert_;
  2385. // Tracks whether a custom CA store was applied via set_ca_cert_store(),
  2386. // since the store handle itself is owned by ctx_ and leaves no other trace.
  2387. // Used to keep custom CA configuration exclusive with system CA loading.
  2388. bool ca_cert_store_set_ = false;
  2389. long verify_result_ = 0;
  2390. std::function<SSLVerifierResponse(tls::session_t)> session_verifier_;
  2391. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  2392. bool enable_windows_cert_verification_ = true;
  2393. #endif
  2394. friend class ClientImpl;
  2395. };
  2396. #endif // CPPHTTPLIB_SSL_ENABLED
  2397. namespace detail {
  2398. template <typename T, typename U>
  2399. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  2400. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  2401. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  2402. duration - std::chrono::seconds(sec))
  2403. .count();
  2404. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  2405. }
  2406. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  2407. return N - 1;
  2408. }
  2409. inline bool is_numeric(const std::string &str) {
  2410. return !str.empty() && std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  2411. }
  2412. inline size_t get_header_value_u64(const Headers &headers,
  2413. const std::string &key, size_t def,
  2414. size_t id, bool &is_invalid_value) {
  2415. is_invalid_value = false;
  2416. auto rng = headers.equal_range(key);
  2417. auto it = rng.first;
  2418. std::advance(it, static_cast<ssize_t>(id));
  2419. if (it != rng.second) {
  2420. if (is_numeric(it->second)) {
  2421. return static_cast<size_t>(std::strtoull(it->second.data(), nullptr, 10));
  2422. } else {
  2423. is_invalid_value = true;
  2424. }
  2425. }
  2426. return def;
  2427. }
  2428. inline size_t get_header_value_u64(const Headers &headers,
  2429. const std::string &key, size_t def,
  2430. size_t id) {
  2431. auto dummy = false;
  2432. return get_header_value_u64(headers, key, def, id, dummy);
  2433. }
  2434. } // namespace detail
  2435. template <class Rep, class Period>
  2436. inline Server &
  2437. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2438. detail::duration_to_sec_and_usec(
  2439. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2440. return *this;
  2441. }
  2442. template <class Rep, class Period>
  2443. inline Server &
  2444. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2445. detail::duration_to_sec_and_usec(
  2446. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2447. return *this;
  2448. }
  2449. template <class Rep, class Period>
  2450. inline Server &
  2451. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  2452. detail::duration_to_sec_and_usec(
  2453. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  2454. return *this;
  2455. }
  2456. template <class Rep, class Period>
  2457. inline void ClientImpl::set_connection_timeout(
  2458. const std::chrono::duration<Rep, Period> &duration) {
  2459. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  2460. set_connection_timeout(sec, usec);
  2461. });
  2462. }
  2463. template <class Rep, class Period>
  2464. inline void ClientImpl::set_read_timeout(
  2465. const std::chrono::duration<Rep, Period> &duration) {
  2466. detail::duration_to_sec_and_usec(
  2467. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  2468. }
  2469. template <class Rep, class Period>
  2470. inline void ClientImpl::set_write_timeout(
  2471. const std::chrono::duration<Rep, Period> &duration) {
  2472. detail::duration_to_sec_and_usec(
  2473. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  2474. }
  2475. template <class Rep, class Period>
  2476. inline void ClientImpl::set_max_timeout(
  2477. const std::chrono::duration<Rep, Period> &duration) {
  2478. auto msec =
  2479. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  2480. set_max_timeout(msec);
  2481. }
  2482. template <class Rep, class Period>
  2483. inline void Client::set_connection_timeout(
  2484. const std::chrono::duration<Rep, Period> &duration) {
  2485. cli_->set_connection_timeout(duration);
  2486. }
  2487. template <class Rep, class Period>
  2488. inline void
  2489. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2490. cli_->set_read_timeout(duration);
  2491. }
  2492. template <class Rep, class Period>
  2493. inline void
  2494. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2495. cli_->set_write_timeout(duration);
  2496. }
  2497. inline void Client::set_max_timeout(time_t msec) {
  2498. cli_->set_max_timeout(msec);
  2499. }
  2500. template <class Rep, class Period>
  2501. inline void
  2502. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  2503. cli_->set_max_timeout(duration);
  2504. }
  2505. /*
  2506. * Forward declarations and types that will be part of the .h file if split into
  2507. * .h + .cc.
  2508. */
  2509. std::string hosted_at(const std::string &hostname);
  2510. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  2511. // JavaScript-style URL encoding/decoding functions
  2512. std::string encode_uri_component(const std::string &value);
  2513. std::string encode_uri(const std::string &value);
  2514. std::string decode_uri_component(const std::string &value);
  2515. std::string decode_uri(const std::string &value);
  2516. // RFC 3986 compliant URL component encoding/decoding functions
  2517. std::string encode_path_component(const std::string &component);
  2518. std::string decode_path_component(const std::string &component);
  2519. std::string encode_query_component(const std::string &component,
  2520. bool space_as_plus = true);
  2521. std::string decode_query_component(const std::string &component,
  2522. bool plus_as_space = true);
  2523. std::string sanitize_filename(const std::string &filename);
  2524. std::string append_query_params(const std::string &path, const Params &params);
  2525. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  2526. std::pair<std::string, std::string>
  2527. make_basic_authentication_header(const std::string &username,
  2528. const std::string &password,
  2529. bool is_proxy = false);
  2530. namespace detail {
  2531. #if defined(_WIN32)
  2532. inline std::wstring u8string_to_wstring(const char *s) {
  2533. if (!s) { return std::wstring(); }
  2534. auto len = static_cast<int>(strlen(s));
  2535. if (!len) { return std::wstring(); }
  2536. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  2537. if (!wlen) { return std::wstring(); }
  2538. std::wstring ws;
  2539. ws.resize(wlen);
  2540. wlen = ::MultiByteToWideChar(
  2541. CP_UTF8, 0, s, len,
  2542. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  2543. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  2544. return ws;
  2545. }
  2546. #endif
  2547. struct FileStat {
  2548. FileStat(const std::string &path);
  2549. bool is_file() const;
  2550. bool is_dir() const;
  2551. time_t mtime() const;
  2552. size_t size() const;
  2553. private:
  2554. #if defined(_WIN32)
  2555. struct _stat st_;
  2556. #else
  2557. struct stat st_;
  2558. #endif
  2559. int ret_ = -1;
  2560. };
  2561. std::string make_host_and_port_string(const std::string &host, int port,
  2562. bool is_ssl);
  2563. std::string trim_copy(const std::string &s);
  2564. void divide(
  2565. const char *data, std::size_t size, char d,
  2566. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2567. fn);
  2568. void divide(
  2569. const std::string &str, char d,
  2570. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2571. fn);
  2572. void split(const char *b, const char *e, char d,
  2573. std::function<void(const char *, const char *)> fn);
  2574. void split(const char *b, const char *e, char d, size_t m,
  2575. std::function<void(const char *, const char *)> fn);
  2576. bool process_client_socket(
  2577. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2578. time_t write_timeout_sec, time_t write_timeout_usec,
  2579. time_t max_timeout_msec,
  2580. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2581. std::function<bool(Stream &)> callback);
  2582. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2583. int port, int address_family, bool tcp_nodelay,
  2584. bool ipv6_v6only, SocketOptions socket_options,
  2585. time_t connection_timeout_sec,
  2586. time_t connection_timeout_usec,
  2587. time_t read_timeout_sec, time_t read_timeout_usec,
  2588. time_t write_timeout_sec,
  2589. time_t write_timeout_usec,
  2590. const std::string &intf, Error &error);
  2591. const char *get_header_value(const Headers &headers, const std::string &key,
  2592. const char *def, size_t id);
  2593. std::string params_to_query_str(const Params &params);
  2594. void parse_query_text(const char *data, std::size_t size, Params &params);
  2595. void parse_query_text(const std::string &s, Params &params);
  2596. bool parse_multipart_boundary(const std::string &content_type,
  2597. std::string &boundary);
  2598. bool parse_range_header(const std::string &s, Ranges &ranges);
  2599. bool parse_accept_header(const std::string &s,
  2600. std::vector<std::string> &content_types);
  2601. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2602. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2603. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2604. EncodingType encoding_type(const Request &req, const Response &res);
  2605. class BufferStream final : public Stream {
  2606. public:
  2607. BufferStream() = default;
  2608. ~BufferStream() override = default;
  2609. bool is_readable() const override;
  2610. bool wait_readable() const override;
  2611. bool wait_writable() const override;
  2612. ssize_t read(char *ptr, size_t size) override;
  2613. ssize_t write(const char *ptr, size_t size) override;
  2614. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2615. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2616. socket_t socket() const override;
  2617. time_t duration() const override;
  2618. const std::string &get_buffer() const;
  2619. private:
  2620. std::string buffer;
  2621. size_t position = 0;
  2622. };
  2623. class compressor {
  2624. public:
  2625. virtual ~compressor() = default;
  2626. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2627. virtual bool compress(const char *data, size_t data_length, bool last,
  2628. Callback callback) = 0;
  2629. };
  2630. class decompressor {
  2631. public:
  2632. virtual ~decompressor() = default;
  2633. virtual bool is_valid() const = 0;
  2634. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2635. virtual bool decompress(const char *data, size_t data_length,
  2636. Callback callback) = 0;
  2637. };
  2638. class nocompressor final : public compressor {
  2639. public:
  2640. ~nocompressor() override = default;
  2641. bool compress(const char *data, size_t data_length, bool /*last*/,
  2642. Callback callback) override;
  2643. };
  2644. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2645. class gzip_compressor final : public compressor {
  2646. public:
  2647. gzip_compressor();
  2648. ~gzip_compressor() override;
  2649. bool compress(const char *data, size_t data_length, bool last,
  2650. Callback callback) override;
  2651. private:
  2652. bool is_valid_ = false;
  2653. z_stream strm_;
  2654. };
  2655. class gzip_decompressor final : public decompressor {
  2656. public:
  2657. gzip_decompressor();
  2658. ~gzip_decompressor() override;
  2659. bool is_valid() const override;
  2660. bool decompress(const char *data, size_t data_length,
  2661. Callback callback) override;
  2662. private:
  2663. bool is_valid_ = false;
  2664. z_stream strm_;
  2665. };
  2666. #endif
  2667. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2668. class brotli_compressor final : public compressor {
  2669. public:
  2670. brotli_compressor();
  2671. ~brotli_compressor();
  2672. bool compress(const char *data, size_t data_length, bool last,
  2673. Callback callback) override;
  2674. private:
  2675. BrotliEncoderState *state_ = nullptr;
  2676. };
  2677. class brotli_decompressor final : public decompressor {
  2678. public:
  2679. brotli_decompressor();
  2680. ~brotli_decompressor();
  2681. bool is_valid() const override;
  2682. bool decompress(const char *data, size_t data_length,
  2683. Callback callback) override;
  2684. private:
  2685. BrotliDecoderResult decoder_r;
  2686. BrotliDecoderState *decoder_s = nullptr;
  2687. };
  2688. #endif
  2689. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2690. class zstd_compressor : public compressor {
  2691. public:
  2692. zstd_compressor();
  2693. ~zstd_compressor();
  2694. bool compress(const char *data, size_t data_length, bool last,
  2695. Callback callback) override;
  2696. private:
  2697. ZSTD_CCtx *ctx_ = nullptr;
  2698. };
  2699. class zstd_decompressor : public decompressor {
  2700. public:
  2701. zstd_decompressor();
  2702. ~zstd_decompressor();
  2703. bool is_valid() const override;
  2704. bool decompress(const char *data, size_t data_length,
  2705. Callback callback) override;
  2706. private:
  2707. ZSTD_DCtx *ctx_ = nullptr;
  2708. };
  2709. #endif
  2710. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2711. // to store data. The call can set memory on stack for performance.
  2712. class stream_line_reader {
  2713. public:
  2714. stream_line_reader(Stream &strm, char *fixed_buffer,
  2715. size_t fixed_buffer_size);
  2716. const char *ptr() const;
  2717. size_t size() const;
  2718. bool end_with_crlf() const;
  2719. bool getline();
  2720. private:
  2721. void append(char c);
  2722. Stream &strm_;
  2723. char *fixed_buffer_;
  2724. const size_t fixed_buffer_size_;
  2725. size_t fixed_buffer_used_size_ = 0;
  2726. std::string growable_buffer_;
  2727. };
  2728. bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  2729. const Headers &src_headers);
  2730. struct ChunkedDecoder {
  2731. Stream &strm;
  2732. size_t chunk_remaining = 0;
  2733. bool finished = false;
  2734. char line_buf[64];
  2735. size_t last_chunk_total = 0;
  2736. size_t last_chunk_offset = 0;
  2737. explicit ChunkedDecoder(Stream &s);
  2738. ssize_t read_payload(char *buf, size_t len, size_t &out_chunk_offset,
  2739. size_t &out_chunk_total);
  2740. bool parse_trailers_into(Headers &dest, const Headers &src_headers);
  2741. };
  2742. class mmap {
  2743. public:
  2744. mmap(const char *path);
  2745. ~mmap();
  2746. bool open(const char *path);
  2747. void close();
  2748. bool is_open() const;
  2749. size_t size() const;
  2750. const char *data() const;
  2751. private:
  2752. #if defined(_WIN32)
  2753. HANDLE hFile_ = NULL;
  2754. HANDLE hMapping_ = NULL;
  2755. #else
  2756. int fd_ = -1;
  2757. #endif
  2758. size_t size_ = 0;
  2759. void *addr_ = nullptr;
  2760. bool is_open_empty_file = false;
  2761. };
  2762. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2763. namespace fields {
  2764. bool is_token_char(char c);
  2765. bool is_token(const std::string &s);
  2766. bool is_field_name(const std::string &s);
  2767. bool is_vchar(char c);
  2768. bool is_obs_text(char c);
  2769. bool is_field_vchar(char c);
  2770. bool is_field_content(const std::string &s);
  2771. bool is_field_value(const std::string &s);
  2772. } // namespace fields
  2773. } // namespace detail
  2774. /*
  2775. * TLS Abstraction Layer Declarations
  2776. */
  2777. #ifdef CPPHTTPLIB_SSL_ENABLED
  2778. // TLS abstraction layer - backend-specific type declarations
  2779. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  2780. namespace tls {
  2781. namespace impl {
  2782. // Mbed TLS context wrapper (holds config, entropy, DRBG, CA chain, own
  2783. // cert/key). This struct is accessible via tls::impl for use in SSL context
  2784. // setup callbacks (cast ctx_t to tls::impl::MbedTlsContext*).
  2785. struct MbedTlsContext {
  2786. mbedtls_ssl_config conf;
  2787. mbedtls_entropy_context entropy;
  2788. mbedtls_ctr_drbg_context ctr_drbg;
  2789. mbedtls_x509_crt ca_chain;
  2790. mbedtls_x509_crt own_cert;
  2791. mbedtls_pk_context own_key;
  2792. bool is_server = false;
  2793. bool verify_client = false;
  2794. bool has_verify_callback = false;
  2795. MbedTlsContext();
  2796. ~MbedTlsContext();
  2797. MbedTlsContext(const MbedTlsContext &) = delete;
  2798. MbedTlsContext &operator=(const MbedTlsContext &) = delete;
  2799. };
  2800. } // namespace impl
  2801. } // namespace tls
  2802. #endif
  2803. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  2804. namespace tls {
  2805. namespace impl {
  2806. // wolfSSL context wrapper (holds WOLFSSL_CTX and related state).
  2807. // This struct is accessible via tls::impl for use in SSL context
  2808. // setup callbacks (cast ctx_t to tls::impl::WolfSSLContext*).
  2809. struct WolfSSLContext {
  2810. WOLFSSL_CTX *ctx = nullptr;
  2811. bool is_server = false;
  2812. bool verify_client = false;
  2813. bool has_verify_callback = false;
  2814. std::string ca_pem_data_; // accumulated PEM for get_ca_names/get_ca_certs
  2815. WolfSSLContext();
  2816. ~WolfSSLContext();
  2817. WolfSSLContext(const WolfSSLContext &) = delete;
  2818. WolfSSLContext &operator=(const WolfSSLContext &) = delete;
  2819. };
  2820. // CA store for wolfSSL: holds raw PEM bytes to allow reloading into any ctx
  2821. struct WolfSSLCAStore {
  2822. std::string pem_data;
  2823. };
  2824. } // namespace impl
  2825. } // namespace tls
  2826. #endif
  2827. #endif // CPPHTTPLIB_SSL_ENABLED
  2828. namespace stream {
  2829. class Result {
  2830. public:
  2831. Result();
  2832. explicit Result(ClientImpl::StreamHandle &&handle, size_t chunk_size = 8192);
  2833. Result(Result &&other) noexcept;
  2834. Result &operator=(Result &&other) noexcept;
  2835. Result(const Result &) = delete;
  2836. Result &operator=(const Result &) = delete;
  2837. // Response info
  2838. bool is_valid() const;
  2839. explicit operator bool() const;
  2840. int status() const;
  2841. const Headers &headers() const;
  2842. std::string get_header_value(const std::string &key,
  2843. const char *def = "") const;
  2844. bool has_header(const std::string &key) const;
  2845. Error error() const;
  2846. Error read_error() const;
  2847. bool has_read_error() const;
  2848. // Stream reading
  2849. bool next();
  2850. const char *data() const;
  2851. size_t size() const;
  2852. std::string read_all();
  2853. private:
  2854. ClientImpl::StreamHandle handle_;
  2855. std::string buffer_;
  2856. size_t current_size_ = 0;
  2857. size_t chunk_size_;
  2858. bool finished_ = false;
  2859. };
  2860. // GET
  2861. template <typename ClientType>
  2862. inline Result Get(ClientType &cli, const std::string &path,
  2863. size_t chunk_size = 8192) {
  2864. return Result{cli.open_stream("GET", path), chunk_size};
  2865. }
  2866. template <typename ClientType>
  2867. inline Result Get(ClientType &cli, const std::string &path,
  2868. const Headers &headers, size_t chunk_size = 8192) {
  2869. return Result{cli.open_stream("GET", path, {}, headers), chunk_size};
  2870. }
  2871. template <typename ClientType>
  2872. inline Result Get(ClientType &cli, const std::string &path,
  2873. const Params &params, size_t chunk_size = 8192) {
  2874. return Result{cli.open_stream("GET", path, params), chunk_size};
  2875. }
  2876. template <typename ClientType>
  2877. inline Result Get(ClientType &cli, const std::string &path,
  2878. const Params &params, const Headers &headers,
  2879. size_t chunk_size = 8192) {
  2880. return Result{cli.open_stream("GET", path, params, headers), chunk_size};
  2881. }
  2882. // POST
  2883. template <typename ClientType>
  2884. inline Result Post(ClientType &cli, const std::string &path,
  2885. const std::string &body, const std::string &content_type,
  2886. size_t chunk_size = 8192) {
  2887. return Result{cli.open_stream("POST", path, {}, {}, body, content_type),
  2888. chunk_size};
  2889. }
  2890. template <typename ClientType>
  2891. inline Result Post(ClientType &cli, const std::string &path,
  2892. const Headers &headers, const std::string &body,
  2893. const std::string &content_type, size_t chunk_size = 8192) {
  2894. return Result{cli.open_stream("POST", path, {}, headers, body, content_type),
  2895. chunk_size};
  2896. }
  2897. template <typename ClientType>
  2898. inline Result Post(ClientType &cli, const std::string &path,
  2899. const Params &params, const std::string &body,
  2900. const std::string &content_type, size_t chunk_size = 8192) {
  2901. return Result{cli.open_stream("POST", path, params, {}, body, content_type),
  2902. chunk_size};
  2903. }
  2904. template <typename ClientType>
  2905. inline Result Post(ClientType &cli, const std::string &path,
  2906. const Params &params, const Headers &headers,
  2907. const std::string &body, const std::string &content_type,
  2908. size_t chunk_size = 8192) {
  2909. return Result{
  2910. cli.open_stream("POST", path, params, headers, body, content_type),
  2911. chunk_size};
  2912. }
  2913. // PUT
  2914. template <typename ClientType>
  2915. inline Result Put(ClientType &cli, const std::string &path,
  2916. const std::string &body, const std::string &content_type,
  2917. size_t chunk_size = 8192) {
  2918. return Result{cli.open_stream("PUT", path, {}, {}, body, content_type),
  2919. chunk_size};
  2920. }
  2921. template <typename ClientType>
  2922. inline Result Put(ClientType &cli, const std::string &path,
  2923. const Headers &headers, const std::string &body,
  2924. const std::string &content_type, size_t chunk_size = 8192) {
  2925. return Result{cli.open_stream("PUT", path, {}, headers, body, content_type),
  2926. chunk_size};
  2927. }
  2928. template <typename ClientType>
  2929. inline Result Put(ClientType &cli, const std::string &path,
  2930. const Params &params, const std::string &body,
  2931. const std::string &content_type, size_t chunk_size = 8192) {
  2932. return Result{cli.open_stream("PUT", path, params, {}, body, content_type),
  2933. chunk_size};
  2934. }
  2935. template <typename ClientType>
  2936. inline Result Put(ClientType &cli, const std::string &path,
  2937. const Params &params, const Headers &headers,
  2938. const std::string &body, const std::string &content_type,
  2939. size_t chunk_size = 8192) {
  2940. return Result{
  2941. cli.open_stream("PUT", path, params, headers, body, content_type),
  2942. chunk_size};
  2943. }
  2944. // PATCH
  2945. template <typename ClientType>
  2946. inline Result Patch(ClientType &cli, const std::string &path,
  2947. const std::string &body, const std::string &content_type,
  2948. size_t chunk_size = 8192) {
  2949. return Result{cli.open_stream("PATCH", path, {}, {}, body, content_type),
  2950. chunk_size};
  2951. }
  2952. template <typename ClientType>
  2953. inline Result Patch(ClientType &cli, const std::string &path,
  2954. const Headers &headers, const std::string &body,
  2955. const std::string &content_type, size_t chunk_size = 8192) {
  2956. return Result{cli.open_stream("PATCH", path, {}, headers, body, content_type),
  2957. chunk_size};
  2958. }
  2959. template <typename ClientType>
  2960. inline Result Patch(ClientType &cli, const std::string &path,
  2961. const Params &params, const std::string &body,
  2962. const std::string &content_type, size_t chunk_size = 8192) {
  2963. return Result{cli.open_stream("PATCH", path, params, {}, body, content_type),
  2964. chunk_size};
  2965. }
  2966. template <typename ClientType>
  2967. inline Result Patch(ClientType &cli, const std::string &path,
  2968. const Params &params, const Headers &headers,
  2969. const std::string &body, const std::string &content_type,
  2970. size_t chunk_size = 8192) {
  2971. return Result{
  2972. cli.open_stream("PATCH", path, params, headers, body, content_type),
  2973. chunk_size};
  2974. }
  2975. // DELETE
  2976. template <typename ClientType>
  2977. inline Result Delete(ClientType &cli, const std::string &path,
  2978. size_t chunk_size = 8192) {
  2979. return Result{cli.open_stream("DELETE", path), chunk_size};
  2980. }
  2981. template <typename ClientType>
  2982. inline Result Delete(ClientType &cli, const std::string &path,
  2983. const Headers &headers, size_t chunk_size = 8192) {
  2984. return Result{cli.open_stream("DELETE", path, {}, headers), chunk_size};
  2985. }
  2986. template <typename ClientType>
  2987. inline Result Delete(ClientType &cli, const std::string &path,
  2988. const std::string &body, const std::string &content_type,
  2989. size_t chunk_size = 8192) {
  2990. return Result{cli.open_stream("DELETE", path, {}, {}, body, content_type),
  2991. chunk_size};
  2992. }
  2993. template <typename ClientType>
  2994. inline Result Delete(ClientType &cli, const std::string &path,
  2995. const Headers &headers, const std::string &body,
  2996. const std::string &content_type,
  2997. size_t chunk_size = 8192) {
  2998. return Result{
  2999. cli.open_stream("DELETE", path, {}, headers, body, content_type),
  3000. chunk_size};
  3001. }
  3002. template <typename ClientType>
  3003. inline Result Delete(ClientType &cli, const std::string &path,
  3004. const Params &params, size_t chunk_size = 8192) {
  3005. return Result{cli.open_stream("DELETE", path, params), chunk_size};
  3006. }
  3007. template <typename ClientType>
  3008. inline Result Delete(ClientType &cli, const std::string &path,
  3009. const Params &params, const Headers &headers,
  3010. size_t chunk_size = 8192) {
  3011. return Result{cli.open_stream("DELETE", path, params, headers), chunk_size};
  3012. }
  3013. template <typename ClientType>
  3014. inline Result Delete(ClientType &cli, const std::string &path,
  3015. const Params &params, const std::string &body,
  3016. const std::string &content_type,
  3017. size_t chunk_size = 8192) {
  3018. return Result{cli.open_stream("DELETE", path, params, {}, body, content_type),
  3019. chunk_size};
  3020. }
  3021. template <typename ClientType>
  3022. inline Result Delete(ClientType &cli, const std::string &path,
  3023. const Params &params, const Headers &headers,
  3024. const std::string &body, const std::string &content_type,
  3025. size_t chunk_size = 8192) {
  3026. return Result{
  3027. cli.open_stream("DELETE", path, params, headers, body, content_type),
  3028. chunk_size};
  3029. }
  3030. // HEAD
  3031. template <typename ClientType>
  3032. inline Result Head(ClientType &cli, const std::string &path,
  3033. size_t chunk_size = 8192) {
  3034. return Result{cli.open_stream("HEAD", path), chunk_size};
  3035. }
  3036. template <typename ClientType>
  3037. inline Result Head(ClientType &cli, const std::string &path,
  3038. const Headers &headers, size_t chunk_size = 8192) {
  3039. return Result{cli.open_stream("HEAD", path, {}, headers), chunk_size};
  3040. }
  3041. template <typename ClientType>
  3042. inline Result Head(ClientType &cli, const std::string &path,
  3043. const Params &params, size_t chunk_size = 8192) {
  3044. return Result{cli.open_stream("HEAD", path, params), chunk_size};
  3045. }
  3046. template <typename ClientType>
  3047. inline Result Head(ClientType &cli, const std::string &path,
  3048. const Params &params, const Headers &headers,
  3049. size_t chunk_size = 8192) {
  3050. return Result{cli.open_stream("HEAD", path, params, headers), chunk_size};
  3051. }
  3052. // OPTIONS
  3053. template <typename ClientType>
  3054. inline Result Options(ClientType &cli, const std::string &path,
  3055. size_t chunk_size = 8192) {
  3056. return Result{cli.open_stream("OPTIONS", path), chunk_size};
  3057. }
  3058. template <typename ClientType>
  3059. inline Result Options(ClientType &cli, const std::string &path,
  3060. const Headers &headers, size_t chunk_size = 8192) {
  3061. return Result{cli.open_stream("OPTIONS", path, {}, headers), chunk_size};
  3062. }
  3063. template <typename ClientType>
  3064. inline Result Options(ClientType &cli, const std::string &path,
  3065. const Params &params, size_t chunk_size = 8192) {
  3066. return Result{cli.open_stream("OPTIONS", path, params), chunk_size};
  3067. }
  3068. template <typename ClientType>
  3069. inline Result Options(ClientType &cli, const std::string &path,
  3070. const Params &params, const Headers &headers,
  3071. size_t chunk_size = 8192) {
  3072. return Result{cli.open_stream("OPTIONS", path, params, headers), chunk_size};
  3073. }
  3074. } // namespace stream
  3075. namespace sse {
  3076. struct SSEMessage {
  3077. std::string event; // Event type (default: "message")
  3078. std::string data; // Event payload
  3079. std::string id; // Event ID for Last-Event-ID header
  3080. SSEMessage();
  3081. void clear();
  3082. };
  3083. class SSEClient {
  3084. public:
  3085. using MessageHandler = std::function<void(const SSEMessage &)>;
  3086. using ErrorHandler = std::function<void(Error)>;
  3087. using OpenHandler = std::function<void()>;
  3088. SSEClient(Client &client, const std::string &path);
  3089. SSEClient(Client &client, const std::string &path, const Headers &headers);
  3090. ~SSEClient();
  3091. SSEClient(const SSEClient &) = delete;
  3092. SSEClient &operator=(const SSEClient &) = delete;
  3093. // Event handlers
  3094. SSEClient &on_message(MessageHandler handler);
  3095. SSEClient &on_event(const std::string &type, MessageHandler handler);
  3096. SSEClient &on_open(OpenHandler handler);
  3097. SSEClient &on_error(ErrorHandler handler);
  3098. SSEClient &set_reconnect_interval(int ms);
  3099. SSEClient &set_max_reconnect_attempts(int n);
  3100. // Update headers (thread-safe)
  3101. SSEClient &set_headers(const Headers &headers);
  3102. // State accessors
  3103. bool is_connected() const;
  3104. const std::string &last_event_id() const;
  3105. // Blocking start - runs event loop with auto-reconnect
  3106. void start();
  3107. // Non-blocking start - runs in background thread
  3108. void start_async();
  3109. // Stop the client (thread-safe)
  3110. void stop();
  3111. private:
  3112. bool parse_sse_line(const std::string &line, SSEMessage &msg, int &retry_ms);
  3113. void run_event_loop();
  3114. void dispatch_event(const SSEMessage &msg);
  3115. bool should_reconnect(int count) const;
  3116. void wait_for_reconnect();
  3117. // Client and path
  3118. Client &client_;
  3119. std::string path_;
  3120. Headers headers_;
  3121. mutable std::mutex headers_mutex_;
  3122. // Callbacks
  3123. MessageHandler on_message_;
  3124. std::map<std::string, MessageHandler> event_handlers_;
  3125. OpenHandler on_open_;
  3126. ErrorHandler on_error_;
  3127. // Configuration
  3128. int reconnect_interval_ms_ = 3000;
  3129. int max_reconnect_attempts_ = 0; // 0 = unlimited
  3130. // State
  3131. std::atomic<bool> running_{false};
  3132. std::atomic<bool> connected_{false};
  3133. std::string last_event_id_;
  3134. // Async support
  3135. std::thread async_thread_;
  3136. };
  3137. } // namespace sse
  3138. namespace ws {
  3139. enum class Opcode : uint8_t {
  3140. Continuation = 0x0,
  3141. Text = 0x1,
  3142. Binary = 0x2,
  3143. Close = 0x8,
  3144. Ping = 0x9,
  3145. Pong = 0xA,
  3146. };
  3147. enum class CloseStatus : uint16_t {
  3148. Normal = 1000,
  3149. GoingAway = 1001,
  3150. ProtocolError = 1002,
  3151. UnsupportedData = 1003,
  3152. NoStatus = 1005,
  3153. Abnormal = 1006,
  3154. InvalidPayload = 1007,
  3155. PolicyViolation = 1008,
  3156. MessageTooBig = 1009,
  3157. MandatoryExtension = 1010,
  3158. InternalError = 1011,
  3159. };
  3160. enum ReadResult : int { Fail = 0, Text = 1, Binary = 2 };
  3161. class WebSocket {
  3162. public:
  3163. WebSocket(const WebSocket &) = delete;
  3164. WebSocket &operator=(const WebSocket &) = delete;
  3165. ~WebSocket();
  3166. ReadResult read(std::string &msg);
  3167. bool send(const std::string &data);
  3168. bool send(const char *data, size_t len);
  3169. void close(CloseStatus status = CloseStatus::Normal,
  3170. const std::string &reason = "");
  3171. const Request &request() const;
  3172. bool is_open() const;
  3173. private:
  3174. friend class httplib::Server;
  3175. friend class WebSocketClient;
  3176. WebSocket(
  3177. Stream &strm, const Request &req, bool is_server,
  3178. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3179. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3180. : strm_(strm), req_(req), is_server_(is_server),
  3181. ping_interval_sec_(ping_interval_sec),
  3182. max_missed_pongs_(max_missed_pongs) {
  3183. start_heartbeat();
  3184. }
  3185. WebSocket(
  3186. std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
  3187. time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
  3188. int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
  3189. : strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
  3190. is_server_(is_server), ping_interval_sec_(ping_interval_sec),
  3191. max_missed_pongs_(max_missed_pongs) {
  3192. start_heartbeat();
  3193. }
  3194. void start_heartbeat();
  3195. bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
  3196. Stream &strm_;
  3197. std::unique_ptr<Stream> owned_strm_;
  3198. Request req_;
  3199. bool is_server_;
  3200. time_t ping_interval_sec_;
  3201. int max_missed_pongs_;
  3202. int unacked_pings_ = 0;
  3203. std::atomic<bool> closed_{false};
  3204. std::mutex write_mutex_;
  3205. std::thread ping_thread_;
  3206. std::mutex ping_mutex_;
  3207. std::condition_variable ping_cv_;
  3208. };
  3209. class WebSocketClient {
  3210. public:
  3211. explicit WebSocketClient(const std::string &scheme_host_port_path,
  3212. const Headers &headers = {});
  3213. ~WebSocketClient();
  3214. WebSocketClient(const WebSocketClient &) = delete;
  3215. WebSocketClient &operator=(const WebSocketClient &) = delete;
  3216. bool is_valid() const;
  3217. bool connect();
  3218. ReadResult read(std::string &msg);
  3219. bool send(const std::string &data);
  3220. bool send(const char *data, size_t len);
  3221. void close(CloseStatus status = CloseStatus::Normal,
  3222. const std::string &reason = "");
  3223. bool is_open() const;
  3224. const std::string &subprotocol() const;
  3225. void set_read_timeout(time_t sec, time_t usec = 0);
  3226. void set_write_timeout(time_t sec, time_t usec = 0);
  3227. void set_websocket_ping_interval(time_t sec);
  3228. void set_websocket_max_missed_pongs(int count);
  3229. void set_tcp_nodelay(bool on);
  3230. void set_address_family(int family);
  3231. void set_ipv6_v6only(bool on);
  3232. void set_socket_options(SocketOptions socket_options);
  3233. void set_connection_timeout(time_t sec, time_t usec = 0);
  3234. void set_interface(const std::string &intf);
  3235. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  3236. #ifdef CPPHTTPLIB_SSL_ENABLED
  3237. void set_ca_cert_path(const std::string &path);
  3238. void set_ca_cert_store(tls::ca_store_t store);
  3239. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  3240. void enable_server_certificate_verification(bool enabled);
  3241. void enable_system_ca(bool enabled);
  3242. #endif
  3243. private:
  3244. void shutdown_and_close();
  3245. bool create_stream(std::unique_ptr<Stream> &strm);
  3246. std::string host_;
  3247. int port_;
  3248. std::string path_;
  3249. Headers headers_;
  3250. std::string subprotocol_;
  3251. bool is_valid_ = false;
  3252. socket_t sock_ = INVALID_SOCKET;
  3253. std::unique_ptr<WebSocket> ws_;
  3254. time_t read_timeout_sec_ = CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND;
  3255. time_t read_timeout_usec_ = 0;
  3256. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  3257. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  3258. time_t websocket_ping_interval_sec_ =
  3259. CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND;
  3260. int websocket_max_missed_pongs_ = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS;
  3261. int address_family_ = AF_UNSPEC;
  3262. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  3263. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  3264. SocketOptions socket_options_ = nullptr;
  3265. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  3266. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  3267. std::string interface_;
  3268. // Hostname-IP map
  3269. std::map<std::string, std::string> addr_map_;
  3270. #ifdef CPPHTTPLIB_SSL_ENABLED
  3271. bool is_ssl_ = false;
  3272. tls::ctx_t tls_ctx_ = nullptr;
  3273. tls::session_t tls_session_ = nullptr;
  3274. std::string ca_cert_file_path_;
  3275. bool custom_ca_loaded_ = false;
  3276. bool certs_loaded_ = false;
  3277. SystemCAMode system_ca_mode_ = SystemCAMode::Auto;
  3278. bool server_certificate_verification_ = true;
  3279. #endif
  3280. };
  3281. namespace impl {
  3282. bool is_valid_utf8(const std::string &s);
  3283. bool read_websocket_frame(Stream &strm, Opcode &opcode, std::string &payload,
  3284. bool &fin, bool expect_masked, size_t max_len);
  3285. } // namespace impl
  3286. } // namespace ws
  3287. // ----------------------------------------------------------------------------
  3288. /*
  3289. * Implementation that will be part of the .cc file if split into .h + .cc.
  3290. */
  3291. namespace stream {
  3292. // stream::Result implementations
  3293. inline Result::Result() : chunk_size_(8192) {}
  3294. inline Result::Result(ClientImpl::StreamHandle &&handle, size_t chunk_size)
  3295. : handle_(std::move(handle)), chunk_size_(chunk_size) {}
  3296. inline Result::Result(Result &&other) noexcept
  3297. : handle_(std::move(other.handle_)), buffer_(std::move(other.buffer_)),
  3298. current_size_(other.current_size_), chunk_size_(other.chunk_size_),
  3299. finished_(other.finished_) {
  3300. other.current_size_ = 0;
  3301. other.finished_ = true;
  3302. }
  3303. inline Result &Result::operator=(Result &&other) noexcept {
  3304. if (this != &other) {
  3305. handle_ = std::move(other.handle_);
  3306. buffer_ = std::move(other.buffer_);
  3307. current_size_ = other.current_size_;
  3308. chunk_size_ = other.chunk_size_;
  3309. finished_ = other.finished_;
  3310. other.current_size_ = 0;
  3311. other.finished_ = true;
  3312. }
  3313. return *this;
  3314. }
  3315. inline bool Result::is_valid() const { return handle_.is_valid(); }
  3316. inline Result::operator bool() const { return is_valid(); }
  3317. inline int Result::status() const {
  3318. return handle_.response ? handle_.response->status : -1;
  3319. }
  3320. inline const Headers &Result::headers() const {
  3321. static const Headers empty_headers;
  3322. return handle_.response ? handle_.response->headers : empty_headers;
  3323. }
  3324. inline std::string Result::get_header_value(const std::string &key,
  3325. const char *def) const {
  3326. return handle_.response ? handle_.response->get_header_value(key, def) : def;
  3327. }
  3328. inline bool Result::has_header(const std::string &key) const {
  3329. return handle_.response ? handle_.response->has_header(key) : false;
  3330. }
  3331. inline Error Result::error() const { return handle_.error; }
  3332. inline Error Result::read_error() const { return handle_.get_read_error(); }
  3333. inline bool Result::has_read_error() const { return handle_.has_read_error(); }
  3334. inline bool Result::next() {
  3335. if (!handle_.is_valid() || finished_) { return false; }
  3336. if (buffer_.size() < chunk_size_) { buffer_.resize(chunk_size_); }
  3337. ssize_t n = handle_.read(&buffer_[0], chunk_size_);
  3338. if (n > 0) {
  3339. current_size_ = static_cast<size_t>(n);
  3340. return true;
  3341. }
  3342. current_size_ = 0;
  3343. finished_ = true;
  3344. return false;
  3345. }
  3346. inline const char *Result::data() const { return buffer_.data(); }
  3347. inline size_t Result::size() const { return current_size_; }
  3348. inline std::string Result::read_all() {
  3349. std::string result;
  3350. while (next()) {
  3351. result.append(data(), size());
  3352. }
  3353. return result;
  3354. }
  3355. } // namespace stream
  3356. namespace sse {
  3357. // SSEMessage implementations
  3358. inline SSEMessage::SSEMessage() : event("message") {}
  3359. inline void SSEMessage::clear() {
  3360. event = "message";
  3361. data.clear();
  3362. id.clear();
  3363. }
  3364. // SSEClient implementations
  3365. inline SSEClient::SSEClient(Client &client, const std::string &path)
  3366. : client_(client), path_(path) {}
  3367. inline SSEClient::SSEClient(Client &client, const std::string &path,
  3368. const Headers &headers)
  3369. : client_(client), path_(path), headers_(headers) {}
  3370. inline SSEClient::~SSEClient() { stop(); }
  3371. inline SSEClient &SSEClient::on_message(MessageHandler handler) {
  3372. on_message_ = std::move(handler);
  3373. return *this;
  3374. }
  3375. inline SSEClient &SSEClient::on_event(const std::string &type,
  3376. MessageHandler handler) {
  3377. event_handlers_[type] = std::move(handler);
  3378. return *this;
  3379. }
  3380. inline SSEClient &SSEClient::on_open(OpenHandler handler) {
  3381. on_open_ = std::move(handler);
  3382. return *this;
  3383. }
  3384. inline SSEClient &SSEClient::on_error(ErrorHandler handler) {
  3385. on_error_ = std::move(handler);
  3386. return *this;
  3387. }
  3388. inline SSEClient &SSEClient::set_reconnect_interval(int ms) {
  3389. reconnect_interval_ms_ = ms;
  3390. return *this;
  3391. }
  3392. inline SSEClient &SSEClient::set_max_reconnect_attempts(int n) {
  3393. max_reconnect_attempts_ = n;
  3394. return *this;
  3395. }
  3396. inline SSEClient &SSEClient::set_headers(const Headers &headers) {
  3397. std::lock_guard<std::mutex> lock(headers_mutex_);
  3398. headers_ = headers;
  3399. return *this;
  3400. }
  3401. inline bool SSEClient::is_connected() const { return connected_.load(); }
  3402. inline const std::string &SSEClient::last_event_id() const {
  3403. return last_event_id_;
  3404. }
  3405. inline void SSEClient::start() {
  3406. running_.store(true);
  3407. run_event_loop();
  3408. }
  3409. inline void SSEClient::start_async() {
  3410. running_.store(true);
  3411. async_thread_ = std::thread([this]() { run_event_loop(); });
  3412. }
  3413. inline void SSEClient::stop() {
  3414. running_.store(false);
  3415. client_.stop(); // Cancel any pending operations
  3416. if (async_thread_.joinable()) { async_thread_.join(); }
  3417. }
  3418. inline bool SSEClient::parse_sse_line(const std::string &line, SSEMessage &msg,
  3419. int &retry_ms) {
  3420. // Blank line signals end of event
  3421. if (line.empty() || line == "\r") { return true; }
  3422. // Lines starting with ':' are comments (ignored)
  3423. if (!line.empty() && line[0] == ':') { return false; }
  3424. // Find the colon separator
  3425. auto colon_pos = line.find(':');
  3426. if (colon_pos == std::string::npos) {
  3427. // Line with no colon is treated as field name with empty value
  3428. return false;
  3429. }
  3430. auto field = line.substr(0, colon_pos);
  3431. std::string value;
  3432. // Value starts after colon, skip optional single space
  3433. if (colon_pos + 1 < line.size()) {
  3434. auto value_start = colon_pos + 1;
  3435. if (line[value_start] == ' ') { value_start++; }
  3436. value = line.substr(value_start);
  3437. // Remove trailing \r if present
  3438. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  3439. }
  3440. // Handle known fields
  3441. if (field == "event") {
  3442. msg.event = value;
  3443. } else if (field == "data") {
  3444. // Multiple data lines are concatenated with newlines
  3445. if (!msg.data.empty()) { msg.data += "\n"; }
  3446. msg.data += value;
  3447. } else if (field == "id") {
  3448. // Empty id is valid (clears the last event ID)
  3449. msg.id = value;
  3450. } else if (field == "retry") {
  3451. // Parse retry interval in milliseconds
  3452. {
  3453. int v = 0;
  3454. auto res =
  3455. detail::from_chars(value.data(), value.data() + value.size(), v);
  3456. if (res.ec == std::errc{}) { retry_ms = v; }
  3457. }
  3458. }
  3459. // Unknown fields are ignored per SSE spec
  3460. return false;
  3461. }
  3462. inline void SSEClient::run_event_loop() {
  3463. auto reconnect_count = 0;
  3464. while (running_.load()) {
  3465. // Build headers, including Last-Event-ID if we have one
  3466. Headers request_headers;
  3467. {
  3468. std::lock_guard<std::mutex> lock(headers_mutex_);
  3469. request_headers = headers_;
  3470. }
  3471. if (!last_event_id_.empty()) {
  3472. request_headers.emplace("Last-Event-ID", last_event_id_);
  3473. }
  3474. // Open streaming connection
  3475. auto result = stream::Get(client_, path_, request_headers);
  3476. // Connection error handling
  3477. if (!result) {
  3478. connected_.store(false);
  3479. if (on_error_) { on_error_(result.error()); }
  3480. if (!should_reconnect(reconnect_count)) { break; }
  3481. wait_for_reconnect();
  3482. reconnect_count++;
  3483. continue;
  3484. }
  3485. if (result.status() != StatusCode::OK_200) {
  3486. connected_.store(false);
  3487. if (on_error_) { on_error_(Error::Connection); }
  3488. // For certain errors, don't reconnect.
  3489. // Note: 401 is intentionally absent so that handlers can refresh
  3490. // credentials via set_headers() and let the client reconnect.
  3491. if (result.status() == StatusCode::NoContent_204 ||
  3492. result.status() == StatusCode::NotFound_404 ||
  3493. result.status() == StatusCode::Forbidden_403) {
  3494. break;
  3495. }
  3496. if (!should_reconnect(reconnect_count)) { break; }
  3497. wait_for_reconnect();
  3498. reconnect_count++;
  3499. continue;
  3500. }
  3501. // Connection successful
  3502. connected_.store(true);
  3503. reconnect_count = 0;
  3504. if (on_open_) { on_open_(); }
  3505. // Event receiving loop
  3506. std::string buffer;
  3507. SSEMessage current_msg;
  3508. while (running_.load() && result.next()) {
  3509. buffer.append(result.data(), result.size());
  3510. // Process complete lines in the buffer
  3511. size_t line_start = 0;
  3512. size_t newline_pos;
  3513. while ((newline_pos = buffer.find('\n', line_start)) !=
  3514. std::string::npos) {
  3515. auto line = buffer.substr(line_start, newline_pos - line_start);
  3516. line_start = newline_pos + 1;
  3517. // Parse the line and check if event is complete
  3518. auto event_complete =
  3519. parse_sse_line(line, current_msg, reconnect_interval_ms_);
  3520. if (event_complete && !current_msg.data.empty()) {
  3521. // Update last_event_id for reconnection
  3522. if (!current_msg.id.empty()) { last_event_id_ = current_msg.id; }
  3523. // Dispatch event to appropriate handler
  3524. dispatch_event(current_msg);
  3525. current_msg.clear();
  3526. }
  3527. }
  3528. // Keep unprocessed data in buffer
  3529. buffer.erase(0, line_start);
  3530. }
  3531. // Connection ended
  3532. connected_.store(false);
  3533. if (!running_.load()) { break; }
  3534. // Check for read errors
  3535. if (result.has_read_error()) {
  3536. if (on_error_) { on_error_(result.read_error()); }
  3537. }
  3538. if (!should_reconnect(reconnect_count)) { break; }
  3539. wait_for_reconnect();
  3540. reconnect_count++;
  3541. }
  3542. connected_.store(false);
  3543. }
  3544. inline void SSEClient::dispatch_event(const SSEMessage &msg) {
  3545. // Check for specific event type handler first
  3546. auto it = event_handlers_.find(msg.event);
  3547. if (it != event_handlers_.end()) {
  3548. it->second(msg);
  3549. return;
  3550. }
  3551. // Fall back to generic message handler
  3552. if (on_message_) { on_message_(msg); }
  3553. }
  3554. inline bool SSEClient::should_reconnect(int count) const {
  3555. if (!running_.load()) { return false; }
  3556. if (max_reconnect_attempts_ == 0) { return true; } // unlimited
  3557. return count < max_reconnect_attempts_;
  3558. }
  3559. inline void SSEClient::wait_for_reconnect() {
  3560. // Use small increments to check running_ flag frequently
  3561. auto waited = 0;
  3562. while (running_.load() && waited < reconnect_interval_ms_) {
  3563. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3564. waited += 100;
  3565. }
  3566. }
  3567. } // namespace sse
  3568. #ifdef CPPHTTPLIB_SSL_ENABLED
  3569. /*
  3570. * TLS abstraction layer - internal function declarations
  3571. * These are implementation details and not part of the public API.
  3572. */
  3573. namespace tls {
  3574. // Client context
  3575. ctx_t create_client_context();
  3576. void free_context(ctx_t ctx);
  3577. bool set_min_version(ctx_t ctx, Version version);
  3578. bool load_ca_pem(ctx_t ctx, const char *pem, size_t len);
  3579. bool load_ca_file(ctx_t ctx, const char *file_path);
  3580. bool load_ca_dir(ctx_t ctx, const char *dir_path);
  3581. bool load_system_certs(ctx_t ctx);
  3582. bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3583. const char *password);
  3584. bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  3585. const char *key_path, const char *password);
  3586. // Server context
  3587. ctx_t create_server_context();
  3588. bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  3589. const char *password);
  3590. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  3591. const char *key_path, const char *password);
  3592. bool set_client_ca_file(ctx_t ctx, const char *ca_file, const char *ca_dir);
  3593. void set_verify_client(ctx_t ctx, bool require);
  3594. // Session management
  3595. session_t create_session(ctx_t ctx, socket_t sock);
  3596. void free_session(session_t session);
  3597. bool set_sni(session_t session, const char *hostname);
  3598. bool set_hostname(session_t session, const char *hostname);
  3599. // Handshake (non-blocking capable)
  3600. TlsError connect(session_t session);
  3601. TlsError accept(session_t session);
  3602. // Handshake with timeout (blocking until timeout)
  3603. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3604. time_t timeout_usec, TlsError *err);
  3605. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  3606. time_t timeout_usec, TlsError *err);
  3607. // I/O (non-blocking capable)
  3608. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  3609. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  3610. int pending(const_session_t session);
  3611. void shutdown(session_t session, bool graceful);
  3612. // Connection state
  3613. bool is_peer_closed(session_t session, socket_t sock);
  3614. // Certificate verification
  3615. cert_t get_peer_cert(const_session_t session);
  3616. void free_cert(cert_t cert);
  3617. bool verify_hostname(cert_t cert, const char *hostname);
  3618. uint64_t hostname_mismatch_code();
  3619. long get_verify_result(const_session_t session);
  3620. // Certificate introspection
  3621. std::string get_cert_subject_cn(cert_t cert);
  3622. std::string get_cert_issuer_name(cert_t cert);
  3623. bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans);
  3624. bool get_cert_validity(cert_t cert, time_t &not_before, time_t &not_after);
  3625. std::string get_cert_serial(cert_t cert);
  3626. bool get_cert_der(cert_t cert, std::vector<unsigned char> &der);
  3627. const char *get_sni(const_session_t session);
  3628. // CA store management
  3629. ca_store_t create_ca_store(const char *pem, size_t len);
  3630. void free_ca_store(ca_store_t store);
  3631. bool set_ca_store(ctx_t ctx, ca_store_t store);
  3632. size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs);
  3633. std::vector<std::string> get_ca_names(ctx_t ctx);
  3634. // Dynamic certificate update (for servers)
  3635. bool update_server_cert(ctx_t ctx, const char *cert_pem, const char *key_pem,
  3636. const char *password);
  3637. bool update_server_client_ca(ctx_t ctx, const char *ca_pem);
  3638. // Certificate verification callback
  3639. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  3640. long get_verify_error(const_session_t session);
  3641. std::string verify_error_string(long error_code);
  3642. // TlsError information
  3643. uint64_t peek_error();
  3644. uint64_t get_error();
  3645. std::string error_string(uint64_t code);
  3646. } // namespace tls
  3647. #endif // CPPHTTPLIB_SSL_ENABLED
  3648. /*
  3649. * Group 1: detail namespace - Non-SSL utilities
  3650. */
  3651. namespace detail {
  3652. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  3653. const void *optval, socklen_t optlen) {
  3654. return setsockopt(sock, level, optname,
  3655. #ifdef _WIN32
  3656. reinterpret_cast<const char *>(optval),
  3657. #else
  3658. optval,
  3659. #endif
  3660. optlen) == 0;
  3661. }
  3662. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  3663. time_t sec, time_t usec) {
  3664. #ifdef _WIN32
  3665. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  3666. #else
  3667. timeval timeout;
  3668. timeout.tv_sec = static_cast<long>(sec);
  3669. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  3670. #endif
  3671. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  3672. }
  3673. inline bool is_hex(char c, int &v) {
  3674. if (is_ascii_digit(c)) {
  3675. v = c - '0';
  3676. return true;
  3677. } else if ('A' <= c && c <= 'F') {
  3678. v = c - 'A' + 10;
  3679. return true;
  3680. } else if ('a' <= c && c <= 'f') {
  3681. v = c - 'a' + 10;
  3682. return true;
  3683. }
  3684. return false;
  3685. }
  3686. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  3687. int &val) {
  3688. if (i >= s.size()) { return false; }
  3689. val = 0;
  3690. for (; cnt; i++, cnt--) {
  3691. if (!s[i]) { return false; }
  3692. auto v = 0;
  3693. if (is_hex(s[i], v)) {
  3694. val = val * 16 + v;
  3695. } else {
  3696. return false;
  3697. }
  3698. }
  3699. return true;
  3700. }
  3701. inline std::string from_i_to_hex(size_t n) {
  3702. static const auto charset = "0123456789abcdef";
  3703. std::string ret;
  3704. do {
  3705. ret = charset[n & 15] + ret;
  3706. n >>= 4;
  3707. } while (n > 0);
  3708. return ret;
  3709. }
  3710. inline std::string compute_etag(const FileStat &fs) {
  3711. if (!fs.is_file()) { return std::string(); }
  3712. // If mtime cannot be determined (negative value indicates an error
  3713. // or sentinel), do not generate an ETag. Returning a neutral / fixed
  3714. // value like 0 could collide with a real file that legitimately has
  3715. // mtime == 0 (epoch) and lead to misleading validators.
  3716. auto mtime_raw = fs.mtime();
  3717. if (mtime_raw < 0) { return std::string(); }
  3718. auto mtime = static_cast<size_t>(mtime_raw);
  3719. auto size = fs.size();
  3720. return std::string("W/\"") + from_i_to_hex(mtime) + "-" +
  3721. from_i_to_hex(size) + "\"";
  3722. }
  3723. // Format time_t as HTTP-date (RFC 9110 Section 5.6.7): "Sun, 06 Nov 1994
  3724. // 08:49:37 GMT" This implementation is defensive: it validates `mtime`, checks
  3725. // return values from `gmtime_r`/`gmtime_s`, and ensures `strftime` succeeds.
  3726. inline std::string file_mtime_to_http_date(time_t mtime) {
  3727. if (mtime < 0) { return std::string(); }
  3728. struct tm tm_buf;
  3729. #ifdef _WIN32
  3730. if (gmtime_s(&tm_buf, &mtime) != 0) { return std::string(); }
  3731. #else
  3732. if (gmtime_r(&mtime, &tm_buf) == nullptr) { return std::string(); }
  3733. #endif
  3734. char buf[64];
  3735. if (strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S GMT", &tm_buf) == 0) {
  3736. return std::string();
  3737. }
  3738. return std::string(buf);
  3739. }
  3740. // Parse HTTP-date (RFC 9110 Section 5.6.7) to time_t. Returns -1 on failure.
  3741. inline time_t parse_http_date(const std::string &date_str) {
  3742. struct tm tm_buf;
  3743. // Create a classic locale object once for all parsing attempts
  3744. const std::locale classic_locale = std::locale::classic();
  3745. // Try to parse using std::get_time (C++11, cross-platform)
  3746. auto try_parse = [&](const char *fmt) -> bool {
  3747. std::istringstream ss(date_str);
  3748. ss.imbue(classic_locale);
  3749. memset(&tm_buf, 0, sizeof(tm_buf));
  3750. ss >> std::get_time(&tm_buf, fmt);
  3751. return !ss.fail();
  3752. };
  3753. // RFC 9110 preferred format (HTTP-date): "Sun, 06 Nov 1994 08:49:37 GMT"
  3754. if (!try_parse("%a, %d %b %Y %H:%M:%S")) {
  3755. // RFC 850 format: "Sunday, 06-Nov-94 08:49:37 GMT"
  3756. if (!try_parse("%A, %d-%b-%y %H:%M:%S")) {
  3757. // asctime format: "Sun Nov 6 08:49:37 1994"
  3758. if (!try_parse("%a %b %d %H:%M:%S %Y")) {
  3759. return static_cast<time_t>(-1);
  3760. }
  3761. }
  3762. }
  3763. #ifdef _WIN32
  3764. return _mkgmtime(&tm_buf);
  3765. #elif defined _AIX
  3766. return mktime(&tm_buf);
  3767. #else
  3768. return timegm(&tm_buf);
  3769. #endif
  3770. }
  3771. inline bool is_weak_etag(const std::string &s) {
  3772. // Check if the string is a weak ETag (starts with 'W/"')
  3773. return s.size() > 3 && s[0] == 'W' && s[1] == '/' && s[2] == '"';
  3774. }
  3775. inline bool is_strong_etag(const std::string &s) {
  3776. // Check if the string is a strong ETag (starts and ends with '"', at least 2
  3777. // chars)
  3778. return s.size() >= 2 && s[0] == '"' && s.back() == '"';
  3779. }
  3780. inline size_t to_utf8(int code, char *buff) {
  3781. if (code < 0x0080) {
  3782. buff[0] = static_cast<char>(code & 0x7F);
  3783. return 1;
  3784. } else if (code < 0x0800) {
  3785. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  3786. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  3787. return 2;
  3788. } else if (code < 0xD800) {
  3789. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3790. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3791. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3792. return 3;
  3793. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  3794. return 0;
  3795. } else if (code < 0x10000) {
  3796. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  3797. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3798. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  3799. return 3;
  3800. } else if (code < 0x110000) {
  3801. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  3802. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  3803. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  3804. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  3805. return 4;
  3806. }
  3807. // NOTREACHED
  3808. return 0;
  3809. }
  3810. } // namespace detail
  3811. namespace ws {
  3812. namespace impl {
  3813. inline bool is_valid_utf8(const std::string &s) {
  3814. size_t i = 0;
  3815. auto n = s.size();
  3816. while (i < n) {
  3817. auto c = static_cast<unsigned char>(s[i]);
  3818. size_t len;
  3819. uint32_t cp;
  3820. if (c < 0x80) {
  3821. i++;
  3822. continue;
  3823. } else if ((c & 0xE0) == 0xC0) {
  3824. len = 2;
  3825. cp = c & 0x1F;
  3826. } else if ((c & 0xF0) == 0xE0) {
  3827. len = 3;
  3828. cp = c & 0x0F;
  3829. } else if ((c & 0xF8) == 0xF0) {
  3830. len = 4;
  3831. cp = c & 0x07;
  3832. } else {
  3833. return false;
  3834. }
  3835. if (i + len > n) { return false; }
  3836. for (size_t j = 1; j < len; j++) {
  3837. auto b = static_cast<unsigned char>(s[i + j]);
  3838. if ((b & 0xC0) != 0x80) { return false; }
  3839. cp = (cp << 6) | (b & 0x3F);
  3840. }
  3841. // Overlong encoding check
  3842. if (len == 2 && cp < 0x80) { return false; }
  3843. if (len == 3 && cp < 0x800) { return false; }
  3844. if (len == 4 && cp < 0x10000) { return false; }
  3845. // Surrogate halves (U+D800..U+DFFF) and beyond U+10FFFF are invalid
  3846. if (cp >= 0xD800 && cp <= 0xDFFF) { return false; }
  3847. if (cp > 0x10FFFF) { return false; }
  3848. i += len;
  3849. }
  3850. return true;
  3851. }
  3852. } // namespace impl
  3853. } // namespace ws
  3854. namespace detail {
  3855. // NOTE: This code came up with the following stackoverflow post:
  3856. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  3857. inline std::string base64_encode(const std::string &in) {
  3858. static const auto lookup =
  3859. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3860. std::string out;
  3861. out.reserve(in.size());
  3862. // Unsigned: the accumulator is never masked, so with a signed int the
  3863. // `val << 8` below overflows once enough bytes are folded in (undefined
  3864. // behaviour before C++20). Only the low bits are ever emitted, so the
  3865. // wrap-around of an unsigned accumulator does not affect the output.
  3866. uint32_t val = 0;
  3867. auto valb = -6;
  3868. for (auto c : in) {
  3869. val = (val << 8) + static_cast<uint8_t>(c);
  3870. valb += 8;
  3871. while (valb >= 0) {
  3872. out.push_back(lookup[(val >> valb) & 0x3F]);
  3873. valb -= 6;
  3874. }
  3875. }
  3876. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  3877. while (out.size() % 4) {
  3878. out.push_back('=');
  3879. }
  3880. return out;
  3881. }
  3882. inline std::string sha1(const std::string &input) {
  3883. // RFC 3174 SHA-1 implementation
  3884. auto left_rotate = [](uint32_t x, uint32_t n) -> uint32_t {
  3885. return (x << n) | (x >> (32 - n));
  3886. };
  3887. uint32_t h0 = 0x67452301;
  3888. uint32_t h1 = 0xEFCDAB89;
  3889. uint32_t h2 = 0x98BADCFE;
  3890. uint32_t h3 = 0x10325476;
  3891. uint32_t h4 = 0xC3D2E1F0;
  3892. // Pre-processing: adding padding bits
  3893. std::string msg = input;
  3894. uint64_t original_bit_len = static_cast<uint64_t>(msg.size()) * 8;
  3895. msg.push_back(static_cast<char>(0x80u));
  3896. while (msg.size() % 64 != 56) {
  3897. msg.push_back(0);
  3898. }
  3899. // Append original length in bits as 64-bit big-endian
  3900. for (int i = 56; i >= 0; i -= 8) {
  3901. msg.push_back(static_cast<char>((original_bit_len >> i) & 0xFF));
  3902. }
  3903. // Process each 512-bit chunk
  3904. for (size_t offset = 0; offset < msg.size(); offset += 64) {
  3905. uint32_t w[80];
  3906. for (size_t i = 0; i < 16; i++) {
  3907. w[i] =
  3908. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4]))
  3909. << 24) |
  3910. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 1]))
  3911. << 16) |
  3912. (static_cast<uint32_t>(static_cast<uint8_t>(msg[offset + i * 4 + 2]))
  3913. << 8) |
  3914. (static_cast<uint32_t>(
  3915. static_cast<uint8_t>(msg[offset + i * 4 + 3])));
  3916. }
  3917. for (int i = 16; i < 80; i++) {
  3918. w[i] = left_rotate(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
  3919. }
  3920. uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
  3921. for (int i = 0; i < 80; i++) {
  3922. uint32_t f, k;
  3923. if (i < 20) {
  3924. f = (b & c) | ((~b) & d);
  3925. k = 0x5A827999;
  3926. } else if (i < 40) {
  3927. f = b ^ c ^ d;
  3928. k = 0x6ED9EBA1;
  3929. } else if (i < 60) {
  3930. f = (b & c) | (b & d) | (c & d);
  3931. k = 0x8F1BBCDC;
  3932. } else {
  3933. f = b ^ c ^ d;
  3934. k = 0xCA62C1D6;
  3935. }
  3936. uint32_t temp = left_rotate(a, 5) + f + e + k + w[i];
  3937. e = d;
  3938. d = c;
  3939. c = left_rotate(b, 30);
  3940. b = a;
  3941. a = temp;
  3942. }
  3943. h0 += a;
  3944. h1 += b;
  3945. h2 += c;
  3946. h3 += d;
  3947. h4 += e;
  3948. }
  3949. // Produce the final hash as a 20-byte binary string
  3950. std::string hash(20, '\0');
  3951. for (size_t i = 0; i < 4; i++) {
  3952. hash[i] = static_cast<char>((h0 >> (24 - i * 8)) & 0xFF);
  3953. hash[4 + i] = static_cast<char>((h1 >> (24 - i * 8)) & 0xFF);
  3954. hash[8 + i] = static_cast<char>((h2 >> (24 - i * 8)) & 0xFF);
  3955. hash[12 + i] = static_cast<char>((h3 >> (24 - i * 8)) & 0xFF);
  3956. hash[16 + i] = static_cast<char>((h4 >> (24 - i * 8)) & 0xFF);
  3957. }
  3958. return hash;
  3959. }
  3960. inline std::string websocket_accept_key(const std::string &client_key) {
  3961. const std::string magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3962. return base64_encode(sha1(client_key + magic));
  3963. }
  3964. inline bool is_websocket_upgrade(const Request &req) {
  3965. if (req.method != "GET") { return false; }
  3966. // Check Upgrade: websocket (case-insensitive)
  3967. auto upgrade_it = req.headers.find("Upgrade");
  3968. if (upgrade_it == req.headers.end()) { return false; }
  3969. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  3970. if (upgrade_val != "websocket") { return false; }
  3971. // Check Connection header contains "Upgrade"
  3972. auto connection_it = req.headers.find("Connection");
  3973. if (connection_it == req.headers.end()) { return false; }
  3974. auto connection_val = case_ignore::to_lower(connection_it->second);
  3975. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  3976. // Check Sec-WebSocket-Key is a valid base64-encoded 16-byte value (24 chars)
  3977. // RFC 6455 Section 4.2.1
  3978. auto ws_key = req.get_header_value("Sec-WebSocket-Key");
  3979. if (ws_key.size() != 24 || ws_key[22] != '=' || ws_key[23] != '=') {
  3980. return false;
  3981. }
  3982. static const std::string b64chars =
  3983. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3984. for (size_t i = 0; i < 22; i++) {
  3985. if (b64chars.find(ws_key[i]) == std::string::npos) { return false; }
  3986. }
  3987. // Check Sec-WebSocket-Version: 13
  3988. auto version = req.get_header_value("Sec-WebSocket-Version");
  3989. if (version != "13") { return false; }
  3990. return true;
  3991. }
  3992. inline bool write_websocket_frame(Stream &strm, ws::Opcode opcode,
  3993. const char *data, size_t len, bool fin,
  3994. bool mask) {
  3995. // First byte: FIN + opcode
  3996. uint8_t header[2];
  3997. header[0] = static_cast<uint8_t>((fin ? 0x80 : 0x00) |
  3998. (static_cast<uint8_t>(opcode) & 0x0F));
  3999. // Second byte: MASK + payload length
  4000. if (len < 126) {
  4001. header[1] = static_cast<uint8_t>(len);
  4002. if (mask) { header[1] |= 0x80; }
  4003. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4004. } else if (len <= 0xFFFF) {
  4005. header[1] = 126;
  4006. if (mask) { header[1] |= 0x80; }
  4007. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4008. uint8_t ext[2];
  4009. ext[0] = static_cast<uint8_t>((len >> 8) & 0xFF);
  4010. ext[1] = static_cast<uint8_t>(len & 0xFF);
  4011. if (strm.write(reinterpret_cast<char *>(ext), 2) < 0) { return false; }
  4012. } else {
  4013. header[1] = 127;
  4014. if (mask) { header[1] |= 0x80; }
  4015. if (strm.write(reinterpret_cast<char *>(header), 2) < 0) { return false; }
  4016. uint8_t ext[8];
  4017. for (int i = 7; i >= 0; i--) {
  4018. ext[7 - i] =
  4019. static_cast<uint8_t>((static_cast<uint64_t>(len) >> (i * 8)) & 0xFF);
  4020. }
  4021. if (strm.write(reinterpret_cast<char *>(ext), 8) < 0) { return false; }
  4022. }
  4023. if (mask) {
  4024. // Generate random mask key
  4025. thread_local std::mt19937 rng(std::random_device{}());
  4026. uint8_t mask_key[4];
  4027. auto r = rng();
  4028. std::memcpy(mask_key, &r, 4);
  4029. if (strm.write(reinterpret_cast<char *>(mask_key), 4) < 0) { return false; }
  4030. // Write masked payload in chunks
  4031. const size_t chunk_size = 4096;
  4032. std::vector<char> buf((std::min)(len, chunk_size));
  4033. for (size_t offset = 0; offset < len; offset += chunk_size) {
  4034. size_t n = (std::min)(chunk_size, len - offset);
  4035. for (size_t i = 0; i < n; i++) {
  4036. buf[i] =
  4037. data[offset + i] ^ static_cast<char>(mask_key[(offset + i) % 4]);
  4038. }
  4039. if (strm.write(buf.data(), n) < 0) { return false; }
  4040. }
  4041. } else {
  4042. if (len > 0) {
  4043. if (strm.write(data, len) < 0) { return false; }
  4044. }
  4045. }
  4046. return true;
  4047. }
  4048. } // namespace detail
  4049. namespace ws {
  4050. namespace impl {
  4051. inline bool read_websocket_frame(Stream &strm, Opcode &opcode,
  4052. std::string &payload, bool &fin,
  4053. bool expect_masked, size_t max_len) {
  4054. // Read first 2 bytes
  4055. uint8_t header[2];
  4056. if (strm.read(reinterpret_cast<char *>(header), 2) != 2) { return false; }
  4057. fin = (header[0] & 0x80) != 0;
  4058. // RSV1, RSV2, RSV3 must be 0 when no extension is negotiated
  4059. if (header[0] & 0x70) { return false; }
  4060. opcode = static_cast<Opcode>(header[0] & 0x0F);
  4061. bool masked = (header[1] & 0x80) != 0;
  4062. uint64_t payload_len = header[1] & 0x7F;
  4063. // RFC 6455 Section 5.5: control frames MUST NOT be fragmented and
  4064. // MUST have a payload length of 125 bytes or less
  4065. bool is_control = (static_cast<uint8_t>(opcode) & 0x08) != 0;
  4066. if (is_control) {
  4067. if (!fin) { return false; }
  4068. if (payload_len > 125) { return false; }
  4069. }
  4070. if (masked != expect_masked) { return false; }
  4071. // Extended payload length
  4072. if (payload_len == 126) {
  4073. uint8_t ext[2];
  4074. if (strm.read(reinterpret_cast<char *>(ext), 2) != 2) { return false; }
  4075. payload_len = (static_cast<uint64_t>(ext[0]) << 8) | ext[1];
  4076. } else if (payload_len == 127) {
  4077. uint8_t ext[8];
  4078. if (strm.read(reinterpret_cast<char *>(ext), 8) != 8) { return false; }
  4079. // RFC 6455 Section 5.2: the most significant bit MUST be 0
  4080. if (ext[0] & 0x80) { return false; }
  4081. payload_len = 0;
  4082. for (int i = 0; i < 8; i++) {
  4083. payload_len = (payload_len << 8) | ext[i];
  4084. }
  4085. }
  4086. if (payload_len > max_len) { return false; }
  4087. // Read mask key if present
  4088. uint8_t mask_key[4] = {0};
  4089. if (masked) {
  4090. if (strm.read(reinterpret_cast<char *>(mask_key), 4) != 4) { return false; }
  4091. }
  4092. // Read payload
  4093. payload.resize(static_cast<size_t>(payload_len));
  4094. if (payload_len > 0) {
  4095. size_t total_read = 0;
  4096. while (total_read < payload_len) {
  4097. auto n = strm.read(&payload[total_read],
  4098. static_cast<size_t>(payload_len - total_read));
  4099. if (n <= 0) { return false; }
  4100. total_read += static_cast<size_t>(n);
  4101. }
  4102. }
  4103. // Unmask if needed
  4104. if (masked) {
  4105. for (size_t i = 0; i < payload.size(); i++) {
  4106. payload[i] ^= static_cast<char>(mask_key[i % 4]);
  4107. }
  4108. }
  4109. return true;
  4110. }
  4111. } // namespace impl
  4112. } // namespace ws
  4113. namespace detail {
  4114. inline bool is_valid_path(const std::string &path) {
  4115. size_t level = 0;
  4116. size_t i = 0;
  4117. // Skip slash
  4118. while (i < path.size() && path[i] == '/') {
  4119. i++;
  4120. }
  4121. while (i < path.size()) {
  4122. // Read component
  4123. auto beg = i;
  4124. while (i < path.size() && path[i] != '/') {
  4125. if (path[i] == '\0') {
  4126. return false;
  4127. } else if (path[i] == '\\') {
  4128. return false;
  4129. }
  4130. i++;
  4131. }
  4132. auto len = i - beg;
  4133. assert(len > 0);
  4134. if (!path.compare(beg, len, ".")) {
  4135. ;
  4136. } else if (!path.compare(beg, len, "..")) {
  4137. if (level == 0) { return false; }
  4138. level--;
  4139. } else {
  4140. level++;
  4141. }
  4142. // Skip slash
  4143. while (i < path.size() && path[i] == '/') {
  4144. i++;
  4145. }
  4146. }
  4147. return true;
  4148. }
  4149. inline bool canonicalize_path(const char *path, std::string &resolved) {
  4150. #if defined(_WIN32)
  4151. char buf[_MAX_PATH];
  4152. if (_fullpath(buf, path, _MAX_PATH) == nullptr) { return false; }
  4153. resolved = buf;
  4154. #elif defined(PATH_MAX)
  4155. char buf[PATH_MAX];
  4156. if (realpath(path, buf) == nullptr) { return false; }
  4157. resolved = buf;
  4158. #else
  4159. auto buf = realpath(path, nullptr);
  4160. auto guard = scope_exit([&]() { std::free(buf); });
  4161. if (buf == nullptr) { return false; }
  4162. resolved = buf;
  4163. #endif
  4164. return true;
  4165. }
  4166. inline bool is_path_within_base(const std::string &resolved_path,
  4167. const std::string &resolved_base) {
  4168. #if defined(_WIN32)
  4169. return _strnicmp(resolved_path.c_str(), resolved_base.c_str(),
  4170. resolved_base.size()) == 0;
  4171. #else
  4172. return strncmp(resolved_path.c_str(), resolved_base.c_str(),
  4173. resolved_base.size()) == 0;
  4174. #endif
  4175. }
  4176. inline FileStat::FileStat(const std::string &path) {
  4177. #if defined(_WIN32)
  4178. auto wpath = u8string_to_wstring(path.c_str());
  4179. ret_ = _wstat(wpath.c_str(), &st_);
  4180. #else
  4181. ret_ = stat(path.c_str(), &st_);
  4182. #endif
  4183. }
  4184. inline bool FileStat::is_file() const {
  4185. return ret_ >= 0 && S_ISREG(st_.st_mode);
  4186. }
  4187. inline bool FileStat::is_dir() const {
  4188. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  4189. }
  4190. inline time_t FileStat::mtime() const {
  4191. return ret_ >= 0 ? static_cast<time_t>(st_.st_mtime)
  4192. : static_cast<time_t>(-1);
  4193. }
  4194. inline size_t FileStat::size() const {
  4195. return ret_ >= 0 ? static_cast<size_t>(st_.st_size) : 0;
  4196. }
  4197. inline std::string encode_path(const std::string &s) {
  4198. std::string result;
  4199. result.reserve(s.size());
  4200. for (size_t i = 0; s[i]; i++) {
  4201. switch (s[i]) {
  4202. case ' ': result += "%20"; break;
  4203. case '+': result += "%2B"; break;
  4204. case '\r': result += "%0D"; break;
  4205. case '\n': result += "%0A"; break;
  4206. case '\'': result += "%27"; break;
  4207. case ',': result += "%2C"; break;
  4208. // case ':': result += "%3A"; break; // ok? probably...
  4209. case ';': result += "%3B"; break;
  4210. default:
  4211. auto c = static_cast<uint8_t>(s[i]);
  4212. if (c >= 0x80) {
  4213. result += '%';
  4214. char hex[4];
  4215. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  4216. assert(len == 2);
  4217. result.append(hex, static_cast<size_t>(len));
  4218. } else {
  4219. result += s[i];
  4220. }
  4221. break;
  4222. }
  4223. }
  4224. return result;
  4225. }
  4226. inline std::string file_extension(const std::string &path) {
  4227. std::smatch m;
  4228. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  4229. if (std::regex_search(path, m, re)) { return m[1].str(); }
  4230. return std::string();
  4231. }
  4232. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  4233. template <typename T>
  4234. inline bool parse_header(const char *beg, const char *end, T fn);
  4235. template <typename T>
  4236. inline bool parse_header(const char *beg, const char *end, T fn) {
  4237. // Skip trailing spaces and tabs.
  4238. while (beg < end && is_space_or_tab(end[-1])) {
  4239. end--;
  4240. }
  4241. auto p = beg;
  4242. while (p < end && *p != ':') {
  4243. p++;
  4244. }
  4245. auto name = std::string(beg, p);
  4246. if (!detail::fields::is_field_name(name)) { return false; }
  4247. if (p == end) { return false; }
  4248. auto key_end = p;
  4249. if (*p++ != ':') { return false; }
  4250. while (p < end && is_space_or_tab(*p)) {
  4251. p++;
  4252. }
  4253. if (p <= end) {
  4254. auto key_len = key_end - beg;
  4255. if (!key_len) { return false; }
  4256. auto key = std::string(beg, key_end);
  4257. auto val = std::string(p, end);
  4258. if (!detail::fields::is_field_value(val)) { return false; }
  4259. // RFC 9110 §5.5: header field values are opaque octets and MUST NOT be
  4260. // percent-decoded by the recipient. Applications that need to interpret a
  4261. // value as a URI component should call httplib::decode_uri_component()
  4262. // (or decode_path_component()) explicitly.
  4263. fn(key, val);
  4264. return true;
  4265. }
  4266. return false;
  4267. }
  4268. inline bool parse_trailers(stream_line_reader &line_reader, Headers &dest,
  4269. const Headers &src_headers) {
  4270. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  4271. // transfer coding is complete when a chunk with a chunk-size of zero is
  4272. // received, possibly followed by a trailer section, and finally terminated by
  4273. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  4274. //
  4275. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  4276. // doesn't care for the existence of the final CRLF. In other words, it seems
  4277. // to be ok whether the final CRLF exists or not in the chunked data.
  4278. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  4279. //
  4280. // According to the reference code in RFC 9112, cpp-httplib now allows
  4281. // chunked transfer coding data without the final CRLF.
  4282. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  4283. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  4284. "transfer-encoding",
  4285. "content-length",
  4286. "host",
  4287. "authorization",
  4288. "www-authenticate",
  4289. "proxy-authenticate",
  4290. "proxy-authorization",
  4291. "cookie",
  4292. "set-cookie",
  4293. "cache-control",
  4294. "expect",
  4295. "max-forwards",
  4296. "pragma",
  4297. "range",
  4298. "te",
  4299. "age",
  4300. "expires",
  4301. "date",
  4302. "location",
  4303. "retry-after",
  4304. "vary",
  4305. "warning",
  4306. "content-encoding",
  4307. "content-type",
  4308. "content-range",
  4309. "trailer"};
  4310. case_ignore::unordered_set<std::string> declared_trailers;
  4311. auto trailer_header = get_header_value(src_headers, "Trailer", "", 0);
  4312. if (trailer_header && std::strlen(trailer_header)) {
  4313. auto len = std::strlen(trailer_header);
  4314. split(trailer_header, trailer_header + len, ',',
  4315. [&](const char *b, const char *e) {
  4316. const char *kbeg = b;
  4317. const char *kend = e;
  4318. while (kbeg < kend && (*kbeg == ' ' || *kbeg == '\t')) {
  4319. ++kbeg;
  4320. }
  4321. while (kend > kbeg && (kend[-1] == ' ' || kend[-1] == '\t')) {
  4322. --kend;
  4323. }
  4324. std::string key(kbeg, static_cast<size_t>(kend - kbeg));
  4325. if (!key.empty() &&
  4326. prohibited_trailers.find(key) == prohibited_trailers.end()) {
  4327. declared_trailers.insert(key);
  4328. }
  4329. });
  4330. }
  4331. size_t trailer_header_count = 0;
  4332. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  4333. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4334. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  4335. constexpr auto line_terminator_len = 2;
  4336. auto line_beg = line_reader.ptr();
  4337. auto line_end =
  4338. line_reader.ptr() + line_reader.size() - line_terminator_len;
  4339. if (!parse_header(line_beg, line_end,
  4340. [&](const std::string &key, const std::string &val) {
  4341. if (declared_trailers.find(key) !=
  4342. declared_trailers.end()) {
  4343. dest.emplace(key, val);
  4344. trailer_header_count++;
  4345. }
  4346. })) {
  4347. return false;
  4348. }
  4349. if (!line_reader.getline()) { return false; }
  4350. }
  4351. return true;
  4352. }
  4353. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  4354. size_t right) {
  4355. while (b + left < e && is_space_or_tab(b[left])) {
  4356. left++;
  4357. }
  4358. while (right > 0 && is_space_or_tab(b[right - 1])) {
  4359. right--;
  4360. }
  4361. return std::make_pair(left, right);
  4362. }
  4363. inline std::string trim_copy(const std::string &s) {
  4364. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  4365. return s.substr(r.first, r.second - r.first);
  4366. }
  4367. inline std::string trim_double_quotes_copy(const std::string &s) {
  4368. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  4369. return s.substr(1, s.size() - 2);
  4370. }
  4371. return s;
  4372. }
  4373. inline void
  4374. divide(const char *data, std::size_t size, char d,
  4375. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4376. fn) {
  4377. const auto it = std::find(data, data + size, d);
  4378. const auto found = static_cast<std::size_t>(it != data + size);
  4379. const auto lhs_data = data;
  4380. const auto lhs_size = static_cast<std::size_t>(it - data);
  4381. const auto rhs_data = it + found;
  4382. const auto rhs_size = size - lhs_size - found;
  4383. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  4384. }
  4385. inline void
  4386. divide(const std::string &str, char d,
  4387. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  4388. fn) {
  4389. divide(str.data(), str.size(), d, std::move(fn));
  4390. }
  4391. inline void split(const char *b, const char *e, char d,
  4392. std::function<void(const char *, const char *)> fn) {
  4393. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  4394. }
  4395. inline void split(const char *b, const char *e, char d, size_t m,
  4396. std::function<void(const char *, const char *)> fn) {
  4397. size_t i = 0;
  4398. size_t beg = 0;
  4399. size_t count = 1;
  4400. while (e ? (b + i < e) : (b[i] != '\0')) {
  4401. if (b[i] == d && count < m) {
  4402. auto r = trim(b, e, beg, i);
  4403. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4404. beg = i + 1;
  4405. count++;
  4406. }
  4407. i++;
  4408. }
  4409. if (i) {
  4410. auto r = trim(b, e, beg, i);
  4411. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  4412. }
  4413. }
  4414. inline bool split_find(const char *b, const char *e, char d, size_t m,
  4415. std::function<bool(const char *, const char *)> fn) {
  4416. size_t i = 0;
  4417. size_t beg = 0;
  4418. size_t count = 1;
  4419. while (e ? (b + i < e) : (b[i] != '\0')) {
  4420. if (b[i] == d && count < m) {
  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. beg = i + 1;
  4427. count++;
  4428. }
  4429. i++;
  4430. }
  4431. if (i) {
  4432. auto r = trim(b, e, beg, i);
  4433. if (r.first < r.second) {
  4434. auto found = fn(&b[r.first], &b[r.second]);
  4435. if (found) { return true; }
  4436. }
  4437. }
  4438. return false;
  4439. }
  4440. inline bool split_find(const char *b, const char *e, char d,
  4441. std::function<bool(const char *, const char *)> fn) {
  4442. return split_find(b, e, d, (std::numeric_limits<size_t>::max)(),
  4443. std::move(fn));
  4444. }
  4445. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  4446. size_t fixed_buffer_size)
  4447. : strm_(strm), fixed_buffer_(fixed_buffer),
  4448. fixed_buffer_size_(fixed_buffer_size) {}
  4449. inline const char *stream_line_reader::ptr() const {
  4450. if (growable_buffer_.empty()) {
  4451. return fixed_buffer_;
  4452. } else {
  4453. return growable_buffer_.data();
  4454. }
  4455. }
  4456. inline size_t stream_line_reader::size() const {
  4457. if (growable_buffer_.empty()) {
  4458. return fixed_buffer_used_size_;
  4459. } else {
  4460. return growable_buffer_.size();
  4461. }
  4462. }
  4463. inline bool stream_line_reader::end_with_crlf() const {
  4464. auto end = ptr() + size();
  4465. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  4466. }
  4467. inline bool stream_line_reader::getline() {
  4468. fixed_buffer_used_size_ = 0;
  4469. growable_buffer_.clear();
  4470. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4471. char prev_byte = 0;
  4472. #endif
  4473. for (size_t i = 0;; i++) {
  4474. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  4475. // Treat exceptionally long lines as an error to
  4476. // prevent infinite loops/memory exhaustion
  4477. return false;
  4478. }
  4479. char byte;
  4480. auto n = strm_.read(&byte, 1);
  4481. if (n < 0) {
  4482. return false;
  4483. } else if (n == 0) {
  4484. if (i == 0) {
  4485. return false;
  4486. } else {
  4487. break;
  4488. }
  4489. }
  4490. append(byte);
  4491. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  4492. if (byte == '\n') { break; }
  4493. #else
  4494. if (prev_byte == '\r' && byte == '\n') { break; }
  4495. prev_byte = byte;
  4496. #endif
  4497. }
  4498. return true;
  4499. }
  4500. inline void stream_line_reader::append(char c) {
  4501. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  4502. fixed_buffer_[fixed_buffer_used_size_++] = c;
  4503. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  4504. } else {
  4505. if (growable_buffer_.empty()) {
  4506. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  4507. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  4508. }
  4509. growable_buffer_ += c;
  4510. }
  4511. }
  4512. inline mmap::mmap(const char *path) { open(path); }
  4513. inline mmap::~mmap() { close(); }
  4514. inline bool mmap::open(const char *path) {
  4515. close();
  4516. #if defined(_WIN32)
  4517. auto wpath = u8string_to_wstring(path);
  4518. if (wpath.empty()) { return false; }
  4519. hFile_ =
  4520. ::CreateFile2(wpath.c_str(), GENERIC_READ,
  4521. FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
  4522. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  4523. LARGE_INTEGER size{};
  4524. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  4525. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  4526. // See:
  4527. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  4528. if (static_cast<ULONGLONG>(size.QuadPart) >
  4529. (std::numeric_limits<decltype(size_)>::max)()) {
  4530. // `size_t` might be 32-bits, on 32-bits Windows.
  4531. return false;
  4532. }
  4533. size_ = static_cast<size_t>(size.QuadPart);
  4534. hMapping_ =
  4535. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  4536. // Special treatment for an empty file...
  4537. if (hMapping_ == NULL && size_ == 0) {
  4538. close();
  4539. is_open_empty_file = true;
  4540. return true;
  4541. }
  4542. if (hMapping_ == NULL) {
  4543. close();
  4544. return false;
  4545. }
  4546. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  4547. if (addr_ == nullptr) {
  4548. close();
  4549. return false;
  4550. }
  4551. #else
  4552. fd_ = ::open(path, O_RDONLY);
  4553. if (fd_ == -1) { return false; }
  4554. struct stat sb;
  4555. if (fstat(fd_, &sb) == -1) {
  4556. close();
  4557. return false;
  4558. }
  4559. size_ = static_cast<size_t>(sb.st_size);
  4560. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  4561. // Special treatment for an empty file...
  4562. if (addr_ == MAP_FAILED && size_ == 0) {
  4563. close();
  4564. is_open_empty_file = true;
  4565. return false;
  4566. }
  4567. #endif
  4568. return true;
  4569. }
  4570. inline bool mmap::is_open() const {
  4571. return is_open_empty_file ? true : addr_ != nullptr;
  4572. }
  4573. inline size_t mmap::size() const { return size_; }
  4574. inline const char *mmap::data() const {
  4575. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  4576. }
  4577. inline void mmap::close() {
  4578. #if defined(_WIN32)
  4579. if (addr_) {
  4580. ::UnmapViewOfFile(addr_);
  4581. addr_ = nullptr;
  4582. }
  4583. if (hMapping_) {
  4584. ::CloseHandle(hMapping_);
  4585. hMapping_ = NULL;
  4586. }
  4587. if (hFile_ != INVALID_HANDLE_VALUE) {
  4588. ::CloseHandle(hFile_);
  4589. hFile_ = INVALID_HANDLE_VALUE;
  4590. }
  4591. is_open_empty_file = false;
  4592. #else
  4593. if (addr_ != nullptr) {
  4594. munmap(addr_, size_);
  4595. addr_ = nullptr;
  4596. }
  4597. if (fd_ != -1) {
  4598. ::close(fd_);
  4599. fd_ = -1;
  4600. }
  4601. #endif
  4602. size_ = 0;
  4603. }
  4604. inline int close_socket(socket_t sock) noexcept {
  4605. #ifdef _WIN32
  4606. return closesocket(sock);
  4607. #else
  4608. return close(sock);
  4609. #endif
  4610. }
  4611. template <typename T> inline ssize_t handle_EINTR(T fn) {
  4612. ssize_t res = 0;
  4613. while (true) {
  4614. res = fn();
  4615. if (res < 0 && errno == EINTR) {
  4616. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4617. continue;
  4618. }
  4619. break;
  4620. }
  4621. return res;
  4622. }
  4623. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  4624. return handle_EINTR([&]() {
  4625. return recv(sock,
  4626. #ifdef _WIN32
  4627. static_cast<char *>(ptr), static_cast<int>(size),
  4628. #else
  4629. ptr, size,
  4630. #endif
  4631. flags);
  4632. });
  4633. }
  4634. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  4635. int flags) {
  4636. return handle_EINTR([&]() {
  4637. return send(sock,
  4638. #ifdef _WIN32
  4639. static_cast<const char *>(ptr), static_cast<int>(size),
  4640. #else
  4641. ptr, size,
  4642. #endif
  4643. flags);
  4644. });
  4645. }
  4646. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  4647. #ifdef _WIN32
  4648. return ::WSAPoll(fds, nfds, timeout);
  4649. #else
  4650. return ::poll(fds, nfds, timeout);
  4651. #endif
  4652. }
  4653. inline ssize_t select_impl(socket_t sock, short events, time_t sec,
  4654. time_t usec) {
  4655. struct pollfd pfd;
  4656. pfd.fd = sock;
  4657. pfd.events = events;
  4658. pfd.revents = 0;
  4659. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4660. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  4661. }
  4662. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  4663. return select_impl(sock, POLLIN, sec, usec);
  4664. }
  4665. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  4666. return select_impl(sock, POLLOUT, sec, usec);
  4667. }
  4668. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  4669. time_t usec) {
  4670. struct pollfd pfd_read;
  4671. pfd_read.fd = sock;
  4672. pfd_read.events = POLLIN | POLLOUT;
  4673. pfd_read.revents = 0;
  4674. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  4675. auto poll_res =
  4676. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  4677. if (poll_res == 0) { return Error::ConnectionTimeout; }
  4678. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  4679. auto error = 0;
  4680. socklen_t len = sizeof(error);
  4681. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  4682. reinterpret_cast<char *>(&error), &len);
  4683. auto successful = res >= 0 && !error;
  4684. return successful ? Error::Success : Error::Connection;
  4685. }
  4686. return Error::Connection;
  4687. }
  4688. inline bool is_socket_alive(socket_t sock) {
  4689. const auto val = detail::select_read(sock, 0, 0);
  4690. if (val == 0) {
  4691. return true;
  4692. } else if (val < 0 && errno == EBADF) {
  4693. return false;
  4694. }
  4695. char buf[1];
  4696. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  4697. }
  4698. class SocketStream final : public Stream {
  4699. public:
  4700. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4701. time_t write_timeout_sec, time_t write_timeout_usec,
  4702. time_t max_timeout_msec = 0,
  4703. std::chrono::time_point<std::chrono::steady_clock> start_time =
  4704. (std::chrono::steady_clock::time_point::min)());
  4705. ~SocketStream() override;
  4706. bool is_readable() const override;
  4707. bool wait_readable() const override;
  4708. bool wait_writable() const override;
  4709. bool is_peer_alive() const override;
  4710. ssize_t read(char *ptr, size_t size) override;
  4711. ssize_t write(const char *ptr, size_t size) override;
  4712. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  4713. void get_local_ip_and_port(std::string &ip, int &port) const override;
  4714. socket_t socket() const override;
  4715. time_t duration() const override;
  4716. void set_read_timeout(time_t sec, time_t usec = 0) override;
  4717. private:
  4718. socket_t sock_;
  4719. time_t read_timeout_sec_;
  4720. time_t read_timeout_usec_;
  4721. time_t write_timeout_sec_;
  4722. time_t write_timeout_usec_;
  4723. time_t max_timeout_msec_;
  4724. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  4725. std::vector<char> read_buff_;
  4726. size_t read_buff_off_ = 0;
  4727. size_t read_buff_content_size_ = 0;
  4728. static const size_t read_buff_size_ = 1024l * 4;
  4729. };
  4730. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4731. time_t keep_alive_timeout_sec) {
  4732. using namespace std::chrono;
  4733. const auto interval_usec =
  4734. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  4735. // Avoid expensive `steady_clock::now()` call for the first time
  4736. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  4737. const auto start = steady_clock::now() - microseconds{interval_usec};
  4738. const auto timeout = seconds{keep_alive_timeout_sec};
  4739. while (true) {
  4740. if (svr_sock == INVALID_SOCKET) {
  4741. break; // Server socket is closed
  4742. }
  4743. auto val = select_read(sock, 0, interval_usec);
  4744. if (val < 0) {
  4745. break; // Ssocket error
  4746. } else if (val == 0) {
  4747. if (steady_clock::now() - start > timeout) {
  4748. break; // Timeout
  4749. }
  4750. } else {
  4751. return true; // Ready for read
  4752. }
  4753. }
  4754. return false;
  4755. }
  4756. template <typename T>
  4757. inline bool
  4758. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4759. size_t keep_alive_max_count,
  4760. time_t keep_alive_timeout_sec, T callback) {
  4761. assert(keep_alive_max_count > 0);
  4762. auto ret = false;
  4763. auto count = keep_alive_max_count;
  4764. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  4765. auto close_connection = count == 1;
  4766. auto connection_closed = false;
  4767. ret = callback(close_connection, connection_closed);
  4768. if (!ret || connection_closed) { break; }
  4769. count--;
  4770. }
  4771. return ret;
  4772. }
  4773. template <typename T>
  4774. inline bool
  4775. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  4776. size_t keep_alive_max_count,
  4777. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  4778. time_t read_timeout_usec, time_t write_timeout_sec,
  4779. time_t write_timeout_usec, T callback) {
  4780. return process_server_socket_core(
  4781. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  4782. [&](bool close_connection, bool &connection_closed) {
  4783. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4784. write_timeout_sec, write_timeout_usec);
  4785. return callback(strm, close_connection, connection_closed);
  4786. });
  4787. }
  4788. inline bool process_client_socket(
  4789. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  4790. time_t write_timeout_sec, time_t write_timeout_usec,
  4791. time_t max_timeout_msec,
  4792. std::chrono::time_point<std::chrono::steady_clock> start_time,
  4793. std::function<bool(Stream &)> callback) {
  4794. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  4795. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  4796. start_time);
  4797. return callback(strm);
  4798. }
  4799. inline int shutdown_socket(socket_t sock) noexcept {
  4800. #ifdef _WIN32
  4801. return shutdown(sock, SD_BOTH);
  4802. #else
  4803. return shutdown(sock, SHUT_RDWR);
  4804. #endif
  4805. }
  4806. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  4807. if (s.size() > 1 && s[0] == '\0') {
  4808. auto ret = s;
  4809. ret[0] = '@';
  4810. return ret;
  4811. }
  4812. return s;
  4813. }
  4814. inline std::string
  4815. unescape_abstract_namespace_unix_domain(const std::string &s) {
  4816. if (s.size() > 1 && s[0] == '@') {
  4817. auto ret = s;
  4818. ret[0] = '\0';
  4819. return ret;
  4820. }
  4821. return s;
  4822. }
  4823. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  4824. const struct addrinfo *hints,
  4825. struct addrinfo **res, time_t timeout_sec) {
  4826. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  4827. if (timeout_sec <= 0) {
  4828. // No timeout specified, use standard getaddrinfo
  4829. return getaddrinfo(node, service, hints, res);
  4830. }
  4831. #ifdef _WIN32
  4832. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  4833. OVERLAPPED overlapped = {};
  4834. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  4835. if (!event) { return EAI_FAIL; }
  4836. overlapped.hEvent = event;
  4837. PADDRINFOEXW result_addrinfo = nullptr;
  4838. HANDLE cancel_handle = nullptr;
  4839. ADDRINFOEXW hints_ex = {};
  4840. if (hints) {
  4841. hints_ex.ai_flags = hints->ai_flags;
  4842. hints_ex.ai_family = hints->ai_family;
  4843. hints_ex.ai_socktype = hints->ai_socktype;
  4844. hints_ex.ai_protocol = hints->ai_protocol;
  4845. }
  4846. auto wnode = u8string_to_wstring(node);
  4847. auto wservice = u8string_to_wstring(service);
  4848. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  4849. hints ? &hints_ex : nullptr, &result_addrinfo,
  4850. nullptr, &overlapped, nullptr, &cancel_handle);
  4851. if (ret == WSA_IO_PENDING) {
  4852. auto wait_result =
  4853. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  4854. if (wait_result == WAIT_TIMEOUT) {
  4855. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  4856. ::CloseHandle(event);
  4857. return EAI_AGAIN;
  4858. }
  4859. DWORD bytes_returned;
  4860. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  4861. &bytes_returned, FALSE)) {
  4862. ::CloseHandle(event);
  4863. return ::WSAGetLastError();
  4864. }
  4865. }
  4866. ::CloseHandle(event);
  4867. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  4868. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  4869. return 0;
  4870. }
  4871. return ret;
  4872. #elif TARGET_OS_MAC && defined(__clang__)
  4873. if (!node) { return EAI_NONAME; }
  4874. // macOS implementation using CFHost API for asynchronous DNS resolution
  4875. CFStringRef hostname_ref = CFStringCreateWithCString(
  4876. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  4877. if (!hostname_ref) { return EAI_MEMORY; }
  4878. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  4879. CFRelease(hostname_ref);
  4880. if (!host_ref) { return EAI_MEMORY; }
  4881. // Set up context for callback
  4882. struct CFHostContext {
  4883. bool completed = false;
  4884. bool success = false;
  4885. CFArrayRef addresses = nullptr;
  4886. std::mutex mutex;
  4887. std::condition_variable cv;
  4888. } context;
  4889. CFHostClientContext client_context;
  4890. memset(&client_context, 0, sizeof(client_context));
  4891. client_context.info = &context;
  4892. // Set callback
  4893. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  4894. const CFStreamError *error, void *info) {
  4895. auto ctx = static_cast<CFHostContext *>(info);
  4896. std::lock_guard<std::mutex> lock(ctx->mutex);
  4897. if (error && error->error != 0) {
  4898. ctx->success = false;
  4899. } else {
  4900. Boolean hasBeenResolved;
  4901. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  4902. if (ctx->addresses && hasBeenResolved) {
  4903. CFRetain(ctx->addresses);
  4904. ctx->success = true;
  4905. } else {
  4906. ctx->success = false;
  4907. }
  4908. }
  4909. ctx->completed = true;
  4910. ctx->cv.notify_one();
  4911. };
  4912. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  4913. CFRelease(host_ref);
  4914. return EAI_SYSTEM;
  4915. }
  4916. // Schedule on run loop
  4917. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  4918. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4919. // Start resolution
  4920. CFStreamError stream_error;
  4921. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  4922. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4923. CFRelease(host_ref);
  4924. return EAI_FAIL;
  4925. }
  4926. // Wait for completion with timeout
  4927. auto timeout_time =
  4928. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  4929. bool timed_out = false;
  4930. {
  4931. std::unique_lock<std::mutex> lock(context.mutex);
  4932. while (!context.completed) {
  4933. auto now = std::chrono::steady_clock::now();
  4934. if (now >= timeout_time) {
  4935. timed_out = true;
  4936. break;
  4937. }
  4938. // Run the runloop for a short time
  4939. lock.unlock();
  4940. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  4941. lock.lock();
  4942. }
  4943. }
  4944. // Clean up
  4945. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  4946. CFHostSetClient(host_ref, nullptr, nullptr);
  4947. if (timed_out || !context.completed) {
  4948. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  4949. CFRelease(host_ref);
  4950. return EAI_AGAIN;
  4951. }
  4952. if (!context.success || !context.addresses) {
  4953. CFRelease(host_ref);
  4954. return EAI_NODATA;
  4955. }
  4956. // Convert CFArray to addrinfo
  4957. CFIndex count = CFArrayGetCount(context.addresses);
  4958. if (count == 0) {
  4959. CFRelease(context.addresses);
  4960. CFRelease(host_ref);
  4961. return EAI_NODATA;
  4962. }
  4963. struct addrinfo *result_addrinfo = nullptr;
  4964. struct addrinfo **current = &result_addrinfo;
  4965. for (CFIndex i = 0; i < count; i++) {
  4966. CFDataRef addr_data =
  4967. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  4968. if (!addr_data) continue;
  4969. const struct sockaddr *sockaddr_ptr =
  4970. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  4971. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  4972. // Allocate addrinfo structure
  4973. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  4974. if (!*current) {
  4975. freeaddrinfo(result_addrinfo);
  4976. CFRelease(context.addresses);
  4977. CFRelease(host_ref);
  4978. return EAI_MEMORY;
  4979. }
  4980. memset(*current, 0, sizeof(struct addrinfo));
  4981. // Set up addrinfo fields
  4982. (*current)->ai_family = sockaddr_ptr->sa_family;
  4983. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  4984. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  4985. (*current)->ai_addrlen = sockaddr_len;
  4986. // Copy sockaddr
  4987. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  4988. if (!(*current)->ai_addr) {
  4989. freeaddrinfo(result_addrinfo);
  4990. CFRelease(context.addresses);
  4991. CFRelease(host_ref);
  4992. return EAI_MEMORY;
  4993. }
  4994. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  4995. // Set port if service is specified
  4996. if (service && *service) {
  4997. int port = 0;
  4998. if (parse_port(service, strlen(service), port)) {
  4999. if (sockaddr_ptr->sa_family == AF_INET) {
  5000. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  5001. ->sin_port = htons(static_cast<uint16_t>(port));
  5002. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  5003. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  5004. ->sin6_port = htons(static_cast<uint16_t>(port));
  5005. }
  5006. }
  5007. }
  5008. current = &((*current)->ai_next);
  5009. }
  5010. CFRelease(context.addresses);
  5011. CFRelease(host_ref);
  5012. *res = result_addrinfo;
  5013. return 0;
  5014. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  5015. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  5016. // #2431: gai_cancel() is non-blocking and may return EAI_NOTCANCELED while
  5017. // the resolver worker still references the stack-local gaicb. The cancel
  5018. // path therefore waits (gai_suspend with no timeout) for the worker to
  5019. // actually finish before letting the stack frame go. The trade-off is that
  5020. // a wedged DNS server can hold this thread for the system resolver timeout
  5021. // (~30s by default) past the caller's connection timeout.
  5022. struct gaicb request {};
  5023. struct gaicb *requests[1] = {&request};
  5024. struct sigevent sevp {};
  5025. struct timespec timeout {
  5026. timeout_sec, 0
  5027. };
  5028. request.ar_name = node;
  5029. request.ar_service = service;
  5030. request.ar_request = hints;
  5031. sevp.sigev_notify = SIGEV_NONE;
  5032. int rc = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  5033. if (rc != 0) { return rc; }
  5034. auto cleanup = scope_exit([&] {
  5035. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  5036. });
  5037. int wait_result = gai_suspend(requests, 1, &timeout);
  5038. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  5039. int gai_result = gai_error(&request);
  5040. if (gai_result == 0) {
  5041. *res = request.ar_result;
  5042. request.ar_result = nullptr;
  5043. return 0;
  5044. }
  5045. return gai_result;
  5046. }
  5047. gai_cancel(&request);
  5048. while (gai_error(&request) == EAI_INPROGRESS) {
  5049. gai_suspend(requests, 1, nullptr);
  5050. }
  5051. return wait_result;
  5052. #else
  5053. // Fallback implementation using thread-based timeout for other Unix systems.
  5054. struct GetAddrInfoState {
  5055. ~GetAddrInfoState() {
  5056. if (info) { freeaddrinfo(info); }
  5057. }
  5058. std::mutex mutex;
  5059. std::condition_variable result_cv;
  5060. bool completed = false;
  5061. int result = EAI_SYSTEM;
  5062. std::string node;
  5063. std::string service;
  5064. struct addrinfo hints;
  5065. struct addrinfo *info = nullptr;
  5066. };
  5067. // Allocate on the heap, so the resolver thread can keep using the data.
  5068. auto state = std::make_shared<GetAddrInfoState>();
  5069. if (node) { state->node = node; }
  5070. state->service = service;
  5071. state->hints = *hints;
  5072. std::thread resolve_thread([state]() {
  5073. auto thread_result =
  5074. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  5075. &state->info);
  5076. std::lock_guard<std::mutex> lock(state->mutex);
  5077. state->result = thread_result;
  5078. state->completed = true;
  5079. state->result_cv.notify_one();
  5080. });
  5081. // Wait for completion or timeout
  5082. std::unique_lock<std::mutex> lock(state->mutex);
  5083. auto finished =
  5084. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  5085. [&] { return state->completed; });
  5086. if (finished) {
  5087. // Operation completed within timeout
  5088. resolve_thread.join();
  5089. *res = state->info;
  5090. state->info = nullptr; // Pass ownership to caller
  5091. return state->result;
  5092. } else {
  5093. // Timeout occurred
  5094. resolve_thread.detach(); // Let the thread finish in background
  5095. return EAI_AGAIN; // Return timeout error
  5096. }
  5097. #endif
  5098. #else
  5099. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  5100. return getaddrinfo(node, service, hints, res);
  5101. #endif
  5102. }
  5103. template <typename BindOrConnect>
  5104. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  5105. int address_family, int socket_flags, bool tcp_nodelay,
  5106. bool ipv6_v6only, SocketOptions socket_options,
  5107. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  5108. // Get address info
  5109. const char *node = nullptr;
  5110. struct addrinfo hints;
  5111. struct addrinfo *result;
  5112. memset(&hints, 0, sizeof(struct addrinfo));
  5113. hints.ai_socktype = SOCK_STREAM;
  5114. hints.ai_protocol = IPPROTO_IP;
  5115. if (!ip.empty()) {
  5116. node = ip.c_str();
  5117. // Ask getaddrinfo to convert IP in c-string to address
  5118. hints.ai_family = AF_UNSPEC;
  5119. hints.ai_flags = AI_NUMERICHOST;
  5120. } else {
  5121. if (!host.empty()) { node = host.c_str(); }
  5122. hints.ai_family = address_family;
  5123. hints.ai_flags = socket_flags;
  5124. }
  5125. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  5126. if (hints.ai_family == AF_UNIX) {
  5127. const auto addrlen = host.length();
  5128. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  5129. #ifdef SOCK_CLOEXEC
  5130. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  5131. hints.ai_protocol);
  5132. #else
  5133. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  5134. #endif
  5135. if (sock != INVALID_SOCKET) {
  5136. sockaddr_un addr{};
  5137. addr.sun_family = AF_UNIX;
  5138. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  5139. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  5140. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  5141. hints.ai_addrlen = static_cast<socklen_t>(
  5142. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  5143. #ifndef SOCK_CLOEXEC
  5144. #ifndef _WIN32
  5145. fcntl(sock, F_SETFD, FD_CLOEXEC);
  5146. #endif
  5147. #endif
  5148. if (socket_options) { socket_options(sock); }
  5149. #ifdef _WIN32
  5150. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  5151. // remove the option.
  5152. set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  5153. #endif
  5154. bool dummy;
  5155. if (!bind_or_connect(sock, hints, dummy)) {
  5156. close_socket(sock);
  5157. sock = INVALID_SOCKET;
  5158. }
  5159. }
  5160. return sock;
  5161. }
  5162. #endif
  5163. auto service = std::to_string(port);
  5164. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  5165. timeout_sec)) {
  5166. #if defined __linux__ && !defined __ANDROID__
  5167. res_init();
  5168. #endif
  5169. return INVALID_SOCKET;
  5170. }
  5171. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5172. for (auto rp = result; rp; rp = rp->ai_next) {
  5173. // Create a socket
  5174. #ifdef _WIN32
  5175. auto sock =
  5176. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  5177. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  5178. /**
  5179. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  5180. * and above the socket creation fails on older Windows Systems.
  5181. *
  5182. * Let's try to create a socket the old way in this case.
  5183. *
  5184. * Reference:
  5185. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  5186. *
  5187. * WSA_FLAG_NO_HANDLE_INHERIT:
  5188. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  5189. * SP1, and later
  5190. *
  5191. */
  5192. if (sock == INVALID_SOCKET) {
  5193. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5194. }
  5195. #else
  5196. #ifdef SOCK_CLOEXEC
  5197. auto sock =
  5198. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  5199. #else
  5200. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  5201. #endif
  5202. #endif
  5203. if (sock == INVALID_SOCKET) { continue; }
  5204. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  5205. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  5206. close_socket(sock);
  5207. continue;
  5208. }
  5209. #endif
  5210. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  5211. if (rp->ai_family == AF_INET6) {
  5212. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  5213. }
  5214. if (socket_options) { socket_options(sock); }
  5215. // bind or connect
  5216. auto quit = false;
  5217. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  5218. close_socket(sock);
  5219. if (quit) { break; }
  5220. }
  5221. return INVALID_SOCKET;
  5222. }
  5223. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  5224. #ifdef _WIN32
  5225. auto flags = nonblocking ? 1UL : 0UL;
  5226. ioctlsocket(sock, FIONBIO, &flags);
  5227. #else
  5228. auto flags = fcntl(sock, F_GETFL, 0);
  5229. fcntl(sock, F_SETFL,
  5230. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  5231. #endif
  5232. }
  5233. inline bool is_connection_error() {
  5234. #ifdef _WIN32
  5235. return WSAGetLastError() != WSAEWOULDBLOCK;
  5236. #else
  5237. return errno != EINPROGRESS;
  5238. #endif
  5239. }
  5240. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  5241. struct addrinfo hints;
  5242. struct addrinfo *result;
  5243. memset(&hints, 0, sizeof(struct addrinfo));
  5244. hints.ai_family = AF_UNSPEC;
  5245. hints.ai_socktype = SOCK_STREAM;
  5246. hints.ai_protocol = 0;
  5247. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  5248. return false;
  5249. }
  5250. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5251. auto ret = false;
  5252. for (auto rp = result; rp; rp = rp->ai_next) {
  5253. const auto &ai = *rp;
  5254. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  5255. ret = true;
  5256. break;
  5257. }
  5258. }
  5259. return ret;
  5260. }
  5261. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  5262. #define USE_IF2IP
  5263. #endif
  5264. #ifdef USE_IF2IP
  5265. inline std::string if2ip(int address_family, const std::string &ifn) {
  5266. struct ifaddrs *ifap;
  5267. getifaddrs(&ifap);
  5268. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  5269. std::string addr_candidate;
  5270. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  5271. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  5272. (AF_UNSPEC == address_family ||
  5273. ifa->ifa_addr->sa_family == address_family)) {
  5274. if (ifa->ifa_addr->sa_family == AF_INET) {
  5275. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  5276. char buf[INET_ADDRSTRLEN];
  5277. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  5278. return std::string(buf, INET_ADDRSTRLEN);
  5279. }
  5280. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  5281. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  5282. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  5283. char buf[INET6_ADDRSTRLEN] = {};
  5284. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  5285. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  5286. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  5287. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  5288. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  5289. } else {
  5290. return std::string(buf, INET6_ADDRSTRLEN);
  5291. }
  5292. }
  5293. }
  5294. }
  5295. }
  5296. }
  5297. return addr_candidate;
  5298. }
  5299. #endif
  5300. inline socket_t create_client_socket(
  5301. const std::string &host, const std::string &ip, int port,
  5302. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  5303. SocketOptions socket_options, time_t connection_timeout_sec,
  5304. time_t connection_timeout_usec, time_t read_timeout_sec,
  5305. time_t read_timeout_usec, time_t write_timeout_sec,
  5306. time_t write_timeout_usec, const std::string &intf, Error &error) {
  5307. auto sock = create_socket(
  5308. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  5309. std::move(socket_options),
  5310. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  5311. if (!intf.empty()) {
  5312. #ifdef USE_IF2IP
  5313. auto ip_from_if = if2ip(address_family, intf);
  5314. if (ip_from_if.empty()) { ip_from_if = intf; }
  5315. if (!bind_ip_address(sock2, ip_from_if)) {
  5316. error = Error::BindIPAddress;
  5317. return false;
  5318. }
  5319. #endif
  5320. }
  5321. set_nonblocking(sock2, true);
  5322. auto ret =
  5323. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  5324. if (ret < 0) {
  5325. if (is_connection_error()) {
  5326. error = Error::Connection;
  5327. return false;
  5328. }
  5329. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  5330. connection_timeout_usec);
  5331. if (error != Error::Success) {
  5332. if (error == Error::ConnectionTimeout) { quit = true; }
  5333. return false;
  5334. }
  5335. }
  5336. set_nonblocking(sock2, false);
  5337. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  5338. read_timeout_usec);
  5339. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  5340. write_timeout_usec);
  5341. error = Error::Success;
  5342. return true;
  5343. },
  5344. connection_timeout_sec); // Pass DNS timeout
  5345. if (sock != INVALID_SOCKET) {
  5346. error = Error::Success;
  5347. } else {
  5348. if (error == Error::Success) { error = Error::Connection; }
  5349. }
  5350. return sock;
  5351. }
  5352. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  5353. socklen_t addr_len, std::string &ip, int &port) {
  5354. if (addr.ss_family == AF_INET) {
  5355. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  5356. } else if (addr.ss_family == AF_INET6) {
  5357. port =
  5358. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  5359. } else {
  5360. return false;
  5361. }
  5362. std::array<char, NI_MAXHOST> ipstr{};
  5363. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  5364. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  5365. 0, NI_NUMERICHOST)) {
  5366. return false;
  5367. }
  5368. ip = ipstr.data();
  5369. return true;
  5370. }
  5371. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5372. struct sockaddr_storage addr;
  5373. socklen_t addr_len = sizeof(addr);
  5374. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5375. &addr_len)) {
  5376. get_ip_and_port(addr, addr_len, ip, port);
  5377. }
  5378. }
  5379. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  5380. struct sockaddr_storage addr;
  5381. socklen_t addr_len = sizeof(addr);
  5382. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  5383. &addr_len)) {
  5384. #ifndef _WIN32
  5385. if (addr.ss_family == AF_UNIX) {
  5386. #if defined(__linux__)
  5387. struct ucred ucred;
  5388. socklen_t len = sizeof(ucred);
  5389. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  5390. port = ucred.pid;
  5391. }
  5392. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  5393. pid_t pid;
  5394. socklen_t len = sizeof(pid);
  5395. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  5396. port = pid;
  5397. }
  5398. #endif
  5399. return;
  5400. }
  5401. #endif
  5402. get_ip_and_port(addr, addr_len, ip, port);
  5403. }
  5404. }
  5405. // Recursive form retained so operator""_t below can compute hashes for
  5406. // switch-case labels at compile time (C++11 constexpr forbids loops). Do not
  5407. // call from runtime paths with arbitrary-length inputs — use str2tag()
  5408. // instead, which is iterative and stack-safe.
  5409. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  5410. unsigned int h) {
  5411. return (l == 0)
  5412. ? h
  5413. : str2tag_core(
  5414. s + 1, l - 1,
  5415. // Unsets the 6 high bits of h, therefore no overflow happens
  5416. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  5417. h * 33) ^
  5418. static_cast<unsigned char>(*s));
  5419. }
  5420. inline unsigned int str2tag(const std::string &s) {
  5421. // Iterative form of str2tag_core: the recursive constexpr version is kept
  5422. // for compile-time UDL evaluation of short string literals, but at runtime
  5423. // we may receive arbitrarily long inputs (e.g. fuzzed Content-Type) that
  5424. // would blow the stack with one frame per character.
  5425. unsigned int h = 0;
  5426. for (auto c : s) {
  5427. h = (((std::numeric_limits<unsigned int>::max)() >> 6) & h * 33) ^
  5428. static_cast<unsigned char>(c);
  5429. }
  5430. return h;
  5431. }
  5432. namespace udl {
  5433. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  5434. return str2tag_core(s, l, 0);
  5435. }
  5436. } // namespace udl
  5437. inline std::string
  5438. find_content_type(const std::string &path,
  5439. const std::map<std::string, std::string> &user_data,
  5440. const std::string &default_content_type) {
  5441. auto ext = file_extension(path);
  5442. auto it = user_data.find(ext);
  5443. if (it != user_data.end()) { return it->second; }
  5444. using udl::operator""_t;
  5445. switch (str2tag(ext)) {
  5446. default: return default_content_type;
  5447. case "css"_t: return "text/css";
  5448. case "csv"_t: return "text/csv";
  5449. case "htm"_t:
  5450. case "html"_t: return "text/html";
  5451. case "js"_t:
  5452. case "mjs"_t: return "text/javascript";
  5453. case "txt"_t: return "text/plain";
  5454. case "vtt"_t: return "text/vtt";
  5455. case "apng"_t: return "image/apng";
  5456. case "avif"_t: return "image/avif";
  5457. case "bmp"_t: return "image/bmp";
  5458. case "gif"_t: return "image/gif";
  5459. case "png"_t: return "image/png";
  5460. case "svg"_t: return "image/svg+xml";
  5461. case "webp"_t: return "image/webp";
  5462. case "ico"_t: return "image/x-icon";
  5463. case "tif"_t: return "image/tiff";
  5464. case "tiff"_t: return "image/tiff";
  5465. case "jpg"_t:
  5466. case "jpeg"_t: return "image/jpeg";
  5467. case "mp4"_t: return "video/mp4";
  5468. case "mpeg"_t: return "video/mpeg";
  5469. case "webm"_t: return "video/webm";
  5470. case "mp3"_t: return "audio/mp3";
  5471. case "mpga"_t: return "audio/mpeg";
  5472. case "weba"_t: return "audio/webm";
  5473. case "wav"_t: return "audio/wave";
  5474. case "otf"_t: return "font/otf";
  5475. case "ttf"_t: return "font/ttf";
  5476. case "woff"_t: return "font/woff";
  5477. case "woff2"_t: return "font/woff2";
  5478. case "7z"_t: return "application/x-7z-compressed";
  5479. case "atom"_t: return "application/atom+xml";
  5480. case "pdf"_t: return "application/pdf";
  5481. case "json"_t: return "application/json";
  5482. case "rss"_t: return "application/rss+xml";
  5483. case "tar"_t: return "application/x-tar";
  5484. case "xht"_t:
  5485. case "xhtml"_t: return "application/xhtml+xml";
  5486. case "xslt"_t: return "application/xslt+xml";
  5487. case "xml"_t: return "application/xml";
  5488. case "gz"_t: return "application/gzip";
  5489. case "zip"_t: return "application/zip";
  5490. case "wasm"_t: return "application/wasm";
  5491. }
  5492. }
  5493. inline std::string
  5494. extract_media_type(const std::string &content_type,
  5495. std::map<std::string, std::string> *params = nullptr) {
  5496. // Extract type/subtype from Content-Type value (RFC 2045)
  5497. // e.g. "application/json; charset=utf-8" -> "application/json"
  5498. auto media_type = content_type;
  5499. auto semicolon_pos = media_type.find(';');
  5500. if (semicolon_pos != std::string::npos) {
  5501. auto param_str = media_type.substr(semicolon_pos + 1);
  5502. media_type = media_type.substr(0, semicolon_pos);
  5503. if (params) {
  5504. // Parse parameters: key=value pairs separated by ';'
  5505. split(param_str.data(), param_str.data() + param_str.size(), ';',
  5506. [&](const char *b, const char *e) {
  5507. std::string key;
  5508. std::string val;
  5509. split(b, e, '=', [&](const char *b2, const char *e2) {
  5510. if (key.empty()) {
  5511. key.assign(b2, e2);
  5512. } else {
  5513. val.assign(b2, e2);
  5514. }
  5515. });
  5516. if (!key.empty()) {
  5517. params->emplace(trim_copy(key), trim_double_quotes_copy(val));
  5518. }
  5519. });
  5520. }
  5521. }
  5522. // Trim whitespace from media type
  5523. return trim_copy(media_type);
  5524. }
  5525. inline bool can_compress_content_type(const std::string &content_type) {
  5526. using udl::operator""_t;
  5527. auto mime_type = extract_media_type(content_type);
  5528. auto tag = str2tag(mime_type);
  5529. switch (tag) {
  5530. case "image/svg+xml"_t:
  5531. case "application/javascript"_t:
  5532. case "application/x-javascript"_t:
  5533. case "application/json"_t:
  5534. case "application/ld+json"_t:
  5535. case "application/xml"_t:
  5536. case "application/xhtml+xml"_t:
  5537. case "application/rss+xml"_t:
  5538. case "application/atom+xml"_t:
  5539. case "application/xslt+xml"_t:
  5540. case "application/protobuf"_t: return true;
  5541. case "text/event-stream"_t: return false;
  5542. default: return !mime_type.rfind("text/", 0);
  5543. }
  5544. }
  5545. inline bool parse_quality(const char *b, const char *e, std::string &token,
  5546. double &quality) {
  5547. quality = 1.0;
  5548. token.clear();
  5549. // Split on first ';': left = token name, right = parameters
  5550. const char *params_b = nullptr;
  5551. std::size_t params_len = 0;
  5552. divide(
  5553. b, static_cast<std::size_t>(e - b), ';',
  5554. [&](const char *lb, std::size_t llen, const char *rb, std::size_t rlen) {
  5555. auto r = trim(lb, lb + llen, 0, llen);
  5556. if (r.first < r.second) { token.assign(lb + r.first, lb + r.second); }
  5557. params_b = rb;
  5558. params_len = rlen;
  5559. });
  5560. if (token.empty()) { return false; }
  5561. if (params_len == 0) { return true; }
  5562. // Scan parameters for q= (stops on first match)
  5563. bool invalid = false;
  5564. split_find(params_b, params_b + params_len, ';',
  5565. (std::numeric_limits<size_t>::max)(),
  5566. [&](const char *pb, const char *pe) -> bool {
  5567. // Match exactly "q=" or "Q=" (not "query=" etc.)
  5568. auto len = static_cast<size_t>(pe - pb);
  5569. if (len < 2) { return false; }
  5570. if ((pb[0] != 'q' && pb[0] != 'Q') || pb[1] != '=') {
  5571. return false;
  5572. }
  5573. // Trim the value portion
  5574. auto r = trim(pb, pe, 2, len);
  5575. if (r.first >= r.second) {
  5576. invalid = true;
  5577. return true;
  5578. }
  5579. double v = 0.0;
  5580. auto res = from_chars(pb + r.first, pb + r.second, v);
  5581. if (res.ec != std::errc{} || v < 0.0 || v > 1.0) {
  5582. invalid = true;
  5583. return true;
  5584. }
  5585. quality = v;
  5586. return true;
  5587. });
  5588. return !invalid;
  5589. }
  5590. inline EncodingType encoding_type(const Request &req, const Response &res) {
  5591. if (!can_compress_content_type(res.get_header_value("Content-Type"))) {
  5592. return EncodingType::None;
  5593. }
  5594. const auto &s = req.get_header_value("Accept-Encoding");
  5595. if (s.empty()) { return EncodingType::None; }
  5596. // Single-pass: iterate tokens and track the best supported encoding.
  5597. // Server preference breaks ties (br > gzip > zstd).
  5598. EncodingType best = EncodingType::None;
  5599. double best_q = 0.0; // q=0 means "not acceptable"
  5600. // Server preference: Brotli > Gzip > Zstd (lower = more preferred)
  5601. auto priority = [](EncodingType t) -> int {
  5602. switch (t) {
  5603. case EncodingType::Brotli: return 0;
  5604. case EncodingType::Gzip: return 1;
  5605. case EncodingType::Zstd: return 2;
  5606. default: return 3;
  5607. }
  5608. };
  5609. std::string name;
  5610. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  5611. double quality = 1.0;
  5612. if (!parse_quality(b, e, name, quality)) { return; }
  5613. if (quality <= 0.0) { return; }
  5614. EncodingType type = EncodingType::None;
  5615. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5616. if (case_ignore::equal(name, "br")) { type = EncodingType::Brotli; }
  5617. #endif
  5618. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5619. if (type == EncodingType::None && case_ignore::equal(name, "gzip")) {
  5620. type = EncodingType::Gzip;
  5621. }
  5622. #endif
  5623. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5624. if (type == EncodingType::None && case_ignore::equal(name, "zstd")) {
  5625. type = EncodingType::Zstd;
  5626. }
  5627. #endif
  5628. if (type == EncodingType::None) { return; }
  5629. // Higher q-value wins; for equal q, server preference breaks ties
  5630. if (quality > best_q ||
  5631. (quality == best_q && priority(type) < priority(best))) {
  5632. best_q = quality;
  5633. best = type;
  5634. }
  5635. });
  5636. return best;
  5637. }
  5638. inline std::unique_ptr<compressor> make_compressor(EncodingType type) {
  5639. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5640. if (type == EncodingType::Gzip) {
  5641. return detail::make_unique<gzip_compressor>();
  5642. }
  5643. #endif
  5644. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5645. if (type == EncodingType::Brotli) {
  5646. return detail::make_unique<brotli_compressor>();
  5647. }
  5648. #endif
  5649. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5650. if (type == EncodingType::Zstd) {
  5651. return detail::make_unique<zstd_compressor>();
  5652. }
  5653. #endif
  5654. (void)type;
  5655. return nullptr;
  5656. }
  5657. inline const char *encoding_name(EncodingType type) {
  5658. switch (type) {
  5659. case EncodingType::Gzip: return "gzip";
  5660. case EncodingType::Brotli: return "br";
  5661. case EncodingType::Zstd: return "zstd";
  5662. default: return "";
  5663. }
  5664. }
  5665. inline bool nocompressor::compress(const char *data, size_t data_length,
  5666. bool /*last*/, Callback callback) {
  5667. if (!data_length) { return true; }
  5668. return callback(data, data_length);
  5669. }
  5670. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5671. inline gzip_compressor::gzip_compressor() {
  5672. std::memset(&strm_, 0, sizeof(strm_));
  5673. strm_.zalloc = Z_NULL;
  5674. strm_.zfree = Z_NULL;
  5675. strm_.opaque = Z_NULL;
  5676. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  5677. Z_DEFAULT_STRATEGY) == Z_OK;
  5678. }
  5679. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  5680. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  5681. bool last, Callback callback) {
  5682. assert(is_valid_);
  5683. do {
  5684. constexpr size_t max_avail_in =
  5685. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5686. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5687. (std::min)(data_length, max_avail_in));
  5688. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5689. data_length -= strm_.avail_in;
  5690. data += strm_.avail_in;
  5691. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  5692. auto ret = Z_OK;
  5693. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5694. do {
  5695. strm_.avail_out = static_cast<uInt>(buff.size());
  5696. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5697. ret = deflate(&strm_, flush);
  5698. if (ret == Z_STREAM_ERROR) { return false; }
  5699. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5700. return false;
  5701. }
  5702. } while (strm_.avail_out == 0);
  5703. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  5704. (flush == Z_NO_FLUSH && ret == Z_OK));
  5705. assert(strm_.avail_in == 0);
  5706. } while (data_length > 0);
  5707. return true;
  5708. }
  5709. inline gzip_decompressor::gzip_decompressor() {
  5710. std::memset(&strm_, 0, sizeof(strm_));
  5711. strm_.zalloc = Z_NULL;
  5712. strm_.zfree = Z_NULL;
  5713. strm_.opaque = Z_NULL;
  5714. // 15 is the value of wbits, which should be at the maximum possible value
  5715. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  5716. // that the stream type should be automatically detected either gzip or
  5717. // deflate.
  5718. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  5719. }
  5720. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  5721. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  5722. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  5723. Callback callback) {
  5724. assert(is_valid_);
  5725. auto ret = Z_OK;
  5726. do {
  5727. constexpr size_t max_avail_in =
  5728. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  5729. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  5730. (std::min)(data_length, max_avail_in));
  5731. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  5732. data_length -= strm_.avail_in;
  5733. data += strm_.avail_in;
  5734. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5735. while (strm_.avail_in > 0 && ret == Z_OK) {
  5736. strm_.avail_out = static_cast<uInt>(buff.size());
  5737. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  5738. ret = inflate(&strm_, Z_NO_FLUSH);
  5739. assert(ret != Z_STREAM_ERROR);
  5740. switch (ret) {
  5741. case Z_NEED_DICT:
  5742. case Z_DATA_ERROR:
  5743. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  5744. }
  5745. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  5746. return false;
  5747. }
  5748. }
  5749. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  5750. } while (data_length > 0);
  5751. return true;
  5752. }
  5753. #endif
  5754. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5755. inline brotli_compressor::brotli_compressor() {
  5756. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  5757. }
  5758. inline brotli_compressor::~brotli_compressor() {
  5759. BrotliEncoderDestroyInstance(state_);
  5760. }
  5761. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  5762. bool last, Callback callback) {
  5763. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5764. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  5765. auto available_in = data_length;
  5766. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5767. for (;;) {
  5768. if (last) {
  5769. if (BrotliEncoderIsFinished(state_)) { break; }
  5770. } else {
  5771. if (!available_in) { break; }
  5772. }
  5773. auto available_out = buff.size();
  5774. auto next_out = buff.data();
  5775. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  5776. &available_out, &next_out, nullptr)) {
  5777. return false;
  5778. }
  5779. auto output_bytes = buff.size() - available_out;
  5780. if (output_bytes) {
  5781. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  5782. }
  5783. }
  5784. return true;
  5785. }
  5786. inline brotli_decompressor::brotli_decompressor() {
  5787. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  5788. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  5789. : BROTLI_DECODER_RESULT_ERROR;
  5790. }
  5791. inline brotli_decompressor::~brotli_decompressor() {
  5792. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  5793. }
  5794. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  5795. inline bool brotli_decompressor::decompress(const char *data,
  5796. size_t data_length,
  5797. Callback callback) {
  5798. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5799. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  5800. return 0;
  5801. }
  5802. auto next_in = reinterpret_cast<const uint8_t *>(data);
  5803. size_t avail_in = data_length;
  5804. size_t total_out;
  5805. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  5806. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5807. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  5808. char *next_out = buff.data();
  5809. size_t avail_out = buff.size();
  5810. decoder_r = BrotliDecoderDecompressStream(
  5811. decoder_s, &avail_in, &next_in, &avail_out,
  5812. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  5813. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  5814. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  5815. }
  5816. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  5817. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  5818. }
  5819. #endif
  5820. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5821. inline zstd_compressor::zstd_compressor() {
  5822. ctx_ = ZSTD_createCCtx();
  5823. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  5824. }
  5825. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  5826. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  5827. bool last, Callback callback) {
  5828. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5829. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  5830. ZSTD_inBuffer input = {data, data_length, 0};
  5831. bool finished;
  5832. do {
  5833. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5834. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  5835. if (ZSTD_isError(remaining)) { return false; }
  5836. if (!callback(buff.data(), output.pos)) { return false; }
  5837. finished = last ? (remaining == 0) : (input.pos == input.size);
  5838. } while (!finished);
  5839. return true;
  5840. }
  5841. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  5842. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  5843. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  5844. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  5845. Callback callback) {
  5846. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  5847. ZSTD_inBuffer input = {data, data_length, 0};
  5848. while (input.pos < input.size) {
  5849. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  5850. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  5851. if (ZSTD_isError(remaining)) { return false; }
  5852. if (!callback(buff.data(), output.pos)) { return false; }
  5853. }
  5854. return true;
  5855. }
  5856. #endif
  5857. inline std::unique_ptr<decompressor>
  5858. create_decompressor(const std::string &encoding) {
  5859. std::unique_ptr<decompressor> decompressor;
  5860. if (encoding == "gzip" || encoding == "deflate") {
  5861. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5862. decompressor = detail::make_unique<gzip_decompressor>();
  5863. #endif
  5864. } else if (encoding.find("br") != std::string::npos) {
  5865. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5866. decompressor = detail::make_unique<brotli_decompressor>();
  5867. #endif
  5868. } else if (encoding == "zstd" || encoding.find("zstd") != std::string::npos) {
  5869. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5870. decompressor = detail::make_unique<zstd_decompressor>();
  5871. #endif
  5872. }
  5873. return decompressor;
  5874. }
  5875. // Returns the best available compressor and its Content-Encoding name.
  5876. // Priority: Brotli > Gzip > Zstd (matches server-side preference).
  5877. inline std::pair<std::unique_ptr<compressor>, const char *>
  5878. create_compressor() {
  5879. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5880. return {detail::make_unique<brotli_compressor>(), "br"};
  5881. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  5882. return {detail::make_unique<gzip_compressor>(), "gzip"};
  5883. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5884. return {detail::make_unique<zstd_compressor>(), "zstd"};
  5885. #else
  5886. return {nullptr, nullptr};
  5887. #endif
  5888. }
  5889. inline bool is_prohibited_header_name(const std::string &name) {
  5890. using udl::operator""_t;
  5891. switch (str2tag(name)) {
  5892. case "REMOTE_ADDR"_t:
  5893. case "REMOTE_PORT"_t:
  5894. case "LOCAL_ADDR"_t:
  5895. case "LOCAL_PORT"_t: return true;
  5896. default: return false;
  5897. }
  5898. }
  5899. inline bool has_header(const Headers &headers, const std::string &key) {
  5900. if (is_prohibited_header_name(key)) { return false; }
  5901. return headers.find(key) != headers.end();
  5902. }
  5903. inline const char *get_header_value(const Headers &headers,
  5904. const std::string &key, const char *def,
  5905. size_t id) {
  5906. if (is_prohibited_header_name(key)) {
  5907. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5908. std::string msg = "Prohibited header name '" + key + "' is specified.";
  5909. throw std::invalid_argument(msg);
  5910. #else
  5911. return "";
  5912. #endif
  5913. }
  5914. auto rng = headers.equal_range(key);
  5915. auto it = rng.first;
  5916. std::advance(it, static_cast<ssize_t>(id));
  5917. if (it != rng.second) { return it->second.c_str(); }
  5918. return def;
  5919. }
  5920. inline size_t get_header_value_count(const Headers &headers,
  5921. const std::string &key) {
  5922. auto r = headers.equal_range(key);
  5923. return static_cast<size_t>(std::distance(r.first, r.second));
  5924. }
  5925. template <typename Map>
  5926. inline typename Map::mapped_type
  5927. get_multimap_value(const Map &m, const std::string &key, size_t id) {
  5928. auto rng = m.equal_range(key);
  5929. auto it = rng.first;
  5930. std::advance(it, static_cast<ssize_t>(id));
  5931. if (it != rng.second) { return it->second; }
  5932. return typename Map::mapped_type();
  5933. }
  5934. inline void set_header(Headers &headers, const std::string &key,
  5935. const std::string &val) {
  5936. if (fields::is_field_name(key) && fields::is_field_value(val)) {
  5937. headers.emplace(key, val);
  5938. }
  5939. }
  5940. inline bool read_headers(Stream &strm, Headers &headers) {
  5941. const auto bufsiz = 2048;
  5942. char buf[bufsiz];
  5943. stream_line_reader line_reader(strm, buf, bufsiz);
  5944. size_t header_count = 0;
  5945. for (;;) {
  5946. if (!line_reader.getline()) { return false; }
  5947. // Check if the line ends with CRLF.
  5948. auto line_terminator_len = 2;
  5949. if (line_reader.end_with_crlf()) {
  5950. // Blank line indicates end of headers.
  5951. if (line_reader.size() == 2) { break; }
  5952. } else {
  5953. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5954. // Blank line indicates end of headers.
  5955. if (line_reader.size() == 1) { break; }
  5956. line_terminator_len = 1;
  5957. #else
  5958. continue; // Skip invalid line.
  5959. #endif
  5960. }
  5961. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  5962. // Check header count limit
  5963. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  5964. // Exclude line terminator
  5965. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  5966. if (!parse_header(line_reader.ptr(), end,
  5967. [&](const std::string &key, const std::string &val) {
  5968. headers.emplace(key, val);
  5969. })) {
  5970. return false;
  5971. }
  5972. header_count++;
  5973. }
  5974. // RFC 9110 Section 8.6: Reject requests with multiple Content-Length
  5975. // headers that have different values to prevent request smuggling.
  5976. auto cl_range = headers.equal_range("Content-Length");
  5977. if (cl_range.first != cl_range.second) {
  5978. const auto &first_val = cl_range.first->second;
  5979. for (auto it = std::next(cl_range.first); it != cl_range.second; ++it) {
  5980. if (it->second != first_val) { return false; }
  5981. }
  5982. }
  5983. return true;
  5984. }
  5985. inline bool read_websocket_upgrade_response(Stream &strm,
  5986. const std::string &expected_accept,
  5987. std::string &selected_subprotocol) {
  5988. // Read status line
  5989. const auto bufsiz = 2048;
  5990. char buf[bufsiz];
  5991. stream_line_reader line_reader(strm, buf, bufsiz);
  5992. if (!line_reader.getline()) { return false; }
  5993. // Check for "HTTP/1.1 101"
  5994. auto line = std::string(line_reader.ptr(), line_reader.size());
  5995. if (line.find("HTTP/1.1 101") == std::string::npos) { return false; }
  5996. // Parse headers using existing read_headers
  5997. Headers headers;
  5998. if (!read_headers(strm, headers)) { return false; }
  5999. // Verify Upgrade: websocket (case-insensitive)
  6000. auto upgrade_it = headers.find("Upgrade");
  6001. if (upgrade_it == headers.end()) { return false; }
  6002. auto upgrade_val = case_ignore::to_lower(upgrade_it->second);
  6003. if (upgrade_val != "websocket") { return false; }
  6004. // Verify Connection header contains "Upgrade" (case-insensitive)
  6005. auto connection_it = headers.find("Connection");
  6006. if (connection_it == headers.end()) { return false; }
  6007. auto connection_val = case_ignore::to_lower(connection_it->second);
  6008. if (connection_val.find("upgrade") == std::string::npos) { return false; }
  6009. // Verify Sec-WebSocket-Accept header value
  6010. auto it = headers.find("Sec-WebSocket-Accept");
  6011. if (it == headers.end() || it->second != expected_accept) { return false; }
  6012. // Extract negotiated subprotocol
  6013. auto proto_it = headers.find("Sec-WebSocket-Protocol");
  6014. if (proto_it != headers.end()) { selected_subprotocol = proto_it->second; }
  6015. return true;
  6016. }
  6017. enum class ReadContentResult {
  6018. Success, // Successfully read the content
  6019. PayloadTooLarge, // The content exceeds the specified payload limit
  6020. Error // An error occurred while reading the content
  6021. };
  6022. inline ReadContentResult read_content_with_length(
  6023. Stream &strm, size_t len, DownloadProgress progress,
  6024. ContentReceiverWithProgress out,
  6025. size_t payload_max_length = (std::numeric_limits<size_t>::max)()) {
  6026. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6027. detail::BodyReader br;
  6028. br.stream = &strm;
  6029. br.has_content_length = true;
  6030. br.content_length = len;
  6031. br.payload_max_length = payload_max_length;
  6032. br.chunked = false;
  6033. br.bytes_read = 0;
  6034. br.last_error = Error::Success;
  6035. size_t r = 0;
  6036. while (r < len) {
  6037. auto read_len = static_cast<size_t>(len - r);
  6038. auto to_read = (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ);
  6039. auto n = detail::read_body_content(&strm, br, buf, to_read);
  6040. if (n <= 0) {
  6041. // Check if it was a payload size error
  6042. if (br.last_error == Error::ExceedMaxPayloadSize) {
  6043. return ReadContentResult::PayloadTooLarge;
  6044. }
  6045. return ReadContentResult::Error;
  6046. }
  6047. if (!out(buf, static_cast<size_t>(n), r, len)) {
  6048. return ReadContentResult::Error;
  6049. }
  6050. r += static_cast<size_t>(n);
  6051. if (progress) {
  6052. if (!progress(r, len)) { return ReadContentResult::Error; }
  6053. }
  6054. }
  6055. return ReadContentResult::Success;
  6056. }
  6057. inline ReadContentResult
  6058. read_content_without_length(Stream &strm, size_t payload_max_length,
  6059. ContentReceiverWithProgress out) {
  6060. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6061. size_t r = 0;
  6062. for (;;) {
  6063. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  6064. if (n == 0) { return ReadContentResult::Success; }
  6065. if (n < 0) { return ReadContentResult::Error; }
  6066. // Check if adding this data would exceed the payload limit
  6067. if (r > payload_max_length ||
  6068. payload_max_length - r < static_cast<size_t>(n)) {
  6069. return ReadContentResult::PayloadTooLarge;
  6070. }
  6071. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  6072. return ReadContentResult::Error;
  6073. }
  6074. r += static_cast<size_t>(n);
  6075. }
  6076. return ReadContentResult::Success;
  6077. }
  6078. template <typename T>
  6079. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  6080. size_t payload_max_length,
  6081. ContentReceiverWithProgress out) {
  6082. detail::ChunkedDecoder dec(strm);
  6083. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  6084. size_t total_len = 0;
  6085. for (;;) {
  6086. size_t chunk_offset = 0;
  6087. size_t chunk_total = 0;
  6088. auto n = dec.read_payload(buf, sizeof(buf), chunk_offset, chunk_total);
  6089. if (n < 0) { return ReadContentResult::Error; }
  6090. if (n == 0) {
  6091. if (!dec.parse_trailers_into(x.trailers, x.headers)) {
  6092. return ReadContentResult::Error;
  6093. }
  6094. return ReadContentResult::Success;
  6095. }
  6096. if (total_len > payload_max_length ||
  6097. payload_max_length - total_len < static_cast<size_t>(n)) {
  6098. return ReadContentResult::PayloadTooLarge;
  6099. }
  6100. if (!out(buf, static_cast<size_t>(n), chunk_offset, chunk_total)) {
  6101. return ReadContentResult::Error;
  6102. }
  6103. total_len += static_cast<size_t>(n);
  6104. }
  6105. }
  6106. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  6107. return case_ignore::equal(
  6108. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  6109. }
  6110. template <typename T, typename U>
  6111. bool prepare_content_receiver(T &x, int &status,
  6112. ContentReceiverWithProgress receiver,
  6113. bool decompress, size_t payload_max_length,
  6114. bool &exceed_payload_max_length, U callback) {
  6115. if (decompress) {
  6116. std::string encoding = x.get_header_value("Content-Encoding");
  6117. std::unique_ptr<decompressor> decompressor;
  6118. if (!encoding.empty()) {
  6119. decompressor = detail::create_decompressor(encoding);
  6120. if (!decompressor) {
  6121. // Unsupported encoding or no support compiled in
  6122. status = StatusCode::UnsupportedMediaType_415;
  6123. return false;
  6124. }
  6125. }
  6126. if (decompressor) {
  6127. if (decompressor->is_valid()) {
  6128. size_t decompressed_size = 0;
  6129. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  6130. size_t off, size_t len) {
  6131. return decompressor->decompress(
  6132. buf, n, [&](const char *buf2, size_t n2) {
  6133. // Guard against zip-bomb: check
  6134. // decompressed size against limit.
  6135. if (payload_max_length > 0 &&
  6136. (decompressed_size >= payload_max_length ||
  6137. n2 > payload_max_length - decompressed_size)) {
  6138. exceed_payload_max_length = true;
  6139. return false;
  6140. }
  6141. decompressed_size += n2;
  6142. return receiver(buf2, n2, off, len);
  6143. });
  6144. };
  6145. return callback(std::move(out));
  6146. } else {
  6147. status = StatusCode::InternalServerError_500;
  6148. return false;
  6149. }
  6150. }
  6151. }
  6152. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  6153. size_t len) {
  6154. return receiver(buf, n, off, len);
  6155. };
  6156. return callback(std::move(out));
  6157. }
  6158. template <typename T>
  6159. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  6160. DownloadProgress progress,
  6161. ContentReceiverWithProgress receiver, bool decompress) {
  6162. bool exceed_payload_max_length = false;
  6163. return prepare_content_receiver(
  6164. x, status, std::move(receiver), decompress, payload_max_length,
  6165. exceed_payload_max_length, [&](const ContentReceiverWithProgress &out) {
  6166. auto ret = true;
  6167. // Note: exceed_payload_max_length may also be set by the decompressor
  6168. // wrapper in prepare_content_receiver when the decompressed payload
  6169. // size exceeds the limit.
  6170. if (is_chunked_transfer_encoding(x.headers)) {
  6171. auto result = read_content_chunked(strm, x, 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 if (!has_header(x.headers, "Content-Length")) {
  6181. auto result =
  6182. read_content_without_length(strm, payload_max_length, out);
  6183. if (result == ReadContentResult::Success) {
  6184. ret = true;
  6185. } else if (result == ReadContentResult::PayloadTooLarge) {
  6186. exceed_payload_max_length = true;
  6187. ret = false;
  6188. } else {
  6189. ret = false;
  6190. }
  6191. } else {
  6192. auto is_invalid_value = false;
  6193. auto len = get_header_value_u64(x.headers, "Content-Length",
  6194. (std::numeric_limits<size_t>::max)(),
  6195. 0, is_invalid_value);
  6196. if (is_invalid_value) {
  6197. ret = false;
  6198. } else if (len > 0) {
  6199. auto result = read_content_with_length(
  6200. strm, len, std::move(progress), out, payload_max_length);
  6201. ret = (result == ReadContentResult::Success);
  6202. if (result == ReadContentResult::PayloadTooLarge) {
  6203. exceed_payload_max_length = true;
  6204. }
  6205. }
  6206. }
  6207. if (!ret) {
  6208. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  6209. : StatusCode::BadRequest_400;
  6210. }
  6211. return ret;
  6212. });
  6213. }
  6214. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  6215. const std::string &path) {
  6216. std::string s = method;
  6217. s += ' ';
  6218. s += path;
  6219. s += " HTTP/1.1\r\n";
  6220. return strm.write(s.data(), s.size());
  6221. }
  6222. inline ssize_t write_response_line(Stream &strm, int status) {
  6223. std::string s = "HTTP/1.1 ";
  6224. s += std::to_string(status);
  6225. s += ' ';
  6226. s += httplib::status_message(status);
  6227. s += "\r\n";
  6228. return strm.write(s.data(), s.size());
  6229. }
  6230. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  6231. ssize_t write_len = 0;
  6232. for (const auto &x : headers) {
  6233. std::string s;
  6234. s = x.first;
  6235. s += ": ";
  6236. s += x.second;
  6237. s += "\r\n";
  6238. auto len = strm.write(s.data(), s.size());
  6239. if (len < 0) { return len; }
  6240. write_len += len;
  6241. }
  6242. auto len = strm.write("\r\n");
  6243. if (len < 0) { return len; }
  6244. write_len += len;
  6245. return write_len;
  6246. }
  6247. inline bool write_data(Stream &strm, const char *d, size_t l) {
  6248. size_t offset = 0;
  6249. while (offset < l) {
  6250. auto length = strm.write(d + offset, l - offset);
  6251. if (length < 0) { return false; }
  6252. offset += static_cast<size_t>(length);
  6253. }
  6254. return true;
  6255. }
  6256. template <typename T>
  6257. inline bool write_content_with_progress(Stream &strm,
  6258. const ContentProvider &content_provider,
  6259. size_t offset, size_t length,
  6260. T is_shutting_down,
  6261. const UploadProgress &upload_progress,
  6262. Error &error) {
  6263. size_t end_offset = offset + length;
  6264. size_t start_offset = offset;
  6265. auto ok = true;
  6266. DataSink data_sink;
  6267. data_sink.write = [&](const char *d, size_t l) -> bool {
  6268. if (ok) {
  6269. if (write_data(strm, d, l)) {
  6270. offset += l;
  6271. if (upload_progress && length > 0) {
  6272. size_t current_written = offset - start_offset;
  6273. if (!upload_progress(current_written, length)) {
  6274. ok = false;
  6275. return false;
  6276. }
  6277. }
  6278. } else {
  6279. ok = false;
  6280. }
  6281. }
  6282. return ok;
  6283. };
  6284. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6285. while (offset < end_offset && !is_shutting_down()) {
  6286. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6287. error = Error::Write;
  6288. return false;
  6289. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  6290. error = Error::Canceled;
  6291. return false;
  6292. } else if (!ok) {
  6293. error = Error::Write;
  6294. return false;
  6295. }
  6296. }
  6297. if (offset < end_offset) { // exited due to is_shutting_down(), not completion
  6298. error = Error::Write;
  6299. return false;
  6300. }
  6301. error = Error::Success;
  6302. return true;
  6303. }
  6304. template <typename T>
  6305. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6306. size_t offset, size_t length, T is_shutting_down,
  6307. Error &error) {
  6308. return write_content_with_progress<T>(strm, content_provider, offset, length,
  6309. is_shutting_down, nullptr, error);
  6310. }
  6311. template <typename T>
  6312. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  6313. size_t offset, size_t length,
  6314. const T &is_shutting_down) {
  6315. auto error = Error::Success;
  6316. return write_content(strm, content_provider, offset, length, is_shutting_down,
  6317. error);
  6318. }
  6319. template <typename T>
  6320. inline bool
  6321. write_content_without_length(Stream &strm,
  6322. const ContentProvider &content_provider,
  6323. const T &is_shutting_down) {
  6324. size_t offset = 0;
  6325. auto data_available = true;
  6326. auto ok = true;
  6327. DataSink data_sink;
  6328. data_sink.write = [&](const char *d, size_t l) -> bool {
  6329. if (ok) {
  6330. offset += l;
  6331. if (!write_data(strm, d, l)) { ok = false; }
  6332. }
  6333. return ok;
  6334. };
  6335. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6336. data_sink.done = [&](void) { data_available = false; };
  6337. while (data_available && !is_shutting_down()) {
  6338. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6339. return false;
  6340. } else if (!content_provider(offset, 0, data_sink)) {
  6341. return false;
  6342. } else if (!ok) {
  6343. return false;
  6344. }
  6345. }
  6346. return !data_available; // true only if done() was called, false if shutting
  6347. // down
  6348. }
  6349. template <typename T, typename U>
  6350. inline bool
  6351. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  6352. const T &is_shutting_down, U &compressor, Error &error) {
  6353. size_t offset = 0;
  6354. auto data_available = true;
  6355. auto ok = true;
  6356. DataSink data_sink;
  6357. data_sink.write = [&](const char *d, size_t l) -> bool {
  6358. if (ok) {
  6359. data_available = l > 0;
  6360. offset += l;
  6361. std::string payload;
  6362. if (compressor.compress(d, l, false,
  6363. [&](const char *data, size_t data_len) {
  6364. payload.append(data, data_len);
  6365. return true;
  6366. })) {
  6367. if (!payload.empty()) {
  6368. // Emit chunked response header and footer for each chunk
  6369. auto chunk =
  6370. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6371. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  6372. }
  6373. } else {
  6374. ok = false;
  6375. }
  6376. }
  6377. return ok;
  6378. };
  6379. data_sink.is_writable = [&]() -> bool { return strm.is_peer_alive(); };
  6380. auto done_with_trailer = [&](const Headers *trailer) {
  6381. if (!ok) { return; }
  6382. data_available = false;
  6383. std::string payload;
  6384. if (!compressor.compress(nullptr, 0, true,
  6385. [&](const char *data, size_t data_len) {
  6386. payload.append(data, data_len);
  6387. return true;
  6388. })) {
  6389. ok = false;
  6390. return;
  6391. }
  6392. if (!payload.empty()) {
  6393. // Emit chunked response header and footer for each chunk
  6394. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  6395. if (!write_data(strm, chunk.data(), chunk.size())) {
  6396. ok = false;
  6397. return;
  6398. }
  6399. }
  6400. constexpr const char done_marker[] = "0\r\n";
  6401. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  6402. // Trailer
  6403. if (trailer) {
  6404. for (const auto &kv : *trailer) {
  6405. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  6406. if (!write_data(strm, field_line.data(), field_line.size())) {
  6407. ok = false;
  6408. }
  6409. }
  6410. }
  6411. constexpr const char crlf[] = "\r\n";
  6412. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  6413. };
  6414. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  6415. data_sink.done_with_trailer = [&](const Headers &trailer) {
  6416. done_with_trailer(&trailer);
  6417. };
  6418. while (data_available && !is_shutting_down()) {
  6419. if (!strm.wait_writable() || !strm.is_peer_alive()) {
  6420. error = Error::Write;
  6421. return false;
  6422. } else if (!content_provider(offset, 0, data_sink)) {
  6423. error = Error::Canceled;
  6424. return false;
  6425. } else if (!ok) {
  6426. error = Error::Write;
  6427. return false;
  6428. }
  6429. }
  6430. if (data_available) { // exited due to is_shutting_down(), not done()
  6431. error = Error::Write;
  6432. return false;
  6433. }
  6434. error = Error::Success;
  6435. return true;
  6436. }
  6437. template <typename T, typename U>
  6438. inline bool write_content_chunked(Stream &strm,
  6439. const ContentProvider &content_provider,
  6440. const T &is_shutting_down, U &compressor) {
  6441. auto error = Error::Success;
  6442. return write_content_chunked(strm, content_provider, is_shutting_down,
  6443. compressor, error);
  6444. }
  6445. template <typename T>
  6446. inline bool redirect(T &cli, Request &req, Response &res,
  6447. const std::string &path, const std::string &location,
  6448. Error &error) {
  6449. Request new_req = req;
  6450. new_req.path = path;
  6451. new_req.redirect_count_ -= 1;
  6452. if (res.status == StatusCode::SeeOther_303 &&
  6453. (req.method != "GET" && req.method != "HEAD")) {
  6454. new_req.method = "GET";
  6455. new_req.body.clear();
  6456. new_req.headers.clear();
  6457. }
  6458. Response new_res;
  6459. auto ret = cli.send(new_req, new_res, error);
  6460. if (ret) {
  6461. req = std::move(new_req);
  6462. res = std::move(new_res);
  6463. if (res.location.empty()) { res.location = location; }
  6464. }
  6465. return ret;
  6466. }
  6467. inline std::string params_to_query_str(const Params &params) {
  6468. std::string query;
  6469. for (auto it = params.begin(); it != params.end(); ++it) {
  6470. if (it != params.begin()) { query += '&'; }
  6471. query += encode_query_component(it->first);
  6472. query += '=';
  6473. query += encode_query_component(it->second);
  6474. }
  6475. return query;
  6476. }
  6477. inline void parse_query_text(const char *data, std::size_t size,
  6478. Params &params) {
  6479. std::set<std::string> cache;
  6480. split(data, data + size, '&', [&](const char *b, const char *e) {
  6481. std::string kv(b, e);
  6482. if (cache.find(kv) != cache.end()) { return; }
  6483. cache.insert(std::move(kv));
  6484. std::string key;
  6485. std::string val;
  6486. divide(b, static_cast<std::size_t>(e - b), '=',
  6487. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  6488. std::size_t rhs_size) {
  6489. key.assign(lhs_data, lhs_size);
  6490. val.assign(rhs_data, rhs_size);
  6491. });
  6492. if (!key.empty()) {
  6493. params.emplace(decode_query_component(key), decode_query_component(val));
  6494. }
  6495. });
  6496. }
  6497. inline void parse_query_text(const std::string &s, Params &params) {
  6498. parse_query_text(s.data(), s.size(), params);
  6499. }
  6500. // Normalize a query string by decoding and re-encoding each key/value pair
  6501. // while preserving the original parameter order. This avoids double-encoding
  6502. // and ensures consistent encoding without reordering (unlike Params which
  6503. // uses std::multimap and sorts keys).
  6504. inline std::string normalize_query_string(const std::string &query) {
  6505. std::string result;
  6506. split(query.data(), query.data() + query.size(), '&',
  6507. [&](const char *b, const char *e) {
  6508. std::string key;
  6509. std::string val;
  6510. divide(b, static_cast<std::size_t>(e - b), '=',
  6511. [&](const char *lhs_data, std::size_t lhs_size,
  6512. const char *rhs_data, std::size_t rhs_size) {
  6513. key.assign(lhs_data, lhs_size);
  6514. val.assign(rhs_data, rhs_size);
  6515. });
  6516. if (!key.empty()) {
  6517. auto dec_key = decode_query_component(key);
  6518. auto dec_val = decode_query_component(val);
  6519. if (!result.empty()) { result += '&'; }
  6520. result += encode_query_component(dec_key);
  6521. if (!val.empty() || std::find(b, e, '=') != e) {
  6522. result += '=';
  6523. result += encode_query_component(dec_val);
  6524. }
  6525. }
  6526. });
  6527. return result;
  6528. }
  6529. inline bool parse_multipart_boundary(const std::string &content_type,
  6530. std::string &boundary) {
  6531. std::map<std::string, std::string> params;
  6532. extract_media_type(content_type, &params);
  6533. auto it = params.find("boundary");
  6534. if (it == params.end()) { return false; }
  6535. boundary = it->second;
  6536. return !boundary.empty();
  6537. }
  6538. inline void parse_disposition_params(const std::string &s, Params &params) {
  6539. std::set<std::string> cache;
  6540. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  6541. std::string kv(b, e);
  6542. if (cache.find(kv) != cache.end()) { return; }
  6543. cache.insert(kv);
  6544. std::string key;
  6545. std::string val;
  6546. split(b, e, '=', [&](const char *b2, const char *e2) {
  6547. if (key.empty()) {
  6548. key.assign(b2, e2);
  6549. } else {
  6550. val.assign(b2, e2);
  6551. }
  6552. });
  6553. if (!key.empty()) {
  6554. params.emplace(trim_double_quotes_copy((key)),
  6555. trim_double_quotes_copy((val)));
  6556. }
  6557. });
  6558. }
  6559. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6560. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  6561. #else
  6562. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  6563. #endif
  6564. auto is_valid = [](const std::string &str) {
  6565. return std::all_of(str.cbegin(), str.cend(), is_ascii_digit);
  6566. };
  6567. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  6568. const auto pos = static_cast<size_t>(6);
  6569. const auto len = static_cast<size_t>(s.size() - 6);
  6570. auto all_valid_ranges = true;
  6571. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  6572. if (!all_valid_ranges) { return; }
  6573. const auto it = std::find(b, e, '-');
  6574. if (it == e) {
  6575. all_valid_ranges = false;
  6576. return;
  6577. }
  6578. const auto lhs = std::string(b, it);
  6579. const auto rhs = std::string(it + 1, e);
  6580. if (!is_valid(lhs) || !is_valid(rhs)) {
  6581. all_valid_ranges = false;
  6582. return;
  6583. }
  6584. ssize_t first = -1;
  6585. if (!lhs.empty()) {
  6586. ssize_t v;
  6587. auto res = detail::from_chars(lhs.data(), lhs.data() + lhs.size(), v);
  6588. if (res.ec == std::errc{}) { first = v; }
  6589. }
  6590. ssize_t last = -1;
  6591. if (!rhs.empty()) {
  6592. ssize_t v;
  6593. auto res = detail::from_chars(rhs.data(), rhs.data() + rhs.size(), v);
  6594. if (res.ec == std::errc{}) { last = v; }
  6595. }
  6596. if ((first == -1 && last == -1) ||
  6597. (first != -1 && last != -1 && first > last)) {
  6598. all_valid_ranges = false;
  6599. return;
  6600. }
  6601. ranges.emplace_back(first, last);
  6602. });
  6603. return all_valid_ranges && !ranges.empty();
  6604. }
  6605. return false;
  6606. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6607. }
  6608. #else
  6609. } catch (...) { return false; }
  6610. #endif
  6611. inline bool parse_accept_header(const std::string &s,
  6612. std::vector<std::string> &content_types) {
  6613. content_types.clear();
  6614. // Empty string is considered valid (no preference)
  6615. if (s.empty()) { return true; }
  6616. // Check for invalid patterns: leading/trailing commas or consecutive commas
  6617. if (s.front() == ',' || s.back() == ',' ||
  6618. s.find(",,") != std::string::npos) {
  6619. return false;
  6620. }
  6621. struct AcceptEntry {
  6622. std::string media_type;
  6623. double quality;
  6624. int order;
  6625. };
  6626. std::vector<AcceptEntry> entries;
  6627. int order = 0;
  6628. bool has_invalid_entry = false;
  6629. // Split by comma and parse each entry
  6630. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  6631. std::string entry(b, e);
  6632. entry = trim_copy(entry);
  6633. if (entry.empty()) {
  6634. has_invalid_entry = true;
  6635. return;
  6636. }
  6637. AcceptEntry accept_entry;
  6638. accept_entry.order = order++;
  6639. if (!parse_quality(entry.data(), entry.data() + entry.size(),
  6640. accept_entry.media_type, accept_entry.quality)) {
  6641. has_invalid_entry = true;
  6642. return;
  6643. }
  6644. // Remove additional parameters from media type
  6645. accept_entry.media_type = extract_media_type(accept_entry.media_type);
  6646. // Basic validation of media type format
  6647. if (accept_entry.media_type.empty()) {
  6648. has_invalid_entry = true;
  6649. return;
  6650. }
  6651. // Check for basic media type format (should contain '/' or be '*')
  6652. if (accept_entry.media_type != "*" &&
  6653. accept_entry.media_type.find('/') == std::string::npos) {
  6654. has_invalid_entry = true;
  6655. return;
  6656. }
  6657. entries.push_back(std::move(accept_entry));
  6658. });
  6659. // Return false if any invalid entry was found
  6660. if (has_invalid_entry) { return false; }
  6661. // Sort by quality (descending), then by original order (ascending)
  6662. std::sort(entries.begin(), entries.end(),
  6663. [](const AcceptEntry &a, const AcceptEntry &b) {
  6664. if (a.quality != b.quality) {
  6665. return a.quality > b.quality; // Higher quality first
  6666. }
  6667. return a.order < b.order; // Earlier order first for same quality
  6668. });
  6669. // Extract sorted media types
  6670. content_types.reserve(entries.size());
  6671. for (auto &entry : entries) {
  6672. content_types.push_back(std::move(entry.media_type));
  6673. }
  6674. return true;
  6675. }
  6676. class FormDataParser {
  6677. public:
  6678. FormDataParser() = default;
  6679. void set_boundary(std::string &&boundary) {
  6680. boundary_ = std::move(boundary);
  6681. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  6682. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  6683. }
  6684. bool is_valid() const { return is_valid_; }
  6685. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  6686. const ContentReceiver &content_callback) {
  6687. buf_append(buf, n);
  6688. while (buf_size() > 0) {
  6689. switch (state_) {
  6690. case 0: { // Initial boundary
  6691. auto pos = buf_find(dash_boundary_crlf_);
  6692. if (pos == buf_size()) { return true; }
  6693. buf_erase(pos + dash_boundary_crlf_.size());
  6694. state_ = 1;
  6695. break;
  6696. }
  6697. case 1: { // New entry
  6698. clear_file_info();
  6699. state_ = 2;
  6700. break;
  6701. }
  6702. case 2: { // Headers
  6703. auto pos = buf_find(crlf_);
  6704. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  6705. while (pos < buf_size()) {
  6706. // Empty line
  6707. if (pos == 0) {
  6708. if (!header_callback(file_)) {
  6709. is_valid_ = false;
  6710. return false;
  6711. }
  6712. buf_erase(crlf_.size());
  6713. state_ = 3;
  6714. break;
  6715. }
  6716. const auto header = buf_head(pos);
  6717. if (!parse_header(header.data(), header.data() + header.size(),
  6718. [&](const std::string &, const std::string &) {})) {
  6719. is_valid_ = false;
  6720. return false;
  6721. }
  6722. // Parse and emplace space trimmed headers into a map
  6723. if (!parse_header(
  6724. header.data(), header.data() + header.size(),
  6725. [&](const std::string &key, const std::string &val) {
  6726. file_.headers.emplace(key, val);
  6727. })) {
  6728. is_valid_ = false;
  6729. return false;
  6730. }
  6731. constexpr const char header_content_type[] = "Content-Type:";
  6732. if (start_with_case_ignore(header, header_content_type)) {
  6733. file_.content_type =
  6734. trim_copy(header.substr(str_len(header_content_type)));
  6735. } else {
  6736. std::string disposition_params;
  6737. if (parse_content_disposition(header, disposition_params)) {
  6738. Params params;
  6739. parse_disposition_params(disposition_params, params);
  6740. auto it = params.find("name");
  6741. if (it != params.end()) {
  6742. file_.name = it->second;
  6743. } else {
  6744. is_valid_ = false;
  6745. return false;
  6746. }
  6747. it = params.find("filename");
  6748. if (it != params.end()) { file_.filename = it->second; }
  6749. it = params.find("filename*");
  6750. if (it != params.end()) {
  6751. // RFC 5987: only UTF-8 encoding is allowed
  6752. const auto &val = it->second;
  6753. constexpr const char utf8_prefix[] = "UTF-8''";
  6754. constexpr size_t prefix_len = str_len(utf8_prefix);
  6755. if (val.size() > prefix_len &&
  6756. start_with_case_ignore(val, utf8_prefix)) {
  6757. file_.filename = decode_path_component(
  6758. val.substr(prefix_len)); // override...
  6759. } else {
  6760. is_valid_ = false;
  6761. return false;
  6762. }
  6763. }
  6764. }
  6765. }
  6766. buf_erase(pos + crlf_.size());
  6767. pos = buf_find(crlf_);
  6768. }
  6769. if (state_ != 3) { return true; }
  6770. break;
  6771. }
  6772. case 3: { // Body
  6773. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  6774. auto pos = buf_find(crlf_dash_boundary_);
  6775. if (pos < buf_size()) {
  6776. if (!content_callback(buf_data(), pos)) {
  6777. is_valid_ = false;
  6778. return false;
  6779. }
  6780. buf_erase(pos + crlf_dash_boundary_.size());
  6781. state_ = 4;
  6782. } else {
  6783. auto len = buf_size() - crlf_dash_boundary_.size();
  6784. if (len > 0) {
  6785. if (!content_callback(buf_data(), len)) {
  6786. is_valid_ = false;
  6787. return false;
  6788. }
  6789. buf_erase(len);
  6790. }
  6791. return true;
  6792. }
  6793. break;
  6794. }
  6795. case 4: { // Boundary
  6796. if (crlf_.size() > buf_size()) { return true; }
  6797. if (buf_start_with(crlf_)) {
  6798. buf_erase(crlf_.size());
  6799. state_ = 1;
  6800. } else {
  6801. if (dash_.size() > buf_size()) { return true; }
  6802. if (buf_start_with(dash_)) {
  6803. buf_erase(dash_.size());
  6804. is_valid_ = true;
  6805. buf_erase(buf_size()); // Remove epilogue
  6806. } else {
  6807. return true;
  6808. }
  6809. }
  6810. break;
  6811. }
  6812. }
  6813. }
  6814. return true;
  6815. }
  6816. private:
  6817. void clear_file_info() {
  6818. file_.name.clear();
  6819. file_.filename.clear();
  6820. file_.content_type.clear();
  6821. file_.headers.clear();
  6822. }
  6823. bool start_with_case_ignore(const std::string &a, const char *b,
  6824. size_t offset = 0) const {
  6825. const auto b_len = strlen(b);
  6826. if (a.size() < offset + b_len) { return false; }
  6827. for (size_t i = 0; i < b_len; i++) {
  6828. if (case_ignore::to_lower(a[offset + i]) != case_ignore::to_lower(b[i])) {
  6829. return false;
  6830. }
  6831. }
  6832. return true;
  6833. }
  6834. // Parses "Content-Disposition: form-data; <params>" without std::regex.
  6835. // Returns true if header matches, with the params portion in `params_out`.
  6836. bool parse_content_disposition(const std::string &header,
  6837. std::string &params_out) const {
  6838. constexpr const char prefix[] = "Content-Disposition:";
  6839. constexpr size_t prefix_len = str_len(prefix);
  6840. if (!start_with_case_ignore(header, prefix)) { return false; }
  6841. // Skip whitespace after "Content-Disposition:"
  6842. auto pos = prefix_len;
  6843. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6844. pos++;
  6845. }
  6846. // Match "form-data;" (case-insensitive)
  6847. constexpr const char form_data[] = "form-data;";
  6848. constexpr size_t form_data_len = str_len(form_data);
  6849. if (!start_with_case_ignore(header, form_data, pos)) { return false; }
  6850. pos += form_data_len;
  6851. // Skip whitespace after "form-data;"
  6852. while (pos < header.size() && (header[pos] == ' ' || header[pos] == '\t')) {
  6853. pos++;
  6854. }
  6855. params_out = header.substr(pos);
  6856. return true;
  6857. }
  6858. const std::string dash_ = "--";
  6859. const std::string crlf_ = "\r\n";
  6860. std::string boundary_;
  6861. std::string dash_boundary_crlf_;
  6862. std::string crlf_dash_boundary_;
  6863. size_t state_ = 0;
  6864. bool is_valid_ = false;
  6865. FormData file_;
  6866. // Buffer
  6867. bool start_with(const std::string &a, size_t spos, size_t epos,
  6868. const std::string &b) const {
  6869. if (epos - spos < b.size()) { return false; }
  6870. for (size_t i = 0; i < b.size(); i++) {
  6871. if (a[i + spos] != b[i]) { return false; }
  6872. }
  6873. return true;
  6874. }
  6875. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  6876. const char *buf_data() const { return &buf_[buf_spos_]; }
  6877. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  6878. bool buf_start_with(const std::string &s) const {
  6879. return start_with(buf_, buf_spos_, buf_epos_, s);
  6880. }
  6881. size_t buf_find(const std::string &s) const {
  6882. auto c = s.front();
  6883. size_t off = buf_spos_;
  6884. while (off < buf_epos_) {
  6885. auto pos = off;
  6886. while (true) {
  6887. if (pos == buf_epos_) { return buf_size(); }
  6888. if (buf_[pos] == c) { break; }
  6889. pos++;
  6890. }
  6891. auto remaining_size = buf_epos_ - pos;
  6892. if (s.size() > remaining_size) { return buf_size(); }
  6893. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  6894. off = pos + 1;
  6895. }
  6896. return buf_size();
  6897. }
  6898. void buf_append(const char *data, size_t n) {
  6899. auto remaining_size = buf_size();
  6900. if (remaining_size > 0 && buf_spos_ > 0) {
  6901. for (size_t i = 0; i < remaining_size; i++) {
  6902. buf_[i] = buf_[buf_spos_ + i];
  6903. }
  6904. }
  6905. buf_spos_ = 0;
  6906. buf_epos_ = remaining_size;
  6907. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  6908. for (size_t i = 0; i < n; i++) {
  6909. buf_[buf_epos_ + i] = data[i];
  6910. }
  6911. buf_epos_ += n;
  6912. }
  6913. void buf_erase(size_t size) { buf_spos_ += size; }
  6914. std::string buf_;
  6915. size_t buf_spos_ = 0;
  6916. size_t buf_epos_ = 0;
  6917. };
  6918. inline std::string random_string(size_t length) {
  6919. constexpr const char data[] =
  6920. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  6921. thread_local auto engine([]() {
  6922. // std::random_device might actually be deterministic on some
  6923. // platforms, but due to lack of support in the c++ standard library,
  6924. // doing better requires either some ugly hacks or breaking portability.
  6925. std::random_device seed_gen;
  6926. // Request 128 bits of entropy for initialization
  6927. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  6928. return std::mt19937(seed_sequence);
  6929. }());
  6930. std::string result;
  6931. for (size_t i = 0; i < length; i++) {
  6932. result += data[engine() % (sizeof(data) - 1)];
  6933. }
  6934. return result;
  6935. }
  6936. inline std::string make_multipart_data_boundary() {
  6937. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  6938. }
  6939. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  6940. auto valid = true;
  6941. for (size_t i = 0; i < boundary.size(); i++) {
  6942. auto c = boundary[i];
  6943. if (!is_ascii_alnum(c) && c != '-' && c != '_') {
  6944. valid = false;
  6945. break;
  6946. }
  6947. }
  6948. return valid;
  6949. }
  6950. // Escape a multipart field name/filename following the WHATWG HTML standard
  6951. // ("escape a multipart form-data name"), which is what browsers send:
  6952. // '"' -> %22, CR -> %0D, LF -> %0A
  6953. // With escape_quote = false, only CR and LF are escaped; this is for header
  6954. // values outside a quoted-string (e.g. Content-Type), where '"' is legal.
  6955. inline std::string escape_multipart_field(const std::string &s,
  6956. bool escape_quote = true) {
  6957. std::string result;
  6958. result.reserve(s.size());
  6959. for (auto c : s) {
  6960. switch (c) {
  6961. case '"':
  6962. if (escape_quote) {
  6963. result += "%22";
  6964. } else {
  6965. result += c;
  6966. }
  6967. break;
  6968. case '\r': result += "%0D"; break;
  6969. case '\n': result += "%0A"; break;
  6970. default: result += c; break;
  6971. }
  6972. }
  6973. return result;
  6974. }
  6975. template <typename T>
  6976. inline std::string
  6977. serialize_multipart_formdata_item_begin(const T &item,
  6978. const std::string &boundary) {
  6979. std::string body = "--" + boundary + "\r\n";
  6980. body += "Content-Disposition: form-data; name=\"" +
  6981. escape_multipart_field(item.name) + "\"";
  6982. if (!item.filename.empty()) {
  6983. body += "; filename=\"" + escape_multipart_field(item.filename) + "\"";
  6984. }
  6985. body += "\r\n";
  6986. if (!item.content_type.empty()) {
  6987. body +=
  6988. "Content-Type: " + escape_multipart_field(item.content_type, false) +
  6989. "\r\n";
  6990. }
  6991. body += "\r\n";
  6992. return body;
  6993. }
  6994. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  6995. inline std::string
  6996. serialize_multipart_formdata_finish(const std::string &boundary) {
  6997. return "--" + boundary + "--\r\n";
  6998. }
  6999. inline std::string
  7000. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  7001. return "multipart/form-data; boundary=" + boundary;
  7002. }
  7003. inline std::string
  7004. serialize_multipart_formdata(const UploadFormDataItems &items,
  7005. const std::string &boundary, bool finish = true) {
  7006. std::string body;
  7007. for (const auto &item : items) {
  7008. body += serialize_multipart_formdata_item_begin(item, boundary);
  7009. body += item.content + serialize_multipart_formdata_item_end();
  7010. }
  7011. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  7012. return body;
  7013. }
  7014. inline size_t get_multipart_content_length(const UploadFormDataItems &items,
  7015. const std::string &boundary) {
  7016. size_t total = 0;
  7017. for (const auto &item : items) {
  7018. total += serialize_multipart_formdata_item_begin(item, boundary).size();
  7019. total += item.content.size();
  7020. total += serialize_multipart_formdata_item_end().size();
  7021. }
  7022. total += serialize_multipart_formdata_finish(boundary).size();
  7023. return total;
  7024. }
  7025. struct MultipartSegment {
  7026. const char *data;
  7027. size_t size;
  7028. };
  7029. // NOTE: items must outlive the returned ContentProvider
  7030. // (safe for synchronous use inside Post/Put/Patch)
  7031. inline ContentProvider
  7032. make_multipart_content_provider(const UploadFormDataItems &items,
  7033. const std::string &boundary) {
  7034. // Own the per-item header strings and the finish string
  7035. std::vector<std::string> owned;
  7036. owned.reserve(items.size() + 1);
  7037. for (const auto &item : items)
  7038. owned.push_back(serialize_multipart_formdata_item_begin(item, boundary));
  7039. owned.push_back(serialize_multipart_formdata_finish(boundary));
  7040. // Flat segment list: [header, content, "\r\n"] * N + [finish]
  7041. std::vector<MultipartSegment> segs;
  7042. segs.reserve(items.size() * 3 + 1);
  7043. static const char crlf[] = "\r\n";
  7044. for (size_t i = 0; i < items.size(); i++) {
  7045. segs.push_back({owned[i].data(), owned[i].size()});
  7046. segs.push_back({items[i].content.data(), items[i].content.size()});
  7047. segs.push_back({crlf, 2});
  7048. }
  7049. segs.push_back({owned.back().data(), owned.back().size()});
  7050. struct MultipartState {
  7051. std::vector<std::string> owned;
  7052. std::vector<MultipartSegment> segs;
  7053. std::vector<char> buf = std::vector<char>(CPPHTTPLIB_SEND_BUFSIZ);
  7054. };
  7055. auto state = std::make_shared<MultipartState>();
  7056. state->owned = std::move(owned);
  7057. // `segs` holds raw pointers into owned strings; std::string move preserves
  7058. // the data pointer, so these pointers remain valid after the move above.
  7059. state->segs = std::move(segs);
  7060. return [state](size_t offset, size_t length, DataSink &sink) -> bool {
  7061. // Buffer multiple small segments into fewer, larger writes to avoid
  7062. // excessive TCP packets when there are many form data items (#2410)
  7063. auto &buf = state->buf;
  7064. auto buf_size = buf.size();
  7065. size_t buf_len = 0;
  7066. size_t remaining = length;
  7067. // Find the first segment containing 'offset'
  7068. size_t pos = 0;
  7069. size_t seg_idx = 0;
  7070. for (; seg_idx < state->segs.size(); seg_idx++) {
  7071. const auto &seg = state->segs[seg_idx];
  7072. if (seg.size > 0 && offset - pos < seg.size) { break; }
  7073. pos += seg.size;
  7074. }
  7075. size_t seg_offset = (seg_idx < state->segs.size()) ? offset - pos : 0;
  7076. for (; seg_idx < state->segs.size() && remaining > 0; seg_idx++) {
  7077. const auto &seg = state->segs[seg_idx];
  7078. size_t available = seg.size - seg_offset;
  7079. size_t to_copy = (std::min)(available, remaining);
  7080. const char *src = seg.data + seg_offset;
  7081. seg_offset = 0; // only the first segment has a non-zero offset
  7082. while (to_copy > 0) {
  7083. size_t space = buf_size - buf_len;
  7084. size_t chunk = (std::min)(to_copy, space);
  7085. std::memcpy(buf.data() + buf_len, src, chunk);
  7086. buf_len += chunk;
  7087. src += chunk;
  7088. to_copy -= chunk;
  7089. remaining -= chunk;
  7090. if (buf_len == buf_size) {
  7091. if (!sink.write(buf.data(), buf_len)) { return false; }
  7092. buf_len = 0;
  7093. }
  7094. }
  7095. }
  7096. if (buf_len > 0) { return sink.write(buf.data(), buf_len); }
  7097. return true;
  7098. };
  7099. }
  7100. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  7101. if (ranges.size() <= 1) return;
  7102. // Sort ranges by start position
  7103. std::sort(ranges.begin(), ranges.end(),
  7104. [](const Range &a, const Range &b) { return a.first < b.first; });
  7105. Ranges coalesced;
  7106. coalesced.reserve(ranges.size());
  7107. for (auto &r : ranges) {
  7108. auto first_pos = r.first;
  7109. auto last_pos = r.second;
  7110. // Handle special cases like in range_error
  7111. if (first_pos == -1 && last_pos == -1) {
  7112. first_pos = 0;
  7113. last_pos = static_cast<ssize_t>(content_length);
  7114. }
  7115. if (first_pos == -1) {
  7116. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  7117. last_pos = static_cast<ssize_t>(content_length) - 1;
  7118. }
  7119. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  7120. last_pos = static_cast<ssize_t>(content_length) - 1;
  7121. }
  7122. // Skip invalid ranges
  7123. if (!(0 <= first_pos && first_pos <= last_pos &&
  7124. last_pos < static_cast<ssize_t>(content_length))) {
  7125. continue;
  7126. }
  7127. // Coalesce with previous range if overlapping or adjacent (but not
  7128. // identical)
  7129. if (!coalesced.empty()) {
  7130. auto &prev = coalesced.back();
  7131. // Check if current range overlaps or is adjacent to previous range
  7132. // but don't coalesce identical ranges (allow duplicates)
  7133. if (first_pos <= prev.second + 1 &&
  7134. !(first_pos == prev.first && last_pos == prev.second)) {
  7135. // Extend the previous range
  7136. prev.second = (std::max)(prev.second, last_pos);
  7137. continue;
  7138. }
  7139. }
  7140. // Add new range
  7141. coalesced.emplace_back(first_pos, last_pos);
  7142. }
  7143. ranges = std::move(coalesced);
  7144. }
  7145. inline bool range_error(Request &req, Response &res) {
  7146. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  7147. if (res.body.empty() && res.content_provider_ && res.content_length_ == 0) {
  7148. req.ranges.clear();
  7149. if (res.status == StatusCode::PartialContent_206) {
  7150. res.status = StatusCode::OK_200;
  7151. }
  7152. return false;
  7153. }
  7154. ssize_t content_len = static_cast<ssize_t>(
  7155. res.content_length_ ? res.content_length_ : res.body.size());
  7156. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  7157. size_t overwrapping_count = 0;
  7158. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  7159. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  7160. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  7161. // Too many ranges
  7162. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  7163. for (auto &r : req.ranges) {
  7164. auto &first_pos = r.first;
  7165. auto &last_pos = r.second;
  7166. if (first_pos == -1 && last_pos == -1) {
  7167. first_pos = 0;
  7168. last_pos = content_len;
  7169. }
  7170. if (first_pos == -1) {
  7171. first_pos = content_len - last_pos;
  7172. last_pos = content_len - 1;
  7173. }
  7174. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  7175. // A client can limit the number of bytes requested without knowing the
  7176. // size of the selected representation. If the last-pos value is absent,
  7177. // or if the value is greater than or equal to the current length of the
  7178. // representation data, the byte range is interpreted as the remainder of
  7179. // the representation (i.e., the server replaces the value of last-pos
  7180. // with a value that is one less than the current length of the selected
  7181. // representation).
  7182. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  7183. if (last_pos == -1 || last_pos >= content_len) {
  7184. last_pos = content_len - 1;
  7185. }
  7186. // Range must be within content length
  7187. if (!(0 <= first_pos && first_pos <= last_pos &&
  7188. last_pos <= content_len - 1)) {
  7189. return true;
  7190. }
  7191. // Request must not have more than two overlapping ranges
  7192. for (const auto &processed_range : processed_ranges) {
  7193. if (!(last_pos < processed_range.first ||
  7194. first_pos > processed_range.second)) {
  7195. overwrapping_count++;
  7196. if (overwrapping_count > 2) { return true; }
  7197. break; // Only count once per range
  7198. }
  7199. }
  7200. processed_ranges.emplace_back(first_pos, last_pos);
  7201. }
  7202. // After validation, coalesce overlapping ranges as per RFC 9110
  7203. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  7204. }
  7205. return false;
  7206. }
  7207. inline std::pair<size_t, size_t>
  7208. get_range_offset_and_length(Range r, size_t content_length) {
  7209. assert(r.first != -1 && r.second != -1);
  7210. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  7211. assert(r.first <= r.second &&
  7212. r.second < static_cast<ssize_t>(content_length));
  7213. (void)(content_length);
  7214. return std::make_pair(static_cast<size_t>(r.first),
  7215. static_cast<size_t>(r.second - r.first) + 1);
  7216. }
  7217. inline std::string make_content_range_header_field(
  7218. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  7219. auto st = offset_and_length.first;
  7220. auto ed = st + offset_and_length.second - 1;
  7221. std::string field = "bytes ";
  7222. field += std::to_string(st);
  7223. field += '-';
  7224. field += std::to_string(ed);
  7225. field += '/';
  7226. field += std::to_string(content_length);
  7227. return field;
  7228. }
  7229. template <typename SToken, typename CToken, typename Content>
  7230. bool process_multipart_ranges_data(const Request &req,
  7231. const std::string &boundary,
  7232. const std::string &content_type,
  7233. size_t content_length, SToken stoken,
  7234. CToken ctoken, Content content) {
  7235. for (size_t i = 0; i < req.ranges.size(); i++) {
  7236. ctoken("--");
  7237. stoken(boundary);
  7238. ctoken("\r\n");
  7239. if (!content_type.empty()) {
  7240. ctoken("Content-Type: ");
  7241. stoken(content_type);
  7242. ctoken("\r\n");
  7243. }
  7244. auto offset_and_length =
  7245. get_range_offset_and_length(req.ranges[i], content_length);
  7246. ctoken("Content-Range: ");
  7247. stoken(make_content_range_header_field(offset_and_length, content_length));
  7248. ctoken("\r\n");
  7249. ctoken("\r\n");
  7250. if (!content(offset_and_length.first, offset_and_length.second)) {
  7251. return false;
  7252. }
  7253. ctoken("\r\n");
  7254. }
  7255. ctoken("--");
  7256. stoken(boundary);
  7257. ctoken("--");
  7258. return true;
  7259. }
  7260. inline void make_multipart_ranges_data(const Request &req, Response &res,
  7261. const std::string &boundary,
  7262. const std::string &content_type,
  7263. size_t content_length,
  7264. std::string &data) {
  7265. process_multipart_ranges_data(
  7266. req, boundary, content_type, content_length,
  7267. [&](const std::string &token) { data += token; },
  7268. [&](const std::string &token) { data += token; },
  7269. [&](size_t offset, size_t length) {
  7270. assert(offset + length <= content_length);
  7271. data += res.body.substr(offset, length);
  7272. return true;
  7273. });
  7274. }
  7275. inline size_t get_multipart_ranges_data_length(const Request &req,
  7276. const std::string &boundary,
  7277. const std::string &content_type,
  7278. size_t content_length) {
  7279. size_t data_length = 0;
  7280. process_multipart_ranges_data(
  7281. req, boundary, content_type, content_length,
  7282. [&](const std::string &token) { data_length += token.size(); },
  7283. [&](const std::string &token) { data_length += token.size(); },
  7284. [&](size_t /*offset*/, size_t length) {
  7285. data_length += length;
  7286. return true;
  7287. });
  7288. return data_length;
  7289. }
  7290. template <typename T>
  7291. inline bool
  7292. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  7293. const std::string &boundary,
  7294. const std::string &content_type,
  7295. size_t content_length, const T &is_shutting_down) {
  7296. return process_multipart_ranges_data(
  7297. req, boundary, content_type, content_length,
  7298. [&](const std::string &token) { strm.write(token); },
  7299. [&](const std::string &token) { strm.write(token); },
  7300. [&](size_t offset, size_t length) {
  7301. return write_content(strm, res.content_provider_, offset, length,
  7302. is_shutting_down);
  7303. });
  7304. }
  7305. inline bool has_framed_body(const Request &req) {
  7306. return is_chunked_transfer_encoding(req.headers) ||
  7307. req.get_header_value_u64("Content-Length") > 0;
  7308. }
  7309. inline bool is_connection_persistent(const Request &req) {
  7310. auto conn = req.get_header_value("Connection");
  7311. if (conn == "close") { return false; }
  7312. if (req.version == "HTTP/1.0" && conn != "Keep-Alive") { return false; }
  7313. return true;
  7314. }
  7315. inline bool expect_content(const Request &req) {
  7316. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  7317. req.method == "DELETE") {
  7318. return true;
  7319. }
  7320. return has_framed_body(req);
  7321. }
  7322. #ifdef _WIN32
  7323. class WSInit {
  7324. public:
  7325. WSInit() {
  7326. WSADATA wsaData;
  7327. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  7328. }
  7329. ~WSInit() {
  7330. if (is_valid_) WSACleanup();
  7331. }
  7332. bool is_valid_ = false;
  7333. };
  7334. static WSInit wsinit_;
  7335. #endif
  7336. inline bool parse_www_authenticate(const Response &res,
  7337. std::map<std::string, std::string> &auth,
  7338. bool is_proxy) {
  7339. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  7340. if (res.has_header(auth_key)) {
  7341. thread_local auto re =
  7342. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  7343. auto s = res.get_header_value(auth_key);
  7344. auto pos = s.find(' ');
  7345. if (pos != std::string::npos) {
  7346. auto type = s.substr(0, pos);
  7347. if (type == "Basic") {
  7348. return false;
  7349. } else if (type == "Digest") {
  7350. s = s.substr(pos + 1);
  7351. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  7352. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  7353. const auto &m = *i;
  7354. auto key = s.substr(static_cast<size_t>(m.position(1)),
  7355. static_cast<size_t>(m.length(1)));
  7356. auto val = m.length(2) > 0
  7357. ? s.substr(static_cast<size_t>(m.position(2)),
  7358. static_cast<size_t>(m.length(2)))
  7359. : s.substr(static_cast<size_t>(m.position(3)),
  7360. static_cast<size_t>(m.length(3)));
  7361. auth[std::move(key)] = std::move(val);
  7362. }
  7363. return true;
  7364. }
  7365. }
  7366. }
  7367. return false;
  7368. }
  7369. class ContentProviderAdapter {
  7370. public:
  7371. explicit ContentProviderAdapter(
  7372. ContentProviderWithoutLength &&content_provider)
  7373. : content_provider_(std::move(content_provider)) {}
  7374. bool operator()(size_t offset, size_t, DataSink &sink) {
  7375. return content_provider_(offset, sink);
  7376. }
  7377. private:
  7378. ContentProviderWithoutLength content_provider_;
  7379. };
  7380. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  7381. namespace fields {
  7382. inline bool is_token_char(char c) {
  7383. return is_ascii_alnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  7384. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  7385. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  7386. }
  7387. inline bool is_token(const std::string &s) {
  7388. if (s.empty()) { return false; }
  7389. for (auto c : s) {
  7390. if (!is_token_char(c)) { return false; }
  7391. }
  7392. return true;
  7393. }
  7394. inline bool is_field_name(const std::string &s) { return is_token(s); }
  7395. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  7396. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  7397. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  7398. inline bool is_field_content(const std::string &s) {
  7399. if (s.empty()) { return true; }
  7400. if (s.size() == 1) {
  7401. return is_field_vchar(s[0]);
  7402. } else if (s.size() == 2) {
  7403. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  7404. } else {
  7405. size_t i = 0;
  7406. if (!is_field_vchar(s[i])) { return false; }
  7407. i++;
  7408. while (i < s.size() - 1) {
  7409. auto c = s[i++];
  7410. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  7411. } else {
  7412. return false;
  7413. }
  7414. }
  7415. return is_field_vchar(s[i]);
  7416. }
  7417. }
  7418. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  7419. } // namespace fields
  7420. inline bool perform_websocket_handshake(Stream &strm, const std::string &host,
  7421. int port, bool is_ssl,
  7422. const std::string &path,
  7423. const Headers &headers,
  7424. std::string &selected_subprotocol) {
  7425. // Validate path and host
  7426. if (!fields::is_field_value(path) || !fields::is_field_value(host)) {
  7427. return false;
  7428. }
  7429. // Validate user-provided headers
  7430. for (const auto &h : headers) {
  7431. if (!fields::is_field_name(h.first) || !fields::is_field_value(h.second)) {
  7432. return false;
  7433. }
  7434. }
  7435. // Generate random Sec-WebSocket-Key
  7436. thread_local std::mt19937 rng(std::random_device{}());
  7437. std::string key_bytes(16, '\0');
  7438. for (size_t i = 0; i < 16; i += 4) {
  7439. auto r = rng();
  7440. std::memcpy(&key_bytes[i], &r, (std::min)(size_t(4), size_t(16 - i)));
  7441. }
  7442. auto client_key = base64_encode(key_bytes);
  7443. // Build upgrade request
  7444. std::string req_str = "GET " + path + " HTTP/1.1\r\n";
  7445. req_str += "Host: " + make_host_and_port_string(host, port, is_ssl) + "\r\n";
  7446. req_str += "Upgrade: websocket\r\n";
  7447. req_str += "Connection: Upgrade\r\n";
  7448. req_str += "Sec-WebSocket-Key: " + client_key + "\r\n";
  7449. req_str += "Sec-WebSocket-Version: 13\r\n";
  7450. for (const auto &h : headers) {
  7451. req_str += h.first + ": " + h.second + "\r\n";
  7452. }
  7453. req_str += "\r\n";
  7454. if (strm.write(req_str.data(), req_str.size()) < 0) { return false; }
  7455. // Verify 101 response and Sec-WebSocket-Accept header
  7456. auto expected_accept = websocket_accept_key(client_key);
  7457. return read_websocket_upgrade_response(strm, expected_accept,
  7458. selected_subprotocol);
  7459. }
  7460. } // namespace detail
  7461. /*
  7462. * Group 2: detail namespace - SSL common utilities
  7463. */
  7464. #ifdef CPPHTTPLIB_SSL_ENABLED
  7465. namespace detail {
  7466. class SSLSocketStream final : public Stream {
  7467. public:
  7468. SSLSocketStream(
  7469. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  7470. time_t read_timeout_usec, time_t write_timeout_sec,
  7471. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  7472. std::chrono::time_point<std::chrono::steady_clock> start_time =
  7473. (std::chrono::steady_clock::time_point::min)());
  7474. ~SSLSocketStream() override;
  7475. bool is_readable() const override;
  7476. bool wait_readable() const override;
  7477. bool wait_writable() const override;
  7478. bool is_peer_alive() const override;
  7479. ssize_t read(char *ptr, size_t size) override;
  7480. ssize_t write(const char *ptr, size_t size) override;
  7481. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  7482. void get_local_ip_and_port(std::string &ip, int &port) const override;
  7483. socket_t socket() const override;
  7484. time_t duration() const override;
  7485. void set_read_timeout(time_t sec, time_t usec = 0) override;
  7486. private:
  7487. socket_t sock_;
  7488. tls::session_t session_;
  7489. time_t read_timeout_sec_;
  7490. time_t read_timeout_usec_;
  7491. time_t write_timeout_sec_;
  7492. time_t write_timeout_usec_;
  7493. time_t max_timeout_msec_;
  7494. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  7495. };
  7496. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7497. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  7498. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  7499. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  7500. unsigned int hash_length = 0;
  7501. unsigned char hash[EVP_MAX_MD_SIZE];
  7502. EVP_DigestInit_ex(context.get(), algo, nullptr);
  7503. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  7504. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  7505. std::stringstream ss;
  7506. for (auto i = 0u; i < hash_length; ++i) {
  7507. ss << std::hex << std::setw(2) << std::setfill('0')
  7508. << static_cast<unsigned int>(hash[i]);
  7509. }
  7510. return ss.str();
  7511. }
  7512. inline std::string MD5(const std::string &s) {
  7513. return message_digest(s, EVP_md5());
  7514. }
  7515. inline std::string SHA_256(const std::string &s) {
  7516. return message_digest(s, EVP_sha256());
  7517. }
  7518. inline std::string SHA_512(const std::string &s) {
  7519. return message_digest(s, EVP_sha512());
  7520. }
  7521. #elif defined(CPPHTTPLIB_MBEDTLS_SUPPORT)
  7522. namespace {
  7523. template <size_t N>
  7524. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7525. std::stringstream ss;
  7526. for (size_t i = 0; i < N; ++i) {
  7527. ss << std::hex << std::setw(2) << std::setfill('0')
  7528. << static_cast<unsigned int>(hash[i]);
  7529. }
  7530. return ss.str();
  7531. }
  7532. } // namespace
  7533. inline std::string MD5(const std::string &s) {
  7534. unsigned char hash[16];
  7535. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7536. mbedtls_md5(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7537. hash);
  7538. #else
  7539. mbedtls_md5_ret(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7540. hash);
  7541. #endif
  7542. return hash_to_hex(hash);
  7543. }
  7544. inline std::string SHA_256(const std::string &s) {
  7545. unsigned char hash[32];
  7546. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7547. mbedtls_sha256(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7548. hash, 0);
  7549. #else
  7550. mbedtls_sha256_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7551. s.size(), hash, 0);
  7552. #endif
  7553. return hash_to_hex(hash);
  7554. }
  7555. inline std::string SHA_512(const std::string &s) {
  7556. unsigned char hash[64];
  7557. #ifdef CPPHTTPLIB_MBEDTLS_V3
  7558. mbedtls_sha512(reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
  7559. hash, 0);
  7560. #else
  7561. mbedtls_sha512_ret(reinterpret_cast<const unsigned char *>(s.c_str()),
  7562. s.size(), hash, 0);
  7563. #endif
  7564. return hash_to_hex(hash);
  7565. }
  7566. #elif defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7567. namespace {
  7568. template <size_t N>
  7569. inline std::string hash_to_hex(const unsigned char (&hash)[N]) {
  7570. std::stringstream ss;
  7571. for (size_t i = 0; i < N; ++i) {
  7572. ss << std::hex << std::setw(2) << std::setfill('0')
  7573. << static_cast<unsigned int>(hash[i]);
  7574. }
  7575. return ss.str();
  7576. }
  7577. } // namespace
  7578. inline std::string MD5(const std::string &s) {
  7579. unsigned char hash[WC_MD5_DIGEST_SIZE];
  7580. wc_Md5Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7581. static_cast<word32>(s.size()), hash);
  7582. return hash_to_hex(hash);
  7583. }
  7584. inline std::string SHA_256(const std::string &s) {
  7585. unsigned char hash[WC_SHA256_DIGEST_SIZE];
  7586. wc_Sha256Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7587. static_cast<word32>(s.size()), hash);
  7588. return hash_to_hex(hash);
  7589. }
  7590. inline std::string SHA_512(const std::string &s) {
  7591. unsigned char hash[WC_SHA512_DIGEST_SIZE];
  7592. wc_Sha512Hash(reinterpret_cast<const unsigned char *>(s.c_str()),
  7593. static_cast<word32>(s.size()), hash);
  7594. return hash_to_hex(hash);
  7595. }
  7596. #endif
  7597. inline bool is_ip_address(const std::string &host) {
  7598. struct in_addr addr4;
  7599. struct in6_addr addr6;
  7600. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  7601. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  7602. }
  7603. template <typename T>
  7604. inline bool process_server_socket_ssl(
  7605. const std::atomic<socket_t> &svr_sock, tls::session_t session,
  7606. socket_t sock, size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  7607. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  7608. time_t write_timeout_usec, T callback) {
  7609. return process_server_socket_core(
  7610. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  7611. [&](bool close_connection, bool &connection_closed) {
  7612. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7613. write_timeout_sec, write_timeout_usec);
  7614. return callback(strm, close_connection, connection_closed);
  7615. });
  7616. }
  7617. template <typename T>
  7618. inline bool process_client_socket_ssl(
  7619. tls::session_t session, socket_t sock, time_t read_timeout_sec,
  7620. time_t read_timeout_usec, time_t write_timeout_sec,
  7621. time_t write_timeout_usec, time_t max_timeout_msec,
  7622. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  7623. SSLSocketStream strm(sock, session, read_timeout_sec, read_timeout_usec,
  7624. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  7625. start_time);
  7626. return callback(strm);
  7627. }
  7628. inline std::pair<std::string, std::string> make_digest_authentication_header(
  7629. const Request &req, const std::map<std::string, std::string> &auth,
  7630. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  7631. const std::string &password, bool is_proxy = false) {
  7632. std::string nc;
  7633. {
  7634. std::stringstream ss;
  7635. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  7636. nc = ss.str();
  7637. }
  7638. std::string qop;
  7639. if (auth.find("qop") != auth.end()) {
  7640. qop = auth.at("qop");
  7641. if (qop.find("auth-int") != std::string::npos) {
  7642. qop = "auth-int";
  7643. } else if (qop.find("auth") != std::string::npos) {
  7644. qop = "auth";
  7645. } else {
  7646. qop.clear();
  7647. }
  7648. }
  7649. std::string algo = "MD5";
  7650. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  7651. std::string response;
  7652. {
  7653. auto H = algo == "SHA-256" ? detail::SHA_256
  7654. : algo == "SHA-512" ? detail::SHA_512
  7655. : detail::MD5;
  7656. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  7657. auto A2 = req.method + ":" + req.path;
  7658. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  7659. if (qop.empty()) {
  7660. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  7661. } else {
  7662. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  7663. ":" + qop + ":" + H(A2));
  7664. }
  7665. }
  7666. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  7667. auto field = "Digest username=\"" + username + "\", realm=\"" +
  7668. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  7669. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  7670. (qop.empty() ? ", response=\""
  7671. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  7672. cnonce + "\", response=\"") +
  7673. response + "\"" +
  7674. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  7675. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  7676. return std::make_pair(key, field);
  7677. }
  7678. inline bool match_hostname(const std::string &pattern,
  7679. const std::string &hostname) {
  7680. // Exact match (case-insensitive)
  7681. if (detail::case_ignore::equal(hostname, pattern)) { return true; }
  7682. // Split both pattern and hostname into components by '.'
  7683. std::vector<std::string> pattern_components;
  7684. if (!pattern.empty()) {
  7685. split(pattern.data(), pattern.data() + pattern.size(), '.',
  7686. [&](const char *b, const char *e) {
  7687. pattern_components.emplace_back(b, e);
  7688. });
  7689. }
  7690. std::vector<std::string> host_components;
  7691. if (!hostname.empty()) {
  7692. split(hostname.data(), hostname.data() + hostname.size(), '.',
  7693. [&](const char *b, const char *e) {
  7694. host_components.emplace_back(b, e);
  7695. });
  7696. }
  7697. // Component count must match
  7698. if (host_components.size() != pattern_components.size()) { return false; }
  7699. // Compare each component with wildcard support
  7700. // Supports: "*" (full wildcard), "prefix*" (partial wildcard)
  7701. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7702. auto itr = pattern_components.begin();
  7703. for (const auto &h : host_components) {
  7704. auto &p = *itr;
  7705. if (!detail::case_ignore::equal(p, h) && p != "*") {
  7706. bool partial_match = false;
  7707. if (!p.empty() && p[p.size() - 1] == '*') {
  7708. const auto prefix_length = p.size() - 1;
  7709. if (prefix_length == 0) {
  7710. partial_match = true;
  7711. } else if (h.size() >= prefix_length) {
  7712. partial_match =
  7713. std::equal(p.begin(),
  7714. p.begin() + static_cast<std::string::difference_type>(
  7715. prefix_length),
  7716. h.begin(), [](const char ca, const char cb) {
  7717. return detail::case_ignore::to_lower(ca) ==
  7718. detail::case_ignore::to_lower(cb);
  7719. });
  7720. }
  7721. }
  7722. if (!partial_match) { return false; }
  7723. }
  7724. ++itr;
  7725. }
  7726. return true;
  7727. }
  7728. #ifdef _WIN32
  7729. // Verify certificate using Windows CertGetCertificateChain API.
  7730. // This provides real-time certificate validation with Windows Update
  7731. // integration, independent of the TLS backend (OpenSSL or MbedTLS).
  7732. inline bool
  7733. verify_cert_with_windows_schannel(const std::vector<unsigned char> &der_cert,
  7734. const std::string &hostname,
  7735. bool verify_hostname, uint64_t &out_error) {
  7736. if (der_cert.empty()) { return false; }
  7737. out_error = 0;
  7738. // Create Windows certificate context from DER data
  7739. auto cert_context = CertCreateCertificateContext(
  7740. X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, der_cert.data(),
  7741. static_cast<DWORD>(der_cert.size()));
  7742. if (!cert_context) {
  7743. out_error = GetLastError();
  7744. return false;
  7745. }
  7746. auto cert_guard =
  7747. scope_exit([&] { CertFreeCertificateContext(cert_context); });
  7748. // Setup chain parameters
  7749. CERT_CHAIN_PARA chain_para = {};
  7750. chain_para.cbSize = sizeof(chain_para);
  7751. // Build certificate chain with revocation checking
  7752. PCCERT_CHAIN_CONTEXT chain_context = nullptr;
  7753. auto chain_result = CertGetCertificateChain(
  7754. nullptr, cert_context, nullptr, cert_context->hCertStore, &chain_para,
  7755. CERT_CHAIN_CACHE_END_CERT | CERT_CHAIN_REVOCATION_CHECK_END_CERT |
  7756. CERT_CHAIN_REVOCATION_ACCUMULATIVE_TIMEOUT,
  7757. nullptr, &chain_context);
  7758. if (!chain_result || !chain_context) {
  7759. out_error = GetLastError();
  7760. return false;
  7761. }
  7762. auto chain_guard =
  7763. scope_exit([&] { CertFreeCertificateChain(chain_context); });
  7764. // Check if chain has errors
  7765. if (chain_context->TrustStatus.dwErrorStatus != CERT_TRUST_NO_ERROR) {
  7766. out_error = chain_context->TrustStatus.dwErrorStatus;
  7767. return false;
  7768. }
  7769. // Verify SSL policy
  7770. SSL_EXTRA_CERT_CHAIN_POLICY_PARA extra_policy_para = {};
  7771. extra_policy_para.cbSize = sizeof(extra_policy_para);
  7772. #ifdef AUTHTYPE_SERVER
  7773. extra_policy_para.dwAuthType = AUTHTYPE_SERVER;
  7774. #endif
  7775. std::wstring whost;
  7776. if (verify_hostname) {
  7777. whost = u8string_to_wstring(hostname.c_str());
  7778. extra_policy_para.pwszServerName = const_cast<wchar_t *>(whost.c_str());
  7779. }
  7780. CERT_CHAIN_POLICY_PARA policy_para = {};
  7781. policy_para.cbSize = sizeof(policy_para);
  7782. #ifdef CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS
  7783. policy_para.dwFlags = CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS;
  7784. #else
  7785. policy_para.dwFlags = 0;
  7786. #endif
  7787. policy_para.pvExtraPolicyPara = &extra_policy_para;
  7788. CERT_CHAIN_POLICY_STATUS policy_status = {};
  7789. policy_status.cbSize = sizeof(policy_status);
  7790. if (!CertVerifyCertificateChainPolicy(CERT_CHAIN_POLICY_SSL, chain_context,
  7791. &policy_para, &policy_status)) {
  7792. out_error = GetLastError();
  7793. return false;
  7794. }
  7795. if (policy_status.dwError != 0) {
  7796. out_error = policy_status.dwError;
  7797. return false;
  7798. }
  7799. return true;
  7800. }
  7801. #endif // _WIN32
  7802. // Loads CA file/dir configuration and applies the system CA policy to a
  7803. // client TLS context. PEM data and native stores are applied to the context
  7804. // directly at set time; has_custom_store reflects them for the Auto policy
  7805. // decision.
  7806. inline bool load_client_ca_config(tls::ctx_t ctx,
  7807. const std::string &ca_cert_file_path,
  7808. const std::string &ca_cert_dir_path,
  7809. bool has_custom_store, SystemCAMode mode,
  7810. uint64_t &backend_error) {
  7811. auto ret = true;
  7812. if (!ca_cert_file_path.empty()) {
  7813. if (!tls::load_ca_file(ctx, ca_cert_file_path.c_str())) {
  7814. backend_error = tls::get_error();
  7815. ret = false;
  7816. }
  7817. } else if (!ca_cert_dir_path.empty()) {
  7818. if (!tls::load_ca_dir(ctx, ca_cert_dir_path.c_str())) {
  7819. backend_error = tls::get_error();
  7820. ret = false;
  7821. }
  7822. }
  7823. auto has_custom_ca = !ca_cert_file_path.empty() ||
  7824. !ca_cert_dir_path.empty() || has_custom_store;
  7825. if (mode == SystemCAMode::Enabled ||
  7826. (mode == SystemCAMode::Auto && !has_custom_ca)) {
  7827. if (!tls::load_system_certs(ctx)) { backend_error = tls::get_error(); }
  7828. }
  7829. return ret;
  7830. }
  7831. inline bool setup_client_tls_session(const std::string &host, tls::ctx_t ctx,
  7832. tls::session_t &session, socket_t sock,
  7833. bool server_certificate_verification,
  7834. time_t timeout_sec, time_t timeout_usec) {
  7835. using namespace tls;
  7836. if (!ctx) { return false; }
  7837. bool is_ip = is_ip_address(host);
  7838. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  7839. // Chain verification happens during the handshake even for IP hosts; the
  7840. // certificate identity is verified post-handshake via verify_hostname()
  7841. set_verify_client(ctx, server_certificate_verification);
  7842. #endif
  7843. session = create_session(ctx, sock);
  7844. if (!session) { return false; }
  7845. // RFC 6066: SNI must not be set for IP addresses. On Mbed TLS and wolfSSL
  7846. // set_hostname also sets SNI, so it must be skipped for IP hosts as well;
  7847. // their identity is checked post-handshake below instead.
  7848. if (!is_ip) {
  7849. if (server_certificate_verification) {
  7850. set_hostname(session, host.c_str());
  7851. } else {
  7852. set_sni(session, host.c_str());
  7853. }
  7854. }
  7855. if (!connect_nonblocking(session, sock, timeout_sec, timeout_usec, nullptr)) {
  7856. return false;
  7857. }
  7858. if (server_certificate_verification) {
  7859. if (get_verify_result(session) != 0) { return false; }
  7860. // Identity check against the peer certificate, post-handshake for all
  7861. // backends (same as SSLClient). For IP hosts this is the only identity
  7862. // verification since no hostname is bound during the handshake.
  7863. auto server_cert = get_peer_cert(session);
  7864. if (!server_cert) { return false; }
  7865. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  7866. if (!verify_hostname(server_cert, host.c_str())) { return false; }
  7867. }
  7868. return true;
  7869. }
  7870. } // namespace detail
  7871. #endif // CPPHTTPLIB_SSL_ENABLED
  7872. /*
  7873. * Group 3: httplib namespace - Non-SSL public API implementations
  7874. */
  7875. inline void default_socket_options(socket_t sock) {
  7876. set_socket_opt(sock, SOL_SOCKET,
  7877. #ifdef SO_REUSEPORT
  7878. SO_REUSEPORT,
  7879. #else
  7880. SO_REUSEADDR,
  7881. #endif
  7882. 1);
  7883. }
  7884. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  7885. return detail::set_socket_opt_impl(sock, level, optname, &optval,
  7886. sizeof(optval));
  7887. }
  7888. inline std::string get_bearer_token_auth(const Request &req) {
  7889. if (req.has_header("Authorization")) {
  7890. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  7891. return req.get_header_value("Authorization")
  7892. .substr(bearer_header_prefix_len);
  7893. }
  7894. return "";
  7895. }
  7896. inline const char *status_message(int status) {
  7897. switch (status) {
  7898. case StatusCode::Continue_100: return "Continue";
  7899. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  7900. case StatusCode::Processing_102: return "Processing";
  7901. case StatusCode::EarlyHints_103: return "Early Hints";
  7902. case StatusCode::OK_200: return "OK";
  7903. case StatusCode::Created_201: return "Created";
  7904. case StatusCode::Accepted_202: return "Accepted";
  7905. case StatusCode::NonAuthoritativeInformation_203:
  7906. return "Non-Authoritative Information";
  7907. case StatusCode::NoContent_204: return "No Content";
  7908. case StatusCode::ResetContent_205: return "Reset Content";
  7909. case StatusCode::PartialContent_206: return "Partial Content";
  7910. case StatusCode::MultiStatus_207: return "Multi-Status";
  7911. case StatusCode::AlreadyReported_208: return "Already Reported";
  7912. case StatusCode::IMUsed_226: return "IM Used";
  7913. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  7914. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  7915. case StatusCode::Found_302: return "Found";
  7916. case StatusCode::SeeOther_303: return "See Other";
  7917. case StatusCode::NotModified_304: return "Not Modified";
  7918. case StatusCode::UseProxy_305: return "Use Proxy";
  7919. case StatusCode::unused_306: return "unused";
  7920. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  7921. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  7922. case StatusCode::BadRequest_400: return "Bad Request";
  7923. case StatusCode::Unauthorized_401: return "Unauthorized";
  7924. case StatusCode::PaymentRequired_402: return "Payment Required";
  7925. case StatusCode::Forbidden_403: return "Forbidden";
  7926. case StatusCode::NotFound_404: return "Not Found";
  7927. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  7928. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  7929. case StatusCode::ProxyAuthenticationRequired_407:
  7930. return "Proxy Authentication Required";
  7931. case StatusCode::RequestTimeout_408: return "Request Timeout";
  7932. case StatusCode::Conflict_409: return "Conflict";
  7933. case StatusCode::Gone_410: return "Gone";
  7934. case StatusCode::LengthRequired_411: return "Length Required";
  7935. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  7936. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  7937. case StatusCode::UriTooLong_414: return "URI Too Long";
  7938. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  7939. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  7940. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  7941. case StatusCode::ImATeapot_418: return "I'm a teapot";
  7942. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  7943. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  7944. case StatusCode::Locked_423: return "Locked";
  7945. case StatusCode::FailedDependency_424: return "Failed Dependency";
  7946. case StatusCode::TooEarly_425: return "Too Early";
  7947. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  7948. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  7949. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  7950. case StatusCode::RequestHeaderFieldsTooLarge_431:
  7951. return "Request Header Fields Too Large";
  7952. case StatusCode::UnavailableForLegalReasons_451:
  7953. return "Unavailable For Legal Reasons";
  7954. case StatusCode::NotImplemented_501: return "Not Implemented";
  7955. case StatusCode::BadGateway_502: return "Bad Gateway";
  7956. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  7957. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  7958. case StatusCode::HttpVersionNotSupported_505:
  7959. return "HTTP Version Not Supported";
  7960. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  7961. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  7962. case StatusCode::LoopDetected_508: return "Loop Detected";
  7963. case StatusCode::NotExtended_510: return "Not Extended";
  7964. case StatusCode::NetworkAuthenticationRequired_511:
  7965. return "Network Authentication Required";
  7966. default:
  7967. case StatusCode::InternalServerError_500: return "Internal Server Error";
  7968. }
  7969. }
  7970. inline std::string to_string(const Error error) {
  7971. switch (error) {
  7972. case Error::Success: return "Success (no error)";
  7973. case Error::Unknown: return "Unknown";
  7974. case Error::Connection: return "Could not establish connection";
  7975. case Error::BindIPAddress: return "Failed to bind IP address";
  7976. case Error::Read: return "Failed to read connection";
  7977. case Error::Write: return "Failed to write connection";
  7978. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  7979. case Error::Canceled: return "Connection handling canceled";
  7980. case Error::SSLConnection: return "SSL connection failed";
  7981. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  7982. case Error::SSLServerVerification: return "SSL server verification failed";
  7983. case Error::SSLServerHostnameVerification:
  7984. return "SSL server hostname verification failed";
  7985. case Error::UnsupportedMultipartBoundaryChars:
  7986. return "Unsupported HTTP multipart boundary characters";
  7987. case Error::Compression: return "Compression failed";
  7988. case Error::ConnectionTimeout: return "Connection timed out";
  7989. case Error::ProxyConnection: return "Proxy connection failed";
  7990. case Error::ConnectionClosed: return "Connection closed by server";
  7991. case Error::Timeout: return "Read timeout";
  7992. case Error::ResourceExhaustion: return "Resource exhaustion";
  7993. case Error::TooManyFormDataFiles: return "Too many form data files";
  7994. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  7995. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  7996. case Error::ExceedMaxSocketDescriptorCount:
  7997. return "Exceeded maximum socket descriptor count";
  7998. case Error::InvalidRequestLine: return "Invalid request line";
  7999. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  8000. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  8001. case Error::InvalidHeaders: return "Invalid headers";
  8002. case Error::MultipartParsing: return "Multipart parsing failed";
  8003. case Error::OpenFile: return "Failed to open file";
  8004. case Error::Listen: return "Failed to listen on socket";
  8005. case Error::GetSockName: return "Failed to get socket name";
  8006. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  8007. case Error::HTTPParsing: return "HTTP parsing failed";
  8008. case Error::InvalidRangeHeader: return "Invalid Range header";
  8009. default: break;
  8010. }
  8011. return "Invalid";
  8012. }
  8013. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  8014. os << to_string(obj);
  8015. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  8016. return os;
  8017. }
  8018. inline std::string hosted_at(const std::string &hostname) {
  8019. std::vector<std::string> addrs;
  8020. hosted_at(hostname, addrs);
  8021. if (addrs.empty()) { return std::string(); }
  8022. return addrs[0];
  8023. }
  8024. inline void hosted_at(const std::string &hostname,
  8025. std::vector<std::string> &addrs) {
  8026. struct addrinfo hints;
  8027. struct addrinfo *result;
  8028. memset(&hints, 0, sizeof(struct addrinfo));
  8029. hints.ai_family = AF_UNSPEC;
  8030. hints.ai_socktype = SOCK_STREAM;
  8031. hints.ai_protocol = 0;
  8032. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  8033. &result, 0)) {
  8034. #if defined __linux__ && !defined __ANDROID__
  8035. res_init();
  8036. #endif
  8037. return;
  8038. }
  8039. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  8040. for (auto rp = result; rp; rp = rp->ai_next) {
  8041. const auto &addr =
  8042. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  8043. std::string ip;
  8044. auto dummy = -1;
  8045. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  8046. dummy)) {
  8047. addrs.emplace_back(std::move(ip));
  8048. }
  8049. }
  8050. }
  8051. inline std::string encode_uri_component(const std::string &value) {
  8052. std::ostringstream escaped;
  8053. escaped.fill('0');
  8054. escaped << std::hex;
  8055. for (auto c : value) {
  8056. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8057. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
  8058. escaped << c;
  8059. } else {
  8060. escaped << std::uppercase;
  8061. escaped << '%' << std::setw(2)
  8062. << static_cast<int>(static_cast<unsigned char>(c));
  8063. escaped << std::nouppercase;
  8064. }
  8065. }
  8066. return escaped.str();
  8067. }
  8068. inline std::string encode_uri(const std::string &value) {
  8069. std::ostringstream escaped;
  8070. escaped.fill('0');
  8071. escaped << std::hex;
  8072. for (auto c : value) {
  8073. if (detail::is_ascii_alnum(c) || c == '-' || c == '_' || c == '.' ||
  8074. c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')' ||
  8075. c == ';' || c == '/' || c == '?' || c == ':' || c == '@' || c == '&' ||
  8076. c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  8077. escaped << c;
  8078. } else {
  8079. escaped << std::uppercase;
  8080. escaped << '%' << std::setw(2)
  8081. << static_cast<int>(static_cast<unsigned char>(c));
  8082. escaped << std::nouppercase;
  8083. }
  8084. }
  8085. return escaped.str();
  8086. }
  8087. inline std::string decode_uri_component(const std::string &value) {
  8088. std::string result;
  8089. for (size_t i = 0; i < value.size(); i++) {
  8090. if (value[i] == '%' && i + 2 < value.size()) {
  8091. auto val = 0;
  8092. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8093. result += static_cast<char>(val);
  8094. i += 2;
  8095. } else {
  8096. result += value[i];
  8097. }
  8098. } else {
  8099. result += value[i];
  8100. }
  8101. }
  8102. return result;
  8103. }
  8104. inline std::string decode_uri(const std::string &value) {
  8105. std::string result;
  8106. for (size_t i = 0; i < value.size(); i++) {
  8107. if (value[i] == '%' && i + 2 < value.size()) {
  8108. auto val = 0;
  8109. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  8110. result += static_cast<char>(val);
  8111. i += 2;
  8112. } else {
  8113. result += value[i];
  8114. }
  8115. } else {
  8116. result += value[i];
  8117. }
  8118. }
  8119. return result;
  8120. }
  8121. inline std::string encode_path_component(const std::string &component) {
  8122. std::string result;
  8123. result.reserve(component.size() * 3);
  8124. for (size_t i = 0; i < component.size(); i++) {
  8125. auto c = static_cast<unsigned char>(component[i]);
  8126. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  8127. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8128. c == '_' || c == '~') {
  8129. result += static_cast<char>(c);
  8130. }
  8131. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  8132. // "," / ";" / "="
  8133. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  8134. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  8135. c == '=') {
  8136. result += static_cast<char>(c);
  8137. }
  8138. // Colon is allowed in path segments except first segment
  8139. else if (c == ':') {
  8140. result += static_cast<char>(c);
  8141. }
  8142. // @ is allowed in path
  8143. else if (c == '@') {
  8144. result += static_cast<char>(c);
  8145. } else {
  8146. result += '%';
  8147. char hex[3];
  8148. snprintf(hex, sizeof(hex), "%02X", c);
  8149. result.append(hex, 2);
  8150. }
  8151. }
  8152. return result;
  8153. }
  8154. inline std::string decode_path_component(const std::string &component) {
  8155. std::string result;
  8156. result.reserve(component.size());
  8157. for (size_t i = 0; i < component.size(); i++) {
  8158. if (component[i] == '%' && i + 1 < component.size()) {
  8159. if (component[i + 1] == 'u') {
  8160. // Unicode %uXXXX encoding
  8161. auto val = 0;
  8162. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  8163. // 4 digits Unicode codes: val is 0x0000-0xFFFF (from 4 hex digits),
  8164. // so to_utf8 writes at most 3 bytes. buff[4] is safe.
  8165. char buff[4];
  8166. size_t len = detail::to_utf8(val, buff);
  8167. if (len > 0) { result.append(buff, len); }
  8168. i += 5; // 'u0000'
  8169. } else {
  8170. result += component[i];
  8171. }
  8172. } else {
  8173. // Standard %XX encoding
  8174. auto val = 0;
  8175. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8176. // 2 digits hex codes
  8177. result += static_cast<char>(val);
  8178. i += 2; // 'XX'
  8179. } else {
  8180. result += component[i];
  8181. }
  8182. }
  8183. } else {
  8184. result += component[i];
  8185. }
  8186. }
  8187. return result;
  8188. }
  8189. inline std::string encode_query_component(const std::string &component,
  8190. bool space_as_plus) {
  8191. std::string result;
  8192. result.reserve(component.size() * 3);
  8193. for (size_t i = 0; i < component.size(); i++) {
  8194. auto c = static_cast<unsigned char>(component[i]);
  8195. // Unreserved characters per RFC 3986
  8196. if (detail::is_ascii_alnum(static_cast<char>(c)) || c == '-' || c == '.' ||
  8197. c == '_' || c == '~') {
  8198. result += static_cast<char>(c);
  8199. }
  8200. // Space handling
  8201. else if (c == ' ') {
  8202. if (space_as_plus) {
  8203. result += '+';
  8204. } else {
  8205. result += "%20";
  8206. }
  8207. }
  8208. // Plus sign handling
  8209. else if (c == '+') {
  8210. if (space_as_plus) {
  8211. result += "%2B";
  8212. } else {
  8213. result += static_cast<char>(c);
  8214. }
  8215. }
  8216. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  8217. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  8218. c == '*' || c == ',' || c == ';') {
  8219. result += static_cast<char>(c);
  8220. }
  8221. // Colon and @ are allowed in query
  8222. else if (c == ':' || c == '@') {
  8223. result += static_cast<char>(c);
  8224. }
  8225. // Forward slash is allowed in query values
  8226. else if (c == '/') {
  8227. result += static_cast<char>(c);
  8228. }
  8229. // Question mark is allowed in query values (after first ?)
  8230. else if (c == '?') {
  8231. result += static_cast<char>(c);
  8232. } else {
  8233. result += '%';
  8234. char hex[3];
  8235. snprintf(hex, sizeof(hex), "%02X", c);
  8236. result.append(hex, 2);
  8237. }
  8238. }
  8239. return result;
  8240. }
  8241. inline std::string decode_query_component(const std::string &component,
  8242. bool plus_as_space) {
  8243. std::string result;
  8244. result.reserve(component.size());
  8245. for (size_t i = 0; i < component.size(); i++) {
  8246. if (component[i] == '%' && i + 2 < component.size()) {
  8247. auto val = 0;
  8248. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  8249. result += static_cast<char>(val);
  8250. i += 2;
  8251. } else {
  8252. result += component[i];
  8253. }
  8254. } else if (component[i] == '+' && plus_as_space) {
  8255. result += ' '; // + becomes space in form-urlencoded
  8256. } else {
  8257. result += component[i];
  8258. }
  8259. }
  8260. return result;
  8261. }
  8262. inline std::string sanitize_filename(const std::string &filename) {
  8263. // Extract basename: find the last path separator (/ or \)
  8264. auto pos = filename.find_last_of("/\\");
  8265. auto result =
  8266. (pos != std::string::npos) ? filename.substr(pos + 1) : filename;
  8267. // Strip null bytes
  8268. result.erase(std::remove(result.begin(), result.end(), '\0'), result.end());
  8269. // Trim whitespace
  8270. {
  8271. auto start = result.find_first_not_of(" \t");
  8272. auto end = result.find_last_not_of(" \t");
  8273. result = (start == std::string::npos)
  8274. ? ""
  8275. : result.substr(start, end - start + 1);
  8276. }
  8277. // Reject . and ..
  8278. if (result == "." || result == "..") { return ""; }
  8279. return result;
  8280. }
  8281. inline std::string append_query_params(const std::string &path,
  8282. const Params &params) {
  8283. std::string path_with_query = path;
  8284. thread_local const std::regex re("[^?]+\\?.*");
  8285. auto delm = std::regex_match(path, re) ? '&' : '?';
  8286. path_with_query += delm + detail::params_to_query_str(params);
  8287. return path_with_query;
  8288. }
  8289. // Header utilities
  8290. inline std::pair<std::string, std::string>
  8291. make_range_header(const Ranges &ranges) {
  8292. std::string field = "bytes=";
  8293. auto i = 0;
  8294. for (const auto &r : ranges) {
  8295. if (i != 0) { field += ", "; }
  8296. if (r.first != -1) { field += std::to_string(r.first); }
  8297. field += '-';
  8298. if (r.second != -1) { field += std::to_string(r.second); }
  8299. i++;
  8300. }
  8301. return std::make_pair("Range", std::move(field));
  8302. }
  8303. inline std::pair<std::string, std::string>
  8304. make_basic_authentication_header(const std::string &username,
  8305. const std::string &password, bool is_proxy) {
  8306. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  8307. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8308. return std::make_pair(key, std::move(field));
  8309. }
  8310. inline std::pair<std::string, std::string>
  8311. make_bearer_token_authentication_header(const std::string &token,
  8312. bool is_proxy = false) {
  8313. auto field = "Bearer " + token;
  8314. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  8315. return std::make_pair(key, std::move(field));
  8316. }
  8317. // Request implementation
  8318. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  8319. size_t id) const {
  8320. return detail::get_header_value_u64(headers, key, def, id);
  8321. }
  8322. inline bool Request::has_header(const std::string &key) const {
  8323. return detail::has_header(headers, key);
  8324. }
  8325. inline std::string Request::get_header_value(const std::string &key,
  8326. const char *def, size_t id) const {
  8327. return detail::get_header_value(headers, key, def, id);
  8328. }
  8329. inline size_t Request::get_header_value_count(const std::string &key) const {
  8330. return detail::get_header_value_count(headers, key);
  8331. }
  8332. inline void Request::set_header(const std::string &key,
  8333. const std::string &val) {
  8334. detail::set_header(headers, key, val);
  8335. }
  8336. inline bool Request::has_trailer(const std::string &key) const {
  8337. return trailers.find(key) != trailers.end();
  8338. }
  8339. inline std::string Request::get_trailer_value(const std::string &key,
  8340. size_t id) const {
  8341. return detail::get_multimap_value(trailers, key, id);
  8342. }
  8343. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  8344. auto r = trailers.equal_range(key);
  8345. return static_cast<size_t>(std::distance(r.first, r.second));
  8346. }
  8347. inline bool Request::has_param(const std::string &key) const {
  8348. return params.find(key) != params.end();
  8349. }
  8350. inline std::string Request::get_param_value(const std::string &key,
  8351. size_t id) const {
  8352. return detail::get_multimap_value(params, key, id);
  8353. }
  8354. inline std::vector<std::string>
  8355. Request::get_param_values(const std::string &key) const {
  8356. auto rng = params.equal_range(key);
  8357. std::vector<std::string> values;
  8358. values.reserve(static_cast<size_t>(std::distance(rng.first, rng.second)));
  8359. for (auto it = rng.first; it != rng.second; ++it) {
  8360. values.push_back(it->second);
  8361. }
  8362. return values;
  8363. }
  8364. inline size_t Request::get_param_value_count(const std::string &key) const {
  8365. auto r = params.equal_range(key);
  8366. return static_cast<size_t>(std::distance(r.first, r.second));
  8367. }
  8368. inline bool Request::is_multipart_form_data() const {
  8369. const auto &content_type = get_header_value("Content-Type");
  8370. return detail::extract_media_type(content_type) == "multipart/form-data";
  8371. }
  8372. // Multipart FormData implementation
  8373. inline std::string MultipartFormData::get_field(const std::string &key,
  8374. size_t id) const {
  8375. auto rng = fields.equal_range(key);
  8376. auto it = rng.first;
  8377. std::advance(it, static_cast<ssize_t>(id));
  8378. if (it != rng.second) { return it->second.content; }
  8379. return std::string();
  8380. }
  8381. inline std::vector<std::string>
  8382. MultipartFormData::get_fields(const std::string &key) const {
  8383. std::vector<std::string> values;
  8384. auto rng = fields.equal_range(key);
  8385. for (auto it = rng.first; it != rng.second; it++) {
  8386. values.push_back(it->second.content);
  8387. }
  8388. return values;
  8389. }
  8390. inline bool MultipartFormData::has_field(const std::string &key) const {
  8391. return fields.find(key) != fields.end();
  8392. }
  8393. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  8394. auto r = fields.equal_range(key);
  8395. return static_cast<size_t>(std::distance(r.first, r.second));
  8396. }
  8397. inline FormData MultipartFormData::get_file(const std::string &key,
  8398. size_t id) const {
  8399. return detail::get_multimap_value(files, key, id);
  8400. }
  8401. inline std::vector<FormData>
  8402. MultipartFormData::get_files(const std::string &key) const {
  8403. std::vector<FormData> values;
  8404. auto rng = files.equal_range(key);
  8405. for (auto it = rng.first; it != rng.second; it++) {
  8406. values.push_back(it->second);
  8407. }
  8408. return values;
  8409. }
  8410. inline bool MultipartFormData::has_file(const std::string &key) const {
  8411. return files.find(key) != files.end();
  8412. }
  8413. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  8414. auto r = files.equal_range(key);
  8415. return static_cast<size_t>(std::distance(r.first, r.second));
  8416. }
  8417. // Multipart FormData writer implementation
  8418. inline bool is_valid_multipart_boundary(const std::string &boundary) {
  8419. return detail::is_multipart_boundary_chars_valid(boundary);
  8420. }
  8421. inline MultipartFormDataWriter::MultipartFormDataWriter()
  8422. : boundary_(detail::make_multipart_data_boundary()) {}
  8423. inline MultipartFormDataWriter::MultipartFormDataWriter(std::string boundary)
  8424. : boundary_(std::move(boundary)) {}
  8425. inline const std::string &MultipartFormDataWriter::boundary() const {
  8426. return boundary_;
  8427. }
  8428. inline std::string MultipartFormDataWriter::content_type() const {
  8429. return detail::serialize_multipart_formdata_get_content_type(boundary_);
  8430. }
  8431. inline std::string
  8432. MultipartFormDataWriter::serialize(const UploadFormDataItems &items) const {
  8433. return detail::serialize_multipart_formdata(items, boundary_);
  8434. }
  8435. inline size_t MultipartFormDataWriter::content_length(
  8436. const UploadFormDataItems &items) const {
  8437. return detail::get_multipart_content_length(items, boundary_);
  8438. }
  8439. inline std::string
  8440. MultipartFormDataWriter::item_begin(const UploadFormData &item) const {
  8441. return detail::serialize_multipart_formdata_item_begin(item, boundary_);
  8442. }
  8443. inline std::string MultipartFormDataWriter::item_end() {
  8444. return detail::serialize_multipart_formdata_item_end();
  8445. }
  8446. inline std::string MultipartFormDataWriter::finish() const {
  8447. return detail::serialize_multipart_formdata_finish(boundary_);
  8448. }
  8449. // Response implementation
  8450. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  8451. size_t id) const {
  8452. return detail::get_header_value_u64(headers, key, def, id);
  8453. }
  8454. inline bool Response::has_header(const std::string &key) const {
  8455. return headers.find(key) != headers.end();
  8456. }
  8457. inline std::string Response::get_header_value(const std::string &key,
  8458. const char *def,
  8459. size_t id) const {
  8460. return detail::get_header_value(headers, key, def, id);
  8461. }
  8462. inline size_t Response::get_header_value_count(const std::string &key) const {
  8463. return detail::get_header_value_count(headers, key);
  8464. }
  8465. inline void Response::set_header(const std::string &key,
  8466. const std::string &val) {
  8467. detail::set_header(headers, key, val);
  8468. }
  8469. inline bool Response::has_trailer(const std::string &key) const {
  8470. return trailers.find(key) != trailers.end();
  8471. }
  8472. inline std::string Response::get_trailer_value(const std::string &key,
  8473. size_t id) const {
  8474. return detail::get_multimap_value(trailers, key, id);
  8475. }
  8476. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  8477. auto r = trailers.equal_range(key);
  8478. return static_cast<size_t>(std::distance(r.first, r.second));
  8479. }
  8480. inline void Response::set_redirect(const std::string &url, int stat) {
  8481. if (detail::fields::is_field_value(url)) {
  8482. set_header("Location", url);
  8483. if (300 <= stat && stat < 400) {
  8484. this->status = stat;
  8485. } else {
  8486. this->status = StatusCode::Found_302;
  8487. }
  8488. }
  8489. }
  8490. inline void Response::set_content(const char *s, size_t n,
  8491. const std::string &content_type) {
  8492. body.assign(s, n);
  8493. auto rng = headers.equal_range("Content-Type");
  8494. headers.erase(rng.first, rng.second);
  8495. set_header("Content-Type", content_type);
  8496. }
  8497. inline void Response::set_content(const std::string &s,
  8498. const std::string &content_type) {
  8499. set_content(s.data(), s.size(), content_type);
  8500. }
  8501. inline void Response::set_content(std::string &&s,
  8502. const std::string &content_type) {
  8503. body = std::move(s);
  8504. auto rng = headers.equal_range("Content-Type");
  8505. headers.erase(rng.first, rng.second);
  8506. set_header("Content-Type", content_type);
  8507. }
  8508. inline void Response::set_content_provider(
  8509. size_t in_length, const std::string &content_type, ContentProvider provider,
  8510. ContentProviderResourceReleaser resource_releaser) {
  8511. set_header("Content-Type", content_type);
  8512. content_length_ = in_length;
  8513. if (in_length > 0) { content_provider_ = std::move(provider); }
  8514. content_provider_resource_releaser_ = std::move(resource_releaser);
  8515. is_chunked_content_provider_ = false;
  8516. }
  8517. inline void Response::set_content_provider(
  8518. const std::string &content_type, ContentProviderWithoutLength provider,
  8519. ContentProviderResourceReleaser resource_releaser) {
  8520. set_header("Content-Type", content_type);
  8521. content_length_ = 0;
  8522. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8523. content_provider_resource_releaser_ = std::move(resource_releaser);
  8524. is_chunked_content_provider_ = false;
  8525. }
  8526. inline void Response::set_chunked_content_provider(
  8527. const std::string &content_type, ContentProviderWithoutLength provider,
  8528. ContentProviderResourceReleaser resource_releaser) {
  8529. set_header("Content-Type", content_type);
  8530. content_length_ = 0;
  8531. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  8532. content_provider_resource_releaser_ = std::move(resource_releaser);
  8533. is_chunked_content_provider_ = true;
  8534. }
  8535. inline void Response::set_file_content(const std::string &path,
  8536. const std::string &content_type) {
  8537. file_content_path_ = path;
  8538. file_content_content_type_ = content_type;
  8539. }
  8540. inline void Response::set_file_content(const std::string &path) {
  8541. file_content_path_ = path;
  8542. }
  8543. // Result implementation
  8544. inline size_t Result::get_request_header_value_u64(const std::string &key,
  8545. size_t def,
  8546. size_t id) const {
  8547. return detail::get_header_value_u64(request_headers_, key, def, id);
  8548. }
  8549. inline bool Result::has_request_header(const std::string &key) const {
  8550. return request_headers_.find(key) != request_headers_.end();
  8551. }
  8552. inline std::string Result::get_request_header_value(const std::string &key,
  8553. const char *def,
  8554. size_t id) const {
  8555. return detail::get_header_value(request_headers_, key, def, id);
  8556. }
  8557. inline size_t
  8558. Result::get_request_header_value_count(const std::string &key) const {
  8559. auto r = request_headers_.equal_range(key);
  8560. return static_cast<size_t>(std::distance(r.first, r.second));
  8561. }
  8562. // Stream implementation
  8563. inline ssize_t Stream::write(const char *ptr) {
  8564. return write(ptr, strlen(ptr));
  8565. }
  8566. inline ssize_t Stream::write(const std::string &s) {
  8567. return write(s.data(), s.size());
  8568. }
  8569. // BodyReader implementation
  8570. inline ssize_t detail::BodyReader::read(char *buf, size_t len) {
  8571. if (!stream) {
  8572. last_error = Error::Connection;
  8573. return -1;
  8574. }
  8575. if (eof) { return 0; }
  8576. if (!chunked) {
  8577. // Content-Length based reading
  8578. if (has_content_length && bytes_read >= content_length) {
  8579. eof = true;
  8580. return 0;
  8581. }
  8582. auto to_read = len;
  8583. if (has_content_length) {
  8584. auto remaining = content_length - bytes_read;
  8585. to_read = (std::min)(len, remaining);
  8586. }
  8587. auto n = stream->read(buf, to_read);
  8588. if (n < 0) {
  8589. last_error = stream->get_error();
  8590. if (last_error == Error::Success) { last_error = Error::Read; }
  8591. eof = true;
  8592. return n;
  8593. }
  8594. if (n == 0) {
  8595. // Unexpected EOF before content_length
  8596. last_error = stream->get_error();
  8597. if (last_error == Error::Success) { last_error = Error::Read; }
  8598. eof = true;
  8599. return 0;
  8600. }
  8601. bytes_read += static_cast<size_t>(n);
  8602. if (has_content_length && bytes_read >= content_length) { eof = true; }
  8603. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8604. last_error = Error::ExceedMaxPayloadSize;
  8605. eof = true;
  8606. return -1;
  8607. }
  8608. return n;
  8609. }
  8610. // Chunked transfer encoding: delegate to shared decoder instance.
  8611. if (!chunked_decoder) { chunked_decoder.reset(new ChunkedDecoder(*stream)); }
  8612. size_t chunk_offset = 0;
  8613. size_t chunk_total = 0;
  8614. auto n = chunked_decoder->read_payload(buf, len, chunk_offset, chunk_total);
  8615. if (n < 0) {
  8616. last_error = stream->get_error();
  8617. if (last_error == Error::Success) { last_error = Error::Read; }
  8618. eof = true;
  8619. return n;
  8620. }
  8621. if (n == 0) {
  8622. // Final chunk observed. Leave trailer parsing to the caller (StreamHandle).
  8623. eof = true;
  8624. return 0;
  8625. }
  8626. bytes_read += static_cast<size_t>(n);
  8627. if (payload_max_length > 0 && bytes_read > payload_max_length) {
  8628. last_error = Error::ExceedMaxPayloadSize;
  8629. eof = true;
  8630. return -1;
  8631. }
  8632. return n;
  8633. }
  8634. // ThreadPool implementation
  8635. inline ThreadPool::ThreadPool(size_t n, size_t max_n, size_t mqr,
  8636. time_t idle_timeout_sec)
  8637. : base_thread_count_(n), max_queued_requests_(mqr),
  8638. idle_timeout_sec_(idle_timeout_sec), idle_thread_count_(0),
  8639. shutdown_(false) {
  8640. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8641. if (max_n != 0 && max_n < n) {
  8642. std::string msg = "max_threads must be >= base_threads";
  8643. throw std::invalid_argument(msg);
  8644. }
  8645. #endif
  8646. max_thread_count_ = max_n == 0 ? n : max_n;
  8647. threads_.reserve(base_thread_count_);
  8648. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8649. try {
  8650. #endif
  8651. for (size_t i = 0; i < base_thread_count_; i++) {
  8652. threads_.emplace_back(std::thread([this]() { worker(false); }));
  8653. }
  8654. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8655. } catch (...) {
  8656. // If thread creation fails partway (e.g., pthread_create returns EAGAIN),
  8657. // signal the workers we already spawned to exit and join them so the
  8658. // vector destructor does not see joinable threads (which would call
  8659. // std::terminate). Then rethrow so the caller learns of the failure.
  8660. {
  8661. std::unique_lock<std::mutex> lock(mutex_);
  8662. shutdown_ = true;
  8663. }
  8664. cond_.notify_all();
  8665. for (auto &t : threads_) {
  8666. if (t.joinable()) { t.join(); }
  8667. }
  8668. throw;
  8669. }
  8670. #endif
  8671. }
  8672. inline bool ThreadPool::enqueue(std::function<void()> fn) {
  8673. {
  8674. std::unique_lock<std::mutex> lock(mutex_);
  8675. if (shutdown_) { return false; }
  8676. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  8677. return false;
  8678. }
  8679. jobs_.push_back(std::move(fn));
  8680. // Spawn a dynamic thread if no idle threads and under max
  8681. if (idle_thread_count_ == 0 &&
  8682. threads_.size() + dynamic_threads_.size() < max_thread_count_) {
  8683. cleanup_finished_threads();
  8684. dynamic_threads_.emplace_back(std::thread([this]() { worker(true); }));
  8685. }
  8686. }
  8687. cond_.notify_one();
  8688. return true;
  8689. }
  8690. inline void ThreadPool::shutdown() {
  8691. {
  8692. std::unique_lock<std::mutex> lock(mutex_);
  8693. shutdown_ = true;
  8694. }
  8695. cond_.notify_all();
  8696. for (auto &t : threads_) {
  8697. if (t.joinable()) { t.join(); }
  8698. }
  8699. // Move dynamic_threads_ to a local list under the lock to avoid racing
  8700. // with worker threads that call move_to_finished() concurrently.
  8701. std::list<std::thread> remaining_dynamic;
  8702. {
  8703. std::unique_lock<std::mutex> lock(mutex_);
  8704. remaining_dynamic = std::move(dynamic_threads_);
  8705. }
  8706. for (auto &t : remaining_dynamic) {
  8707. if (t.joinable()) { t.join(); }
  8708. }
  8709. std::unique_lock<std::mutex> lock(mutex_);
  8710. cleanup_finished_threads();
  8711. }
  8712. inline void ThreadPool::move_to_finished(std::thread::id id) {
  8713. // Must be called with mutex_ held
  8714. for (auto it = dynamic_threads_.begin(); it != dynamic_threads_.end(); ++it) {
  8715. if (it->get_id() == id) {
  8716. finished_threads_.push_back(std::move(*it));
  8717. dynamic_threads_.erase(it);
  8718. return;
  8719. }
  8720. }
  8721. }
  8722. inline void ThreadPool::cleanup_finished_threads() {
  8723. // Must be called with mutex_ held
  8724. for (auto &t : finished_threads_) {
  8725. if (t.joinable()) { t.join(); }
  8726. }
  8727. finished_threads_.clear();
  8728. }
  8729. inline void ThreadPool::worker(bool is_dynamic) {
  8730. for (;;) {
  8731. std::function<void()> fn;
  8732. {
  8733. std::unique_lock<std::mutex> lock(mutex_);
  8734. idle_thread_count_++;
  8735. if (is_dynamic) {
  8736. auto has_work =
  8737. cond_.wait_for(lock, std::chrono::seconds(idle_timeout_sec_),
  8738. [&] { return !jobs_.empty() || shutdown_; });
  8739. if (!has_work) {
  8740. // Timed out with no work - exit this dynamic thread
  8741. idle_thread_count_--;
  8742. move_to_finished(std::this_thread::get_id());
  8743. break;
  8744. }
  8745. } else {
  8746. cond_.wait(lock, [&] { return !jobs_.empty() || shutdown_; });
  8747. }
  8748. idle_thread_count_--;
  8749. if (shutdown_ && jobs_.empty()) { break; }
  8750. fn = std::move(jobs_.front());
  8751. jobs_.pop_front();
  8752. }
  8753. assert(true == static_cast<bool>(fn));
  8754. fn();
  8755. }
  8756. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  8757. !defined(LIBRESSL_VERSION_NUMBER)
  8758. OPENSSL_thread_stop();
  8759. #endif
  8760. }
  8761. /*
  8762. * Group 1 (continued): detail namespace - Stream implementations
  8763. */
  8764. namespace detail {
  8765. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  8766. time_t timeout_sec, time_t timeout_usec,
  8767. time_t &actual_timeout_sec,
  8768. time_t &actual_timeout_usec) {
  8769. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  8770. auto actual_timeout_msec =
  8771. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  8772. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  8773. actual_timeout_sec = actual_timeout_msec / 1000;
  8774. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  8775. }
  8776. // Socket stream implementation
  8777. inline SocketStream::SocketStream(
  8778. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8779. time_t write_timeout_sec, time_t write_timeout_usec,
  8780. time_t max_timeout_msec,
  8781. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8782. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  8783. read_timeout_usec_(read_timeout_usec),
  8784. write_timeout_sec_(write_timeout_sec),
  8785. write_timeout_usec_(write_timeout_usec),
  8786. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  8787. read_buff_(read_buff_size_, 0) {}
  8788. inline SocketStream::~SocketStream() = default;
  8789. inline bool SocketStream::is_readable() const {
  8790. return read_buff_off_ < read_buff_content_size_;
  8791. }
  8792. inline bool SocketStream::wait_readable() const {
  8793. if (max_timeout_msec_ <= 0) {
  8794. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8795. }
  8796. time_t read_timeout_sec;
  8797. time_t read_timeout_usec;
  8798. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8799. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8800. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8801. }
  8802. inline bool SocketStream::wait_writable() const {
  8803. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  8804. }
  8805. inline bool SocketStream::is_peer_alive() const {
  8806. return detail::is_socket_alive(sock_);
  8807. }
  8808. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  8809. #ifdef _WIN32
  8810. size =
  8811. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8812. #else
  8813. size = (std::min)(size,
  8814. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  8815. #endif
  8816. if (read_buff_off_ < read_buff_content_size_) {
  8817. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  8818. if (size <= remaining_size) {
  8819. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  8820. read_buff_off_ += size;
  8821. return static_cast<ssize_t>(size);
  8822. } else {
  8823. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  8824. read_buff_off_ += remaining_size;
  8825. return static_cast<ssize_t>(remaining_size);
  8826. }
  8827. }
  8828. if (!wait_readable()) {
  8829. error_ = Error::Timeout;
  8830. return -1;
  8831. }
  8832. read_buff_off_ = 0;
  8833. read_buff_content_size_ = 0;
  8834. if (size < read_buff_size_) {
  8835. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  8836. CPPHTTPLIB_RECV_FLAGS);
  8837. if (n <= 0) {
  8838. if (n == 0) {
  8839. error_ = Error::ConnectionClosed;
  8840. } else {
  8841. error_ = Error::Read;
  8842. }
  8843. return n;
  8844. } else if (n <= static_cast<ssize_t>(size)) {
  8845. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  8846. return n;
  8847. } else {
  8848. memcpy(ptr, read_buff_.data(), size);
  8849. read_buff_off_ = size;
  8850. read_buff_content_size_ = static_cast<size_t>(n);
  8851. return static_cast<ssize_t>(size);
  8852. }
  8853. } else {
  8854. auto n = read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  8855. if (n <= 0) {
  8856. if (n == 0) {
  8857. error_ = Error::ConnectionClosed;
  8858. } else {
  8859. error_ = Error::Read;
  8860. }
  8861. }
  8862. return n;
  8863. }
  8864. }
  8865. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  8866. if (!wait_writable()) { return -1; }
  8867. #if defined(_WIN32) && !defined(_WIN64)
  8868. size =
  8869. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  8870. #endif
  8871. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  8872. }
  8873. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  8874. int &port) const {
  8875. return detail::get_remote_ip_and_port(sock_, ip, port);
  8876. }
  8877. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  8878. int &port) const {
  8879. return detail::get_local_ip_and_port(sock_, ip, port);
  8880. }
  8881. inline socket_t SocketStream::socket() const { return sock_; }
  8882. inline time_t SocketStream::duration() const {
  8883. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8884. std::chrono::steady_clock::now() - start_time_)
  8885. .count();
  8886. }
  8887. inline void SocketStream::set_read_timeout(time_t sec, time_t usec) {
  8888. read_timeout_sec_ = sec;
  8889. read_timeout_usec_ = usec;
  8890. }
  8891. // Buffer stream implementation
  8892. inline bool BufferStream::is_readable() const { return true; }
  8893. inline bool BufferStream::wait_readable() const { return true; }
  8894. inline bool BufferStream::wait_writable() const { return true; }
  8895. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  8896. #if defined(_MSC_VER) && _MSC_VER < 1910
  8897. auto len_read = buffer._Copy_s(ptr, size, size, position);
  8898. #else
  8899. auto len_read = buffer.copy(ptr, size, position);
  8900. #endif
  8901. position += static_cast<size_t>(len_read);
  8902. return static_cast<ssize_t>(len_read);
  8903. }
  8904. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  8905. buffer.append(ptr, size);
  8906. return static_cast<ssize_t>(size);
  8907. }
  8908. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  8909. int & /*port*/) const {}
  8910. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  8911. int & /*port*/) const {}
  8912. inline socket_t BufferStream::socket() const { return 0; }
  8913. inline time_t BufferStream::duration() const { return 0; }
  8914. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  8915. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  8916. : MatcherBase(pattern) {
  8917. constexpr const char marker[] = "/:";
  8918. // One past the last ending position of a path param substring
  8919. std::size_t last_param_end = 0;
  8920. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8921. // Needed to ensure that parameter names are unique during matcher
  8922. // construction
  8923. // If exceptions are disabled, only last duplicate path
  8924. // parameter will be set
  8925. std::unordered_set<std::string> param_name_set;
  8926. #endif
  8927. while (true) {
  8928. const auto marker_pos = pattern.find(
  8929. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  8930. if (marker_pos == std::string::npos) { break; }
  8931. static_fragments_.push_back(
  8932. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  8933. const auto param_name_start = marker_pos + str_len(marker);
  8934. auto sep_pos = pattern.find(separator, param_name_start);
  8935. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  8936. auto param_name =
  8937. pattern.substr(param_name_start, sep_pos - param_name_start);
  8938. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8939. if (param_name_set.find(param_name) != param_name_set.cend()) {
  8940. std::string msg = "Encountered path parameter '" + param_name +
  8941. "' multiple times in route pattern '" + pattern + "'.";
  8942. throw std::invalid_argument(msg);
  8943. }
  8944. #endif
  8945. param_names_.push_back(std::move(param_name));
  8946. last_param_end = sep_pos + 1;
  8947. }
  8948. if (last_param_end < pattern.length()) {
  8949. static_fragments_.push_back(pattern.substr(last_param_end));
  8950. }
  8951. }
  8952. inline bool PathParamsMatcher::match(Request &request) const {
  8953. request.matches = std::smatch();
  8954. request.path_params.clear();
  8955. request.path_params.reserve(param_names_.size());
  8956. // One past the position at which the path matched the pattern last time
  8957. std::size_t starting_pos = 0;
  8958. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  8959. const auto &fragment = static_fragments_[i];
  8960. if (starting_pos + fragment.length() > request.path.length()) {
  8961. return false;
  8962. }
  8963. // Avoid unnecessary allocation by using strncmp instead of substr +
  8964. // comparison
  8965. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  8966. fragment.length()) != 0) {
  8967. return false;
  8968. }
  8969. starting_pos += fragment.length();
  8970. // Should only happen when we have a static fragment after a param
  8971. // Example: '/users/:id/subscriptions'
  8972. // The 'subscriptions' fragment here does not have a corresponding param
  8973. if (i >= param_names_.size()) { continue; }
  8974. auto sep_pos = request.path.find(separator, starting_pos);
  8975. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  8976. const auto &param_name = param_names_[i];
  8977. request.path_params.emplace(
  8978. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  8979. // Mark everything up to '/' as matched
  8980. starting_pos = sep_pos + 1;
  8981. }
  8982. // Returns false if the path is longer than the pattern
  8983. return starting_pos >= request.path.length();
  8984. }
  8985. inline bool RegexMatcher::match(Request &request) const {
  8986. request.path_params.clear();
  8987. return std::regex_match(request.path, request.matches, regex_);
  8988. }
  8989. // Enclose IPv6 address in brackets if needed
  8990. inline std::string prepare_host_string(const std::string &host) {
  8991. // Enclose IPv6 address in brackets (but not if already enclosed)
  8992. if (host.find(':') == std::string::npos ||
  8993. (!host.empty() && host[0] == '[')) {
  8994. // IPv4, hostname, or already bracketed IPv6
  8995. return host;
  8996. } else {
  8997. // IPv6 address without brackets
  8998. return "[" + host + "]";
  8999. }
  9000. }
  9001. inline std::string make_host_and_port_string(const std::string &host, int port,
  9002. bool is_ssl) {
  9003. auto result = prepare_host_string(host);
  9004. // Append port if not default
  9005. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  9006. ; // do nothing
  9007. } else {
  9008. result += ":" + std::to_string(port);
  9009. }
  9010. return result;
  9011. }
  9012. // Create "host:port" string always including port number (for CONNECT method)
  9013. inline std::string
  9014. make_host_and_port_string_always_port(const std::string &host, int port) {
  9015. return prepare_host_string(host) + ":" + std::to_string(port);
  9016. }
  9017. bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out);
  9018. NormalizedTarget normalize_target(const std::string &host);
  9019. bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits);
  9020. bool host_matches_no_proxy(const NormalizedTarget &target,
  9021. const std::vector<NoProxyEntry> &entries);
  9022. inline bool ip_in_cidr(const IPBytes &ip, const IPBytes &net, int prefix_bits) {
  9023. if (prefix_bits < 0 || prefix_bits > 128) { return false; }
  9024. if (prefix_bits == 0) { return true; }
  9025. int full_bytes = prefix_bits / 8;
  9026. int rem_bits = prefix_bits % 8;
  9027. if (full_bytes > 0 && std::memcmp(ip.data(), net.data(),
  9028. static_cast<size_t>(full_bytes)) != 0) {
  9029. return false;
  9030. }
  9031. if (rem_bits == 0) { return true; }
  9032. auto i = static_cast<size_t>(full_bytes);
  9033. auto mask = static_cast<uint8_t>(0xFFu << (8 - rem_bits));
  9034. return (ip[i] & mask) == (net[i] & mask);
  9035. }
  9036. inline bool parse_no_proxy_entry(const std::string &token, NoProxyEntry &out) {
  9037. if (token.empty()) { return false; }
  9038. if (token == "*") {
  9039. out.kind = NoProxyKind::Wildcard;
  9040. return true;
  9041. }
  9042. auto slash = token.find('/');
  9043. std::string addr_part =
  9044. (slash == std::string::npos) ? token : token.substr(0, slash);
  9045. std::string prefix_part =
  9046. (slash == std::string::npos) ? std::string() : token.substr(slash + 1);
  9047. // A bare slash or trailing-slash CIDR like "10.0.0.0/" is malformed;
  9048. // don't silently treat it as a /32 (or /128).
  9049. if (slash != std::string::npos && prefix_part.empty()) { return false; }
  9050. // Accept the bracketed IPv6 form ("[::1]", "[fe80::]/10") as well as the
  9051. // bare form. Brackets have no meaning for IPv4, so skip the IPv4 attempt
  9052. // when brackets are present.
  9053. bool bracketed = addr_part.size() >= 2 && addr_part.front() == '[' &&
  9054. addr_part.back() == ']';
  9055. if (bracketed) { addr_part = addr_part.substr(1, addr_part.size() - 2); }
  9056. if (!bracketed) {
  9057. struct in_addr v4;
  9058. if (inet_pton(AF_INET, addr_part.c_str(), &v4) == 1) {
  9059. int prefix = 32;
  9060. if (!prefix_part.empty()) {
  9061. auto r = from_chars(prefix_part.data(),
  9062. prefix_part.data() + prefix_part.size(), prefix);
  9063. if (r.ec != std::errc{} ||
  9064. r.ptr != prefix_part.data() + prefix_part.size()) {
  9065. return false;
  9066. }
  9067. if (prefix < 0 || prefix > 32) { return false; }
  9068. }
  9069. out.kind = NoProxyKind::IPv4Cidr;
  9070. std::memcpy(out.net.data(), &v4, sizeof(v4));
  9071. out.prefix_bits = prefix;
  9072. return true;
  9073. }
  9074. }
  9075. struct in6_addr v6;
  9076. if (inet_pton(AF_INET6, addr_part.c_str(), &v6) == 1) {
  9077. int prefix = 128;
  9078. if (!prefix_part.empty()) {
  9079. auto r = from_chars(prefix_part.data(),
  9080. prefix_part.data() + prefix_part.size(), prefix);
  9081. if (r.ec != std::errc{} ||
  9082. r.ptr != prefix_part.data() + prefix_part.size()) {
  9083. return false;
  9084. }
  9085. if (prefix < 0 || prefix > 128) { return false; }
  9086. }
  9087. out.kind = NoProxyKind::IPv6Cidr;
  9088. std::memcpy(out.net.data(), &v6, sizeof(v6));
  9089. out.prefix_bits = prefix;
  9090. return true;
  9091. }
  9092. // Bracketed entries can only be IPv6. If the IPv6 parse above failed,
  9093. // the entry is malformed — don't fall through to the hostname branch.
  9094. if (bracketed) { return false; }
  9095. // A '/' on a non-IP token means a CIDR prefix without an address. Reject.
  9096. if (slash != std::string::npos) { return false; }
  9097. // Port-specific entries (host:port) are not supported.
  9098. if (token.find(':') != std::string::npos) { return false; }
  9099. std::string hostname = case_ignore::to_lower(token);
  9100. while (!hostname.empty() && hostname.front() == '.') {
  9101. hostname.erase(hostname.begin());
  9102. }
  9103. while (!hostname.empty() && hostname.back() == '.') {
  9104. hostname.pop_back();
  9105. }
  9106. if (hostname.empty()) { return false; }
  9107. out.kind = NoProxyKind::HostnameSuffix;
  9108. out.hostname_pattern = std::move(hostname);
  9109. return true;
  9110. }
  9111. inline NormalizedTarget normalize_target(const std::string &host) {
  9112. NormalizedTarget t;
  9113. std::string h = host;
  9114. if (h.size() >= 2 && h.front() == '[' && h.back() == ']') {
  9115. h = h.substr(1, h.size() - 2);
  9116. }
  9117. // Strip a single trailing dot so "example.com." canonicalizes to
  9118. // "example.com".
  9119. if (!h.empty() && h.back() == '.') { h.pop_back(); }
  9120. t.hostname = case_ignore::to_lower(h);
  9121. if (!t.hostname.empty()) {
  9122. struct in_addr v4;
  9123. struct in6_addr v6;
  9124. if (inet_pton(AF_INET, t.hostname.c_str(), &v4) == 1) {
  9125. t.is_ipv4 = true;
  9126. std::memcpy(t.ip.data(), &v4, sizeof(v4));
  9127. } else if (inet_pton(AF_INET6, t.hostname.c_str(), &v6) == 1) {
  9128. t.is_ipv6 = true;
  9129. std::memcpy(t.ip.data(), &v6, sizeof(v6));
  9130. }
  9131. }
  9132. return t;
  9133. }
  9134. inline bool host_matches_no_proxy(const NormalizedTarget &target,
  9135. const std::vector<NoProxyEntry> &entries) {
  9136. if (target.hostname.empty()) { return false; }
  9137. for (const auto &e : entries) {
  9138. switch (e.kind) {
  9139. case NoProxyKind::Wildcard: return true;
  9140. case NoProxyKind::IPv4Cidr:
  9141. if (target.is_ipv4 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9142. return true;
  9143. }
  9144. break;
  9145. case NoProxyKind::IPv6Cidr:
  9146. if (target.is_ipv6 && ip_in_cidr(target.ip, e.net, e.prefix_bits)) {
  9147. return true;
  9148. }
  9149. break;
  9150. case NoProxyKind::HostnameSuffix:
  9151. if (target.is_ipv4 || target.is_ipv6) { break; }
  9152. if (target.hostname == e.hostname_pattern) { return true; }
  9153. // Dot-boundary suffix match: prevents "evilexample.com" from matching
  9154. // an entry of "example.com".
  9155. if (target.hostname.size() > e.hostname_pattern.size() + 1) {
  9156. auto offset = target.hostname.size() - e.hostname_pattern.size();
  9157. if (target.hostname[offset - 1] == '.' &&
  9158. target.hostname.compare(offset, e.hostname_pattern.size(),
  9159. e.hostname_pattern) == 0) {
  9160. return true;
  9161. }
  9162. }
  9163. break;
  9164. }
  9165. }
  9166. return false;
  9167. }
  9168. template <typename T>
  9169. inline bool check_and_write_headers(Stream &strm, Headers &headers,
  9170. T header_writer, Error &error) {
  9171. for (const auto &h : headers) {
  9172. if (!detail::fields::is_field_name(h.first) ||
  9173. !detail::fields::is_field_value(h.second)) {
  9174. error = Error::InvalidHeaders;
  9175. return false;
  9176. }
  9177. }
  9178. if (header_writer(strm, headers) <= 0) {
  9179. error = Error::Write;
  9180. return false;
  9181. }
  9182. return true;
  9183. }
  9184. } // namespace detail
  9185. /*
  9186. * Group 2 (continued): detail namespace - SSLSocketStream implementation
  9187. */
  9188. #ifdef CPPHTTPLIB_SSL_ENABLED
  9189. namespace detail {
  9190. // SSL socket stream implementation
  9191. inline SSLSocketStream::SSLSocketStream(
  9192. socket_t sock, tls::session_t session, time_t read_timeout_sec,
  9193. time_t read_timeout_usec, time_t write_timeout_sec,
  9194. time_t write_timeout_usec, time_t max_timeout_msec,
  9195. std::chrono::time_point<std::chrono::steady_clock> start_time)
  9196. : sock_(sock), session_(session), read_timeout_sec_(read_timeout_sec),
  9197. read_timeout_usec_(read_timeout_usec),
  9198. write_timeout_sec_(write_timeout_sec),
  9199. write_timeout_usec_(write_timeout_usec),
  9200. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  9201. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9202. // Clear AUTO_RETRY for proper non-blocking I/O timeout handling
  9203. // Note: create_session() also clears this, but SSLClient currently
  9204. // uses ssl_new() which does not. Until full TLS API migration is complete,
  9205. // we need to ensure AUTO_RETRY is cleared here regardless of how the
  9206. // SSL session was created.
  9207. SSL_clear_mode(static_cast<SSL *>(session), SSL_MODE_AUTO_RETRY);
  9208. #endif
  9209. }
  9210. inline SSLSocketStream::~SSLSocketStream() = default;
  9211. inline bool SSLSocketStream::is_readable() const {
  9212. return tls::pending(session_) > 0;
  9213. }
  9214. inline bool SSLSocketStream::wait_readable() const {
  9215. if (max_timeout_msec_ <= 0) {
  9216. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  9217. }
  9218. time_t read_timeout_sec;
  9219. time_t read_timeout_usec;
  9220. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  9221. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  9222. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  9223. }
  9224. inline bool SSLSocketStream::wait_writable() const {
  9225. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  9226. !tls::is_peer_closed(session_, sock_);
  9227. }
  9228. inline bool SSLSocketStream::is_peer_alive() const {
  9229. return !tls::is_peer_closed(session_, sock_);
  9230. }
  9231. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  9232. if (tls::pending(session_) > 0) {
  9233. tls::TlsError err;
  9234. auto ret = tls::read(session_, ptr, size, err);
  9235. if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9236. error_ = Error::ConnectionClosed;
  9237. }
  9238. return ret;
  9239. } else if (wait_readable()) {
  9240. tls::TlsError err;
  9241. auto ret = tls::read(session_, ptr, size, err);
  9242. if (ret < 0) {
  9243. auto n = 1000;
  9244. #ifdef _WIN32
  9245. while (--n >= 0 && (err.code == tls::ErrorCode::WantRead ||
  9246. (err.code == tls::ErrorCode::SyscallError &&
  9247. WSAGetLastError() == WSAETIMEDOUT))) {
  9248. #else
  9249. while (--n >= 0 && err.code == tls::ErrorCode::WantRead) {
  9250. #endif
  9251. if (tls::pending(session_) > 0) {
  9252. return tls::read(session_, ptr, size, err);
  9253. } else if (wait_readable()) {
  9254. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9255. ret = tls::read(session_, ptr, size, err);
  9256. if (ret >= 0) { return ret; }
  9257. } else {
  9258. break;
  9259. }
  9260. }
  9261. assert(ret < 0);
  9262. } else if (ret == 0 || err.code == tls::ErrorCode::PeerClosed) {
  9263. error_ = Error::ConnectionClosed;
  9264. }
  9265. return ret;
  9266. } else {
  9267. error_ = Error::Timeout;
  9268. return -1;
  9269. }
  9270. }
  9271. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  9272. if (wait_writable()) {
  9273. auto handle_size =
  9274. std::min<size_t>(size, (std::numeric_limits<int>::max)());
  9275. tls::TlsError err;
  9276. auto ret = tls::write(session_, ptr, handle_size, err);
  9277. if (ret < 0) {
  9278. auto n = 1000;
  9279. #ifdef _WIN32
  9280. while (--n >= 0 && (err.code == tls::ErrorCode::WantWrite ||
  9281. (err.code == tls::ErrorCode::SyscallError &&
  9282. WSAGetLastError() == WSAETIMEDOUT))) {
  9283. #else
  9284. while (--n >= 0 && err.code == tls::ErrorCode::WantWrite) {
  9285. #endif
  9286. if (wait_writable()) {
  9287. std::this_thread::sleep_for(std::chrono::microseconds{10});
  9288. ret = tls::write(session_, ptr, handle_size, err);
  9289. if (ret >= 0) { return ret; }
  9290. } else {
  9291. break;
  9292. }
  9293. }
  9294. assert(ret < 0);
  9295. }
  9296. return ret;
  9297. }
  9298. return -1;
  9299. }
  9300. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  9301. int &port) const {
  9302. detail::get_remote_ip_and_port(sock_, ip, port);
  9303. }
  9304. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  9305. int &port) const {
  9306. detail::get_local_ip_and_port(sock_, ip, port);
  9307. }
  9308. inline socket_t SSLSocketStream::socket() const { return sock_; }
  9309. inline time_t SSLSocketStream::duration() const {
  9310. return std::chrono::duration_cast<std::chrono::milliseconds>(
  9311. std::chrono::steady_clock::now() - start_time_)
  9312. .count();
  9313. }
  9314. inline void SSLSocketStream::set_read_timeout(time_t sec, time_t usec) {
  9315. read_timeout_sec_ = sec;
  9316. read_timeout_usec_ = usec;
  9317. }
  9318. } // namespace detail
  9319. #endif // CPPHTTPLIB_SSL_ENABLED
  9320. /*
  9321. * Group 4: Server implementation
  9322. */
  9323. // HTTP server implementation
  9324. inline Server::Server()
  9325. : new_task_queue([] {
  9326. return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT,
  9327. CPPHTTPLIB_THREAD_POOL_MAX_COUNT);
  9328. }) {
  9329. #ifndef _WIN32
  9330. signal(SIGPIPE, SIG_IGN);
  9331. #endif
  9332. }
  9333. inline Server::~Server() = default;
  9334. inline std::unique_ptr<detail::MatcherBase>
  9335. Server::make_matcher(const std::string &pattern) {
  9336. if (pattern.find("/:") != std::string::npos) {
  9337. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  9338. } else {
  9339. return detail::make_unique<detail::RegexMatcher>(pattern);
  9340. }
  9341. }
  9342. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  9343. return add_handler(get_handlers_, pattern, std::move(handler));
  9344. }
  9345. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  9346. return add_handler(post_handlers_, pattern, std::move(handler));
  9347. }
  9348. inline Server &Server::Post(const std::string &pattern,
  9349. HandlerWithContentReader handler) {
  9350. return add_handler(post_handlers_for_content_reader_, pattern,
  9351. std::move(handler));
  9352. }
  9353. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  9354. return add_handler(put_handlers_, pattern, std::move(handler));
  9355. }
  9356. inline Server &Server::Put(const std::string &pattern,
  9357. HandlerWithContentReader handler) {
  9358. return add_handler(put_handlers_for_content_reader_, pattern,
  9359. std::move(handler));
  9360. }
  9361. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  9362. return add_handler(patch_handlers_, pattern, std::move(handler));
  9363. }
  9364. inline Server &Server::Patch(const std::string &pattern,
  9365. HandlerWithContentReader handler) {
  9366. return add_handler(patch_handlers_for_content_reader_, pattern,
  9367. std::move(handler));
  9368. }
  9369. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  9370. return add_handler(delete_handlers_, pattern, std::move(handler));
  9371. }
  9372. inline Server &Server::Delete(const std::string &pattern,
  9373. HandlerWithContentReader handler) {
  9374. return add_handler(delete_handlers_for_content_reader_, pattern,
  9375. std::move(handler));
  9376. }
  9377. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  9378. return add_handler(options_handlers_, pattern, std::move(handler));
  9379. }
  9380. inline Server &Server::WebSocket(const std::string &pattern,
  9381. WebSocketHandler handler) {
  9382. websocket_handlers_.push_back(
  9383. {make_matcher(pattern), std::move(handler), nullptr});
  9384. return *this;
  9385. }
  9386. inline Server &Server::WebSocket(const std::string &pattern,
  9387. WebSocketHandler handler,
  9388. SubProtocolSelector sub_protocol_selector) {
  9389. websocket_handlers_.push_back({make_matcher(pattern), std::move(handler),
  9390. std::move(sub_protocol_selector)});
  9391. return *this;
  9392. }
  9393. inline bool Server::set_base_dir(const std::string &dir,
  9394. const std::string &mount_point) {
  9395. return set_mount_point(mount_point, dir);
  9396. }
  9397. inline bool Server::set_mount_point(const std::string &mount_point,
  9398. const std::string &dir, Headers headers) {
  9399. detail::FileStat stat(dir);
  9400. if (stat.is_dir()) {
  9401. std::string mnt = !mount_point.empty() ? mount_point : "/";
  9402. if (!mnt.empty() && mnt[0] == '/') {
  9403. std::string resolved_base;
  9404. if (detail::canonicalize_path(dir.c_str(), resolved_base)) {
  9405. #if defined(_WIN32)
  9406. if (resolved_base.back() != '\\' && resolved_base.back() != '/') {
  9407. resolved_base += '\\';
  9408. }
  9409. #else
  9410. if (resolved_base.back() != '/') { resolved_base += '/'; }
  9411. #endif
  9412. }
  9413. base_dirs_.push_back(
  9414. {std::move(mnt), dir, std::move(resolved_base), std::move(headers)});
  9415. return true;
  9416. }
  9417. }
  9418. return false;
  9419. }
  9420. inline bool Server::remove_mount_point(const std::string &mount_point) {
  9421. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  9422. if (it->mount_point == mount_point) {
  9423. base_dirs_.erase(it);
  9424. return true;
  9425. }
  9426. }
  9427. return false;
  9428. }
  9429. inline Server &
  9430. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  9431. const std::string &mime) {
  9432. file_extension_and_mimetype_map_[ext] = mime;
  9433. return *this;
  9434. }
  9435. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  9436. default_file_mimetype_ = mime;
  9437. return *this;
  9438. }
  9439. inline Server &Server::set_file_request_handler(Handler handler) {
  9440. file_request_handler_ = std::move(handler);
  9441. return *this;
  9442. }
  9443. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  9444. std::true_type) {
  9445. error_handler_ = std::move(handler);
  9446. return *this;
  9447. }
  9448. inline Server &Server::set_error_handler_core(Handler handler,
  9449. std::false_type) {
  9450. error_handler_ = [handler](const Request &req, Response &res) {
  9451. handler(req, res);
  9452. return HandlerResponse::Handled;
  9453. };
  9454. return *this;
  9455. }
  9456. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  9457. exception_handler_ = std::move(handler);
  9458. return *this;
  9459. }
  9460. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  9461. pre_routing_handler_ = std::move(handler);
  9462. return *this;
  9463. }
  9464. inline Server &Server::set_post_routing_handler(Handler handler) {
  9465. post_routing_handler_ = std::move(handler);
  9466. return *this;
  9467. }
  9468. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  9469. pre_request_handler_ = std::move(handler);
  9470. return *this;
  9471. }
  9472. inline Server &Server::set_logger(Logger logger) {
  9473. logger_ = std::move(logger);
  9474. return *this;
  9475. }
  9476. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  9477. error_logger_ = std::move(error_logger);
  9478. return *this;
  9479. }
  9480. inline Server &Server::set_pre_compression_logger(Logger logger) {
  9481. pre_compression_logger_ = std::move(logger);
  9482. return *this;
  9483. }
  9484. inline Server &
  9485. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  9486. expect_100_continue_handler_ = std::move(handler);
  9487. return *this;
  9488. }
  9489. inline Server &Server::set_start_handler(StartHandler handler) {
  9490. start_handler_ = std::move(handler);
  9491. return *this;
  9492. }
  9493. inline Server &Server::set_address_family(int family) {
  9494. address_family_ = family;
  9495. return *this;
  9496. }
  9497. inline Server &Server::set_tcp_nodelay(bool on) {
  9498. tcp_nodelay_ = on;
  9499. return *this;
  9500. }
  9501. inline Server &Server::set_ipv6_v6only(bool on) {
  9502. ipv6_v6only_ = on;
  9503. return *this;
  9504. }
  9505. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  9506. socket_options_ = std::move(socket_options);
  9507. return *this;
  9508. }
  9509. inline Server &Server::set_default_headers(Headers headers) {
  9510. default_headers_ = std::move(headers);
  9511. return *this;
  9512. }
  9513. inline Server &Server::set_header_writer(
  9514. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9515. header_writer_ = writer;
  9516. return *this;
  9517. }
  9518. inline Server &
  9519. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  9520. trusted_proxies_ = proxies;
  9521. return *this;
  9522. }
  9523. inline Server &Server::set_keep_alive_max_count(size_t count) {
  9524. keep_alive_max_count_ = count;
  9525. return *this;
  9526. }
  9527. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  9528. keep_alive_timeout_sec_ = sec;
  9529. return *this;
  9530. }
  9531. template <class Rep, class Period>
  9532. inline Server &Server::set_keep_alive_timeout(
  9533. const std::chrono::duration<Rep, Period> &duration) {
  9534. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9535. set_keep_alive_timeout(sec);
  9536. });
  9537. return *this;
  9538. }
  9539. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  9540. read_timeout_sec_ = sec;
  9541. read_timeout_usec_ = usec;
  9542. return *this;
  9543. }
  9544. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  9545. write_timeout_sec_ = sec;
  9546. write_timeout_usec_ = usec;
  9547. return *this;
  9548. }
  9549. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  9550. idle_interval_sec_ = sec;
  9551. idle_interval_usec_ = usec;
  9552. return *this;
  9553. }
  9554. inline Server &Server::set_payload_max_length(size_t length) {
  9555. payload_max_length_ = length;
  9556. return *this;
  9557. }
  9558. inline Server &Server::set_websocket_max_missed_pongs(int count) {
  9559. websocket_max_missed_pongs_ = count;
  9560. return *this;
  9561. }
  9562. inline Server &Server::set_websocket_ping_interval(time_t sec) {
  9563. websocket_ping_interval_sec_ = sec;
  9564. return *this;
  9565. }
  9566. template <class Rep, class Period>
  9567. inline Server &Server::set_websocket_ping_interval(
  9568. const std::chrono::duration<Rep, Period> &duration) {
  9569. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t /*usec*/) {
  9570. set_websocket_ping_interval(sec);
  9571. });
  9572. return *this;
  9573. }
  9574. inline bool Server::bind_to_port(const std::string &host, int port,
  9575. int socket_flags) {
  9576. auto ret = bind_internal(host, port, socket_flags);
  9577. if (ret == -1) { is_decommissioned = true; }
  9578. return ret >= 0;
  9579. }
  9580. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  9581. auto ret = bind_internal(host, 0, socket_flags);
  9582. if (ret == -1) { is_decommissioned = true; }
  9583. return ret;
  9584. }
  9585. inline bool Server::listen_after_bind() { return listen_internal(); }
  9586. inline bool Server::listen(const std::string &host, int port,
  9587. int socket_flags) {
  9588. return bind_to_port(host, port, socket_flags) && listen_internal();
  9589. }
  9590. inline bool Server::is_running() const { return is_running_; }
  9591. inline void Server::wait_until_ready() const {
  9592. while (!is_running_ && !is_decommissioned) {
  9593. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  9594. }
  9595. }
  9596. inline void Server::stop() noexcept {
  9597. if (is_running_) {
  9598. assert(svr_sock_ != INVALID_SOCKET);
  9599. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  9600. detail::shutdown_socket(sock);
  9601. detail::close_socket(sock);
  9602. }
  9603. is_decommissioned = false;
  9604. }
  9605. inline void Server::decommission() { is_decommissioned = true; }
  9606. inline bool Server::parse_request_line(const char *s, Request &req) const {
  9607. auto len = strlen(s);
  9608. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  9609. len -= 2;
  9610. {
  9611. size_t count = 0;
  9612. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  9613. switch (count) {
  9614. case 0: req.method = std::string(b, e); break;
  9615. case 1: req.target = std::string(b, e); break;
  9616. case 2: req.version = std::string(b, e); break;
  9617. default: break;
  9618. }
  9619. count++;
  9620. });
  9621. if (count != 3) { return false; }
  9622. }
  9623. thread_local const std::set<std::string> methods{
  9624. "GET", "HEAD", "POST", "PUT", "DELETE",
  9625. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9626. if (methods.find(req.method) == methods.end()) {
  9627. output_error_log(Error::InvalidHTTPMethod, &req);
  9628. return false;
  9629. }
  9630. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  9631. output_error_log(Error::InvalidHTTPVersion, &req);
  9632. return false;
  9633. }
  9634. {
  9635. // Skip URL fragment
  9636. for (size_t i = 0; i < req.target.size(); i++) {
  9637. if (req.target[i] == '#') {
  9638. req.target.erase(i);
  9639. break;
  9640. }
  9641. }
  9642. detail::divide(req.target, '?',
  9643. [&](const char *lhs_data, std::size_t lhs_size,
  9644. const char *rhs_data, std::size_t rhs_size) {
  9645. req.path =
  9646. decode_path_component(std::string(lhs_data, lhs_size));
  9647. detail::parse_query_text(rhs_data, rhs_size, req.params);
  9648. });
  9649. }
  9650. return true;
  9651. }
  9652. inline bool Server::write_response(Stream &strm, bool close_connection,
  9653. Request &req, Response &res) {
  9654. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  9655. // incorrectly to the error content.
  9656. req.ranges.clear();
  9657. return write_response_core(strm, close_connection, req, res, false);
  9658. }
  9659. inline bool Server::write_response_with_content(Stream &strm,
  9660. bool close_connection,
  9661. const Request &req,
  9662. Response &res) {
  9663. return write_response_core(strm, close_connection, req, res, true);
  9664. }
  9665. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  9666. const Request &req, Response &res,
  9667. bool need_apply_ranges) {
  9668. assert(res.status != -1);
  9669. if (400 <= res.status && error_handler_ &&
  9670. error_handler_(req, res) == HandlerResponse::Handled) {
  9671. need_apply_ranges = true;
  9672. }
  9673. std::string content_type;
  9674. std::string boundary;
  9675. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  9676. // Prepare additional headers
  9677. if (close_connection || req.get_header_value("Connection") == "close" ||
  9678. 400 <= res.status) { // Don't leave connections open after errors
  9679. res.set_header("Connection", "close");
  9680. } else {
  9681. std::string s = "timeout=";
  9682. s += std::to_string(keep_alive_timeout_sec_);
  9683. s += ", max=";
  9684. s += std::to_string(keep_alive_max_count_);
  9685. res.set_header("Keep-Alive", s);
  9686. }
  9687. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  9688. !res.has_header("Content-Type")) {
  9689. res.set_header("Content-Type", "text/plain");
  9690. }
  9691. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  9692. !res.has_header("Content-Length")) {
  9693. res.set_header("Content-Length", "0");
  9694. }
  9695. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  9696. res.set_header("Accept-Ranges", "bytes");
  9697. }
  9698. if (post_routing_handler_) { post_routing_handler_(req, res); }
  9699. // Response line and headers
  9700. detail::BufferStream bstrm;
  9701. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  9702. if (header_writer_(bstrm, res.headers) <= 0) { return false; }
  9703. // Combine small body with headers to reduce write syscalls
  9704. if (req.method != "HEAD" && !res.body.empty() && !res.content_provider_) {
  9705. bstrm.write(res.body.data(), res.body.size());
  9706. }
  9707. // Log before writing to avoid race condition with client-side code that
  9708. // accesses logger-captured data immediately after receiving the response.
  9709. output_log(req, res);
  9710. // Flush buffer
  9711. auto &data = bstrm.get_buffer();
  9712. if (!detail::write_data(strm, data.data(), data.size())) { return false; }
  9713. // Streaming body
  9714. auto ret = true;
  9715. if (req.method != "HEAD" && res.content_provider_) {
  9716. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  9717. res.content_provider_success_ = true;
  9718. } else {
  9719. ret = false;
  9720. }
  9721. }
  9722. return ret;
  9723. }
  9724. inline bool
  9725. Server::write_content_with_provider(Stream &strm, const Request &req,
  9726. Response &res, const std::string &boundary,
  9727. const std::string &content_type) {
  9728. auto is_shutting_down = [this]() {
  9729. return this->svr_sock_ == INVALID_SOCKET;
  9730. };
  9731. if (res.content_length_ > 0) {
  9732. if (req.ranges.empty()) {
  9733. return detail::write_content(strm, res.content_provider_, 0,
  9734. res.content_length_, is_shutting_down);
  9735. } else if (req.ranges.size() == 1) {
  9736. auto offset_and_length = detail::get_range_offset_and_length(
  9737. req.ranges[0], res.content_length_);
  9738. return detail::write_content(strm, res.content_provider_,
  9739. offset_and_length.first,
  9740. offset_and_length.second, is_shutting_down);
  9741. } else {
  9742. return detail::write_multipart_ranges_data(
  9743. strm, req, res, boundary, content_type, res.content_length_,
  9744. is_shutting_down);
  9745. }
  9746. } else {
  9747. if (res.is_chunked_content_provider_) {
  9748. auto type = detail::encoding_type(req, res);
  9749. auto compressor = detail::make_compressor(type);
  9750. if (!compressor) {
  9751. compressor = detail::make_unique<detail::nocompressor>();
  9752. }
  9753. return detail::write_content_chunked(strm, res.content_provider_,
  9754. is_shutting_down, *compressor);
  9755. } else {
  9756. return detail::write_content_without_length(strm, res.content_provider_,
  9757. is_shutting_down);
  9758. }
  9759. }
  9760. }
  9761. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  9762. FormFields::iterator cur_field;
  9763. FormFiles::iterator cur_file;
  9764. auto is_text_field = false;
  9765. size_t count = 0;
  9766. if (read_content_core(
  9767. strm, req, res,
  9768. // Regular
  9769. [&](const char *buf, size_t n) {
  9770. // Prevent arithmetic overflow when checking sizes.
  9771. // Avoid computing (req.body.size() + n) directly because
  9772. // adding two unsigned `size_t` values can wrap around and
  9773. // produce a small result instead of indicating overflow.
  9774. // Instead, check using subtraction: ensure `n` does not
  9775. // exceed the remaining capacity `max_size() - size()`.
  9776. if (req.body.size() >= req.body.max_size() ||
  9777. n > req.body.max_size() - req.body.size()) {
  9778. return false;
  9779. }
  9780. // Limit decompressed body size to payload_max_length_ to protect
  9781. // against "zip bomb" attacks where a small compressed payload
  9782. // decompresses to a massive size.
  9783. if (payload_max_length_ > 0 &&
  9784. (req.body.size() >= payload_max_length_ ||
  9785. n > payload_max_length_ - req.body.size())) {
  9786. return false;
  9787. }
  9788. req.body.append(buf, n);
  9789. return true;
  9790. },
  9791. // Multipart FormData
  9792. [&](const FormData &file) {
  9793. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  9794. output_error_log(Error::TooManyFormDataFiles, &req);
  9795. return false;
  9796. }
  9797. if (file.filename.empty()) {
  9798. cur_field = req.form.fields.emplace(
  9799. file.name, FormField{file.name, file.content, file.headers});
  9800. is_text_field = true;
  9801. } else {
  9802. cur_file = req.form.files.emplace(file.name, file);
  9803. is_text_field = false;
  9804. }
  9805. return true;
  9806. },
  9807. [&](const char *buf, size_t n) {
  9808. if (is_text_field) {
  9809. auto &content = cur_field->second.content;
  9810. if (content.size() + n > content.max_size()) { return false; }
  9811. content.append(buf, n);
  9812. } else {
  9813. auto &content = cur_file->second.content;
  9814. if (content.size() + n > content.max_size()) { return false; }
  9815. content.append(buf, n);
  9816. }
  9817. return true;
  9818. })) {
  9819. const auto &content_type = req.get_header_value("Content-Type");
  9820. if (detail::extract_media_type(content_type) ==
  9821. "application/x-www-form-urlencoded") {
  9822. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  9823. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  9824. output_error_log(Error::ExceedMaxPayloadSize, &req);
  9825. return false;
  9826. }
  9827. detail::parse_query_text(req.body, req.params);
  9828. }
  9829. return true;
  9830. }
  9831. return false;
  9832. }
  9833. inline bool Server::read_content_with_content_receiver(
  9834. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9835. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  9836. return read_content_core(strm, req, res, std::move(receiver),
  9837. std::move(multipart_header),
  9838. std::move(multipart_receiver));
  9839. }
  9840. inline bool Server::read_content_core(
  9841. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  9842. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  9843. detail::FormDataParser multipart_form_data_parser;
  9844. ContentReceiverWithProgress out;
  9845. if (req.is_multipart_form_data()) {
  9846. const auto &content_type = req.get_header_value("Content-Type");
  9847. std::string boundary;
  9848. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  9849. res.status = StatusCode::BadRequest_400;
  9850. output_error_log(Error::MultipartParsing, &req);
  9851. return false;
  9852. }
  9853. multipart_form_data_parser.set_boundary(std::move(boundary));
  9854. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  9855. return multipart_form_data_parser.parse(buf, n, multipart_header,
  9856. multipart_receiver);
  9857. };
  9858. } else {
  9859. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  9860. size_t /*len*/) { return receiver(buf, n); };
  9861. }
  9862. // RFC 9112 §6: no Transfer-Encoding and no Content-Length means no body.
  9863. // For non-SSL builds we still scan non-persistent connections for stray
  9864. // body bytes so the payload limit is enforced (413). On keep-alive,
  9865. // pending bytes may be the next request (issue #2450), so skip.
  9866. #if !defined(CPPHTTPLIB_SSL_ENABLED)
  9867. if (!req.has_header("Content-Length") &&
  9868. !detail::is_chunked_transfer_encoding(req.headers)) {
  9869. if (!detail::is_connection_persistent(req) && payload_max_length_ > 0 &&
  9870. payload_max_length_ < (std::numeric_limits<size_t>::max)()) {
  9871. auto has_data = strm.is_readable();
  9872. if (!has_data) {
  9873. auto s = strm.socket();
  9874. if (s != INVALID_SOCKET) {
  9875. has_data = detail::select_read(s, 0, 0) > 0;
  9876. }
  9877. }
  9878. if (has_data) {
  9879. auto result =
  9880. detail::read_content_without_length(strm, payload_max_length_, out);
  9881. if (result == detail::ReadContentResult::PayloadTooLarge) {
  9882. res.status = StatusCode::PayloadTooLarge_413;
  9883. return false;
  9884. } else if (result != detail::ReadContentResult::Success) {
  9885. return false;
  9886. }
  9887. return true;
  9888. }
  9889. }
  9890. return true;
  9891. }
  9892. #else
  9893. if (!req.has_header("Content-Length") &&
  9894. !detail::is_chunked_transfer_encoding(req.headers)) {
  9895. return true;
  9896. }
  9897. #endif
  9898. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  9899. out, true)) {
  9900. return false;
  9901. }
  9902. req.body_consumed_ = true;
  9903. if (req.is_multipart_form_data()) {
  9904. if (!multipart_form_data_parser.is_valid()) {
  9905. res.status = StatusCode::BadRequest_400;
  9906. output_error_log(Error::MultipartParsing, &req);
  9907. return false;
  9908. }
  9909. }
  9910. return true;
  9911. }
  9912. inline bool Server::handle_file_request(Request &req, Response &res) {
  9913. for (const auto &entry : base_dirs_) {
  9914. // Prefix match
  9915. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  9916. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  9917. if (detail::is_valid_path(sub_path)) {
  9918. auto path = entry.base_dir + sub_path;
  9919. if (path.back() == '/') { path += "index.html"; }
  9920. // Defense-in-depth: is_valid_path blocks ".." traversal in the URL,
  9921. // but symlinks/junctions can still escape the base directory.
  9922. if (!entry.resolved_base_dir.empty()) {
  9923. std::string resolved_path;
  9924. if (detail::canonicalize_path(path.c_str(), resolved_path) &&
  9925. !detail::is_path_within_base(resolved_path,
  9926. entry.resolved_base_dir)) {
  9927. res.status = StatusCode::Forbidden_403;
  9928. return true;
  9929. }
  9930. }
  9931. detail::FileStat stat(path);
  9932. if (stat.is_dir()) {
  9933. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  9934. return true;
  9935. }
  9936. if (stat.is_file()) {
  9937. for (const auto &kv : entry.headers) {
  9938. res.set_header(kv.first, kv.second);
  9939. }
  9940. auto etag = detail::compute_etag(stat);
  9941. if (!etag.empty()) { res.set_header("ETag", etag); }
  9942. auto mtime = stat.mtime();
  9943. auto last_modified = detail::file_mtime_to_http_date(mtime);
  9944. if (!last_modified.empty()) {
  9945. res.set_header("Last-Modified", last_modified);
  9946. }
  9947. if (check_if_not_modified(req, res, etag, mtime)) { return true; }
  9948. check_if_range(req, etag, mtime);
  9949. auto mm = std::make_shared<detail::mmap>(path.c_str());
  9950. if (!mm->is_open()) {
  9951. output_error_log(Error::OpenFile, &req);
  9952. return false;
  9953. }
  9954. res.set_content_provider(
  9955. mm->size(),
  9956. detail::find_content_type(path, file_extension_and_mimetype_map_,
  9957. default_file_mimetype_),
  9958. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  9959. sink.write(mm->data() + offset, length);
  9960. return true;
  9961. });
  9962. if (req.method != "HEAD" && file_request_handler_) {
  9963. file_request_handler_(req, res);
  9964. }
  9965. return true;
  9966. } else {
  9967. output_error_log(Error::OpenFile, &req);
  9968. }
  9969. }
  9970. }
  9971. }
  9972. return false;
  9973. }
  9974. inline bool Server::check_if_not_modified(const Request &req, Response &res,
  9975. const std::string &etag,
  9976. time_t mtime) const {
  9977. // Handle conditional GET:
  9978. // 1. If-None-Match takes precedence (RFC 9110 Section 13.1.2)
  9979. // 2. If-Modified-Since is checked only when If-None-Match is absent
  9980. if (req.has_header("If-None-Match")) {
  9981. if (!etag.empty()) {
  9982. auto val = req.get_header_value("If-None-Match");
  9983. // NOTE: We use exact string matching here. This works correctly
  9984. // because our server always generates weak ETags (W/"..."), and
  9985. // clients typically send back the same ETag they received.
  9986. // RFC 9110 Section 8.8.3.2 allows weak comparison for
  9987. // If-None-Match, where W/"x" and "x" would match, but this
  9988. // simplified implementation requires exact matches.
  9989. auto ret = detail::split_find(val.data(), val.data() + val.size(), ',',
  9990. [&](const char *b, const char *e) {
  9991. auto seg_len = static_cast<size_t>(e - b);
  9992. return (seg_len == 1 && *b == '*') ||
  9993. (seg_len == etag.size() &&
  9994. std::equal(b, e, etag.begin()));
  9995. });
  9996. if (ret) {
  9997. res.status = StatusCode::NotModified_304;
  9998. return true;
  9999. }
  10000. }
  10001. } else if (req.has_header("If-Modified-Since")) {
  10002. auto val = req.get_header_value("If-Modified-Since");
  10003. auto t = detail::parse_http_date(val);
  10004. if (t != static_cast<time_t>(-1) && mtime <= t) {
  10005. res.status = StatusCode::NotModified_304;
  10006. return true;
  10007. }
  10008. }
  10009. return false;
  10010. }
  10011. inline bool Server::check_if_range(Request &req, const std::string &etag,
  10012. time_t mtime) const {
  10013. // Handle If-Range for partial content requests (RFC 9110
  10014. // Section 13.1.5). If-Range is only evaluated when Range header is
  10015. // present. If the validator matches, serve partial content; otherwise
  10016. // serve full content.
  10017. if (!req.ranges.empty() && req.has_header("If-Range")) {
  10018. auto val = req.get_header_value("If-Range");
  10019. auto is_valid_range = [&]() {
  10020. if (detail::is_strong_etag(val)) {
  10021. // RFC 9110 Section 13.1.5: If-Range requires strong ETag
  10022. // comparison.
  10023. return (!etag.empty() && val == etag);
  10024. } else if (detail::is_weak_etag(val)) {
  10025. // Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
  10026. return false;
  10027. } else {
  10028. // HTTP-date comparison
  10029. auto t = detail::parse_http_date(val);
  10030. return (t != static_cast<time_t>(-1) && mtime <= t);
  10031. }
  10032. };
  10033. if (!is_valid_range()) {
  10034. // Validator doesn't match: ignore Range and serve full content
  10035. req.ranges.clear();
  10036. return false;
  10037. }
  10038. }
  10039. return true;
  10040. }
  10041. inline socket_t
  10042. Server::create_server_socket(const std::string &host, int port,
  10043. int socket_flags,
  10044. SocketOptions socket_options) const {
  10045. return detail::create_socket(
  10046. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  10047. ipv6_v6only_, std::move(socket_options),
  10048. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  10049. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  10050. output_error_log(Error::BindIPAddress, nullptr);
  10051. return false;
  10052. }
  10053. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  10054. output_error_log(Error::Listen, nullptr);
  10055. return false;
  10056. }
  10057. return true;
  10058. });
  10059. }
  10060. inline int Server::bind_internal(const std::string &host, int port,
  10061. int socket_flags) {
  10062. if (is_decommissioned) { return -1; }
  10063. if (!is_valid()) { return -1; }
  10064. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  10065. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  10066. if (port == 0) {
  10067. struct sockaddr_storage addr;
  10068. socklen_t addr_len = sizeof(addr);
  10069. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  10070. &addr_len) == -1) {
  10071. output_error_log(Error::GetSockName, nullptr);
  10072. return -1;
  10073. }
  10074. if (addr.ss_family == AF_INET) {
  10075. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  10076. } else if (addr.ss_family == AF_INET6) {
  10077. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  10078. } else {
  10079. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  10080. return -1;
  10081. }
  10082. } else {
  10083. return port;
  10084. }
  10085. }
  10086. inline bool Server::listen_internal() {
  10087. if (is_decommissioned) { return false; }
  10088. auto ret = true;
  10089. is_running_ = true;
  10090. auto se = detail::scope_exit([&]() { is_running_ = false; });
  10091. if (start_handler_) { start_handler_(); }
  10092. {
  10093. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  10094. while (svr_sock_ != INVALID_SOCKET) {
  10095. #ifndef _WIN32
  10096. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  10097. #endif
  10098. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  10099. idle_interval_usec_);
  10100. if (val == 0) { // Timeout
  10101. task_queue->on_idle();
  10102. continue;
  10103. }
  10104. #ifndef _WIN32
  10105. }
  10106. #endif
  10107. #if defined _WIN32
  10108. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  10109. // OVERLAPPED
  10110. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  10111. #elif defined SOCK_CLOEXEC
  10112. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  10113. #else
  10114. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  10115. #endif
  10116. if (sock == INVALID_SOCKET) {
  10117. if (errno == EMFILE) {
  10118. // The per-process limit of open file descriptors has been reached.
  10119. // Try to accept new connections after a short sleep.
  10120. std::this_thread::sleep_for(std::chrono::microseconds{1});
  10121. continue;
  10122. } else if (errno == EINTR || errno == EAGAIN) {
  10123. continue;
  10124. }
  10125. if (svr_sock_ != INVALID_SOCKET) {
  10126. detail::close_socket(svr_sock_);
  10127. ret = false;
  10128. output_error_log(Error::Connection, nullptr);
  10129. } else {
  10130. ; // The server socket was closed by user.
  10131. }
  10132. break;
  10133. }
  10134. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  10135. read_timeout_sec_, read_timeout_usec_);
  10136. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  10137. write_timeout_sec_, write_timeout_usec_);
  10138. if (tcp_nodelay_) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  10139. if (!task_queue->enqueue(
  10140. [this, sock]() { process_and_close_socket(sock); })) {
  10141. output_error_log(Error::ResourceExhaustion, nullptr);
  10142. detail::shutdown_socket(sock);
  10143. detail::close_socket(sock);
  10144. }
  10145. }
  10146. task_queue->shutdown();
  10147. }
  10148. is_decommissioned = !ret;
  10149. return ret;
  10150. }
  10151. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  10152. if (pre_routing_handler_ &&
  10153. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10154. return true;
  10155. }
  10156. // File handler
  10157. if ((req.method == "GET" || req.method == "HEAD") &&
  10158. handle_file_request(req, res)) {
  10159. return true;
  10160. }
  10161. if (detail::expect_content(req)) {
  10162. // Content reader handler
  10163. {
  10164. // Track whether the ContentReader was aborted due to the decompressed
  10165. // payload exceeding `payload_max_length_`.
  10166. // The user handler runs after the lambda returns, so we must restore the
  10167. // 413 status if the handler overwrites it.
  10168. bool content_reader_payload_too_large = false;
  10169. ContentReader reader(
  10170. [&](ContentReceiver receiver) {
  10171. auto result = read_content_with_content_receiver(
  10172. strm, req, res, std::move(receiver), nullptr, nullptr);
  10173. if (!result) {
  10174. output_error_log(Error::Read, &req);
  10175. if (res.status == StatusCode::PayloadTooLarge_413) {
  10176. content_reader_payload_too_large = true;
  10177. }
  10178. }
  10179. return result;
  10180. },
  10181. [&](FormDataHeader header, ContentReceiver receiver) {
  10182. auto result = read_content_with_content_receiver(
  10183. strm, req, res, nullptr, std::move(header),
  10184. std::move(receiver));
  10185. if (!result) {
  10186. output_error_log(Error::Read, &req);
  10187. if (res.status == StatusCode::PayloadTooLarge_413) {
  10188. content_reader_payload_too_large = true;
  10189. }
  10190. }
  10191. return result;
  10192. });
  10193. bool dispatched = false;
  10194. if (req.method == "POST") {
  10195. dispatched = dispatch_request_for_content_reader(
  10196. req, res, std::move(reader), post_handlers_for_content_reader_);
  10197. } else if (req.method == "PUT") {
  10198. dispatched = dispatch_request_for_content_reader(
  10199. req, res, std::move(reader), put_handlers_for_content_reader_);
  10200. } else if (req.method == "PATCH") {
  10201. dispatched = dispatch_request_for_content_reader(
  10202. req, res, std::move(reader), patch_handlers_for_content_reader_);
  10203. } else if (req.method == "DELETE") {
  10204. dispatched = dispatch_request_for_content_reader(
  10205. req, res, std::move(reader), delete_handlers_for_content_reader_);
  10206. }
  10207. if (dispatched) {
  10208. if (content_reader_payload_too_large) {
  10209. // Enforce the limit: override any status the handler may have set
  10210. // and return false so the error path sends a plain 413 response.
  10211. res.status = StatusCode::PayloadTooLarge_413;
  10212. res.body.clear();
  10213. res.content_length_ = 0;
  10214. res.content_provider_ = nullptr;
  10215. return false;
  10216. }
  10217. return true;
  10218. }
  10219. }
  10220. // NOTE: `req.body` is not read here. For a regular handler the body is
  10221. // read inside dispatch_request(), after the route has matched and the
  10222. // pre-request handler has approved the request, so that a rejected
  10223. // request (e.g. failed authentication) never forces us to buffer a
  10224. // potentially large body.
  10225. }
  10226. // Regular handler
  10227. if (req.method == "GET" || req.method == "HEAD") {
  10228. return dispatch_request(req, res, get_handlers_, strm);
  10229. } else if (req.method == "POST") {
  10230. return dispatch_request(req, res, post_handlers_, strm);
  10231. } else if (req.method == "PUT") {
  10232. return dispatch_request(req, res, put_handlers_, strm);
  10233. } else if (req.method == "DELETE") {
  10234. return dispatch_request(req, res, delete_handlers_, strm);
  10235. } else if (req.method == "OPTIONS") {
  10236. return dispatch_request(req, res, options_handlers_, strm);
  10237. } else if (req.method == "PATCH") {
  10238. return dispatch_request(req, res, patch_handlers_, strm);
  10239. }
  10240. res.status = StatusCode::BadRequest_400;
  10241. return false;
  10242. }
  10243. inline bool Server::dispatch_request(Request &req, Response &res,
  10244. const Handlers &handlers, Stream &strm) {
  10245. for (const auto &x : handlers) {
  10246. const auto &matcher = x.first;
  10247. const auto &handler = x.second;
  10248. if (matcher->match(req)) {
  10249. req.matched_route = matcher->pattern();
  10250. // Run the pre-request handler before reading the body so a rejected
  10251. // request (e.g. failed authentication) never forces us to buffer a
  10252. // potentially large body. `req.matched_route` is available here.
  10253. if (pre_request_handler_ &&
  10254. pre_request_handler_(req, res) == HandlerResponse::Handled) {
  10255. return true;
  10256. }
  10257. // The route matched and the request was approved; read the body now.
  10258. if (detail::expect_content(req) && !read_content(strm, req, res)) {
  10259. output_error_log(Error::Read, &req);
  10260. return false;
  10261. }
  10262. handler(req, res);
  10263. return true;
  10264. }
  10265. }
  10266. return false;
  10267. }
  10268. inline void Server::apply_ranges(const Request &req, Response &res,
  10269. std::string &content_type,
  10270. std::string &boundary) const {
  10271. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  10272. auto it = res.headers.find("Content-Type");
  10273. if (it != res.headers.end()) {
  10274. content_type = it->second;
  10275. res.headers.erase(it);
  10276. }
  10277. boundary = detail::make_multipart_data_boundary();
  10278. res.set_header("Content-Type",
  10279. "multipart/byteranges; boundary=" + boundary);
  10280. }
  10281. auto type = detail::encoding_type(req, res);
  10282. if (res.body.empty()) {
  10283. if (res.content_length_ > 0) {
  10284. size_t length = 0;
  10285. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10286. length = res.content_length_;
  10287. } else if (req.ranges.size() == 1) {
  10288. auto offset_and_length = detail::get_range_offset_and_length(
  10289. req.ranges[0], res.content_length_);
  10290. length = offset_and_length.second;
  10291. auto content_range = detail::make_content_range_header_field(
  10292. offset_and_length, res.content_length_);
  10293. res.set_header("Content-Range", content_range);
  10294. } else {
  10295. length = detail::get_multipart_ranges_data_length(
  10296. req, boundary, content_type, res.content_length_);
  10297. }
  10298. res.set_header("Content-Length", std::to_string(length));
  10299. } else {
  10300. if (res.content_provider_) {
  10301. if (res.is_chunked_content_provider_) {
  10302. res.set_header("Transfer-Encoding", "chunked");
  10303. if (type != detail::EncodingType::None) {
  10304. res.set_header("Content-Encoding", detail::encoding_name(type));
  10305. res.set_header("Vary", "Accept-Encoding");
  10306. }
  10307. }
  10308. }
  10309. }
  10310. } else {
  10311. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  10312. ;
  10313. } else if (req.ranges.size() == 1) {
  10314. auto offset_and_length =
  10315. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  10316. auto offset = offset_and_length.first;
  10317. auto length = offset_and_length.second;
  10318. auto content_range = detail::make_content_range_header_field(
  10319. offset_and_length, res.body.size());
  10320. res.set_header("Content-Range", content_range);
  10321. assert(offset + length <= res.body.size());
  10322. res.body = res.body.substr(offset, length);
  10323. } else {
  10324. std::string data;
  10325. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  10326. res.body.size(), data);
  10327. res.body.swap(data);
  10328. }
  10329. if (type != detail::EncodingType::None) {
  10330. output_pre_compression_log(req, res);
  10331. if (auto compressor = detail::make_compressor(type)) {
  10332. std::string compressed;
  10333. if (compressor->compress(res.body.data(), res.body.size(), true,
  10334. [&](const char *data, size_t data_len) {
  10335. compressed.append(data, data_len);
  10336. return true;
  10337. })) {
  10338. res.body.swap(compressed);
  10339. res.set_header("Content-Encoding", detail::encoding_name(type));
  10340. res.set_header("Vary", "Accept-Encoding");
  10341. }
  10342. }
  10343. }
  10344. auto length = std::to_string(res.body.size());
  10345. res.set_header("Content-Length", length);
  10346. }
  10347. }
  10348. inline bool Server::dispatch_request_for_content_reader(
  10349. Request &req, Response &res, ContentReader content_reader,
  10350. const HandlersForContentReader &handlers) const {
  10351. for (const auto &x : handlers) {
  10352. const auto &matcher = x.first;
  10353. const auto &handler = x.second;
  10354. if (matcher->match(req)) {
  10355. req.matched_route = matcher->pattern();
  10356. if (!pre_request_handler_ ||
  10357. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  10358. handler(req, res, content_reader);
  10359. }
  10360. return true;
  10361. }
  10362. }
  10363. return false;
  10364. }
  10365. inline std::string
  10366. get_client_ip(const std::string &x_forwarded_for,
  10367. const std::vector<std::string> &trusted_proxies) {
  10368. // X-Forwarded-For is a comma-separated list per RFC 7239
  10369. std::vector<std::string> ip_list;
  10370. detail::split(x_forwarded_for.data(),
  10371. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  10372. [&](const char *b, const char *e) {
  10373. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  10374. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  10375. });
  10376. // A malformed X-Forwarded-For (empty, comma-only, whitespace-only) yields
  10377. // no segments. Signal "no client IP derived" with an empty string so the
  10378. // caller can fall back to the connection-level remote address.
  10379. if (ip_list.empty()) { return std::string(); }
  10380. for (size_t i = 0; i < ip_list.size(); ++i) {
  10381. auto ip = ip_list[i];
  10382. auto is_trusted_proxy =
  10383. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  10384. [&](const std::string &proxy) { return ip == proxy; });
  10385. if (is_trusted_proxy) {
  10386. if (i == 0) {
  10387. // If the trusted proxy is the first IP, there's no preceding client IP
  10388. return ip;
  10389. } else {
  10390. // Return the IP immediately before the trusted proxy
  10391. return ip_list[i - 1];
  10392. }
  10393. }
  10394. }
  10395. // If no trusted proxy is found, return the first IP in the list
  10396. return ip_list.front();
  10397. }
  10398. inline bool
  10399. Server::process_request(Stream &strm, const std::string &remote_addr,
  10400. int remote_port, const std::string &local_addr,
  10401. int local_port, bool close_connection,
  10402. bool &connection_closed,
  10403. const std::function<void(Request &)> &setup_request,
  10404. bool *websocket_upgraded) {
  10405. std::array<char, 2048> buf{};
  10406. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10407. // Connection has been closed on client
  10408. if (!line_reader.getline()) { return false; }
  10409. Request req;
  10410. req.start_time_ = std::chrono::steady_clock::now();
  10411. req.remote_addr = remote_addr;
  10412. req.remote_port = remote_port;
  10413. req.local_addr = local_addr;
  10414. req.local_port = local_port;
  10415. Response res;
  10416. res.version = "HTTP/1.1";
  10417. res.headers = default_headers_;
  10418. // Request line and headers
  10419. if (!parse_request_line(line_reader.ptr(), req)) {
  10420. res.status = StatusCode::BadRequest_400;
  10421. output_error_log(Error::InvalidRequestLine, &req);
  10422. return write_response(strm, close_connection, req, res);
  10423. }
  10424. // Request headers
  10425. if (!detail::read_headers(strm, req.headers)) {
  10426. res.status = StatusCode::BadRequest_400;
  10427. output_error_log(Error::InvalidHeaders, &req);
  10428. return write_response(strm, close_connection, req, res);
  10429. }
  10430. // RFC 9112 §6.3: Reject requests with both a non-zero Content-Length and
  10431. // any Transfer-Encoding to prevent request smuggling. Content-Length: 0 is
  10432. // tolerated for compatibility with existing clients.
  10433. if (req.get_header_value_u64("Content-Length") > 0 &&
  10434. req.has_header("Transfer-Encoding")) {
  10435. connection_closed = true;
  10436. res.status = StatusCode::BadRequest_400;
  10437. return write_response(strm, close_connection, req, res);
  10438. }
  10439. // Check if the request URI doesn't exceed the limit
  10440. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  10441. connection_closed = true;
  10442. res.status = StatusCode::UriTooLong_414;
  10443. output_error_log(Error::ExceedUriMaxLength, &req);
  10444. return write_response(strm, close_connection, req, res);
  10445. }
  10446. if (req.get_header_value("Connection") == "close") {
  10447. connection_closed = true;
  10448. }
  10449. if (req.version == "HTTP/1.0" &&
  10450. req.get_header_value("Connection") != "Keep-Alive") {
  10451. connection_closed = true;
  10452. }
  10453. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  10454. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  10455. auto derived = get_client_ip(x_forwarded_for, trusted_proxies_);
  10456. req.remote_addr = derived.empty() ? remote_addr : derived;
  10457. } else {
  10458. req.remote_addr = remote_addr;
  10459. }
  10460. req.remote_port = remote_port;
  10461. req.local_addr = local_addr;
  10462. req.local_port = local_port;
  10463. if (req.has_header("Accept")) {
  10464. const auto &accept_header = req.get_header_value("Accept");
  10465. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  10466. connection_closed = true;
  10467. res.status = StatusCode::BadRequest_400;
  10468. output_error_log(Error::HTTPParsing, &req);
  10469. return write_response(strm, close_connection, req, res);
  10470. }
  10471. }
  10472. if (req.has_header("Range")) {
  10473. const auto &range_header_value = req.get_header_value("Range");
  10474. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  10475. connection_closed = true;
  10476. res.status = StatusCode::RangeNotSatisfiable_416;
  10477. output_error_log(Error::InvalidRangeHeader, &req);
  10478. return write_response(strm, close_connection, req, res);
  10479. }
  10480. }
  10481. if (setup_request) { setup_request(req); }
  10482. if (req.get_header_value("Expect") == "100-continue") {
  10483. int status = StatusCode::Continue_100;
  10484. if (expect_100_continue_handler_) {
  10485. status = expect_100_continue_handler_(req, res);
  10486. }
  10487. switch (status) {
  10488. case StatusCode::Continue_100:
  10489. case StatusCode::ExpectationFailed_417:
  10490. detail::write_response_line(strm, status);
  10491. strm.write("\r\n");
  10492. break;
  10493. default:
  10494. connection_closed = true;
  10495. return write_response(strm, true, req, res);
  10496. }
  10497. }
  10498. // Setup `is_connection_closed` method
  10499. auto sock = strm.socket();
  10500. req.is_connection_closed = [sock]() {
  10501. return !detail::is_socket_alive(sock);
  10502. };
  10503. // WebSocket upgrade
  10504. // Check pre_routing_handler_ before upgrading so that authentication
  10505. // and other middleware can reject the request with an HTTP response
  10506. // (e.g., 401) before the protocol switches.
  10507. if (detail::is_websocket_upgrade(req)) {
  10508. if (pre_routing_handler_ &&
  10509. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  10510. if (res.status == -1) { res.status = StatusCode::OK_200; }
  10511. return write_response(strm, close_connection, req, res);
  10512. }
  10513. // Find matching WebSocket handler
  10514. for (const auto &entry : websocket_handlers_) {
  10515. if (entry.matcher->match(req)) {
  10516. // Compute accept key
  10517. auto client_key = req.get_header_value("Sec-WebSocket-Key");
  10518. auto accept_key = detail::websocket_accept_key(client_key);
  10519. // Negotiate subprotocol
  10520. std::string selected_subprotocol;
  10521. if (entry.sub_protocol_selector) {
  10522. auto protocol_header = req.get_header_value("Sec-WebSocket-Protocol");
  10523. if (!protocol_header.empty()) {
  10524. std::vector<std::string> protocols;
  10525. std::istringstream iss(protocol_header);
  10526. std::string token;
  10527. while (std::getline(iss, token, ',')) {
  10528. // Trim whitespace
  10529. auto start = token.find_first_not_of(' ');
  10530. auto end = token.find_last_not_of(' ');
  10531. if (start != std::string::npos) {
  10532. protocols.push_back(token.substr(start, end - start + 1));
  10533. }
  10534. }
  10535. selected_subprotocol = entry.sub_protocol_selector(protocols);
  10536. }
  10537. }
  10538. // Send 101 Switching Protocols
  10539. std::string handshake_response = "HTTP/1.1 101 Switching Protocols\r\n"
  10540. "Upgrade: websocket\r\n"
  10541. "Connection: Upgrade\r\n"
  10542. "Sec-WebSocket-Accept: " +
  10543. accept_key + "\r\n";
  10544. if (!selected_subprotocol.empty()) {
  10545. if (!detail::fields::is_field_value(selected_subprotocol)) {
  10546. return false;
  10547. }
  10548. handshake_response +=
  10549. "Sec-WebSocket-Protocol: " + selected_subprotocol + "\r\n";
  10550. }
  10551. handshake_response += "\r\n";
  10552. if (strm.write(handshake_response.data(), handshake_response.size()) <
  10553. 0) {
  10554. return false;
  10555. }
  10556. connection_closed = true;
  10557. if (websocket_upgraded) { *websocket_upgraded = true; }
  10558. {
  10559. // Use WebSocket-specific read timeout instead of HTTP timeout
  10560. strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_READ_TIMEOUT_SECOND, 0);
  10561. ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
  10562. websocket_max_missed_pongs_);
  10563. entry.handler(req, ws);
  10564. }
  10565. return true;
  10566. }
  10567. }
  10568. // No matching handler - fall through to 404
  10569. }
  10570. // Routing
  10571. auto routed = false;
  10572. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  10573. routed = routing(req, res, strm);
  10574. #else
  10575. try {
  10576. routed = routing(req, res, strm);
  10577. } catch (std::exception &) {
  10578. if (exception_handler_) {
  10579. auto ep = std::current_exception();
  10580. exception_handler_(req, res, ep);
  10581. routed = true;
  10582. } else {
  10583. res.status = StatusCode::InternalServerError_500;
  10584. }
  10585. } catch (...) {
  10586. if (exception_handler_) {
  10587. auto ep = std::current_exception();
  10588. exception_handler_(req, res, ep);
  10589. routed = true;
  10590. } else {
  10591. res.status = StatusCode::InternalServerError_500;
  10592. }
  10593. }
  10594. #endif
  10595. auto ret = false;
  10596. if (routed) {
  10597. if (res.status == -1) {
  10598. res.status = req.ranges.empty() ? StatusCode::OK_200
  10599. : StatusCode::PartialContent_206;
  10600. }
  10601. // Serve file content by using a content provider
  10602. auto file_open_error = false;
  10603. if (!res.file_content_path_.empty()) {
  10604. const auto &path = res.file_content_path_;
  10605. auto mm = std::make_shared<detail::mmap>(path.c_str());
  10606. if (!mm->is_open()) {
  10607. res.body.clear();
  10608. res.content_length_ = 0;
  10609. res.content_provider_ = nullptr;
  10610. res.status = StatusCode::NotFound_404;
  10611. output_error_log(Error::OpenFile, &req);
  10612. file_open_error = true;
  10613. } else {
  10614. auto content_type = res.file_content_content_type_;
  10615. if (content_type.empty()) {
  10616. content_type = detail::find_content_type(
  10617. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  10618. }
  10619. res.set_content_provider(
  10620. mm->size(), content_type,
  10621. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  10622. sink.write(mm->data() + offset, length);
  10623. return true;
  10624. });
  10625. }
  10626. }
  10627. if (file_open_error) {
  10628. ret = write_response(strm, close_connection, req, res);
  10629. } else if (detail::range_error(req, res)) {
  10630. res.body.clear();
  10631. res.content_length_ = 0;
  10632. res.content_provider_ = nullptr;
  10633. res.status = StatusCode::RangeNotSatisfiable_416;
  10634. ret = write_response(strm, close_connection, req, res);
  10635. } else {
  10636. ret = write_response_with_content(strm, close_connection, req, res);
  10637. }
  10638. } else {
  10639. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  10640. ret = write_response(strm, close_connection, req, res);
  10641. }
  10642. // Drain any unconsumed framed body to prevent request smuggling on
  10643. // keep-alive. Without framing there is no body to drain — reading would
  10644. // consume the next request (issue #2450).
  10645. if (!req.body_consumed_ && detail::has_framed_body(req)) {
  10646. int dummy_status;
  10647. if (!detail::read_content(
  10648. strm, req, payload_max_length_, dummy_status, nullptr,
  10649. [](const char *, size_t, size_t, size_t) { return true; }, false)) {
  10650. connection_closed = true;
  10651. }
  10652. }
  10653. return ret;
  10654. }
  10655. inline bool Server::is_valid() const { return true; }
  10656. inline bool Server::process_and_close_socket(socket_t sock) {
  10657. std::string remote_addr;
  10658. int remote_port = 0;
  10659. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  10660. std::string local_addr;
  10661. int local_port = 0;
  10662. detail::get_local_ip_and_port(sock, local_addr, local_port);
  10663. bool websocket_upgraded = false;
  10664. auto ret = detail::process_server_socket(
  10665. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  10666. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10667. write_timeout_usec_,
  10668. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  10669. return process_request(strm, remote_addr, remote_port, local_addr,
  10670. local_port, close_connection, connection_closed,
  10671. nullptr, &websocket_upgraded);
  10672. });
  10673. detail::shutdown_socket(sock);
  10674. detail::close_socket(sock);
  10675. return ret;
  10676. }
  10677. inline void Server::output_log(const Request &req, const Response &res) const {
  10678. if (logger_) {
  10679. std::lock_guard<std::mutex> guard(logger_mutex_);
  10680. logger_(req, res);
  10681. }
  10682. }
  10683. inline void Server::output_pre_compression_log(const Request &req,
  10684. const Response &res) const {
  10685. if (pre_compression_logger_) {
  10686. std::lock_guard<std::mutex> guard(logger_mutex_);
  10687. pre_compression_logger_(req, res);
  10688. }
  10689. }
  10690. inline void Server::output_error_log(const Error &err,
  10691. const Request *req) const {
  10692. if (error_logger_) {
  10693. std::lock_guard<std::mutex> guard(logger_mutex_);
  10694. error_logger_(err, req);
  10695. }
  10696. }
  10697. /*
  10698. * Group 5: ClientImpl and Client (Universal) implementation
  10699. */
  10700. // HTTP client implementation
  10701. inline ClientImpl::ClientImpl(const std::string &host)
  10702. : ClientImpl(host, 80, std::string(), std::string()) {}
  10703. inline ClientImpl::ClientImpl(const std::string &host, int port)
  10704. : ClientImpl(host, port, std::string(), std::string()) {}
  10705. inline ClientImpl::ClientImpl(const std::string &host, int port,
  10706. const std::string &client_cert_path,
  10707. const std::string &client_key_path)
  10708. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  10709. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  10710. inline ClientImpl::~ClientImpl() {
  10711. // Wait until all the requests in flight are handled.
  10712. size_t retry_count = 10;
  10713. while (retry_count-- > 0) {
  10714. {
  10715. std::lock_guard<std::mutex> guard(socket_mutex_);
  10716. if (socket_requests_in_flight_ == 0) { break; }
  10717. }
  10718. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  10719. }
  10720. std::lock_guard<std::mutex> guard(socket_mutex_);
  10721. shutdown_socket(socket_);
  10722. close_socket(socket_);
  10723. }
  10724. inline bool ClientImpl::is_valid() const { return true; }
  10725. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  10726. client_cert_path_ = rhs.client_cert_path_;
  10727. client_key_path_ = rhs.client_key_path_;
  10728. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  10729. read_timeout_sec_ = rhs.read_timeout_sec_;
  10730. read_timeout_usec_ = rhs.read_timeout_usec_;
  10731. write_timeout_sec_ = rhs.write_timeout_sec_;
  10732. write_timeout_usec_ = rhs.write_timeout_usec_;
  10733. max_timeout_msec_ = rhs.max_timeout_msec_;
  10734. basic_auth_username_ = rhs.basic_auth_username_;
  10735. basic_auth_password_ = rhs.basic_auth_password_;
  10736. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  10737. keep_alive_ = rhs.keep_alive_;
  10738. follow_location_ = rhs.follow_location_;
  10739. path_encode_ = rhs.path_encode_;
  10740. address_family_ = rhs.address_family_;
  10741. tcp_nodelay_ = rhs.tcp_nodelay_;
  10742. ipv6_v6only_ = rhs.ipv6_v6only_;
  10743. socket_options_ = rhs.socket_options_;
  10744. compress_ = rhs.compress_;
  10745. decompress_ = rhs.decompress_;
  10746. payload_max_length_ = rhs.payload_max_length_;
  10747. has_payload_max_length_ = rhs.has_payload_max_length_;
  10748. interface_ = rhs.interface_;
  10749. proxy_host_ = rhs.proxy_host_;
  10750. proxy_port_ = rhs.proxy_port_;
  10751. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  10752. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  10753. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  10754. no_proxy_entries_ = rhs.no_proxy_entries_;
  10755. logger_ = rhs.logger_;
  10756. error_logger_ = rhs.error_logger_;
  10757. #ifdef CPPHTTPLIB_SSL_ENABLED
  10758. digest_auth_username_ = rhs.digest_auth_username_;
  10759. digest_auth_password_ = rhs.digest_auth_password_;
  10760. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  10761. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  10762. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  10763. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  10764. server_certificate_verification_ = rhs.server_certificate_verification_;
  10765. server_hostname_verification_ = rhs.server_hostname_verification_;
  10766. system_ca_mode_ = rhs.system_ca_mode_;
  10767. #endif
  10768. }
  10769. inline bool
  10770. ClientImpl::is_proxy_enabled_for_host(const std::string &host) const {
  10771. if (proxy_host_.empty() || proxy_port_ == -1) { return false; }
  10772. if (no_proxy_entries_.empty()) { return true; }
  10773. // host_ is const so its normalized form is invariant; cache it. The
  10774. // cross-host path (setup_redirect_client passing next_host) re-normalizes.
  10775. if (host == host_) {
  10776. if (!host_normalized_valid_) {
  10777. host_normalized_ = detail::normalize_target(host_);
  10778. host_normalized_valid_ = true;
  10779. }
  10780. return !detail::host_matches_no_proxy(host_normalized_, no_proxy_entries_);
  10781. }
  10782. auto target = detail::normalize_target(host);
  10783. return !detail::host_matches_no_proxy(target, no_proxy_entries_);
  10784. }
  10785. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  10786. if (is_proxy_enabled_for_host(host_)) {
  10787. return detail::create_client_socket(
  10788. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  10789. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  10790. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  10791. write_timeout_sec_, write_timeout_usec_, interface_, error);
  10792. }
  10793. // Check is custom IP specified for host_
  10794. std::string ip;
  10795. auto it = addr_map_.find(host_);
  10796. if (it != addr_map_.end()) { ip = it->second; }
  10797. return detail::create_client_socket(
  10798. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  10799. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  10800. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  10801. write_timeout_usec_, interface_, error);
  10802. }
  10803. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  10804. Error &error) {
  10805. auto sock = create_client_socket(error);
  10806. if (sock == INVALID_SOCKET) { return false; }
  10807. socket.sock = sock;
  10808. return true;
  10809. }
  10810. inline bool ClientImpl::ensure_socket_connection(Socket &socket, Error &error) {
  10811. return create_and_connect_socket(socket, error);
  10812. }
  10813. inline bool ClientImpl::setup_proxy_connection(
  10814. Socket & /*socket*/,
  10815. std::chrono::time_point<std::chrono::steady_clock> /*start_time*/,
  10816. Response & /*res*/, bool & /*success*/, Error & /*error*/) {
  10817. return true;
  10818. }
  10819. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  10820. bool /*shutdown_gracefully*/) {
  10821. // If there are any requests in flight from threads other than us, then it's
  10822. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  10823. assert(socket_requests_in_flight_ == 0 ||
  10824. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10825. }
  10826. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  10827. if (socket.sock == INVALID_SOCKET) { return; }
  10828. detail::shutdown_socket(socket.sock);
  10829. }
  10830. inline void ClientImpl::close_socket(Socket &socket) {
  10831. // If there are requests in flight in another thread, usually closing
  10832. // the socket will be fine and they will simply receive an error when
  10833. // using the closed socket, but it is still a bug since rarely the OS
  10834. // may reassign the socket id to be used for a new socket, and then
  10835. // suddenly they will be operating on a live socket that is different
  10836. // than the one they intended!
  10837. assert(socket_requests_in_flight_ == 0 ||
  10838. socket_requests_are_from_thread_ == std::this_thread::get_id());
  10839. // It is also a bug if this happens while SSL is still active
  10840. #ifdef CPPHTTPLIB_SSL_ENABLED
  10841. assert(socket.ssl == nullptr);
  10842. #endif
  10843. if (socket.sock == INVALID_SOCKET) { return; }
  10844. detail::close_socket(socket.sock);
  10845. socket.sock = INVALID_SOCKET;
  10846. }
  10847. inline void ClientImpl::disconnect(bool gracefully) {
  10848. shutdown_ssl(socket_, gracefully);
  10849. shutdown_socket(socket_);
  10850. close_socket(socket_);
  10851. }
  10852. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  10853. Response &res,
  10854. bool skip_100_continue) const {
  10855. std::array<char, 2048> buf{};
  10856. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  10857. if (!line_reader.getline()) { return false; }
  10858. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  10859. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  10860. #else
  10861. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  10862. #endif
  10863. std::cmatch m;
  10864. if (!std::regex_match(line_reader.ptr(), m, re)) {
  10865. return req.method == "CONNECT";
  10866. }
  10867. res.version = std::string(m[1]);
  10868. res.status = std::stoi(std::string(m[2]));
  10869. res.reason = std::string(m[3]);
  10870. // Ignore '100 Continue' (only when not using Expect: 100-continue explicitly)
  10871. while (skip_100_continue && res.status == StatusCode::Continue_100) {
  10872. if (!line_reader.getline()) { return false; } // CRLF
  10873. if (!line_reader.getline()) { return false; } // next response line
  10874. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  10875. res.version = std::string(m[1]);
  10876. res.status = std::stoi(std::string(m[2]));
  10877. res.reason = std::string(m[3]);
  10878. }
  10879. return true;
  10880. }
  10881. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  10882. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  10883. auto ret = send_(req, res, error);
  10884. if (error == Error::SSLPeerCouldBeClosed_) {
  10885. assert(!ret);
  10886. ret = send_(req, res, error);
  10887. // If still failing with SSLPeerCouldBeClosed_, convert to Read error
  10888. if (error == Error::SSLPeerCouldBeClosed_) { error = Error::Read; }
  10889. }
  10890. return ret;
  10891. }
  10892. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  10893. {
  10894. std::lock_guard<std::mutex> guard(socket_mutex_);
  10895. // Set this to false immediately - if it ever gets set to true by the end
  10896. // of the request, we know another thread instructed us to close the
  10897. // socket.
  10898. socket_should_be_closed_when_request_is_done_ = false;
  10899. auto is_alive = false;
  10900. if (socket_.is_open()) {
  10901. is_alive = detail::is_socket_alive(socket_.sock);
  10902. #ifdef CPPHTTPLIB_SSL_ENABLED
  10903. if (is_alive && is_ssl()) {
  10904. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  10905. is_alive = false;
  10906. }
  10907. }
  10908. #endif
  10909. if (!is_alive) {
  10910. // Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
  10911. disconnect(/*gracefully=*/false);
  10912. }
  10913. }
  10914. if (!is_alive) {
  10915. if (!ensure_socket_connection(socket_, error)) {
  10916. output_error_log(error, &req);
  10917. return false;
  10918. }
  10919. {
  10920. auto success = true;
  10921. if (!setup_proxy_connection(socket_, req.start_time_, res, success,
  10922. error)) {
  10923. if (!success) { output_error_log(error, &req); }
  10924. return success;
  10925. }
  10926. }
  10927. }
  10928. // Mark the current socket as being in use so that it cannot be closed by
  10929. // anyone else while this request is ongoing, even though we will be
  10930. // releasing the mutex.
  10931. if (socket_requests_in_flight_ > 1) {
  10932. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  10933. }
  10934. socket_requests_in_flight_ += 1;
  10935. socket_requests_are_from_thread_ = std::this_thread::get_id();
  10936. }
  10937. for (const auto &header : default_headers_) {
  10938. if (req.headers.find(header.first) == req.headers.end()) {
  10939. req.headers.insert(header);
  10940. }
  10941. }
  10942. auto ret = false;
  10943. auto close_connection = !keep_alive_;
  10944. auto se = detail::scope_exit([&]() {
  10945. // Briefly lock mutex in order to mark that a request is no longer ongoing
  10946. std::lock_guard<std::mutex> guard(socket_mutex_);
  10947. socket_requests_in_flight_ -= 1;
  10948. if (socket_requests_in_flight_ <= 0) {
  10949. assert(socket_requests_in_flight_ == 0);
  10950. socket_requests_are_from_thread_ = std::thread::id();
  10951. }
  10952. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  10953. !ret) {
  10954. disconnect(/*gracefully=*/true);
  10955. }
  10956. });
  10957. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  10958. return handle_request(strm, req, res, close_connection, error);
  10959. });
  10960. if (!ret) {
  10961. if (error == Error::Success) {
  10962. error = Error::Unknown;
  10963. output_error_log(error, &req);
  10964. }
  10965. }
  10966. return ret;
  10967. }
  10968. inline Result ClientImpl::send(const Request &req) {
  10969. auto req2 = req;
  10970. return send_(std::move(req2));
  10971. }
  10972. inline Result ClientImpl::send_(Request &&req) {
  10973. auto res = detail::make_unique<Response>();
  10974. auto error = Error::Success;
  10975. auto ret = send(req, *res, error);
  10976. #ifdef CPPHTTPLIB_SSL_ENABLED
  10977. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  10978. last_ssl_error_, last_backend_error_};
  10979. #else
  10980. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  10981. #endif
  10982. }
  10983. inline void ClientImpl::prepare_default_headers(Request &r, bool for_stream,
  10984. const std::string &ct) {
  10985. (void)for_stream;
  10986. for (const auto &header : default_headers_) {
  10987. if (!r.has_header(header.first)) { r.headers.insert(header); }
  10988. }
  10989. if (!r.has_header("Host")) {
  10990. if (address_family_ == AF_UNIX) {
  10991. r.headers.emplace("Host", "localhost");
  10992. } else {
  10993. r.headers.emplace(
  10994. "Host", detail::make_host_and_port_string(host_, port_, is_ssl()));
  10995. }
  10996. }
  10997. if (!r.has_header("Accept")) { r.headers.emplace("Accept", "*/*"); }
  10998. if (!r.content_receiver) {
  10999. if (!r.has_header("Accept-Encoding")) {
  11000. std::string accept_encoding;
  11001. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  11002. accept_encoding = "br";
  11003. #endif
  11004. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11005. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11006. accept_encoding += "gzip, deflate";
  11007. #endif
  11008. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  11009. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  11010. accept_encoding += "zstd";
  11011. #endif
  11012. r.set_header("Accept-Encoding", accept_encoding);
  11013. }
  11014. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  11015. if (!r.has_header("User-Agent")) {
  11016. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  11017. r.set_header("User-Agent", agent);
  11018. }
  11019. #endif
  11020. }
  11021. if (!r.body.empty()) {
  11022. if (!ct.empty() && !r.has_header("Content-Type")) {
  11023. r.headers.emplace("Content-Type", ct);
  11024. }
  11025. if (!r.has_header("Content-Length")) {
  11026. r.headers.emplace("Content-Length", std::to_string(r.body.size()));
  11027. }
  11028. }
  11029. }
  11030. inline ClientImpl::StreamHandle
  11031. ClientImpl::open_stream(const std::string &method, const std::string &path,
  11032. const Params &params, const Headers &headers,
  11033. const std::string &body,
  11034. const std::string &content_type) {
  11035. StreamHandle handle;
  11036. handle.response = detail::make_unique<Response>();
  11037. handle.error = Error::Success;
  11038. auto query_path = params.empty() ? path : append_query_params(path, params);
  11039. handle.connection_ = detail::make_unique<ClientConnection>();
  11040. {
  11041. std::lock_guard<std::mutex> guard(socket_mutex_);
  11042. auto is_alive = false;
  11043. if (socket_.is_open()) {
  11044. is_alive = detail::is_socket_alive(socket_.sock);
  11045. #ifdef CPPHTTPLIB_SSL_ENABLED
  11046. if (is_alive && is_ssl()) {
  11047. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11048. is_alive = false;
  11049. }
  11050. }
  11051. #endif
  11052. if (!is_alive) { disconnect(/*gracefully=*/false); }
  11053. }
  11054. if (!is_alive) {
  11055. if (!ensure_socket_connection(socket_, handle.error)) {
  11056. handle.response.reset();
  11057. return handle;
  11058. }
  11059. {
  11060. auto success = true;
  11061. auto start_time = std::chrono::steady_clock::now();
  11062. if (!setup_proxy_connection(socket_, start_time, *handle.response,
  11063. success, handle.error)) {
  11064. if (!success) { handle.response.reset(); }
  11065. return handle;
  11066. }
  11067. }
  11068. }
  11069. transfer_socket_ownership_to_handle(handle);
  11070. }
  11071. #ifdef CPPHTTPLIB_SSL_ENABLED
  11072. if (is_ssl() && handle.connection_->session) {
  11073. handle.socket_stream_ = detail::make_unique<detail::SSLSocketStream>(
  11074. handle.connection_->sock, handle.connection_->session,
  11075. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  11076. write_timeout_usec_);
  11077. } else {
  11078. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11079. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11080. write_timeout_sec_, write_timeout_usec_);
  11081. }
  11082. #else
  11083. handle.socket_stream_ = detail::make_unique<detail::SocketStream>(
  11084. handle.connection_->sock, read_timeout_sec_, read_timeout_usec_,
  11085. write_timeout_sec_, write_timeout_usec_);
  11086. #endif
  11087. handle.stream_ = handle.socket_stream_.get();
  11088. Request req;
  11089. req.method = method;
  11090. req.path = query_path;
  11091. req.headers = headers;
  11092. req.body = body;
  11093. prepare_default_headers(req, true, content_type);
  11094. auto &strm = *handle.stream_;
  11095. if (detail::write_request_line(strm, req.method, req.path) < 0) {
  11096. handle.error = Error::Write;
  11097. handle.response.reset();
  11098. return handle;
  11099. }
  11100. if (!detail::check_and_write_headers(strm, req.headers, header_writer_,
  11101. handle.error)) {
  11102. handle.response.reset();
  11103. return handle;
  11104. }
  11105. if (!body.empty()) {
  11106. if (strm.write(body.data(), body.size()) < 0) {
  11107. handle.error = Error::Write;
  11108. handle.response.reset();
  11109. return handle;
  11110. }
  11111. }
  11112. if (!read_response_line(strm, req, *handle.response) ||
  11113. !detail::read_headers(strm, handle.response->headers)) {
  11114. handle.error = Error::Read;
  11115. handle.response.reset();
  11116. return handle;
  11117. }
  11118. handle.body_reader_.stream = handle.stream_;
  11119. handle.body_reader_.payload_max_length = payload_max_length_;
  11120. if (handle.response->has_header("Content-Length")) {
  11121. bool is_invalid = false;
  11122. auto content_length = detail::get_header_value_u64(
  11123. handle.response->headers, "Content-Length", 0, 0, is_invalid);
  11124. if (is_invalid) {
  11125. handle.error = Error::Read;
  11126. handle.response.reset();
  11127. return handle;
  11128. }
  11129. handle.body_reader_.has_content_length = true;
  11130. handle.body_reader_.content_length = content_length;
  11131. }
  11132. auto transfer_encoding =
  11133. handle.response->get_header_value("Transfer-Encoding");
  11134. handle.body_reader_.chunked = (transfer_encoding == "chunked");
  11135. auto content_encoding = handle.response->get_header_value("Content-Encoding");
  11136. if (!content_encoding.empty()) {
  11137. handle.decompressor_ = detail::create_decompressor(content_encoding);
  11138. }
  11139. return handle;
  11140. }
  11141. inline ssize_t ClientImpl::StreamHandle::read(char *buf, size_t len) {
  11142. if (!is_valid() || !response) { return -1; }
  11143. if (decompressor_) { return read_with_decompression(buf, len); }
  11144. auto n = detail::read_body_content(stream_, body_reader_, buf, len);
  11145. if (n <= 0 && body_reader_.chunked && !trailers_parsed_ && stream_) {
  11146. trailers_parsed_ = true;
  11147. if (body_reader_.chunked_decoder) {
  11148. if (!body_reader_.chunked_decoder->parse_trailers_into(
  11149. response->trailers, response->headers)) {
  11150. return n;
  11151. }
  11152. } else {
  11153. detail::ChunkedDecoder dec(*stream_);
  11154. if (!dec.parse_trailers_into(response->trailers, response->headers)) {
  11155. return n;
  11156. }
  11157. }
  11158. }
  11159. return n;
  11160. }
  11161. inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
  11162. size_t len) {
  11163. if (decompress_offset_ < decompress_buffer_.size()) {
  11164. auto available = decompress_buffer_.size() - decompress_offset_;
  11165. auto to_copy = (std::min)(len, available);
  11166. std::memcpy(buf, decompress_buffer_.data() + decompress_offset_, to_copy);
  11167. decompress_offset_ += to_copy;
  11168. decompressed_bytes_read_ += to_copy;
  11169. return static_cast<ssize_t>(to_copy);
  11170. }
  11171. decompress_buffer_.clear();
  11172. decompress_offset_ = 0;
  11173. constexpr size_t kDecompressionBufferSize = 8192;
  11174. char compressed_buf[kDecompressionBufferSize];
  11175. while (true) {
  11176. auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
  11177. sizeof(compressed_buf));
  11178. if (n <= 0) { return n; }
  11179. bool decompress_ok = decompressor_->decompress(
  11180. compressed_buf, static_cast<size_t>(n),
  11181. [this](const char *data, size_t data_len) {
  11182. decompress_buffer_.append(data, data_len);
  11183. auto limit = body_reader_.payload_max_length;
  11184. if (decompressed_bytes_read_ + decompress_buffer_.size() > limit) {
  11185. return false;
  11186. }
  11187. return true;
  11188. });
  11189. if (!decompress_ok) {
  11190. body_reader_.last_error = Error::Read;
  11191. return -1;
  11192. }
  11193. if (!decompress_buffer_.empty()) { break; }
  11194. }
  11195. auto to_copy = (std::min)(len, decompress_buffer_.size());
  11196. std::memcpy(buf, decompress_buffer_.data(), to_copy);
  11197. decompress_offset_ = to_copy;
  11198. decompressed_bytes_read_ += to_copy;
  11199. return static_cast<ssize_t>(to_copy);
  11200. }
  11201. inline void ClientImpl::StreamHandle::parse_trailers_if_needed() {
  11202. if (!response || !stream_ || !body_reader_.chunked || trailers_parsed_) {
  11203. return;
  11204. }
  11205. trailers_parsed_ = true;
  11206. const auto bufsiz = 128;
  11207. char line_buf[bufsiz];
  11208. detail::stream_line_reader line_reader(*stream_, line_buf, bufsiz);
  11209. if (!line_reader.getline()) { return; }
  11210. if (!detail::parse_trailers(line_reader, response->trailers,
  11211. response->headers)) {
  11212. return;
  11213. }
  11214. }
  11215. namespace detail {
  11216. inline ChunkedDecoder::ChunkedDecoder(Stream &s) : strm(s) {}
  11217. inline ssize_t ChunkedDecoder::read_payload(char *buf, size_t len,
  11218. size_t &out_chunk_offset,
  11219. size_t &out_chunk_total) {
  11220. if (finished) { return 0; }
  11221. if (chunk_remaining == 0) {
  11222. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11223. if (!lr.getline()) { return -1; }
  11224. // RFC 9112 §7.1: chunk-size = 1*HEXDIG
  11225. const char *p = lr.ptr();
  11226. int v = 0;
  11227. if (!is_hex(*p, v)) { return -1; }
  11228. size_t chunk_len = 0;
  11229. constexpr size_t chunk_len_max = (std::numeric_limits<size_t>::max)();
  11230. for (; is_hex(*p, v); ++p) {
  11231. if (chunk_len > (chunk_len_max >> 4)) { return -1; }
  11232. chunk_len = (chunk_len << 4) | static_cast<size_t>(v);
  11233. }
  11234. while (is_space_or_tab(*p)) {
  11235. ++p;
  11236. }
  11237. if (*p != '\0' && *p != ';' && *p != '\r' && *p != '\n') { return -1; }
  11238. if (chunk_len == 0) {
  11239. chunk_remaining = 0;
  11240. finished = true;
  11241. out_chunk_offset = 0;
  11242. out_chunk_total = 0;
  11243. return 0;
  11244. }
  11245. chunk_remaining = chunk_len;
  11246. last_chunk_total = chunk_remaining;
  11247. last_chunk_offset = 0;
  11248. }
  11249. auto to_read = (std::min)(chunk_remaining, len);
  11250. auto n = strm.read(buf, to_read);
  11251. if (n <= 0) { return -1; }
  11252. auto offset_before = last_chunk_offset;
  11253. last_chunk_offset += static_cast<size_t>(n);
  11254. chunk_remaining -= static_cast<size_t>(n);
  11255. out_chunk_offset = offset_before;
  11256. out_chunk_total = last_chunk_total;
  11257. if (chunk_remaining == 0) {
  11258. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11259. if (!lr.getline()) { return -1; }
  11260. if (std::strcmp(lr.ptr(), "\r\n") != 0) { return -1; }
  11261. }
  11262. return n;
  11263. }
  11264. inline bool ChunkedDecoder::parse_trailers_into(Headers &dest,
  11265. const Headers &src_headers) {
  11266. stream_line_reader lr(strm, line_buf, sizeof(line_buf));
  11267. if (!lr.getline()) { return false; }
  11268. return parse_trailers(lr, dest, src_headers);
  11269. }
  11270. } // namespace detail
  11271. inline void
  11272. ClientImpl::transfer_socket_ownership_to_handle(StreamHandle &handle) {
  11273. handle.connection_->sock = socket_.sock;
  11274. #ifdef CPPHTTPLIB_SSL_ENABLED
  11275. handle.connection_->session = socket_.ssl;
  11276. socket_.ssl = nullptr;
  11277. #endif
  11278. socket_.sock = INVALID_SOCKET;
  11279. }
  11280. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  11281. Response &res, bool close_connection,
  11282. Error &error) {
  11283. if (req.path.empty()) {
  11284. error = Error::Connection;
  11285. output_error_log(error, &req);
  11286. return false;
  11287. }
  11288. auto req_save = req;
  11289. bool ret;
  11290. if (!is_ssl() && is_proxy_enabled_for_host(host_)) {
  11291. auto req2 = req;
  11292. req2.path = "http://" +
  11293. detail::make_host_and_port_string(host_, port_, false) +
  11294. req.path;
  11295. ret = process_request(strm, req2, res, close_connection, error);
  11296. req = std::move(req2);
  11297. req.path = req_save.path;
  11298. } else {
  11299. ret = process_request(strm, req, res, close_connection, error);
  11300. }
  11301. if (!ret) { return false; }
  11302. if (res.get_header_value("Connection") == "close" ||
  11303. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  11304. // NOTE: this requires a not-entirely-obvious chain of calls to be correct
  11305. // for this to be safe.
  11306. // This is safe to call because handle_request is only called by send_
  11307. // which locks the request mutex during the process. It would be a bug
  11308. // to call it from a different thread since it's a thread-safety issue
  11309. // to do these things to the socket if another thread is using the socket.
  11310. std::lock_guard<std::mutex> guard(socket_mutex_);
  11311. disconnect(/*gracefully=*/true);
  11312. }
  11313. if (300 < res.status && res.status < 400 && follow_location_) {
  11314. req = std::move(req_save);
  11315. ret = redirect(req, res, error);
  11316. }
  11317. #ifdef CPPHTTPLIB_SSL_ENABLED
  11318. if ((res.status == StatusCode::Unauthorized_401 ||
  11319. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  11320. req.authorization_count_ < 5) {
  11321. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  11322. // Only retry when the 407 actually came from a proxy hop: plain HTTP
  11323. // through an enabled proxy. HTTPS via CONNECT tunnels the 407 from the
  11324. // origin (#2457); direct/bypassed origins have no proxy hop at all.
  11325. if (is_proxy && !(!is_ssl() && is_proxy_enabled_for_host(host_))) {
  11326. return ret;
  11327. }
  11328. const auto &username =
  11329. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  11330. const auto &password =
  11331. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  11332. if (!username.empty() && !password.empty()) {
  11333. std::map<std::string, std::string> auth;
  11334. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  11335. Request new_req = req;
  11336. new_req.authorization_count_ += 1;
  11337. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  11338. : "Authorization");
  11339. new_req.headers.insert(detail::make_digest_authentication_header(
  11340. req, auth, new_req.authorization_count_, detail::random_string(10),
  11341. username, password, is_proxy));
  11342. Response new_res;
  11343. ret = send(new_req, new_res, error);
  11344. if (ret) { res = std::move(new_res); }
  11345. }
  11346. }
  11347. }
  11348. #endif
  11349. return ret;
  11350. }
  11351. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  11352. if (req.redirect_count_ == 0) {
  11353. error = Error::ExceedRedirectCount;
  11354. output_error_log(error, &req);
  11355. return false;
  11356. }
  11357. auto location = res.get_header_value("location");
  11358. if (location.empty()) { return false; }
  11359. detail::UrlComponents uc;
  11360. if (!detail::parse_url(location, uc)) { return false; }
  11361. // Only follow http/https redirects
  11362. if (!uc.scheme.empty() && uc.scheme != "http" && uc.scheme != "https") {
  11363. return false;
  11364. }
  11365. auto scheme = is_ssl() ? "https" : "http";
  11366. auto next_scheme = std::move(uc.scheme);
  11367. auto next_host = std::move(uc.host);
  11368. auto port_str = std::move(uc.port);
  11369. auto next_path = std::move(uc.path);
  11370. auto next_query = std::move(uc.query);
  11371. auto next_port = port_;
  11372. if (!port_str.empty()) {
  11373. if (!detail::parse_port(port_str, next_port)) { return false; }
  11374. } else if (!next_scheme.empty()) {
  11375. next_port = next_scheme == "https" ? 443 : 80;
  11376. }
  11377. if (next_scheme.empty()) { next_scheme = scheme; }
  11378. if (next_host.empty()) { next_host = host_; }
  11379. if (next_path.empty()) { next_path = "/"; }
  11380. auto path = decode_path_component(next_path) + next_query;
  11381. // Same host redirect - use current client
  11382. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  11383. return detail::redirect(*this, req, res, path, location, error);
  11384. }
  11385. // Cross-host/scheme redirect - create new client with robust setup
  11386. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  11387. path, location, error);
  11388. }
  11389. // New method for robust redirect client creation
  11390. inline bool ClientImpl::create_redirect_client(
  11391. const std::string &scheme, const std::string &host, int port, Request &req,
  11392. Response &res, const std::string &path, const std::string &location,
  11393. Error &error) {
  11394. // Determine if we need SSL
  11395. auto need_ssl = (scheme == "https");
  11396. // Clean up request headers that are host/client specific
  11397. // Remove headers that should not be carried over to new host
  11398. auto headers_to_remove =
  11399. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  11400. for (const auto &header_name : headers_to_remove) {
  11401. auto it = req.headers.find(header_name);
  11402. while (it != req.headers.end()) {
  11403. it = req.headers.erase(it);
  11404. it = req.headers.find(header_name);
  11405. }
  11406. }
  11407. // Create appropriate client type and handle redirect
  11408. if (need_ssl) {
  11409. #ifdef CPPHTTPLIB_SSL_ENABLED
  11410. // Create SSL client for HTTPS redirect
  11411. SSLClient redirect_client(host, port);
  11412. // Setup basic client configuration first
  11413. setup_redirect_client(redirect_client);
  11414. redirect_client.enable_server_certificate_verification(
  11415. server_certificate_verification_);
  11416. redirect_client.enable_server_hostname_verification(
  11417. server_hostname_verification_);
  11418. redirect_client.system_ca_mode_ = system_ca_mode_;
  11419. // Transfer CA certificate to redirect client
  11420. if (!ca_cert_pem_.empty()) {
  11421. redirect_client.load_ca_cert_store(ca_cert_pem_.c_str(),
  11422. ca_cert_pem_.size());
  11423. }
  11424. if (!ca_cert_file_path_.empty()) {
  11425. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  11426. }
  11427. // Client certificates are set through constructor for SSLClient
  11428. // NOTE: SSLClient constructor already takes client_cert_path and
  11429. // client_key_path so we need to create it properly if client certs are
  11430. // needed
  11431. // Execute the redirect
  11432. return detail::redirect(redirect_client, req, res, path, location, error);
  11433. #else
  11434. // SSL not supported - set appropriate error
  11435. error = Error::SSLConnection;
  11436. output_error_log(error, &req);
  11437. return false;
  11438. #endif
  11439. } else {
  11440. // HTTP redirect
  11441. ClientImpl redirect_client(host, port);
  11442. // Setup client with robust configuration
  11443. setup_redirect_client(redirect_client);
  11444. // Execute the redirect
  11445. return detail::redirect(redirect_client, req, res, path, location, error);
  11446. }
  11447. }
  11448. // New method for robust client setup (based on basic_manual_redirect.cpp
  11449. // logic)
  11450. template <typename ClientType>
  11451. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  11452. // Copy basic settings first
  11453. client.set_connection_timeout(connection_timeout_sec_);
  11454. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11455. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  11456. client.set_keep_alive(keep_alive_);
  11457. client.set_follow_location(
  11458. true); // Enable redirects to handle multi-step redirects
  11459. client.set_path_encode(path_encode_);
  11460. client.set_compress(compress_);
  11461. client.set_decompress(decompress_);
  11462. // NOTE: Authentication credentials (basic auth, bearer token, digest auth)
  11463. // are intentionally NOT copied to the redirect client. Per RFC 9110 Section
  11464. // 15.4, credentials must not be forwarded when redirecting to a different
  11465. // host. This function is only called for cross-host redirects; same-host
  11466. // redirects are handled directly in ClientImpl::redirect().
  11467. // Copy the proxy configuration unconditionally; the per-target bypass is
  11468. // re-evaluated at send time, so a later hop to a non-bypassed host can
  11469. // still use the proxy.
  11470. client.no_proxy_entries_ = no_proxy_entries_;
  11471. if (!proxy_host_.empty() && proxy_port_ != -1) {
  11472. client.set_proxy(proxy_host_, proxy_port_);
  11473. if (!proxy_basic_auth_username_.empty()) {
  11474. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  11475. proxy_basic_auth_password_);
  11476. }
  11477. if (!proxy_bearer_token_auth_token_.empty()) {
  11478. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  11479. }
  11480. #ifdef CPPHTTPLIB_SSL_ENABLED
  11481. if (!proxy_digest_auth_username_.empty()) {
  11482. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  11483. proxy_digest_auth_password_);
  11484. }
  11485. #endif
  11486. }
  11487. // Copy network and socket settings
  11488. client.set_address_family(address_family_);
  11489. client.set_tcp_nodelay(tcp_nodelay_);
  11490. client.set_ipv6_v6only(ipv6_v6only_);
  11491. if (socket_options_) { client.set_socket_options(socket_options_); }
  11492. if (!interface_.empty()) { client.set_interface(interface_); }
  11493. // Copy logging and headers
  11494. if (logger_) { client.set_logger(logger_); }
  11495. if (error_logger_) { client.set_error_logger(error_logger_); }
  11496. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  11497. // Each new client should generate its own headers based on its target host
  11498. }
  11499. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  11500. const Request &req,
  11501. Error &error) const {
  11502. auto is_shutting_down = []() { return false; };
  11503. if (req.is_chunked_content_provider_) {
  11504. auto compressor = compress_ ? detail::create_compressor().first
  11505. : std::unique_ptr<detail::compressor>();
  11506. if (!compressor) {
  11507. compressor = detail::make_unique<detail::nocompressor>();
  11508. }
  11509. return detail::write_content_chunked(strm, req.content_provider_,
  11510. is_shutting_down, *compressor, error);
  11511. } else {
  11512. return detail::write_content_with_progress(
  11513. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  11514. req.upload_progress, error);
  11515. }
  11516. }
  11517. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  11518. bool close_connection, Error &error,
  11519. bool skip_body) {
  11520. // Prepare additional headers
  11521. if (close_connection) {
  11522. if (!req.has_header("Connection")) {
  11523. req.set_header("Connection", "close");
  11524. }
  11525. }
  11526. std::string ct_for_defaults;
  11527. if (!req.has_header("Content-Type") && !req.body.empty()) {
  11528. ct_for_defaults = "text/plain";
  11529. }
  11530. prepare_default_headers(req, false, ct_for_defaults);
  11531. if (req.body.empty()) {
  11532. if (req.content_provider_) {
  11533. if (!req.is_chunked_content_provider_) {
  11534. if (!req.has_header("Content-Length")) {
  11535. auto length = std::to_string(req.content_length_);
  11536. req.set_header("Content-Length", length);
  11537. }
  11538. }
  11539. } else {
  11540. if (req.method == "POST" || req.method == "PUT" ||
  11541. req.method == "PATCH") {
  11542. req.set_header("Content-Length", "0");
  11543. }
  11544. }
  11545. }
  11546. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  11547. if (!req.has_header("Authorization")) {
  11548. req.headers.insert(make_basic_authentication_header(
  11549. basic_auth_username_, basic_auth_password_, false));
  11550. }
  11551. }
  11552. if (!bearer_token_auth_token_.empty()) {
  11553. if (!req.has_header("Authorization")) {
  11554. req.headers.insert(make_bearer_token_authentication_header(
  11555. bearer_token_auth_token_, false));
  11556. }
  11557. }
  11558. // Proxy-Authorization is only sent when the proxy is actually used for
  11559. // this target — otherwise NO_PROXY-matched requests would leak proxy
  11560. // credentials directly to the destination server.
  11561. if (is_proxy_enabled_for_host(host_)) {
  11562. if (!proxy_basic_auth_username_.empty() &&
  11563. !proxy_basic_auth_password_.empty() &&
  11564. !req.has_header("Proxy-Authorization")) {
  11565. req.headers.insert(make_basic_authentication_header(
  11566. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  11567. }
  11568. if (!proxy_bearer_token_auth_token_.empty() &&
  11569. !req.has_header("Proxy-Authorization")) {
  11570. req.headers.insert(make_bearer_token_authentication_header(
  11571. proxy_bearer_token_auth_token_, true));
  11572. }
  11573. }
  11574. // Request line and headers
  11575. {
  11576. detail::BufferStream bstrm;
  11577. // Extract path and query from req.path
  11578. std::string path_part, query_part;
  11579. auto query_pos = req.path.find('?');
  11580. if (query_pos != std::string::npos) {
  11581. path_part = req.path.substr(0, query_pos);
  11582. query_part = req.path.substr(query_pos + 1);
  11583. } else {
  11584. path_part = req.path;
  11585. query_part = "";
  11586. }
  11587. // Encode path part. If the original `req.path` already contained a
  11588. // query component, preserve its raw query string (including parameter
  11589. // order) instead of reparsing and reassembling it which may reorder
  11590. // parameters due to container ordering (e.g. `Params` uses
  11591. // `std::multimap`). When there is no query in `req.path`, fall back to
  11592. // building a query from `req.params` so existing callers that pass
  11593. // `Params` continue to work.
  11594. auto path_with_query =
  11595. path_encode_ ? detail::encode_path(path_part) : path_part;
  11596. if (!query_part.empty()) {
  11597. // Normalize the query string (decode then re-encode) while preserving
  11598. // the original parameter order. When path encoding is disabled the
  11599. // caller has supplied an already-encoded target and expects the exact
  11600. // bytes to be sent on the wire, so skip normalization for the query
  11601. // too. Normalizing here would decode-then-re-encode the query and
  11602. // corrupt pre-encoded binary payloads (e.g. turning `%20` into `+`,
  11603. // which a strict RFC 3986 server decodes back as `+`, not a space).
  11604. if (path_encode_) {
  11605. auto normalized = detail::normalize_query_string(query_part);
  11606. if (!normalized.empty()) { path_with_query += '?' + normalized; }
  11607. } else {
  11608. path_with_query += '?' + query_part;
  11609. }
  11610. // Still populate req.params for handlers/users who read them.
  11611. detail::parse_query_text(query_part, req.params);
  11612. } else {
  11613. // No query in path; parse any query_part (empty) and append params
  11614. // from `req.params` when present (preserves prior behavior for
  11615. // callers who provide Params separately).
  11616. detail::parse_query_text(query_part, req.params);
  11617. if (!req.params.empty()) {
  11618. path_with_query = append_query_params(path_with_query, req.params);
  11619. }
  11620. }
  11621. // Write request line and headers
  11622. detail::write_request_line(bstrm, req.method, path_with_query);
  11623. if (!detail::check_and_write_headers(bstrm, req.headers, header_writer_,
  11624. error)) {
  11625. output_error_log(error, &req);
  11626. return false;
  11627. }
  11628. // Flush buffer
  11629. auto &data = bstrm.get_buffer();
  11630. if (!detail::write_data(strm, data.data(), data.size())) {
  11631. error = Error::Write;
  11632. output_error_log(error, &req);
  11633. return false;
  11634. }
  11635. }
  11636. // After sending request line and headers, wait briefly for an early server
  11637. // response (e.g. 4xx) and avoid sending a potentially large request body
  11638. // unnecessarily. This workaround is only enabled on Windows because Unix
  11639. // platforms surface write errors (EPIPE) earlier; on Windows kernel send
  11640. // buffering can accept large writes even when the peer already responded.
  11641. // Check the stream first (which covers SSL via `is_readable()`), then
  11642. // fall back to select on the socket. Only perform the wait for very large
  11643. // request bodies to avoid interfering with normal small requests and
  11644. // reduce side-effects. Poll briefly (up to 50ms as default) for an early
  11645. // response. Skip this check when using Expect: 100-continue, as the protocol
  11646. // handles early responses properly.
  11647. #if defined(_WIN32)
  11648. if (!skip_body &&
  11649. req.body.size() > CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_THRESHOLD &&
  11650. req.path.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  11651. auto start = std::chrono::high_resolution_clock::now();
  11652. for (;;) {
  11653. // Prefer socket-level readiness to avoid SSL_pending() false-positives
  11654. // from SSL internals. If the underlying socket is readable, assume an
  11655. // early response may be present.
  11656. auto sock = strm.socket();
  11657. if (sock != INVALID_SOCKET && detail::select_read(sock, 0, 0) > 0) {
  11658. return false;
  11659. }
  11660. // Fallback to stream-level check for non-socket streams or when the
  11661. // socket isn't reporting readable. Avoid using `is_readable()` for
  11662. // SSL, since `SSL_pending()` may report buffered records that do not
  11663. // indicate a complete application-level response yet.
  11664. if (!is_ssl() && strm.is_readable()) { return false; }
  11665. auto now = std::chrono::high_resolution_clock::now();
  11666. auto elapsed =
  11667. std::chrono::duration_cast<std::chrono::milliseconds>(now - start)
  11668. .count();
  11669. if (elapsed >= CPPHTTPLIB_WAIT_EARLY_SERVER_RESPONSE_TIMEOUT_MSECOND) {
  11670. break;
  11671. }
  11672. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  11673. }
  11674. }
  11675. #endif
  11676. // Body
  11677. if (skip_body) { return true; }
  11678. return write_request_body(strm, req, error);
  11679. }
  11680. inline bool ClientImpl::write_request_body(Stream &strm, Request &req,
  11681. Error &error) {
  11682. if (req.body.empty()) {
  11683. return write_content_with_provider(strm, req, error);
  11684. }
  11685. if (req.upload_progress) {
  11686. auto body_size = req.body.size();
  11687. size_t written = 0;
  11688. auto data = req.body.data();
  11689. while (written < body_size) {
  11690. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  11691. if (!detail::write_data(strm, data + written, to_write)) {
  11692. error = Error::Write;
  11693. output_error_log(error, &req);
  11694. return false;
  11695. }
  11696. written += to_write;
  11697. if (!req.upload_progress(written, body_size)) {
  11698. error = Error::Canceled;
  11699. output_error_log(error, &req);
  11700. return false;
  11701. }
  11702. }
  11703. } else {
  11704. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  11705. error = Error::Write;
  11706. output_error_log(error, &req);
  11707. return false;
  11708. }
  11709. }
  11710. return true;
  11711. }
  11712. inline std::unique_ptr<Response>
  11713. ClientImpl::send_with_content_provider_and_receiver(
  11714. Request &req, const char *body, size_t content_length,
  11715. ContentProvider content_provider,
  11716. ContentProviderWithoutLength content_provider_without_length,
  11717. const std::string &content_type, ContentReceiver content_receiver,
  11718. Error &error) {
  11719. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  11720. auto enc = compress_
  11721. ? detail::create_compressor()
  11722. : std::pair<std::unique_ptr<detail::compressor>, const char *>(
  11723. nullptr, nullptr);
  11724. if (enc.second) { req.set_header("Content-Encoding", enc.second); }
  11725. if (enc.first && !content_provider_without_length) {
  11726. auto &compressor = enc.first;
  11727. if (content_provider) {
  11728. auto ok = true;
  11729. size_t offset = 0;
  11730. DataSink data_sink;
  11731. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  11732. if (ok) {
  11733. auto last = offset + data_len == content_length;
  11734. auto ret = compressor->compress(
  11735. data, data_len, last,
  11736. [&](const char *compressed_data, size_t compressed_data_len) {
  11737. req.body.append(compressed_data, compressed_data_len);
  11738. return true;
  11739. });
  11740. if (ret) {
  11741. offset += data_len;
  11742. } else {
  11743. ok = false;
  11744. }
  11745. }
  11746. return ok;
  11747. };
  11748. while (ok && offset < content_length) {
  11749. if (!content_provider(offset, content_length - offset, data_sink)) {
  11750. error = Error::Canceled;
  11751. output_error_log(error, &req);
  11752. return nullptr;
  11753. }
  11754. }
  11755. } else {
  11756. if (!compressor->compress(body, content_length, true,
  11757. [&](const char *data, size_t data_len) {
  11758. req.body.append(data, data_len);
  11759. return true;
  11760. })) {
  11761. error = Error::Compression;
  11762. output_error_log(error, &req);
  11763. return nullptr;
  11764. }
  11765. }
  11766. } else {
  11767. if (content_provider) {
  11768. req.content_length_ = content_length;
  11769. req.content_provider_ = std::move(content_provider);
  11770. req.is_chunked_content_provider_ = false;
  11771. } else if (content_provider_without_length) {
  11772. req.content_length_ = 0;
  11773. req.content_provider_ = detail::ContentProviderAdapter(
  11774. std::move(content_provider_without_length));
  11775. req.is_chunked_content_provider_ = true;
  11776. req.set_header("Transfer-Encoding", "chunked");
  11777. } else {
  11778. req.body.assign(body, content_length);
  11779. }
  11780. }
  11781. if (content_receiver) {
  11782. req.content_receiver =
  11783. [content_receiver](const char *data, size_t data_length,
  11784. size_t /*offset*/, size_t /*total_length*/) {
  11785. return content_receiver(data, data_length);
  11786. };
  11787. }
  11788. auto res = detail::make_unique<Response>();
  11789. return send(req, *res, error) ? std::move(res) : nullptr;
  11790. }
  11791. inline Result ClientImpl::send_with_content_provider_and_receiver(
  11792. const std::string &method, const std::string &path, const Headers &headers,
  11793. const char *body, size_t content_length, ContentProvider content_provider,
  11794. ContentProviderWithoutLength content_provider_without_length,
  11795. const std::string &content_type, ContentReceiver content_receiver,
  11796. UploadProgress progress) {
  11797. Request req;
  11798. req.method = method;
  11799. req.headers = headers;
  11800. req.path = path;
  11801. req.upload_progress = std::move(progress);
  11802. if (max_timeout_msec_ > 0) {
  11803. req.start_time_ = std::chrono::steady_clock::now();
  11804. }
  11805. auto error = Error::Success;
  11806. auto res = send_with_content_provider_and_receiver(
  11807. req, body, content_length, std::move(content_provider),
  11808. std::move(content_provider_without_length), content_type,
  11809. std::move(content_receiver), error);
  11810. #ifdef CPPHTTPLIB_SSL_ENABLED
  11811. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  11812. last_backend_error_};
  11813. #else
  11814. return Result{std::move(res), error, std::move(req.headers)};
  11815. #endif
  11816. }
  11817. inline void ClientImpl::output_log(const Request &req,
  11818. const Response &res) const {
  11819. if (logger_) {
  11820. std::lock_guard<std::mutex> guard(logger_mutex_);
  11821. logger_(req, res);
  11822. }
  11823. }
  11824. inline void ClientImpl::output_error_log(const Error &err,
  11825. const Request *req) const {
  11826. if (error_logger_) {
  11827. std::lock_guard<std::mutex> guard(logger_mutex_);
  11828. error_logger_(err, req);
  11829. }
  11830. }
  11831. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  11832. Response &res, bool close_connection,
  11833. Error &error) {
  11834. // Auto-add Expect: 100-continue for large bodies
  11835. if (CPPHTTPLIB_EXPECT_100_THRESHOLD > 0 && !req.has_header("Expect")) {
  11836. auto body_size = req.body.empty() ? req.content_length_ : req.body.size();
  11837. if (body_size >= CPPHTTPLIB_EXPECT_100_THRESHOLD) {
  11838. req.set_header("Expect", "100-continue");
  11839. }
  11840. }
  11841. // Check for Expect: 100-continue
  11842. auto expect_100_continue = req.get_header_value("Expect") == "100-continue";
  11843. // Send request (skip body if using Expect: 100-continue)
  11844. auto write_request_success =
  11845. write_request(strm, req, close_connection, error, expect_100_continue);
  11846. #ifdef CPPHTTPLIB_SSL_ENABLED
  11847. if (is_ssl() && !expect_100_continue) {
  11848. auto is_proxy_enabled = is_proxy_enabled_for_host(host_);
  11849. if (!is_proxy_enabled) {
  11850. if (tls::is_peer_closed(socket_.ssl, socket_.sock)) {
  11851. error = Error::SSLPeerCouldBeClosed_;
  11852. output_error_log(error, &req);
  11853. return false;
  11854. }
  11855. }
  11856. }
  11857. #endif
  11858. // Handle Expect: 100-continue.
  11859. //
  11860. // Wait for an interim/early response by attempting to read the status line
  11861. // under a short timeout, instead of trusting raw socket readability. Over
  11862. // TLS, post-handshake records (e.g. session tickets) make the socket
  11863. // readable without any HTTP response being available; relying on
  11864. // `select_read` there caused the body to be withheld forever and the
  11865. // request to fail with `Read` (#2458). If no status line arrives within the
  11866. // timeout, send the body anyway (matching curl's behavior).
  11867. auto status_line_read = false;
  11868. if (expect_100_continue && write_request_success) {
  11869. if (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND > 0) {
  11870. time_t sec = CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND / 1000;
  11871. time_t usec = (CPPHTTPLIB_EXPECT_100_TIMEOUT_MSECOND % 1000) * 1000;
  11872. strm.set_read_timeout(sec, usec);
  11873. status_line_read = read_response_line(strm, req, res, false);
  11874. strm.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  11875. }
  11876. if (!status_line_read) {
  11877. // No interim response within the timeout: send the body and handle the
  11878. // response as usual.
  11879. if (!write_request_body(strm, req, error)) { return false; }
  11880. expect_100_continue = false; // Switch to normal response handling
  11881. }
  11882. }
  11883. // Receive response and headers
  11884. // When using Expect: 100-continue, don't auto-skip `100 Continue` response
  11885. if ((!status_line_read &&
  11886. !read_response_line(strm, req, res, !expect_100_continue)) ||
  11887. !detail::read_headers(strm, res.headers)) {
  11888. if (write_request_success) { error = Error::Read; }
  11889. output_error_log(error, &req);
  11890. return false;
  11891. }
  11892. if (!write_request_success) { return false; }
  11893. // Handle Expect: 100-continue response
  11894. if (expect_100_continue) {
  11895. if (res.status == StatusCode::Continue_100) {
  11896. // Server accepted, send the body
  11897. if (!write_request_body(strm, req, error)) { return false; }
  11898. // Read the actual response
  11899. res.headers.clear();
  11900. res.body.clear();
  11901. if (!read_response_line(strm, req, res) ||
  11902. !detail::read_headers(strm, res.headers)) {
  11903. error = Error::Read;
  11904. output_error_log(error, &req);
  11905. return false;
  11906. }
  11907. }
  11908. // If not 100 Continue, server returned an error; proceed with that response
  11909. }
  11910. // Body
  11911. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  11912. req.method != "CONNECT") {
  11913. auto redirect = 300 < res.status && res.status < 400 &&
  11914. res.status != StatusCode::NotModified_304 &&
  11915. follow_location_;
  11916. if (req.response_handler && !redirect) {
  11917. if (!req.response_handler(res)) {
  11918. error = Error::Canceled;
  11919. output_error_log(error, &req);
  11920. return false;
  11921. }
  11922. }
  11923. auto out =
  11924. req.content_receiver
  11925. ? static_cast<ContentReceiverWithProgress>(
  11926. [&](const char *buf, size_t n, size_t off, size_t len) {
  11927. if (redirect) { return true; }
  11928. auto ret = req.content_receiver(buf, n, off, len);
  11929. if (!ret) {
  11930. error = Error::Canceled;
  11931. output_error_log(error, &req);
  11932. }
  11933. return ret;
  11934. })
  11935. : static_cast<ContentReceiverWithProgress>(
  11936. [&](const char *buf, size_t n, size_t /*off*/,
  11937. size_t /*len*/) {
  11938. assert(res.body.size() + n <= res.body.max_size());
  11939. if (payload_max_length_ > 0 &&
  11940. (res.body.size() >= payload_max_length_ ||
  11941. n > payload_max_length_ - res.body.size())) {
  11942. return false;
  11943. }
  11944. res.body.append(buf, n);
  11945. return true;
  11946. });
  11947. auto progress = [&](size_t current, size_t total) {
  11948. if (!req.download_progress || redirect) { return true; }
  11949. auto ret = req.download_progress(current, total);
  11950. if (!ret) {
  11951. error = Error::Canceled;
  11952. output_error_log(error, &req);
  11953. }
  11954. return ret;
  11955. };
  11956. if (res.has_header("Content-Length")) {
  11957. if (!req.content_receiver) {
  11958. auto len = res.get_header_value_u64("Content-Length");
  11959. if (len > res.body.max_size()) {
  11960. error = Error::Read;
  11961. output_error_log(error, &req);
  11962. return false;
  11963. }
  11964. // Cap the reservation by payload_max_length_ to avoid OOM when a
  11965. // hostile or malformed server sends an enormous Content-Length.
  11966. // The actual body read below is bounded by payload_max_length_,
  11967. // so reserving more than that is never useful.
  11968. auto reserve_len = static_cast<size_t>(len);
  11969. if (payload_max_length_ > 0 && reserve_len > payload_max_length_) {
  11970. reserve_len = payload_max_length_;
  11971. }
  11972. res.body.reserve(reserve_len);
  11973. }
  11974. }
  11975. if (res.status != StatusCode::NotModified_304) {
  11976. int dummy_status;
  11977. auto max_length = (!has_payload_max_length_ && req.content_receiver)
  11978. ? (std::numeric_limits<size_t>::max)()
  11979. : payload_max_length_;
  11980. if (!detail::read_content(strm, res, max_length, dummy_status,
  11981. std::move(progress), std::move(out),
  11982. decompress_)) {
  11983. if (error != Error::Canceled) { error = Error::Read; }
  11984. output_error_log(error, &req);
  11985. return false;
  11986. }
  11987. }
  11988. }
  11989. // Log
  11990. output_log(req, res);
  11991. return true;
  11992. }
  11993. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  11994. const std::string &boundary, const UploadFormDataItems &items,
  11995. const FormDataProviderItems &provider_items) const {
  11996. size_t cur_item = 0;
  11997. size_t cur_start = 0;
  11998. // cur_item and cur_start are copied to within the std::function and
  11999. // maintain state between successive calls
  12000. return [&, cur_item, cur_start](size_t offset,
  12001. DataSink &sink) mutable -> bool {
  12002. if (!offset && !items.empty()) {
  12003. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  12004. return true;
  12005. } else if (cur_item < provider_items.size()) {
  12006. if (!cur_start) {
  12007. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  12008. provider_items[cur_item], boundary);
  12009. offset += begin.size();
  12010. cur_start = offset;
  12011. sink.os << begin;
  12012. }
  12013. DataSink cur_sink;
  12014. auto has_data = true;
  12015. cur_sink.write = sink.write;
  12016. cur_sink.done = [&]() { has_data = false; };
  12017. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  12018. return false;
  12019. }
  12020. if (!has_data) {
  12021. sink.os << detail::serialize_multipart_formdata_item_end();
  12022. cur_item++;
  12023. cur_start = 0;
  12024. }
  12025. return true;
  12026. } else {
  12027. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  12028. sink.done();
  12029. return true;
  12030. }
  12031. };
  12032. }
  12033. inline bool ClientImpl::process_socket(
  12034. const Socket &socket,
  12035. std::chrono::time_point<std::chrono::steady_clock> start_time,
  12036. std::function<bool(Stream &strm)> callback) {
  12037. return detail::process_client_socket(
  12038. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  12039. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  12040. }
  12041. inline bool ClientImpl::is_ssl() const { return false; }
  12042. inline Result ClientImpl::Get(const std::string &path,
  12043. DownloadProgress progress) {
  12044. return Get(path, Headers(), std::move(progress));
  12045. }
  12046. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12047. DownloadProgress progress) {
  12048. return Get(path, params, Headers(), std::move(progress));
  12049. }
  12050. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12051. const Headers &headers,
  12052. DownloadProgress progress) {
  12053. if (params.empty()) { return Get(path, headers); }
  12054. std::string path_with_query = append_query_params(path, params);
  12055. return Get(path_with_query, headers, std::move(progress));
  12056. }
  12057. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12058. DownloadProgress progress) {
  12059. Request req;
  12060. req.method = "GET";
  12061. req.path = path;
  12062. req.headers = headers;
  12063. req.download_progress = std::move(progress);
  12064. if (max_timeout_msec_ > 0) {
  12065. req.start_time_ = std::chrono::steady_clock::now();
  12066. }
  12067. return send_(std::move(req));
  12068. }
  12069. inline Result ClientImpl::Get(const std::string &path,
  12070. ContentReceiver content_receiver,
  12071. DownloadProgress progress) {
  12072. return Get(path, Headers(), nullptr, std::move(content_receiver),
  12073. std::move(progress));
  12074. }
  12075. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12076. ContentReceiver content_receiver,
  12077. DownloadProgress progress) {
  12078. return Get(path, headers, nullptr, std::move(content_receiver),
  12079. std::move(progress));
  12080. }
  12081. inline Result ClientImpl::Get(const std::string &path,
  12082. ResponseHandler response_handler,
  12083. ContentReceiver content_receiver,
  12084. DownloadProgress progress) {
  12085. return Get(path, Headers(), std::move(response_handler),
  12086. std::move(content_receiver), std::move(progress));
  12087. }
  12088. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  12089. ResponseHandler response_handler,
  12090. ContentReceiver content_receiver,
  12091. DownloadProgress progress) {
  12092. Request req;
  12093. req.method = "GET";
  12094. req.path = path;
  12095. req.headers = headers;
  12096. req.response_handler = std::move(response_handler);
  12097. req.content_receiver =
  12098. [content_receiver](const char *data, size_t data_length,
  12099. size_t /*offset*/, size_t /*total_length*/) {
  12100. return content_receiver(data, data_length);
  12101. };
  12102. req.download_progress = std::move(progress);
  12103. if (max_timeout_msec_ > 0) {
  12104. req.start_time_ = std::chrono::steady_clock::now();
  12105. }
  12106. return send_(std::move(req));
  12107. }
  12108. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12109. const Headers &headers,
  12110. ContentReceiver content_receiver,
  12111. DownloadProgress progress) {
  12112. return Get(path, params, headers, nullptr, std::move(content_receiver),
  12113. std::move(progress));
  12114. }
  12115. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  12116. const Headers &headers,
  12117. ResponseHandler response_handler,
  12118. ContentReceiver content_receiver,
  12119. DownloadProgress progress) {
  12120. if (params.empty()) {
  12121. return Get(path, headers, std::move(response_handler),
  12122. std::move(content_receiver), std::move(progress));
  12123. }
  12124. std::string path_with_query = append_query_params(path, params);
  12125. return Get(path_with_query, headers, std::move(response_handler),
  12126. std::move(content_receiver), std::move(progress));
  12127. }
  12128. inline Result ClientImpl::Head(const std::string &path) {
  12129. return Head(path, Headers());
  12130. }
  12131. inline Result ClientImpl::Head(const std::string &path,
  12132. const Headers &headers) {
  12133. Request req;
  12134. req.method = "HEAD";
  12135. req.headers = headers;
  12136. req.path = path;
  12137. if (max_timeout_msec_ > 0) {
  12138. req.start_time_ = std::chrono::steady_clock::now();
  12139. }
  12140. return send_(std::move(req));
  12141. }
  12142. inline Result ClientImpl::Post(const std::string &path) {
  12143. return Post(path, std::string(), std::string());
  12144. }
  12145. inline Result ClientImpl::Post(const std::string &path,
  12146. const Headers &headers) {
  12147. return Post(path, headers, nullptr, 0, std::string());
  12148. }
  12149. inline Result ClientImpl::Post(const std::string &path, const char *body,
  12150. size_t content_length,
  12151. const std::string &content_type,
  12152. UploadProgress progress) {
  12153. return Post(path, Headers(), body, content_length, content_type, progress);
  12154. }
  12155. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  12156. const std::string &content_type,
  12157. UploadProgress progress) {
  12158. return Post(path, Headers(), body, content_type, progress);
  12159. }
  12160. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  12161. return Post(path, Headers(), params);
  12162. }
  12163. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12164. ContentProvider content_provider,
  12165. const std::string &content_type,
  12166. UploadProgress progress) {
  12167. return Post(path, Headers(), content_length, std::move(content_provider),
  12168. content_type, progress);
  12169. }
  12170. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  12171. ContentProvider content_provider,
  12172. const std::string &content_type,
  12173. ContentReceiver content_receiver,
  12174. UploadProgress progress) {
  12175. return Post(path, Headers(), content_length, std::move(content_provider),
  12176. content_type, std::move(content_receiver), progress);
  12177. }
  12178. inline Result ClientImpl::Post(const std::string &path,
  12179. ContentProviderWithoutLength content_provider,
  12180. const std::string &content_type,
  12181. UploadProgress progress) {
  12182. return Post(path, Headers(), std::move(content_provider), content_type,
  12183. progress);
  12184. }
  12185. inline Result ClientImpl::Post(const std::string &path,
  12186. ContentProviderWithoutLength content_provider,
  12187. const std::string &content_type,
  12188. ContentReceiver content_receiver,
  12189. UploadProgress progress) {
  12190. return Post(path, Headers(), std::move(content_provider), content_type,
  12191. std::move(content_receiver), progress);
  12192. }
  12193. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12194. const Params &params) {
  12195. auto query = detail::params_to_query_str(params);
  12196. return Post(path, headers, query, "application/x-www-form-urlencoded");
  12197. }
  12198. inline Result ClientImpl::Post(const std::string &path,
  12199. const UploadFormDataItems &items,
  12200. UploadProgress progress) {
  12201. return Post(path, Headers(), items, progress);
  12202. }
  12203. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12204. const UploadFormDataItems &items,
  12205. UploadProgress progress) {
  12206. const auto &boundary = detail::make_multipart_data_boundary();
  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 UploadFormDataItems &items,
  12216. const std::string &boundary,
  12217. UploadProgress progress) {
  12218. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12219. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12220. }
  12221. const auto &content_type =
  12222. detail::serialize_multipart_formdata_get_content_type(boundary);
  12223. auto content_length = detail::get_multipart_content_length(items, boundary);
  12224. return Post(path, headers, content_length,
  12225. detail::make_multipart_content_provider(items, boundary),
  12226. content_type, progress);
  12227. }
  12228. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12229. const char *body, size_t content_length,
  12230. const std::string &content_type,
  12231. UploadProgress progress) {
  12232. return send_with_content_provider_and_receiver(
  12233. "POST", path, headers, body, content_length, nullptr, nullptr,
  12234. content_type, nullptr, progress);
  12235. }
  12236. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12237. const std::string &body,
  12238. const std::string &content_type,
  12239. UploadProgress progress) {
  12240. return send_with_content_provider_and_receiver(
  12241. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  12242. content_type, nullptr, progress);
  12243. }
  12244. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12245. size_t content_length,
  12246. ContentProvider content_provider,
  12247. const std::string &content_type,
  12248. UploadProgress progress) {
  12249. return send_with_content_provider_and_receiver(
  12250. "POST", path, headers, nullptr, content_length,
  12251. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12252. }
  12253. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12254. size_t content_length,
  12255. ContentProvider content_provider,
  12256. const std::string &content_type,
  12257. ContentReceiver content_receiver,
  12258. DownloadProgress progress) {
  12259. return send_with_content_provider_and_receiver(
  12260. "POST", path, headers, nullptr, content_length,
  12261. std::move(content_provider), nullptr, content_type,
  12262. std::move(content_receiver), std::move(progress));
  12263. }
  12264. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12265. ContentProviderWithoutLength content_provider,
  12266. const std::string &content_type,
  12267. UploadProgress progress) {
  12268. return send_with_content_provider_and_receiver(
  12269. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12270. content_type, nullptr, progress);
  12271. }
  12272. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12273. ContentProviderWithoutLength content_provider,
  12274. const std::string &content_type,
  12275. ContentReceiver content_receiver,
  12276. DownloadProgress progress) {
  12277. return send_with_content_provider_and_receiver(
  12278. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12279. content_type, std::move(content_receiver), std::move(progress));
  12280. }
  12281. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12282. const UploadFormDataItems &items,
  12283. const FormDataProviderItems &provider_items,
  12284. UploadProgress progress) {
  12285. const auto &boundary = detail::make_multipart_data_boundary();
  12286. const auto &content_type =
  12287. detail::serialize_multipart_formdata_get_content_type(boundary);
  12288. return send_with_content_provider_and_receiver(
  12289. "POST", path, headers, nullptr, 0, nullptr,
  12290. get_multipart_content_provider(boundary, items, provider_items),
  12291. content_type, nullptr, progress);
  12292. }
  12293. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  12294. const std::string &body,
  12295. const std::string &content_type,
  12296. ContentReceiver content_receiver,
  12297. DownloadProgress progress) {
  12298. Request req;
  12299. req.method = "POST";
  12300. req.path = path;
  12301. req.headers = headers;
  12302. req.body = body;
  12303. req.content_receiver =
  12304. [content_receiver](const char *data, size_t data_length,
  12305. size_t /*offset*/, size_t /*total_length*/) {
  12306. return content_receiver(data, data_length);
  12307. };
  12308. req.download_progress = std::move(progress);
  12309. if (max_timeout_msec_ > 0) {
  12310. req.start_time_ = std::chrono::steady_clock::now();
  12311. }
  12312. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12313. return send_(std::move(req));
  12314. }
  12315. inline Result ClientImpl::Put(const std::string &path) {
  12316. return Put(path, std::string(), std::string());
  12317. }
  12318. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  12319. return Put(path, headers, nullptr, 0, std::string());
  12320. }
  12321. inline Result ClientImpl::Put(const std::string &path, const char *body,
  12322. size_t content_length,
  12323. const std::string &content_type,
  12324. UploadProgress progress) {
  12325. return Put(path, Headers(), body, content_length, content_type, progress);
  12326. }
  12327. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  12328. const std::string &content_type,
  12329. UploadProgress progress) {
  12330. return Put(path, Headers(), body, content_type, progress);
  12331. }
  12332. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  12333. return Put(path, Headers(), params);
  12334. }
  12335. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12336. ContentProvider content_provider,
  12337. const std::string &content_type,
  12338. UploadProgress progress) {
  12339. return Put(path, Headers(), content_length, std::move(content_provider),
  12340. content_type, progress);
  12341. }
  12342. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  12343. ContentProvider content_provider,
  12344. const std::string &content_type,
  12345. ContentReceiver content_receiver,
  12346. UploadProgress progress) {
  12347. return Put(path, Headers(), content_length, std::move(content_provider),
  12348. content_type, std::move(content_receiver), progress);
  12349. }
  12350. inline Result ClientImpl::Put(const std::string &path,
  12351. ContentProviderWithoutLength content_provider,
  12352. const std::string &content_type,
  12353. UploadProgress progress) {
  12354. return Put(path, Headers(), std::move(content_provider), content_type,
  12355. progress);
  12356. }
  12357. inline Result ClientImpl::Put(const std::string &path,
  12358. ContentProviderWithoutLength content_provider,
  12359. const std::string &content_type,
  12360. ContentReceiver content_receiver,
  12361. UploadProgress progress) {
  12362. return Put(path, Headers(), std::move(content_provider), content_type,
  12363. std::move(content_receiver), progress);
  12364. }
  12365. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12366. const Params &params) {
  12367. auto query = detail::params_to_query_str(params);
  12368. return Put(path, headers, query, "application/x-www-form-urlencoded");
  12369. }
  12370. inline Result ClientImpl::Put(const std::string &path,
  12371. const UploadFormDataItems &items,
  12372. UploadProgress progress) {
  12373. return Put(path, Headers(), items, progress);
  12374. }
  12375. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12376. const UploadFormDataItems &items,
  12377. UploadProgress progress) {
  12378. const auto &boundary = detail::make_multipart_data_boundary();
  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 UploadFormDataItems &items,
  12388. const std::string &boundary,
  12389. UploadProgress progress) {
  12390. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12391. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12392. }
  12393. const auto &content_type =
  12394. detail::serialize_multipart_formdata_get_content_type(boundary);
  12395. auto content_length = detail::get_multipart_content_length(items, boundary);
  12396. return Put(path, headers, content_length,
  12397. detail::make_multipart_content_provider(items, boundary),
  12398. content_type, progress);
  12399. }
  12400. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12401. const char *body, size_t content_length,
  12402. const std::string &content_type,
  12403. UploadProgress progress) {
  12404. return send_with_content_provider_and_receiver(
  12405. "PUT", path, headers, body, content_length, nullptr, nullptr,
  12406. content_type, nullptr, progress);
  12407. }
  12408. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12409. const std::string &body,
  12410. const std::string &content_type,
  12411. UploadProgress progress) {
  12412. return send_with_content_provider_and_receiver(
  12413. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  12414. content_type, nullptr, progress);
  12415. }
  12416. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12417. size_t content_length,
  12418. ContentProvider content_provider,
  12419. const std::string &content_type,
  12420. UploadProgress progress) {
  12421. return send_with_content_provider_and_receiver(
  12422. "PUT", path, headers, nullptr, content_length,
  12423. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12424. }
  12425. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12426. size_t content_length,
  12427. ContentProvider content_provider,
  12428. const std::string &content_type,
  12429. ContentReceiver content_receiver,
  12430. UploadProgress progress) {
  12431. return send_with_content_provider_and_receiver(
  12432. "PUT", path, headers, nullptr, content_length,
  12433. std::move(content_provider), nullptr, content_type,
  12434. std::move(content_receiver), progress);
  12435. }
  12436. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12437. ContentProviderWithoutLength content_provider,
  12438. const std::string &content_type,
  12439. UploadProgress progress) {
  12440. return send_with_content_provider_and_receiver(
  12441. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12442. content_type, nullptr, progress);
  12443. }
  12444. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12445. ContentProviderWithoutLength content_provider,
  12446. const std::string &content_type,
  12447. ContentReceiver content_receiver,
  12448. UploadProgress progress) {
  12449. return send_with_content_provider_and_receiver(
  12450. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12451. content_type, std::move(content_receiver), progress);
  12452. }
  12453. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12454. const UploadFormDataItems &items,
  12455. const FormDataProviderItems &provider_items,
  12456. UploadProgress progress) {
  12457. const auto &boundary = detail::make_multipart_data_boundary();
  12458. const auto &content_type =
  12459. detail::serialize_multipart_formdata_get_content_type(boundary);
  12460. return send_with_content_provider_and_receiver(
  12461. "PUT", path, headers, nullptr, 0, nullptr,
  12462. get_multipart_content_provider(boundary, items, provider_items),
  12463. content_type, nullptr, progress);
  12464. }
  12465. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  12466. const std::string &body,
  12467. const std::string &content_type,
  12468. ContentReceiver content_receiver,
  12469. DownloadProgress progress) {
  12470. Request req;
  12471. req.method = "PUT";
  12472. req.path = path;
  12473. req.headers = headers;
  12474. req.body = body;
  12475. req.content_receiver =
  12476. [content_receiver](const char *data, size_t data_length,
  12477. size_t /*offset*/, size_t /*total_length*/) {
  12478. return content_receiver(data, data_length);
  12479. };
  12480. req.download_progress = std::move(progress);
  12481. if (max_timeout_msec_ > 0) {
  12482. req.start_time_ = std::chrono::steady_clock::now();
  12483. }
  12484. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12485. return send_(std::move(req));
  12486. }
  12487. inline Result ClientImpl::Patch(const std::string &path) {
  12488. return Patch(path, std::string(), std::string());
  12489. }
  12490. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12491. UploadProgress progress) {
  12492. return Patch(path, headers, nullptr, 0, std::string(), progress);
  12493. }
  12494. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  12495. size_t content_length,
  12496. const std::string &content_type,
  12497. UploadProgress progress) {
  12498. return Patch(path, Headers(), body, content_length, content_type, progress);
  12499. }
  12500. inline Result ClientImpl::Patch(const std::string &path,
  12501. const std::string &body,
  12502. const std::string &content_type,
  12503. UploadProgress progress) {
  12504. return Patch(path, Headers(), body, content_type, progress);
  12505. }
  12506. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  12507. return Patch(path, Headers(), params);
  12508. }
  12509. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12510. ContentProvider content_provider,
  12511. const std::string &content_type,
  12512. UploadProgress progress) {
  12513. return Patch(path, Headers(), content_length, std::move(content_provider),
  12514. content_type, progress);
  12515. }
  12516. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  12517. ContentProvider content_provider,
  12518. const std::string &content_type,
  12519. ContentReceiver content_receiver,
  12520. UploadProgress progress) {
  12521. return Patch(path, Headers(), content_length, std::move(content_provider),
  12522. content_type, std::move(content_receiver), progress);
  12523. }
  12524. inline Result ClientImpl::Patch(const std::string &path,
  12525. ContentProviderWithoutLength content_provider,
  12526. const std::string &content_type,
  12527. UploadProgress progress) {
  12528. return Patch(path, Headers(), std::move(content_provider), content_type,
  12529. progress);
  12530. }
  12531. inline Result ClientImpl::Patch(const std::string &path,
  12532. ContentProviderWithoutLength content_provider,
  12533. const std::string &content_type,
  12534. ContentReceiver content_receiver,
  12535. UploadProgress progress) {
  12536. return Patch(path, Headers(), std::move(content_provider), content_type,
  12537. std::move(content_receiver), progress);
  12538. }
  12539. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12540. const Params &params) {
  12541. auto query = detail::params_to_query_str(params);
  12542. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  12543. }
  12544. inline Result ClientImpl::Patch(const std::string &path,
  12545. const UploadFormDataItems &items,
  12546. UploadProgress progress) {
  12547. return Patch(path, Headers(), items, progress);
  12548. }
  12549. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12550. const UploadFormDataItems &items,
  12551. UploadProgress progress) {
  12552. const auto &boundary = detail::make_multipart_data_boundary();
  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 UploadFormDataItems &items,
  12562. const std::string &boundary,
  12563. UploadProgress progress) {
  12564. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  12565. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  12566. }
  12567. const auto &content_type =
  12568. detail::serialize_multipart_formdata_get_content_type(boundary);
  12569. auto content_length = detail::get_multipart_content_length(items, boundary);
  12570. return Patch(path, headers, content_length,
  12571. detail::make_multipart_content_provider(items, boundary),
  12572. content_type, progress);
  12573. }
  12574. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12575. const char *body, size_t content_length,
  12576. const std::string &content_type,
  12577. UploadProgress progress) {
  12578. return send_with_content_provider_and_receiver(
  12579. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  12580. content_type, nullptr, progress);
  12581. }
  12582. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12583. const std::string &body,
  12584. const std::string &content_type,
  12585. UploadProgress progress) {
  12586. return send_with_content_provider_and_receiver(
  12587. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  12588. content_type, nullptr, progress);
  12589. }
  12590. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12591. size_t content_length,
  12592. ContentProvider content_provider,
  12593. const std::string &content_type,
  12594. UploadProgress progress) {
  12595. return send_with_content_provider_and_receiver(
  12596. "PATCH", path, headers, nullptr, content_length,
  12597. std::move(content_provider), nullptr, content_type, nullptr, progress);
  12598. }
  12599. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12600. size_t content_length,
  12601. ContentProvider content_provider,
  12602. const std::string &content_type,
  12603. ContentReceiver content_receiver,
  12604. UploadProgress progress) {
  12605. return send_with_content_provider_and_receiver(
  12606. "PATCH", path, headers, nullptr, content_length,
  12607. std::move(content_provider), nullptr, content_type,
  12608. std::move(content_receiver), progress);
  12609. }
  12610. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12611. ContentProviderWithoutLength content_provider,
  12612. const std::string &content_type,
  12613. UploadProgress progress) {
  12614. return send_with_content_provider_and_receiver(
  12615. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12616. content_type, nullptr, progress);
  12617. }
  12618. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12619. ContentProviderWithoutLength content_provider,
  12620. const std::string &content_type,
  12621. ContentReceiver content_receiver,
  12622. UploadProgress progress) {
  12623. return send_with_content_provider_and_receiver(
  12624. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  12625. content_type, std::move(content_receiver), progress);
  12626. }
  12627. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12628. const UploadFormDataItems &items,
  12629. const FormDataProviderItems &provider_items,
  12630. UploadProgress progress) {
  12631. const auto &boundary = detail::make_multipart_data_boundary();
  12632. const auto &content_type =
  12633. detail::serialize_multipart_formdata_get_content_type(boundary);
  12634. return send_with_content_provider_and_receiver(
  12635. "PATCH", path, headers, nullptr, 0, nullptr,
  12636. get_multipart_content_provider(boundary, items, provider_items),
  12637. content_type, nullptr, progress);
  12638. }
  12639. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  12640. const std::string &body,
  12641. const std::string &content_type,
  12642. ContentReceiver content_receiver,
  12643. DownloadProgress progress) {
  12644. Request req;
  12645. req.method = "PATCH";
  12646. req.path = path;
  12647. req.headers = headers;
  12648. req.body = body;
  12649. req.content_receiver =
  12650. [content_receiver](const char *data, size_t data_length,
  12651. size_t /*offset*/, size_t /*total_length*/) {
  12652. return content_receiver(data, data_length);
  12653. };
  12654. req.download_progress = std::move(progress);
  12655. if (max_timeout_msec_ > 0) {
  12656. req.start_time_ = std::chrono::steady_clock::now();
  12657. }
  12658. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12659. return send_(std::move(req));
  12660. }
  12661. inline Result ClientImpl::Delete(const std::string &path,
  12662. DownloadProgress progress) {
  12663. return Delete(path, Headers(), std::string(), std::string(), progress);
  12664. }
  12665. inline Result ClientImpl::Delete(const std::string &path,
  12666. const Headers &headers,
  12667. DownloadProgress progress) {
  12668. return Delete(path, headers, std::string(), std::string(), progress);
  12669. }
  12670. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  12671. size_t content_length,
  12672. const std::string &content_type,
  12673. DownloadProgress progress) {
  12674. return Delete(path, Headers(), body, content_length, content_type, progress);
  12675. }
  12676. inline Result ClientImpl::Delete(const std::string &path,
  12677. const std::string &body,
  12678. const std::string &content_type,
  12679. DownloadProgress progress) {
  12680. return Delete(path, Headers(), body.data(), body.size(), content_type,
  12681. progress);
  12682. }
  12683. inline Result ClientImpl::Delete(const std::string &path,
  12684. const Headers &headers,
  12685. const std::string &body,
  12686. const std::string &content_type,
  12687. DownloadProgress progress) {
  12688. return Delete(path, headers, body.data(), body.size(), content_type,
  12689. progress);
  12690. }
  12691. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  12692. DownloadProgress progress) {
  12693. return Delete(path, Headers(), params, progress);
  12694. }
  12695. inline Result ClientImpl::Delete(const std::string &path,
  12696. const Headers &headers, const Params &params,
  12697. DownloadProgress progress) {
  12698. auto query = detail::params_to_query_str(params);
  12699. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  12700. progress);
  12701. }
  12702. inline Result ClientImpl::Delete(const std::string &path,
  12703. const Headers &headers, const char *body,
  12704. size_t content_length,
  12705. const std::string &content_type,
  12706. DownloadProgress progress) {
  12707. Request req;
  12708. req.method = "DELETE";
  12709. req.headers = headers;
  12710. req.path = path;
  12711. req.download_progress = std::move(progress);
  12712. if (max_timeout_msec_ > 0) {
  12713. req.start_time_ = std::chrono::steady_clock::now();
  12714. }
  12715. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  12716. req.body.assign(body, content_length);
  12717. return send_(std::move(req));
  12718. }
  12719. inline Result ClientImpl::Options(const std::string &path) {
  12720. return Options(path, Headers());
  12721. }
  12722. inline Result ClientImpl::Options(const std::string &path,
  12723. const Headers &headers) {
  12724. Request req;
  12725. req.method = "OPTIONS";
  12726. req.headers = headers;
  12727. req.path = path;
  12728. if (max_timeout_msec_ > 0) {
  12729. req.start_time_ = std::chrono::steady_clock::now();
  12730. }
  12731. return send_(std::move(req));
  12732. }
  12733. inline void ClientImpl::stop() {
  12734. std::lock_guard<std::mutex> guard(socket_mutex_);
  12735. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  12736. // do is to shutdown_socket, so that threads using this socket suddenly
  12737. // discover they can't read/write any more and error out. Everything else
  12738. // (closing the socket, shutting ssl down) is unsafe because these actions
  12739. // are not thread-safe.
  12740. if (socket_requests_in_flight_ > 0) {
  12741. shutdown_socket(socket_);
  12742. // Aside from that, we set a flag for the socket to be closed when we're
  12743. // done.
  12744. socket_should_be_closed_when_request_is_done_ = true;
  12745. return;
  12746. }
  12747. disconnect(/*gracefully=*/true);
  12748. }
  12749. inline std::string ClientImpl::host() const { return host_; }
  12750. inline int ClientImpl::port() const { return port_; }
  12751. inline size_t ClientImpl::is_socket_open() const {
  12752. std::lock_guard<std::mutex> guard(socket_mutex_);
  12753. return socket_.is_open();
  12754. }
  12755. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  12756. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  12757. connection_timeout_sec_ = sec;
  12758. connection_timeout_usec_ = usec;
  12759. }
  12760. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  12761. read_timeout_sec_ = sec;
  12762. read_timeout_usec_ = usec;
  12763. }
  12764. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  12765. write_timeout_sec_ = sec;
  12766. write_timeout_usec_ = usec;
  12767. }
  12768. inline void ClientImpl::set_max_timeout(time_t msec) {
  12769. max_timeout_msec_ = msec;
  12770. }
  12771. inline void ClientImpl::set_basic_auth(const std::string &username,
  12772. const std::string &password) {
  12773. basic_auth_username_ = username;
  12774. basic_auth_password_ = password;
  12775. }
  12776. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  12777. bearer_token_auth_token_ = token;
  12778. }
  12779. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  12780. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  12781. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  12782. inline void
  12783. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  12784. addr_map_ = std::move(addr_map);
  12785. }
  12786. inline void ClientImpl::set_default_headers(Headers headers) {
  12787. default_headers_ = std::move(headers);
  12788. }
  12789. inline void ClientImpl::set_header_writer(
  12790. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  12791. header_writer_ = writer;
  12792. }
  12793. inline void ClientImpl::set_address_family(int family) {
  12794. address_family_ = family;
  12795. }
  12796. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  12797. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  12798. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  12799. socket_options_ = std::move(socket_options);
  12800. }
  12801. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  12802. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  12803. inline void ClientImpl::set_payload_max_length(size_t length) {
  12804. payload_max_length_ = length;
  12805. has_payload_max_length_ = true;
  12806. }
  12807. inline void ClientImpl::set_interface(const std::string &intf) {
  12808. interface_ = intf;
  12809. }
  12810. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  12811. proxy_host_ = host;
  12812. proxy_port_ = port;
  12813. std::lock_guard<std::mutex> guard(socket_mutex_);
  12814. disconnect(/*gracefully=*/true);
  12815. }
  12816. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  12817. const std::string &password) {
  12818. proxy_basic_auth_username_ = username;
  12819. proxy_basic_auth_password_ = password;
  12820. }
  12821. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  12822. proxy_bearer_token_auth_token_ = token;
  12823. }
  12824. inline void ClientImpl::set_no_proxy(const std::vector<std::string> &patterns) {
  12825. std::vector<detail::NoProxyEntry> parsed;
  12826. parsed.reserve(patterns.size());
  12827. for (const auto &p : patterns) {
  12828. auto trimmed = detail::trim_copy(p);
  12829. if (trimmed.empty()) { continue; }
  12830. detail::NoProxyEntry entry;
  12831. if (detail::parse_no_proxy_entry(trimmed, entry)) {
  12832. parsed.push_back(std::move(entry));
  12833. }
  12834. }
  12835. no_proxy_entries_ = std::move(parsed);
  12836. std::lock_guard<std::mutex> guard(socket_mutex_);
  12837. disconnect(/*gracefully=*/true);
  12838. }
  12839. #ifdef CPPHTTPLIB_SSL_ENABLED
  12840. inline void ClientImpl::set_digest_auth(const std::string &username,
  12841. const std::string &password) {
  12842. digest_auth_username_ = username;
  12843. digest_auth_password_ = password;
  12844. }
  12845. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  12846. const std::string &ca_cert_dir_path) {
  12847. ca_cert_file_path_ = ca_cert_file_path;
  12848. ca_cert_dir_path_ = ca_cert_dir_path;
  12849. }
  12850. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  12851. const std::string &password) {
  12852. proxy_digest_auth_username_ = username;
  12853. proxy_digest_auth_password_ = password;
  12854. }
  12855. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  12856. server_certificate_verification_ = enabled;
  12857. }
  12858. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  12859. server_hostname_verification_ = enabled;
  12860. }
  12861. inline void ClientImpl::enable_system_ca(bool enabled) {
  12862. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  12863. }
  12864. #endif
  12865. inline void ClientImpl::set_logger(Logger logger) {
  12866. logger_ = std::move(logger);
  12867. }
  12868. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  12869. error_logger_ = std::move(error_logger);
  12870. }
  12871. /*
  12872. * SSL/TLS Common Implementation
  12873. */
  12874. inline ClientConnection::~ClientConnection() {
  12875. #ifdef CPPHTTPLIB_SSL_ENABLED
  12876. if (session) {
  12877. tls::shutdown(session, true);
  12878. tls::free_session(session);
  12879. session = nullptr;
  12880. }
  12881. #endif
  12882. if (sock != INVALID_SOCKET) {
  12883. detail::close_socket(sock);
  12884. sock = INVALID_SOCKET;
  12885. }
  12886. }
  12887. // Universal client implementation
  12888. inline Client::Client(const std::string &scheme_host_port)
  12889. : Client(scheme_host_port, std::string(), std::string()) {}
  12890. inline Client::Client(const std::string &scheme_host_port,
  12891. const std::string &client_cert_path,
  12892. const std::string &client_key_path) {
  12893. detail::UrlComponents uc;
  12894. if (detail::parse_url(scheme_host_port, uc) && !uc.host.empty()) {
  12895. auto &scheme = uc.scheme;
  12896. #ifdef CPPHTTPLIB_SSL_ENABLED
  12897. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  12898. #else
  12899. if (!scheme.empty() && scheme != "http") {
  12900. #endif
  12901. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12902. std::string msg = "'" + scheme + "' scheme is not supported.";
  12903. throw std::invalid_argument(msg);
  12904. #endif
  12905. return;
  12906. }
  12907. auto is_ssl = scheme == "https";
  12908. auto host = std::move(uc.host);
  12909. auto port = is_ssl ? 443 : 80;
  12910. if (!uc.port.empty() && !detail::parse_port(uc.port, port)) { return; }
  12911. if (is_ssl) {
  12912. #ifdef CPPHTTPLIB_SSL_ENABLED
  12913. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  12914. client_key_path);
  12915. is_ssl_ = is_ssl;
  12916. #endif
  12917. } else {
  12918. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12919. client_key_path);
  12920. }
  12921. } else {
  12922. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  12923. // if port param below changes.
  12924. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  12925. client_cert_path, client_key_path);
  12926. }
  12927. }
  12928. inline Client::Client(const std::string &host, int port)
  12929. : Client(host, port, std::string(), std::string()) {}
  12930. inline Client::Client(const std::string &host, int port,
  12931. const std::string &client_cert_path,
  12932. const std::string &client_key_path)
  12933. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  12934. client_key_path)) {}
  12935. inline Client::~Client() = default;
  12936. inline bool Client::is_valid() const {
  12937. return cli_ != nullptr && cli_->is_valid();
  12938. }
  12939. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  12940. return cli_->Get(path, std::move(progress));
  12941. }
  12942. inline Result Client::Get(const std::string &path, const Headers &headers,
  12943. DownloadProgress progress) {
  12944. return cli_->Get(path, headers, std::move(progress));
  12945. }
  12946. inline Result Client::Get(const std::string &path,
  12947. ContentReceiver content_receiver,
  12948. DownloadProgress progress) {
  12949. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  12950. }
  12951. inline Result Client::Get(const std::string &path, const Headers &headers,
  12952. ContentReceiver content_receiver,
  12953. DownloadProgress progress) {
  12954. return cli_->Get(path, headers, std::move(content_receiver),
  12955. std::move(progress));
  12956. }
  12957. inline Result Client::Get(const std::string &path,
  12958. ResponseHandler response_handler,
  12959. ContentReceiver content_receiver,
  12960. DownloadProgress progress) {
  12961. return cli_->Get(path, std::move(response_handler),
  12962. std::move(content_receiver), std::move(progress));
  12963. }
  12964. inline Result Client::Get(const std::string &path, const Headers &headers,
  12965. ResponseHandler response_handler,
  12966. ContentReceiver content_receiver,
  12967. DownloadProgress progress) {
  12968. return cli_->Get(path, headers, std::move(response_handler),
  12969. std::move(content_receiver), std::move(progress));
  12970. }
  12971. inline Result Client::Get(const std::string &path, const Params &params,
  12972. DownloadProgress progress) {
  12973. return cli_->Get(path, params, std::move(progress));
  12974. }
  12975. inline Result Client::Get(const std::string &path, const Params &params,
  12976. const Headers &headers, DownloadProgress progress) {
  12977. return cli_->Get(path, params, headers, std::move(progress));
  12978. }
  12979. inline Result Client::Get(const std::string &path, const Params &params,
  12980. const Headers &headers,
  12981. ContentReceiver content_receiver,
  12982. DownloadProgress progress) {
  12983. return cli_->Get(path, params, headers, std::move(content_receiver),
  12984. std::move(progress));
  12985. }
  12986. inline Result Client::Get(const std::string &path, const Params &params,
  12987. const Headers &headers,
  12988. ResponseHandler response_handler,
  12989. ContentReceiver content_receiver,
  12990. DownloadProgress progress) {
  12991. return cli_->Get(path, params, headers, std::move(response_handler),
  12992. std::move(content_receiver), std::move(progress));
  12993. }
  12994. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  12995. inline Result Client::Head(const std::string &path, const Headers &headers) {
  12996. return cli_->Head(path, headers);
  12997. }
  12998. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  12999. inline Result Client::Post(const std::string &path, const Headers &headers) {
  13000. return cli_->Post(path, headers);
  13001. }
  13002. inline Result Client::Post(const std::string &path, const char *body,
  13003. size_t content_length,
  13004. const std::string &content_type,
  13005. UploadProgress progress) {
  13006. return cli_->Post(path, body, content_length, content_type, progress);
  13007. }
  13008. inline Result Client::Post(const std::string &path, const Headers &headers,
  13009. const char *body, size_t content_length,
  13010. const std::string &content_type,
  13011. UploadProgress progress) {
  13012. return cli_->Post(path, headers, body, content_length, content_type,
  13013. progress);
  13014. }
  13015. inline Result Client::Post(const std::string &path, const std::string &body,
  13016. const std::string &content_type,
  13017. UploadProgress progress) {
  13018. return cli_->Post(path, body, content_type, progress);
  13019. }
  13020. inline Result Client::Post(const std::string &path, const Headers &headers,
  13021. const std::string &body,
  13022. const std::string &content_type,
  13023. UploadProgress progress) {
  13024. return cli_->Post(path, headers, body, content_type, progress);
  13025. }
  13026. inline Result Client::Post(const std::string &path, size_t content_length,
  13027. ContentProvider content_provider,
  13028. const std::string &content_type,
  13029. UploadProgress progress) {
  13030. return cli_->Post(path, content_length, std::move(content_provider),
  13031. content_type, progress);
  13032. }
  13033. inline Result Client::Post(const std::string &path, size_t content_length,
  13034. ContentProvider content_provider,
  13035. const std::string &content_type,
  13036. ContentReceiver content_receiver,
  13037. UploadProgress progress) {
  13038. return cli_->Post(path, content_length, std::move(content_provider),
  13039. content_type, std::move(content_receiver), progress);
  13040. }
  13041. inline Result Client::Post(const std::string &path,
  13042. ContentProviderWithoutLength content_provider,
  13043. const std::string &content_type,
  13044. UploadProgress progress) {
  13045. return cli_->Post(path, std::move(content_provider), content_type, progress);
  13046. }
  13047. inline Result Client::Post(const std::string &path,
  13048. ContentProviderWithoutLength content_provider,
  13049. const std::string &content_type,
  13050. ContentReceiver content_receiver,
  13051. UploadProgress progress) {
  13052. return cli_->Post(path, std::move(content_provider), content_type,
  13053. std::move(content_receiver), progress);
  13054. }
  13055. inline Result Client::Post(const std::string &path, const Headers &headers,
  13056. size_t content_length,
  13057. ContentProvider content_provider,
  13058. const std::string &content_type,
  13059. UploadProgress progress) {
  13060. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13061. content_type, progress);
  13062. }
  13063. inline Result Client::Post(const std::string &path, const Headers &headers,
  13064. size_t content_length,
  13065. ContentProvider content_provider,
  13066. const std::string &content_type,
  13067. ContentReceiver content_receiver,
  13068. DownloadProgress progress) {
  13069. return cli_->Post(path, headers, content_length, std::move(content_provider),
  13070. content_type, std::move(content_receiver), progress);
  13071. }
  13072. inline Result Client::Post(const std::string &path, const Headers &headers,
  13073. ContentProviderWithoutLength content_provider,
  13074. const std::string &content_type,
  13075. UploadProgress progress) {
  13076. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13077. progress);
  13078. }
  13079. inline Result Client::Post(const std::string &path, const Headers &headers,
  13080. ContentProviderWithoutLength content_provider,
  13081. const std::string &content_type,
  13082. ContentReceiver content_receiver,
  13083. DownloadProgress progress) {
  13084. return cli_->Post(path, headers, std::move(content_provider), content_type,
  13085. std::move(content_receiver), progress);
  13086. }
  13087. inline Result Client::Post(const std::string &path, const Params &params) {
  13088. return cli_->Post(path, params);
  13089. }
  13090. inline Result Client::Post(const std::string &path, const Headers &headers,
  13091. const Params &params) {
  13092. return cli_->Post(path, headers, params);
  13093. }
  13094. inline Result Client::Post(const std::string &path,
  13095. const UploadFormDataItems &items,
  13096. UploadProgress progress) {
  13097. return cli_->Post(path, items, progress);
  13098. }
  13099. inline Result Client::Post(const std::string &path, const Headers &headers,
  13100. const UploadFormDataItems &items,
  13101. UploadProgress progress) {
  13102. return cli_->Post(path, headers, items, progress);
  13103. }
  13104. inline Result Client::Post(const std::string &path, const Headers &headers,
  13105. const UploadFormDataItems &items,
  13106. const std::string &boundary,
  13107. UploadProgress progress) {
  13108. return cli_->Post(path, headers, items, boundary, progress);
  13109. }
  13110. inline Result Client::Post(const std::string &path, const Headers &headers,
  13111. const UploadFormDataItems &items,
  13112. const FormDataProviderItems &provider_items,
  13113. UploadProgress progress) {
  13114. return cli_->Post(path, headers, items, provider_items, progress);
  13115. }
  13116. inline Result Client::Post(const std::string &path, const Headers &headers,
  13117. const std::string &body,
  13118. const std::string &content_type,
  13119. ContentReceiver content_receiver,
  13120. DownloadProgress progress) {
  13121. return cli_->Post(path, headers, body, content_type,
  13122. std::move(content_receiver), progress);
  13123. }
  13124. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  13125. inline Result Client::Put(const std::string &path, const Headers &headers) {
  13126. return cli_->Put(path, headers);
  13127. }
  13128. inline Result Client::Put(const std::string &path, const char *body,
  13129. size_t content_length,
  13130. const std::string &content_type,
  13131. UploadProgress progress) {
  13132. return cli_->Put(path, body, content_length, content_type, progress);
  13133. }
  13134. inline Result Client::Put(const std::string &path, const Headers &headers,
  13135. const char *body, size_t content_length,
  13136. const std::string &content_type,
  13137. UploadProgress progress) {
  13138. return cli_->Put(path, headers, body, content_length, content_type, progress);
  13139. }
  13140. inline Result Client::Put(const std::string &path, const std::string &body,
  13141. const std::string &content_type,
  13142. UploadProgress progress) {
  13143. return cli_->Put(path, body, content_type, progress);
  13144. }
  13145. inline Result Client::Put(const std::string &path, const Headers &headers,
  13146. const std::string &body,
  13147. const std::string &content_type,
  13148. UploadProgress progress) {
  13149. return cli_->Put(path, headers, body, content_type, progress);
  13150. }
  13151. inline Result Client::Put(const std::string &path, size_t content_length,
  13152. ContentProvider content_provider,
  13153. const std::string &content_type,
  13154. UploadProgress progress) {
  13155. return cli_->Put(path, content_length, std::move(content_provider),
  13156. content_type, progress);
  13157. }
  13158. inline Result Client::Put(const std::string &path, size_t content_length,
  13159. ContentProvider content_provider,
  13160. const std::string &content_type,
  13161. ContentReceiver content_receiver,
  13162. UploadProgress progress) {
  13163. return cli_->Put(path, content_length, std::move(content_provider),
  13164. content_type, std::move(content_receiver), progress);
  13165. }
  13166. inline Result Client::Put(const std::string &path,
  13167. ContentProviderWithoutLength content_provider,
  13168. const std::string &content_type,
  13169. UploadProgress progress) {
  13170. return cli_->Put(path, std::move(content_provider), content_type, progress);
  13171. }
  13172. inline Result Client::Put(const std::string &path,
  13173. ContentProviderWithoutLength content_provider,
  13174. const std::string &content_type,
  13175. ContentReceiver content_receiver,
  13176. UploadProgress progress) {
  13177. return cli_->Put(path, std::move(content_provider), content_type,
  13178. std::move(content_receiver), progress);
  13179. }
  13180. inline Result Client::Put(const std::string &path, const Headers &headers,
  13181. size_t content_length,
  13182. ContentProvider content_provider,
  13183. const std::string &content_type,
  13184. UploadProgress progress) {
  13185. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13186. content_type, progress);
  13187. }
  13188. inline Result Client::Put(const std::string &path, const Headers &headers,
  13189. size_t content_length,
  13190. ContentProvider content_provider,
  13191. const std::string &content_type,
  13192. ContentReceiver content_receiver,
  13193. UploadProgress progress) {
  13194. return cli_->Put(path, headers, content_length, std::move(content_provider),
  13195. content_type, std::move(content_receiver), progress);
  13196. }
  13197. inline Result Client::Put(const std::string &path, const Headers &headers,
  13198. ContentProviderWithoutLength content_provider,
  13199. const std::string &content_type,
  13200. UploadProgress progress) {
  13201. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13202. progress);
  13203. }
  13204. inline Result Client::Put(const std::string &path, const Headers &headers,
  13205. ContentProviderWithoutLength content_provider,
  13206. const std::string &content_type,
  13207. ContentReceiver content_receiver,
  13208. UploadProgress progress) {
  13209. return cli_->Put(path, headers, std::move(content_provider), content_type,
  13210. std::move(content_receiver), progress);
  13211. }
  13212. inline Result Client::Put(const std::string &path, const Params &params) {
  13213. return cli_->Put(path, params);
  13214. }
  13215. inline Result Client::Put(const std::string &path, const Headers &headers,
  13216. const Params &params) {
  13217. return cli_->Put(path, headers, params);
  13218. }
  13219. inline Result Client::Put(const std::string &path,
  13220. const UploadFormDataItems &items,
  13221. UploadProgress progress) {
  13222. return cli_->Put(path, items, progress);
  13223. }
  13224. inline Result Client::Put(const std::string &path, const Headers &headers,
  13225. const UploadFormDataItems &items,
  13226. UploadProgress progress) {
  13227. return cli_->Put(path, headers, items, progress);
  13228. }
  13229. inline Result Client::Put(const std::string &path, const Headers &headers,
  13230. const UploadFormDataItems &items,
  13231. const std::string &boundary,
  13232. UploadProgress progress) {
  13233. return cli_->Put(path, headers, items, boundary, progress);
  13234. }
  13235. inline Result Client::Put(const std::string &path, const Headers &headers,
  13236. const UploadFormDataItems &items,
  13237. const FormDataProviderItems &provider_items,
  13238. UploadProgress progress) {
  13239. return cli_->Put(path, headers, items, provider_items, progress);
  13240. }
  13241. inline Result Client::Put(const std::string &path, const Headers &headers,
  13242. const std::string &body,
  13243. const std::string &content_type,
  13244. ContentReceiver content_receiver,
  13245. DownloadProgress progress) {
  13246. return cli_->Put(path, headers, body, content_type, content_receiver,
  13247. progress);
  13248. }
  13249. inline Result Client::Patch(const std::string &path) {
  13250. return cli_->Patch(path);
  13251. }
  13252. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  13253. return cli_->Patch(path, headers);
  13254. }
  13255. inline Result Client::Patch(const std::string &path, const char *body,
  13256. size_t content_length,
  13257. const std::string &content_type,
  13258. UploadProgress progress) {
  13259. return cli_->Patch(path, body, content_length, content_type, progress);
  13260. }
  13261. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13262. const char *body, size_t content_length,
  13263. const std::string &content_type,
  13264. UploadProgress progress) {
  13265. return cli_->Patch(path, headers, body, content_length, content_type,
  13266. progress);
  13267. }
  13268. inline Result Client::Patch(const std::string &path, const std::string &body,
  13269. const std::string &content_type,
  13270. UploadProgress progress) {
  13271. return cli_->Patch(path, body, content_type, progress);
  13272. }
  13273. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13274. const std::string &body,
  13275. const std::string &content_type,
  13276. UploadProgress progress) {
  13277. return cli_->Patch(path, headers, body, content_type, progress);
  13278. }
  13279. inline Result Client::Patch(const std::string &path, size_t content_length,
  13280. ContentProvider content_provider,
  13281. const std::string &content_type,
  13282. UploadProgress progress) {
  13283. return cli_->Patch(path, content_length, std::move(content_provider),
  13284. content_type, progress);
  13285. }
  13286. inline Result Client::Patch(const std::string &path, size_t content_length,
  13287. ContentProvider content_provider,
  13288. const std::string &content_type,
  13289. ContentReceiver content_receiver,
  13290. UploadProgress progress) {
  13291. return cli_->Patch(path, content_length, std::move(content_provider),
  13292. content_type, std::move(content_receiver), progress);
  13293. }
  13294. inline Result Client::Patch(const std::string &path,
  13295. ContentProviderWithoutLength content_provider,
  13296. const std::string &content_type,
  13297. UploadProgress progress) {
  13298. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  13299. }
  13300. inline Result Client::Patch(const std::string &path,
  13301. ContentProviderWithoutLength content_provider,
  13302. const std::string &content_type,
  13303. ContentReceiver content_receiver,
  13304. UploadProgress progress) {
  13305. return cli_->Patch(path, std::move(content_provider), content_type,
  13306. std::move(content_receiver), progress);
  13307. }
  13308. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13309. size_t content_length,
  13310. ContentProvider content_provider,
  13311. const std::string &content_type,
  13312. UploadProgress progress) {
  13313. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13314. content_type, progress);
  13315. }
  13316. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13317. size_t content_length,
  13318. ContentProvider content_provider,
  13319. const std::string &content_type,
  13320. ContentReceiver content_receiver,
  13321. UploadProgress progress) {
  13322. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  13323. content_type, std::move(content_receiver), progress);
  13324. }
  13325. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13326. ContentProviderWithoutLength content_provider,
  13327. const std::string &content_type,
  13328. UploadProgress progress) {
  13329. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13330. progress);
  13331. }
  13332. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13333. ContentProviderWithoutLength content_provider,
  13334. const std::string &content_type,
  13335. ContentReceiver content_receiver,
  13336. UploadProgress progress) {
  13337. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  13338. std::move(content_receiver), progress);
  13339. }
  13340. inline Result Client::Patch(const std::string &path, const Params &params) {
  13341. return cli_->Patch(path, params);
  13342. }
  13343. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13344. const Params &params) {
  13345. return cli_->Patch(path, headers, params);
  13346. }
  13347. inline Result Client::Patch(const std::string &path,
  13348. const UploadFormDataItems &items,
  13349. UploadProgress progress) {
  13350. return cli_->Patch(path, items, progress);
  13351. }
  13352. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13353. const UploadFormDataItems &items,
  13354. UploadProgress progress) {
  13355. return cli_->Patch(path, headers, items, progress);
  13356. }
  13357. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13358. const UploadFormDataItems &items,
  13359. const std::string &boundary,
  13360. UploadProgress progress) {
  13361. return cli_->Patch(path, headers, items, boundary, progress);
  13362. }
  13363. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13364. const UploadFormDataItems &items,
  13365. const FormDataProviderItems &provider_items,
  13366. UploadProgress progress) {
  13367. return cli_->Patch(path, headers, items, provider_items, progress);
  13368. }
  13369. inline Result Client::Patch(const std::string &path, const Headers &headers,
  13370. const std::string &body,
  13371. const std::string &content_type,
  13372. ContentReceiver content_receiver,
  13373. DownloadProgress progress) {
  13374. return cli_->Patch(path, headers, body, content_type, content_receiver,
  13375. progress);
  13376. }
  13377. inline Result Client::Delete(const std::string &path,
  13378. DownloadProgress progress) {
  13379. return cli_->Delete(path, progress);
  13380. }
  13381. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13382. DownloadProgress progress) {
  13383. return cli_->Delete(path, headers, progress);
  13384. }
  13385. inline Result Client::Delete(const std::string &path, const char *body,
  13386. size_t content_length,
  13387. const std::string &content_type,
  13388. DownloadProgress progress) {
  13389. return cli_->Delete(path, body, content_length, content_type, progress);
  13390. }
  13391. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13392. const char *body, size_t content_length,
  13393. const std::string &content_type,
  13394. DownloadProgress progress) {
  13395. return cli_->Delete(path, headers, body, content_length, content_type,
  13396. progress);
  13397. }
  13398. inline Result Client::Delete(const std::string &path, const std::string &body,
  13399. const std::string &content_type,
  13400. DownloadProgress progress) {
  13401. return cli_->Delete(path, body, content_type, progress);
  13402. }
  13403. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13404. const std::string &body,
  13405. const std::string &content_type,
  13406. DownloadProgress progress) {
  13407. return cli_->Delete(path, headers, body, content_type, progress);
  13408. }
  13409. inline Result Client::Delete(const std::string &path, const Params &params,
  13410. DownloadProgress progress) {
  13411. return cli_->Delete(path, params, progress);
  13412. }
  13413. inline Result Client::Delete(const std::string &path, const Headers &headers,
  13414. const Params &params, DownloadProgress progress) {
  13415. return cli_->Delete(path, headers, params, progress);
  13416. }
  13417. inline Result Client::Options(const std::string &path) {
  13418. return cli_->Options(path);
  13419. }
  13420. inline Result Client::Options(const std::string &path, const Headers &headers) {
  13421. return cli_->Options(path, headers);
  13422. }
  13423. inline ClientImpl::StreamHandle
  13424. Client::open_stream(const std::string &method, const std::string &path,
  13425. const Params &params, const Headers &headers,
  13426. const std::string &body, const std::string &content_type) {
  13427. return cli_->open_stream(method, path, params, headers, body, content_type);
  13428. }
  13429. inline bool Client::send(Request &req, Response &res, Error &error) {
  13430. return cli_->send(req, res, error);
  13431. }
  13432. inline Result Client::send(const Request &req) { return cli_->send(req); }
  13433. inline void Client::stop() { cli_->stop(); }
  13434. inline std::string Client::host() const { return cli_->host(); }
  13435. inline int Client::port() const { return cli_->port(); }
  13436. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  13437. inline socket_t Client::socket() const { return cli_->socket(); }
  13438. inline void
  13439. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  13440. cli_->set_hostname_addr_map(std::move(addr_map));
  13441. }
  13442. inline void Client::set_default_headers(Headers headers) {
  13443. cli_->set_default_headers(std::move(headers));
  13444. }
  13445. inline void Client::set_header_writer(
  13446. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  13447. cli_->set_header_writer(writer);
  13448. }
  13449. inline void Client::set_address_family(int family) {
  13450. cli_->set_address_family(family);
  13451. }
  13452. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  13453. inline void Client::set_socket_options(SocketOptions socket_options) {
  13454. cli_->set_socket_options(std::move(socket_options));
  13455. }
  13456. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  13457. cli_->set_connection_timeout(sec, usec);
  13458. }
  13459. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  13460. cli_->set_read_timeout(sec, usec);
  13461. }
  13462. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  13463. cli_->set_write_timeout(sec, usec);
  13464. }
  13465. inline void Client::set_basic_auth(const std::string &username,
  13466. const std::string &password) {
  13467. cli_->set_basic_auth(username, password);
  13468. }
  13469. inline void Client::set_bearer_token_auth(const std::string &token) {
  13470. cli_->set_bearer_token_auth(token);
  13471. }
  13472. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  13473. inline void Client::set_follow_location(bool on) {
  13474. cli_->set_follow_location(on);
  13475. }
  13476. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  13477. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  13478. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  13479. inline void Client::set_payload_max_length(size_t length) {
  13480. cli_->set_payload_max_length(length);
  13481. }
  13482. inline void Client::set_interface(const std::string &intf) {
  13483. cli_->set_interface(intf);
  13484. }
  13485. inline void Client::set_proxy(const std::string &host, int port) {
  13486. cli_->set_proxy(host, port);
  13487. }
  13488. inline void Client::set_proxy_basic_auth(const std::string &username,
  13489. const std::string &password) {
  13490. cli_->set_proxy_basic_auth(username, password);
  13491. }
  13492. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  13493. cli_->set_proxy_bearer_token_auth(token);
  13494. }
  13495. inline void Client::set_no_proxy(const std::vector<std::string> &patterns) {
  13496. cli_->set_no_proxy(patterns);
  13497. }
  13498. inline void Client::set_logger(Logger logger) {
  13499. cli_->set_logger(std::move(logger));
  13500. }
  13501. inline void Client::set_error_logger(ErrorLogger error_logger) {
  13502. cli_->set_error_logger(std::move(error_logger));
  13503. }
  13504. /*
  13505. * Group 6: SSL Server and Client implementation
  13506. */
  13507. #ifdef CPPHTTPLIB_SSL_ENABLED
  13508. // SSL HTTP server implementation
  13509. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  13510. const char *client_ca_cert_file_path,
  13511. const char *client_ca_cert_dir_path,
  13512. const char *private_key_password) {
  13513. using namespace tls;
  13514. ctx_ = create_server_context();
  13515. if (!ctx_) { return; }
  13516. // Load server certificate and private key
  13517. if (!set_server_cert_file(ctx_, cert_path, private_key_path,
  13518. private_key_password)) {
  13519. last_ssl_error_ = static_cast<int>(get_error());
  13520. free_context(ctx_);
  13521. ctx_ = nullptr;
  13522. return;
  13523. }
  13524. // Load client CA certificates for client authentication
  13525. if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  13526. if (!set_client_ca_file(ctx_, client_ca_cert_file_path,
  13527. client_ca_cert_dir_path)) {
  13528. last_ssl_error_ = static_cast<int>(get_error());
  13529. free_context(ctx_);
  13530. ctx_ = nullptr;
  13531. return;
  13532. }
  13533. // Enable client certificate verification
  13534. set_verify_client(ctx_, true);
  13535. }
  13536. }
  13537. inline SSLServer::SSLServer(const PemMemory &pem) {
  13538. using namespace tls;
  13539. ctx_ = create_server_context();
  13540. if (ctx_) {
  13541. if (!set_server_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13542. pem.private_key_password)) {
  13543. last_ssl_error_ = static_cast<int>(get_error());
  13544. free_context(ctx_);
  13545. ctx_ = nullptr;
  13546. } else if (pem.client_ca_pem && pem.client_ca_pem_len > 0) {
  13547. if (!load_ca_pem(ctx_, pem.client_ca_pem, pem.client_ca_pem_len)) {
  13548. last_ssl_error_ = static_cast<int>(get_error());
  13549. free_context(ctx_);
  13550. ctx_ = nullptr;
  13551. } else {
  13552. set_verify_client(ctx_, true);
  13553. }
  13554. }
  13555. }
  13556. }
  13557. inline SSLServer::SSLServer(const tls::ContextSetupCallback &setup_callback) {
  13558. using namespace tls;
  13559. ctx_ = create_server_context();
  13560. if (ctx_) {
  13561. if (!setup_callback(ctx_)) {
  13562. free_context(ctx_);
  13563. ctx_ = nullptr;
  13564. }
  13565. }
  13566. }
  13567. inline SSLServer::~SSLServer() {
  13568. if (ctx_) { tls::free_context(ctx_); }
  13569. }
  13570. inline bool SSLServer::is_valid() const { return ctx_ != nullptr; }
  13571. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  13572. using namespace tls;
  13573. // Create TLS session with mutex protection
  13574. session_t session = nullptr;
  13575. {
  13576. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13577. session = create_session(static_cast<ctx_t>(ctx_), sock);
  13578. }
  13579. if (!session) {
  13580. last_ssl_error_ = static_cast<int>(get_error());
  13581. detail::shutdown_socket(sock);
  13582. detail::close_socket(sock);
  13583. return false;
  13584. }
  13585. // Use scope_exit to ensure cleanup on all paths (including exceptions)
  13586. bool handshake_done = false;
  13587. bool ret = false;
  13588. bool websocket_upgraded = false;
  13589. auto cleanup = detail::scope_exit([&] {
  13590. if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
  13591. free_session(session);
  13592. detail::shutdown_socket(sock);
  13593. detail::close_socket(sock);
  13594. });
  13595. // Perform TLS accept handshake with timeout
  13596. TlsError tls_err;
  13597. if (!accept_nonblocking(session, sock, read_timeout_sec_, read_timeout_usec_,
  13598. &tls_err)) {
  13599. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13600. // Map TlsError to legacy ssl_error for backward compatibility
  13601. if (tls_err.code == ErrorCode::WantRead) {
  13602. last_ssl_error_ = SSL_ERROR_WANT_READ;
  13603. } else if (tls_err.code == ErrorCode::WantWrite) {
  13604. last_ssl_error_ = SSL_ERROR_WANT_WRITE;
  13605. } else {
  13606. last_ssl_error_ = SSL_ERROR_SSL;
  13607. }
  13608. #else
  13609. last_ssl_error_ = static_cast<int>(get_error());
  13610. #endif
  13611. return false;
  13612. }
  13613. handshake_done = true;
  13614. std::string remote_addr;
  13615. int remote_port = 0;
  13616. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  13617. std::string local_addr;
  13618. int local_port = 0;
  13619. detail::get_local_ip_and_port(sock, local_addr, local_port);
  13620. ret = detail::process_server_socket_ssl(
  13621. svr_sock_, session, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  13622. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  13623. write_timeout_usec_,
  13624. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  13625. return process_request(
  13626. strm, remote_addr, remote_port, local_addr, local_port,
  13627. close_connection, connection_closed,
  13628. [&](Request &req) { req.ssl = session; }, &websocket_upgraded);
  13629. });
  13630. return ret;
  13631. }
  13632. inline bool SSLServer::update_certs_pem(const char *cert_pem,
  13633. const char *key_pem,
  13634. const char *client_ca_pem,
  13635. const char *password) {
  13636. if (!ctx_) { return false; }
  13637. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13638. if (!tls::update_server_cert(ctx_, cert_pem, key_pem, password)) {
  13639. return false;
  13640. }
  13641. if (client_ca_pem) {
  13642. return tls::update_server_client_ca(ctx_, client_ca_pem);
  13643. }
  13644. return true;
  13645. }
  13646. // SSL HTTP client implementation
  13647. inline SSLClient::~SSLClient() {
  13648. if (ctx_) { tls::free_context(ctx_); }
  13649. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  13650. // base function rather than the derived function once we get to the
  13651. // base class destructor, and won't free the SSL (causing a leak).
  13652. shutdown_ssl_impl(socket_, true);
  13653. }
  13654. inline bool SSLClient::is_valid() const { return ctx_ != nullptr; }
  13655. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  13656. shutdown_ssl_impl(socket, shutdown_gracefully);
  13657. }
  13658. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  13659. bool shutdown_gracefully) {
  13660. if (socket.sock == INVALID_SOCKET) {
  13661. assert(socket.ssl == nullptr);
  13662. return;
  13663. }
  13664. if (socket.ssl) {
  13665. tls::shutdown(socket.ssl, shutdown_gracefully);
  13666. {
  13667. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13668. tls::free_session(socket.ssl);
  13669. }
  13670. socket.ssl = nullptr;
  13671. }
  13672. assert(socket.ssl == nullptr);
  13673. }
  13674. inline bool SSLClient::process_socket(
  13675. const Socket &socket,
  13676. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13677. std::function<bool(Stream &strm)> callback) {
  13678. assert(socket.ssl);
  13679. return detail::process_client_socket_ssl(
  13680. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  13681. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  13682. std::move(callback));
  13683. }
  13684. inline bool SSLClient::is_ssl() const { return true; }
  13685. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  13686. if (!is_valid()) {
  13687. error = Error::SSLConnection;
  13688. return false;
  13689. }
  13690. return ClientImpl::create_and_connect_socket(socket, error);
  13691. }
  13692. inline bool SSLClient::setup_proxy_connection(
  13693. Socket &socket,
  13694. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13695. Response &res, bool &success, Error &error) {
  13696. if (!is_proxy_enabled_for_host(host_)) { return true; }
  13697. if (!connect_with_proxy(socket, start_time, res, success, error)) {
  13698. return false;
  13699. }
  13700. if (!initialize_ssl(socket, error)) {
  13701. success = false;
  13702. return false;
  13703. }
  13704. return true;
  13705. }
  13706. // Assumes that socket_mutex_ is locked and that there are no requests in
  13707. // flight
  13708. inline bool SSLClient::connect_with_proxy(
  13709. Socket &socket,
  13710. std::chrono::time_point<std::chrono::steady_clock> start_time,
  13711. Response &res, bool &success, Error &error) {
  13712. success = true;
  13713. Response proxy_res;
  13714. if (!detail::process_client_socket(
  13715. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13716. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13717. start_time, [&](Stream &strm) {
  13718. Request req2;
  13719. req2.method = "CONNECT";
  13720. req2.path =
  13721. detail::make_host_and_port_string_always_port(host_, port_);
  13722. if (max_timeout_msec_ > 0) {
  13723. req2.start_time_ = std::chrono::steady_clock::now();
  13724. }
  13725. return process_request(strm, req2, proxy_res, false, error);
  13726. })) {
  13727. // Thread-safe to close everything because we are assuming there are no
  13728. // requests in flight
  13729. shutdown_ssl(socket, true);
  13730. shutdown_socket(socket);
  13731. close_socket(socket);
  13732. success = false;
  13733. return false;
  13734. }
  13735. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  13736. if (!proxy_digest_auth_username_.empty() &&
  13737. !proxy_digest_auth_password_.empty()) {
  13738. std::map<std::string, std::string> auth;
  13739. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  13740. // Close the current socket and create a new one for the authenticated
  13741. // request
  13742. shutdown_ssl(socket, true);
  13743. shutdown_socket(socket);
  13744. close_socket(socket);
  13745. // Create a new socket for the authenticated CONNECT request
  13746. if (!ensure_socket_connection(socket, error)) {
  13747. success = false;
  13748. output_error_log(error, nullptr);
  13749. return false;
  13750. }
  13751. proxy_res = Response();
  13752. if (!detail::process_client_socket(
  13753. socket.sock, read_timeout_sec_, read_timeout_usec_,
  13754. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  13755. start_time, [&](Stream &strm) {
  13756. Request req3;
  13757. req3.method = "CONNECT";
  13758. req3.path = detail::make_host_and_port_string_always_port(
  13759. host_, port_);
  13760. req3.headers.insert(detail::make_digest_authentication_header(
  13761. req3, auth, 1, detail::random_string(10),
  13762. proxy_digest_auth_username_, proxy_digest_auth_password_,
  13763. true));
  13764. if (max_timeout_msec_ > 0) {
  13765. req3.start_time_ = std::chrono::steady_clock::now();
  13766. }
  13767. return process_request(strm, req3, proxy_res, false, error);
  13768. })) {
  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. success = false;
  13775. return false;
  13776. }
  13777. }
  13778. }
  13779. }
  13780. // If status code is not 200, proxy request is failed.
  13781. // Set error to ProxyConnection and return proxy response
  13782. // as the response of the request
  13783. if (proxy_res.status != StatusCode::OK_200) {
  13784. error = Error::ProxyConnection;
  13785. output_error_log(error, nullptr);
  13786. res = std::move(proxy_res);
  13787. // Thread-safe to close everything because we are assuming there are
  13788. // no requests in flight
  13789. shutdown_ssl(socket, true);
  13790. shutdown_socket(socket);
  13791. close_socket(socket);
  13792. return false;
  13793. }
  13794. return true;
  13795. }
  13796. inline bool SSLClient::ensure_socket_connection(Socket &socket, Error &error) {
  13797. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  13798. if (is_proxy_enabled_for_host(host_)) { return true; }
  13799. if (!initialize_ssl(socket, error)) {
  13800. shutdown_socket(socket);
  13801. close_socket(socket);
  13802. return false;
  13803. }
  13804. return true;
  13805. }
  13806. // SSL HTTP client implementation
  13807. inline SSLClient::SSLClient(const std::string &host)
  13808. : SSLClient(host, 443, std::string(), std::string()) {}
  13809. inline SSLClient::SSLClient(const std::string &host, int port)
  13810. : SSLClient(host, port, std::string(), std::string()) {}
  13811. inline void SSLClient::init_ctx() {
  13812. ctx_ = tls::create_client_context();
  13813. if (ctx_) { tls::set_min_version(ctx_, tls::Version::TLS1_2); }
  13814. }
  13815. inline void SSLClient::reset_ctx_on_error() {
  13816. last_backend_error_ = tls::get_error();
  13817. tls::free_context(ctx_);
  13818. ctx_ = nullptr;
  13819. }
  13820. inline SSLClient::SSLClient(const std::string &host, int port,
  13821. const std::string &client_cert_path,
  13822. const std::string &client_key_path,
  13823. const std::string &private_key_password)
  13824. : ClientImpl(host, port, client_cert_path, client_key_path) {
  13825. init_ctx();
  13826. if (!ctx_) { return; }
  13827. if (!client_cert_path.empty() && !client_key_path.empty()) {
  13828. const char *password =
  13829. private_key_password.empty() ? nullptr : private_key_password.c_str();
  13830. if (!tls::set_client_cert_file(ctx_, client_cert_path.c_str(),
  13831. client_key_path.c_str(), password)) {
  13832. reset_ctx_on_error();
  13833. }
  13834. }
  13835. }
  13836. inline SSLClient::SSLClient(const std::string &host, int port,
  13837. const PemMemory &pem)
  13838. : ClientImpl(host, port) {
  13839. init_ctx();
  13840. if (!ctx_) { return; }
  13841. if (pem.cert_pem && pem.key_pem) {
  13842. if (!tls::set_client_cert_pem(ctx_, pem.cert_pem, pem.key_pem,
  13843. pem.private_key_password)) {
  13844. reset_ctx_on_error();
  13845. }
  13846. }
  13847. }
  13848. inline void SSLClient::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  13849. if (ca_cert_store && ctx_) {
  13850. // set_ca_store takes ownership of ca_cert_store
  13851. tls::set_ca_store(ctx_, ca_cert_store);
  13852. ca_cert_store_set_ = true;
  13853. } else if (ca_cert_store) {
  13854. tls::free_ca_store(ca_cert_store);
  13855. }
  13856. }
  13857. inline void
  13858. SSLClient::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  13859. if (!ctx_) { return; }
  13860. tls::set_verify_callback(ctx_, verifier);
  13861. }
  13862. inline void SSLClient::set_session_verifier(
  13863. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  13864. session_verifier_ = std::move(verifier);
  13865. }
  13866. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13867. inline void SSLClient::enable_windows_certificate_verification(bool enabled) {
  13868. enable_windows_cert_verification_ = enabled;
  13869. }
  13870. #endif
  13871. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  13872. std::size_t size) {
  13873. if (ctx_ && ca_cert && size > 0) {
  13874. ca_cert_pem_.assign(ca_cert, size); // Store for redirect transfer
  13875. tls::load_ca_pem(ctx_, ca_cert, size);
  13876. }
  13877. }
  13878. inline bool SSLClient::load_certs() {
  13879. auto ret = true;
  13880. std::call_once(initialize_cert_, [&]() {
  13881. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13882. ret = detail::load_client_ca_config(
  13883. ctx_, ca_cert_file_path_, ca_cert_dir_path_,
  13884. !ca_cert_pem_.empty() || ca_cert_store_set_, system_ca_mode_,
  13885. last_backend_error_);
  13886. });
  13887. return ret;
  13888. }
  13889. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  13890. using namespace tls;
  13891. // Load CA certificates if server verification is enabled
  13892. if (server_certificate_verification_) {
  13893. if (!load_certs()) {
  13894. error = Error::SSLLoadingCerts;
  13895. output_error_log(error, nullptr);
  13896. return false;
  13897. }
  13898. }
  13899. bool is_ip = detail::is_ip_address(host_);
  13900. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) || defined(CPPHTTPLIB_WOLFSSL_SUPPORT)
  13901. // MbedTLS/wolfSSL need explicit verification mode (OpenSSL uses
  13902. // SSL_VERIFY_NONE by default and performs all verification post-handshake).
  13903. // Chain verification happens during the handshake even for IP hosts; the
  13904. // certificate identity is verified post-handshake via verify_hostname().
  13905. set_verify_client(ctx_, server_certificate_verification_);
  13906. #endif
  13907. // Create TLS session
  13908. session_t session = nullptr;
  13909. {
  13910. std::lock_guard<std::mutex> guard(ctx_mutex_);
  13911. session = create_session(ctx_, socket.sock);
  13912. }
  13913. if (!session) {
  13914. error = Error::SSLConnection;
  13915. last_backend_error_ = get_error();
  13916. return false;
  13917. }
  13918. // Use scope_exit to ensure session is freed on error paths
  13919. bool success = false;
  13920. auto session_guard = detail::scope_exit([&] {
  13921. if (!success) { free_session(session); }
  13922. });
  13923. // Set SNI extension (skip for IP addresses per RFC 6066).
  13924. // On MbedTLS, set_sni also enables hostname verification internally.
  13925. // On OpenSSL, set_sni only sets SNI; verification is done post-handshake.
  13926. if (!is_ip) {
  13927. if (!set_sni(session, host_.c_str())) {
  13928. error = Error::SSLConnection;
  13929. last_backend_error_ = get_error();
  13930. return false;
  13931. }
  13932. }
  13933. // Perform non-blocking TLS handshake with timeout
  13934. TlsError tls_err;
  13935. if (!connect_nonblocking(session, socket.sock, connection_timeout_sec_,
  13936. connection_timeout_usec_, &tls_err)) {
  13937. last_ssl_error_ = static_cast<int>(tls_err.code);
  13938. last_backend_error_ = tls_err.backend_code;
  13939. if (tls_err.code == ErrorCode::CertVerifyFailed) {
  13940. error = Error::SSLServerVerification;
  13941. } else if (tls_err.code == ErrorCode::HostnameMismatch) {
  13942. error = Error::SSLServerHostnameVerification;
  13943. } else {
  13944. error = Error::SSLConnection;
  13945. }
  13946. output_error_log(error, nullptr);
  13947. return false;
  13948. }
  13949. // Post-handshake session verifier callback
  13950. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  13951. if (session_verifier_) { verification_status = session_verifier_(session); }
  13952. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  13953. last_backend_error_ = get_error();
  13954. error = Error::SSLServerVerification;
  13955. output_error_log(error, nullptr);
  13956. return false;
  13957. }
  13958. // Default server certificate verification
  13959. if (verification_status == SSLVerifierResponse::NoDecisionMade &&
  13960. server_certificate_verification_) {
  13961. verify_result_ = tls::get_verify_result(session);
  13962. if (verify_result_ != 0) {
  13963. last_backend_error_ = static_cast<uint64_t>(verify_result_);
  13964. error = Error::SSLServerVerification;
  13965. output_error_log(error, nullptr);
  13966. return false;
  13967. }
  13968. auto server_cert = get_peer_cert(session);
  13969. if (!server_cert) {
  13970. last_backend_error_ = get_error();
  13971. error = Error::SSLServerVerification;
  13972. output_error_log(error, nullptr);
  13973. return false;
  13974. }
  13975. auto cert_guard = detail::scope_exit([&] { free_cert(server_cert); });
  13976. // Hostname verification (post-handshake for all cases).
  13977. // On OpenSSL, verification is always post-handshake (SSL_VERIFY_NONE).
  13978. // On MbedTLS, set_sni already enabled hostname verification during
  13979. // handshake for non-IP hosts, but this check is still needed for IP
  13980. // addresses where SNI is not set.
  13981. if (server_hostname_verification_) {
  13982. if (!verify_hostname(server_cert, host_.c_str())) {
  13983. last_backend_error_ = hostname_mismatch_code();
  13984. error = Error::SSLServerHostnameVerification;
  13985. output_error_log(error, nullptr);
  13986. return false;
  13987. }
  13988. }
  13989. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  13990. // Additional Windows Schannel verification.
  13991. // This provides real-time certificate validation with Windows Update
  13992. // integration, working with both OpenSSL and MbedTLS backends.
  13993. // Skip when a custom CA cert is specified, as the Windows certificate
  13994. // store would not know about user-provided CA certificates. Also skip
  13995. // when system CA trust is explicitly disabled.
  13996. if (enable_windows_cert_verification_ &&
  13997. system_ca_mode_ != SystemCAMode::Disabled &&
  13998. ca_cert_file_path_.empty() && ca_cert_dir_path_.empty() &&
  13999. ca_cert_pem_.empty() && !ca_cert_store_set_) {
  14000. std::vector<unsigned char> der;
  14001. if (get_cert_der(server_cert, der)) {
  14002. uint64_t wincrypt_error = 0;
  14003. if (!detail::verify_cert_with_windows_schannel(
  14004. der, host_, server_hostname_verification_, wincrypt_error)) {
  14005. last_backend_error_ = wincrypt_error;
  14006. error = Error::SSLServerVerification;
  14007. output_error_log(error, nullptr);
  14008. return false;
  14009. }
  14010. }
  14011. }
  14012. #endif
  14013. }
  14014. success = true;
  14015. socket.ssl = session;
  14016. return true;
  14017. }
  14018. inline void Client::set_digest_auth(const std::string &username,
  14019. const std::string &password) {
  14020. cli_->set_digest_auth(username, password);
  14021. }
  14022. inline void Client::set_proxy_digest_auth(const std::string &username,
  14023. const std::string &password) {
  14024. cli_->set_proxy_digest_auth(username, password);
  14025. }
  14026. inline void Client::enable_server_certificate_verification(bool enabled) {
  14027. cli_->enable_server_certificate_verification(enabled);
  14028. }
  14029. inline void Client::enable_server_hostname_verification(bool enabled) {
  14030. cli_->enable_server_hostname_verification(enabled);
  14031. }
  14032. inline void Client::enable_system_ca(bool enabled) {
  14033. cli_->enable_system_ca(enabled);
  14034. }
  14035. #ifdef CPPHTTPLIB_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE
  14036. inline void Client::enable_windows_certificate_verification(bool enabled) {
  14037. if (is_ssl_) {
  14038. static_cast<SSLClient &>(*cli_).enable_windows_certificate_verification(
  14039. enabled);
  14040. }
  14041. }
  14042. #endif
  14043. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  14044. const std::string &ca_cert_dir_path) {
  14045. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  14046. }
  14047. inline void Client::set_ca_cert_store(tls::ca_store_t ca_cert_store) {
  14048. if (is_ssl_) {
  14049. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  14050. } else if (ca_cert_store) {
  14051. tls::free_ca_store(ca_cert_store);
  14052. }
  14053. }
  14054. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  14055. if (is_ssl_) {
  14056. // Use the PEM-based path so the CA data is retained for redirect transfer
  14057. static_cast<SSLClient &>(*cli_).load_ca_cert_store(ca_cert, size);
  14058. }
  14059. }
  14060. inline void
  14061. Client::set_server_certificate_verifier(tls::VerifyCallback verifier) {
  14062. if (is_ssl_) {
  14063. static_cast<SSLClient &>(*cli_).set_server_certificate_verifier(
  14064. std::move(verifier));
  14065. }
  14066. }
  14067. inline void Client::set_session_verifier(
  14068. std::function<SSLVerifierResponse(tls::session_t)> verifier) {
  14069. if (is_ssl_) {
  14070. static_cast<SSLClient &>(*cli_).set_session_verifier(std::move(verifier));
  14071. }
  14072. }
  14073. inline tls::ctx_t Client::tls_context() const {
  14074. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).tls_context(); }
  14075. return nullptr;
  14076. }
  14077. #endif // CPPHTTPLIB_SSL_ENABLED
  14078. /*
  14079. * Group 7: TLS abstraction layer - Common API
  14080. */
  14081. #ifdef CPPHTTPLIB_SSL_ENABLED
  14082. namespace tls {
  14083. // Helper for PeerCert construction
  14084. inline PeerCert get_peer_cert_from_session(const_session_t session) {
  14085. return PeerCert(get_peer_cert(session));
  14086. }
  14087. namespace impl {
  14088. inline VerifyCallback &get_verify_callback() {
  14089. static thread_local VerifyCallback callback;
  14090. return callback;
  14091. }
  14092. inline VerifyCallback &get_mbedtls_verify_callback() {
  14093. static thread_local VerifyCallback callback;
  14094. return callback;
  14095. }
  14096. // Check if a string is an IPv4 address
  14097. inline bool is_ipv4_address(const std::string &str) {
  14098. int dots = 0;
  14099. for (char c : str) {
  14100. if (c == '.') {
  14101. dots++;
  14102. } else if (!detail::is_ascii_digit(c)) {
  14103. return false;
  14104. }
  14105. }
  14106. return dots == 3;
  14107. }
  14108. // Parse IPv4 address string to bytes
  14109. inline bool parse_ipv4(const std::string &str, unsigned char *out) {
  14110. const char *p = str.c_str();
  14111. for (int i = 0; i < 4; i++) {
  14112. if (i > 0) {
  14113. if (*p != '.') { return false; }
  14114. p++;
  14115. }
  14116. int val = 0;
  14117. int digits = 0;
  14118. while (detail::is_ascii_digit(*p)) {
  14119. val = val * 10 + (*p - '0');
  14120. if (val > 255) { return false; }
  14121. p++;
  14122. digits++;
  14123. }
  14124. if (digits == 0) { return false; }
  14125. // Reject leading zeros (e.g., "01.002.03.04") to prevent ambiguity
  14126. if (digits > 1 && *(p - digits) == '0') { return false; }
  14127. out[i] = static_cast<unsigned char>(val);
  14128. }
  14129. return *p == '\0';
  14130. }
  14131. // Parse an IP literal (IPv4 or IPv6) into raw network-order bytes.
  14132. // `out` must have room for at least 16 bytes. Returns the address length
  14133. // (4 for IPv4, 16 for IPv6) on success, or 0 if the string is not an IP
  14134. // literal. Used to match a host against iPAddress SANs the same way the
  14135. // OpenSSL backend does via X509_check_ip.
  14136. inline size_t parse_ip_address(const std::string &str, unsigned char *out) {
  14137. if (is_ipv4_address(str)) { return parse_ipv4(str, out) ? 4 : 0; }
  14138. struct in6_addr addr6 = {};
  14139. if (inet_pton(AF_INET6, str.c_str(), &addr6) == 1) {
  14140. memcpy(out, &addr6, 16);
  14141. return 16;
  14142. }
  14143. return 0;
  14144. }
  14145. #ifdef _WIN32
  14146. // Enumerate Windows system certificates and call callback with DER data
  14147. template <typename Callback>
  14148. inline bool enumerate_windows_system_certs(Callback cb) {
  14149. bool loaded = false;
  14150. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14151. for (auto store_name : store_names) {
  14152. HCERTSTORE hStore = CertOpenSystemStoreW(0, store_name);
  14153. if (hStore) {
  14154. PCCERT_CONTEXT pContext = nullptr;
  14155. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14156. nullptr) {
  14157. if (cb(pContext->pbCertEncoded, pContext->cbCertEncoded)) {
  14158. loaded = true;
  14159. }
  14160. }
  14161. CertCloseStore(hStore, 0);
  14162. }
  14163. }
  14164. return loaded;
  14165. }
  14166. #endif
  14167. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14168. // Enumerate macOS Keychain certificates and call callback with DER data
  14169. template <typename Callback>
  14170. inline bool enumerate_macos_keychain_certs(Callback cb) {
  14171. bool loaded = false;
  14172. const SecTrustSettingsDomain domains[] = {
  14173. kSecTrustSettingsDomainSystem,
  14174. kSecTrustSettingsDomainAdmin,
  14175. kSecTrustSettingsDomainUser,
  14176. };
  14177. for (auto domain : domains) {
  14178. CFArrayRef certs = nullptr;
  14179. OSStatus status = SecTrustSettingsCopyCertificates(domain, &certs);
  14180. if (status != errSecSuccess || !certs) {
  14181. if (certs) CFRelease(certs);
  14182. continue;
  14183. }
  14184. CFIndex count = CFArrayGetCount(certs);
  14185. for (CFIndex i = 0; i < count; i++) {
  14186. SecCertificateRef cert =
  14187. (SecCertificateRef)CFArrayGetValueAtIndex(certs, i);
  14188. CFDataRef data = SecCertificateCopyData(cert);
  14189. if (data) {
  14190. if (cb(CFDataGetBytePtr(data),
  14191. static_cast<size_t>(CFDataGetLength(data)))) {
  14192. loaded = true;
  14193. }
  14194. CFRelease(data);
  14195. }
  14196. }
  14197. CFRelease(certs);
  14198. }
  14199. return loaded;
  14200. }
  14201. #endif
  14202. #if !defined(_WIN32) && !(defined(__APPLE__) && \
  14203. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN))
  14204. // Common CA certificate file paths on Linux/Unix
  14205. inline const char **system_ca_paths() {
  14206. static const char *paths[] = {
  14207. "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu
  14208. "/etc/pki/tls/certs/ca-bundle.crt", // RHEL/CentOS
  14209. "/etc/ssl/ca-bundle.pem", // OpenSUSE
  14210. "/etc/pki/tls/cacert.pem", // OpenELEC
  14211. "/etc/ssl/cert.pem", // Alpine, FreeBSD
  14212. nullptr};
  14213. return paths;
  14214. }
  14215. // Common CA certificate directory paths on Linux/Unix
  14216. inline const char **system_ca_dirs() {
  14217. static const char *dirs[] = {"/etc/ssl/certs", // Debian/Ubuntu
  14218. "/etc/pki/tls/certs", // RHEL/CentOS
  14219. "/usr/share/ca-certificates", // Other
  14220. nullptr};
  14221. return dirs;
  14222. }
  14223. #endif
  14224. } // namespace impl
  14225. inline bool set_client_ca_file(ctx_t ctx, const char *ca_file,
  14226. const char *ca_dir) {
  14227. if (!ctx) { return false; }
  14228. bool success = true;
  14229. if (ca_file && *ca_file) {
  14230. if (!load_ca_file(ctx, ca_file)) { success = false; }
  14231. }
  14232. if (ca_dir && *ca_dir) {
  14233. if (!load_ca_dir(ctx, ca_dir)) { success = false; }
  14234. }
  14235. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14236. // Set CA list for client certificate request (CertificateRequest message)
  14237. if (ca_file && *ca_file) {
  14238. auto list = SSL_load_client_CA_file(ca_file);
  14239. if (list) { SSL_CTX_set_client_CA_list(static_cast<SSL_CTX *>(ctx), list); }
  14240. }
  14241. #endif
  14242. return success;
  14243. }
  14244. inline bool set_server_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14245. const char *password) {
  14246. return set_client_cert_pem(ctx, cert, key, password);
  14247. }
  14248. inline bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  14249. const char *key_path, const char *password) {
  14250. return set_client_cert_file(ctx, cert_path, key_path, password);
  14251. }
  14252. // PeerCert implementation
  14253. inline PeerCert::PeerCert() = default;
  14254. inline PeerCert::PeerCert(cert_t cert) : cert_(cert) {}
  14255. inline PeerCert::PeerCert(PeerCert &&other) noexcept : cert_(other.cert_) {
  14256. other.cert_ = nullptr;
  14257. }
  14258. inline PeerCert &PeerCert::operator=(PeerCert &&other) noexcept {
  14259. if (this != &other) {
  14260. if (cert_) { free_cert(cert_); }
  14261. cert_ = other.cert_;
  14262. other.cert_ = nullptr;
  14263. }
  14264. return *this;
  14265. }
  14266. inline PeerCert::~PeerCert() {
  14267. if (cert_) { free_cert(cert_); }
  14268. }
  14269. inline PeerCert::operator bool() const { return cert_ != nullptr; }
  14270. inline std::string PeerCert::subject_cn() const {
  14271. return cert_ ? get_cert_subject_cn(cert_) : std::string();
  14272. }
  14273. inline std::string PeerCert::issuer_name() const {
  14274. return cert_ ? get_cert_issuer_name(cert_) : std::string();
  14275. }
  14276. inline bool PeerCert::check_hostname(const char *hostname) const {
  14277. return cert_ ? verify_hostname(cert_, hostname) : false;
  14278. }
  14279. inline std::vector<SanEntry> PeerCert::sans() const {
  14280. std::vector<SanEntry> result;
  14281. if (cert_) { get_cert_sans(cert_, result); }
  14282. return result;
  14283. }
  14284. inline bool PeerCert::validity(time_t &not_before, time_t &not_after) const {
  14285. return cert_ ? get_cert_validity(cert_, not_before, not_after) : false;
  14286. }
  14287. inline std::string PeerCert::serial() const {
  14288. return cert_ ? get_cert_serial(cert_) : std::string();
  14289. }
  14290. // VerifyContext method implementations
  14291. inline std::string VerifyContext::subject_cn() const {
  14292. return cert ? get_cert_subject_cn(cert) : std::string();
  14293. }
  14294. inline std::string VerifyContext::issuer_name() const {
  14295. return cert ? get_cert_issuer_name(cert) : std::string();
  14296. }
  14297. inline bool VerifyContext::check_hostname(const char *hostname) const {
  14298. return cert ? verify_hostname(cert, hostname) : false;
  14299. }
  14300. inline std::vector<SanEntry> VerifyContext::sans() const {
  14301. std::vector<SanEntry> result;
  14302. if (cert) { get_cert_sans(cert, result); }
  14303. return result;
  14304. }
  14305. inline bool VerifyContext::validity(time_t &not_before,
  14306. time_t &not_after) const {
  14307. return cert ? get_cert_validity(cert, not_before, not_after) : false;
  14308. }
  14309. inline std::string VerifyContext::serial() const {
  14310. return cert ? get_cert_serial(cert) : std::string();
  14311. }
  14312. // TlsError static method implementation
  14313. inline std::string TlsError::verify_error_to_string(long error_code) {
  14314. return verify_error_string(error_code);
  14315. }
  14316. } // namespace tls
  14317. // Request::peer_cert() implementation
  14318. inline tls::PeerCert Request::peer_cert() const {
  14319. return tls::get_peer_cert_from_session(ssl);
  14320. }
  14321. // Request::sni() implementation
  14322. inline std::string Request::sni() const {
  14323. if (!ssl) { return std::string(); }
  14324. const char *s = tls::get_sni(ssl);
  14325. return s ? std::string(s) : std::string();
  14326. }
  14327. #endif // CPPHTTPLIB_SSL_ENABLED
  14328. /*
  14329. * Group 8: TLS abstraction layer - OpenSSL backend
  14330. */
  14331. /*
  14332. * OpenSSL Backend Implementation
  14333. */
  14334. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14335. namespace tls {
  14336. namespace impl {
  14337. // Helper to map OpenSSL SSL_get_error to ErrorCode
  14338. inline ErrorCode map_ssl_error(int ssl_error, int &out_errno) {
  14339. switch (ssl_error) {
  14340. case SSL_ERROR_NONE: return ErrorCode::Success;
  14341. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  14342. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  14343. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  14344. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  14345. case SSL_ERROR_SSL:
  14346. default: return ErrorCode::Fatal;
  14347. }
  14348. }
  14349. // Helper: Create client CA list from PEM string
  14350. // Returns a new STACK_OF(X509_NAME)* or nullptr on failure
  14351. // Caller takes ownership of returned list
  14352. inline STACK_OF(X509_NAME) *
  14353. create_client_ca_list_from_pem(const char *ca_pem) {
  14354. if (!ca_pem) { return nullptr; }
  14355. auto ca_list = sk_X509_NAME_new_null();
  14356. if (!ca_list) { return nullptr; }
  14357. BIO *bio = BIO_new_mem_buf(ca_pem, -1);
  14358. if (!bio) {
  14359. sk_X509_NAME_pop_free(ca_list, X509_NAME_free);
  14360. return nullptr;
  14361. }
  14362. X509 *cert = nullptr;
  14363. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14364. nullptr) {
  14365. const X509_NAME *name = X509_get_subject_name(cert);
  14366. if (name) {
  14367. sk_X509_NAME_push(ca_list, X509_NAME_dup(const_cast<X509_NAME *>(name)));
  14368. }
  14369. X509_free(cert);
  14370. }
  14371. BIO_free(bio);
  14372. return ca_list;
  14373. }
  14374. // OpenSSL verify callback wrapper
  14375. inline int openssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx) {
  14376. auto &callback = get_verify_callback();
  14377. if (!callback) { return preverify_ok; }
  14378. // Get SSL object from X509_STORE_CTX
  14379. auto ssl = static_cast<SSL *>(
  14380. X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
  14381. if (!ssl) { return preverify_ok; }
  14382. // Get current certificate and depth
  14383. auto cert = X509_STORE_CTX_get_current_cert(ctx);
  14384. int depth = X509_STORE_CTX_get_error_depth(ctx);
  14385. int error = X509_STORE_CTX_get_error(ctx);
  14386. // Build context
  14387. VerifyContext verify_ctx;
  14388. verify_ctx.session = static_cast<session_t>(ssl);
  14389. verify_ctx.cert = static_cast<cert_t>(cert);
  14390. verify_ctx.depth = depth;
  14391. verify_ctx.preverify_ok = (preverify_ok != 0);
  14392. verify_ctx.error_code = error;
  14393. verify_ctx.error_string =
  14394. (error != X509_V_OK) ? X509_verify_cert_error_string(error) : nullptr;
  14395. return callback(verify_ctx) ? 1 : 0;
  14396. }
  14397. // X509_STORE_get0_objects is deprecated since OpenSSL 4.0 because it is not
  14398. // thread-safe; X509_STORE_get1_objects (OpenSSL 3.3+) returns a snapshot
  14399. // that must be released with release_store_objects
  14400. #if !defined(OPENSSL_IS_BORINGSSL) && !defined(LIBRESSL_VERSION_NUMBER) && \
  14401. OPENSSL_VERSION_NUMBER >= 0x30300000L
  14402. #define CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14403. #endif
  14404. inline STACK_OF(X509_OBJECT) * get_store_objects(X509_STORE *store) {
  14405. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14406. return X509_STORE_get1_objects(store);
  14407. #else
  14408. return X509_STORE_get0_objects(store);
  14409. #endif
  14410. }
  14411. inline void release_store_objects(STACK_OF(X509_OBJECT) * objs) {
  14412. #ifdef CPPHTTPLIB_HAS_X509_STORE_GET1_OBJECTS
  14413. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  14414. #else
  14415. (void)objs; // get0 variant returns an internal pointer; nothing to free
  14416. #endif
  14417. }
  14418. } // namespace impl
  14419. inline ctx_t create_client_context() {
  14420. SSL_CTX *ctx = SSL_CTX_new(TLS_client_method());
  14421. if (ctx) {
  14422. // Disable auto-retry to properly handle non-blocking I/O
  14423. SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
  14424. // Set minimum TLS version
  14425. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14426. }
  14427. return static_cast<ctx_t>(ctx);
  14428. }
  14429. inline void free_context(ctx_t ctx) {
  14430. if (ctx) { SSL_CTX_free(static_cast<SSL_CTX *>(ctx)); }
  14431. }
  14432. inline bool set_min_version(ctx_t ctx, Version version) {
  14433. if (!ctx) return false;
  14434. return SSL_CTX_set_min_proto_version(static_cast<SSL_CTX *>(ctx),
  14435. static_cast<int>(version)) == 1;
  14436. }
  14437. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  14438. if (!ctx || !pem || len == 0) return false;
  14439. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14440. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14441. if (!store) return false;
  14442. auto bio = BIO_new_mem_buf(pem, static_cast<int>(len));
  14443. if (!bio) return false;
  14444. bool ok = true;
  14445. X509 *cert = nullptr;
  14446. while ((cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr)) !=
  14447. nullptr) {
  14448. if (X509_STORE_add_cert(store, cert) != 1) {
  14449. // Ignore duplicate errors
  14450. auto err = ERR_peek_last_error();
  14451. if (ERR_GET_REASON(err) != X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  14452. ok = false;
  14453. }
  14454. }
  14455. X509_free(cert);
  14456. if (!ok) break;
  14457. }
  14458. BIO_free(bio);
  14459. // Clear any "no more certificates" errors
  14460. ERR_clear_error();
  14461. return ok;
  14462. }
  14463. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  14464. if (!ctx || !file_path) return false;
  14465. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), file_path,
  14466. nullptr) == 1;
  14467. }
  14468. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  14469. if (!ctx || !dir_path) return false;
  14470. return SSL_CTX_load_verify_locations(static_cast<SSL_CTX *>(ctx), nullptr,
  14471. dir_path) == 1;
  14472. }
  14473. inline bool load_system_certs(ctx_t ctx) {
  14474. if (!ctx) return false;
  14475. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14476. #ifdef _WIN32
  14477. // Windows: Load from system certificate store (ROOT and CA)
  14478. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14479. if (!store) return false;
  14480. bool loaded_any = false;
  14481. static const wchar_t *store_names[] = {L"ROOT", L"CA"};
  14482. for (auto store_name : store_names) {
  14483. auto hStore = CertOpenSystemStoreW(NULL, store_name);
  14484. if (!hStore) continue;
  14485. PCCERT_CONTEXT pContext = nullptr;
  14486. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  14487. nullptr) {
  14488. const unsigned char *data = pContext->pbCertEncoded;
  14489. auto x509 = d2i_X509(nullptr, &data, pContext->cbCertEncoded);
  14490. if (x509) {
  14491. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14492. X509_free(x509);
  14493. }
  14494. }
  14495. CertCloseStore(hStore, 0);
  14496. }
  14497. return loaded_any;
  14498. #elif defined(__APPLE__)
  14499. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  14500. // macOS: Load from Keychain
  14501. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  14502. if (!store) return false;
  14503. bool loaded_any = false;
  14504. const SecTrustSettingsDomain domains[] = {
  14505. kSecTrustSettingsDomainSystem,
  14506. kSecTrustSettingsDomainAdmin,
  14507. kSecTrustSettingsDomainUser,
  14508. };
  14509. for (auto domain : domains) {
  14510. CFArrayRef certs = nullptr;
  14511. if (SecTrustSettingsCopyCertificates(domain, &certs) != errSecSuccess ||
  14512. !certs) {
  14513. if (certs) CFRelease(certs);
  14514. continue;
  14515. }
  14516. auto count = CFArrayGetCount(certs);
  14517. for (CFIndex i = 0; i < count; i++) {
  14518. auto cert = reinterpret_cast<SecCertificateRef>(
  14519. const_cast<void *>(CFArrayGetValueAtIndex(certs, i)));
  14520. CFDataRef der = SecCertificateCopyData(cert);
  14521. if (der) {
  14522. const unsigned char *data = CFDataGetBytePtr(der);
  14523. auto x509 = d2i_X509(nullptr, &data, CFDataGetLength(der));
  14524. if (x509) {
  14525. if (X509_STORE_add_cert(store, x509) == 1) { loaded_any = true; }
  14526. X509_free(x509);
  14527. }
  14528. CFRelease(der);
  14529. }
  14530. }
  14531. CFRelease(certs);
  14532. }
  14533. return loaded_any || SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14534. #else
  14535. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14536. #endif
  14537. #else
  14538. // Other Unix: use default verify paths
  14539. return SSL_CTX_set_default_verify_paths(ssl_ctx) == 1;
  14540. #endif
  14541. }
  14542. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  14543. const char *password) {
  14544. if (!ctx || !cert || !key) return false;
  14545. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14546. // Load certificate
  14547. auto cert_bio = BIO_new_mem_buf(cert, -1);
  14548. if (!cert_bio) return false;
  14549. auto x509 = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  14550. BIO_free(cert_bio);
  14551. if (!x509) return false;
  14552. auto cert_ok = SSL_CTX_use_certificate(ssl_ctx, x509) == 1;
  14553. X509_free(x509);
  14554. if (!cert_ok) return false;
  14555. // Load private key
  14556. auto key_bio = BIO_new_mem_buf(key, -1);
  14557. if (!key_bio) return false;
  14558. auto pkey = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  14559. password ? const_cast<char *>(password)
  14560. : nullptr);
  14561. BIO_free(key_bio);
  14562. if (!pkey) return false;
  14563. auto key_ok = SSL_CTX_use_PrivateKey(ssl_ctx, pkey) == 1;
  14564. EVP_PKEY_free(pkey);
  14565. return key_ok && SSL_CTX_check_private_key(ssl_ctx) == 1;
  14566. }
  14567. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  14568. const char *key_path, const char *password) {
  14569. if (!ctx || !cert_path || !key_path) return false;
  14570. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14571. if (password && password[0] != '\0') {
  14572. SSL_CTX_set_default_passwd_cb_userdata(
  14573. ssl_ctx, reinterpret_cast<void *>(const_cast<char *>(password)));
  14574. }
  14575. return SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_path) == 1 &&
  14576. SSL_CTX_use_PrivateKey_file(ssl_ctx, key_path, SSL_FILETYPE_PEM) == 1;
  14577. }
  14578. inline ctx_t create_server_context() {
  14579. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  14580. if (ctx) {
  14581. SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION |
  14582. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  14583. SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
  14584. }
  14585. return static_cast<ctx_t>(ctx);
  14586. }
  14587. inline void set_verify_client(ctx_t ctx, bool require) {
  14588. if (!ctx) return;
  14589. SSL_CTX_set_verify(static_cast<SSL_CTX *>(ctx),
  14590. require
  14591. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  14592. : SSL_VERIFY_NONE,
  14593. nullptr);
  14594. }
  14595. inline session_t create_session(ctx_t ctx, socket_t sock) {
  14596. if (!ctx || sock == INVALID_SOCKET) return nullptr;
  14597. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  14598. SSL *ssl = SSL_new(ssl_ctx);
  14599. if (!ssl) return nullptr;
  14600. // Disable auto-retry for proper non-blocking I/O handling
  14601. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  14602. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  14603. if (!bio) {
  14604. SSL_free(ssl);
  14605. return nullptr;
  14606. }
  14607. SSL_set_bio(ssl, bio, bio);
  14608. return static_cast<session_t>(ssl);
  14609. }
  14610. inline void free_session(session_t session) {
  14611. if (session) { SSL_free(static_cast<SSL *>(session)); }
  14612. }
  14613. inline bool set_sni(session_t session, const char *hostname) {
  14614. if (!session || !hostname) return false;
  14615. auto ssl = static_cast<SSL *>(session);
  14616. // Set SNI (Server Name Indication) only - does not enable verification
  14617. #if defined(OPENSSL_IS_BORINGSSL)
  14618. return SSL_set_tlsext_host_name(ssl, hostname) == 1;
  14619. #else
  14620. // Direct call instead of macro to suppress -Wold-style-cast warning
  14621. return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  14622. static_cast<void *>(const_cast<char *>(hostname))) == 1;
  14623. #endif
  14624. }
  14625. inline bool set_hostname(session_t session, const char *hostname) {
  14626. if (!session || !hostname) return false;
  14627. auto ssl = static_cast<SSL *>(session);
  14628. // Enable hostname verification
  14629. auto param = SSL_get0_param(ssl);
  14630. if (!param) return false;
  14631. if (detail::is_ip_address(hostname)) {
  14632. // RFC 6066: SNI must not be set for IP addresses; verify against the
  14633. // certificate's IP SANs instead of its DNS names
  14634. if (X509_VERIFY_PARAM_set1_ip_asc(param, hostname) != 1) { return false; }
  14635. } else {
  14636. // Set SNI (Server Name Indication)
  14637. if (!set_sni(session, hostname)) { return false; }
  14638. X509_VERIFY_PARAM_set_hostflags(param,
  14639. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  14640. if (X509_VERIFY_PARAM_set1_host(param, hostname, 0) != 1) { return false; }
  14641. }
  14642. SSL_set_verify(ssl, SSL_VERIFY_PEER, nullptr);
  14643. return true;
  14644. }
  14645. inline TlsError connect(session_t session) {
  14646. if (!session) { return TlsError(); }
  14647. auto ssl = static_cast<SSL *>(session);
  14648. auto ret = SSL_connect(ssl);
  14649. TlsError err;
  14650. if (ret == 1) {
  14651. err.code = ErrorCode::Success;
  14652. } else {
  14653. auto ssl_err = SSL_get_error(ssl, ret);
  14654. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14655. err.backend_code = ERR_get_error();
  14656. }
  14657. return err;
  14658. }
  14659. inline TlsError accept(session_t session) {
  14660. if (!session) { return TlsError(); }
  14661. auto ssl = static_cast<SSL *>(session);
  14662. auto ret = SSL_accept(ssl);
  14663. TlsError err;
  14664. if (ret == 1) {
  14665. err.code = ErrorCode::Success;
  14666. } else {
  14667. auto ssl_err = SSL_get_error(ssl, ret);
  14668. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14669. err.backend_code = ERR_get_error();
  14670. }
  14671. return err;
  14672. }
  14673. inline bool connect_nonblocking(session_t session, socket_t sock,
  14674. time_t timeout_sec, time_t timeout_usec,
  14675. TlsError *err) {
  14676. if (!session) {
  14677. if (err) { err->code = ErrorCode::Fatal; }
  14678. return false;
  14679. }
  14680. auto ssl = static_cast<SSL *>(session);
  14681. auto bio = SSL_get_rbio(ssl);
  14682. // Set non-blocking mode for handshake
  14683. detail::set_nonblocking(sock, true);
  14684. if (bio) { BIO_set_nbio(bio, 1); }
  14685. auto cleanup = detail::scope_exit([&]() {
  14686. // Restore blocking mode after handshake
  14687. if (bio) { BIO_set_nbio(bio, 0); }
  14688. detail::set_nonblocking(sock, false);
  14689. });
  14690. auto res = 0;
  14691. while ((res = SSL_connect(ssl)) != 1) {
  14692. auto ssl_err = SSL_get_error(ssl, res);
  14693. switch (ssl_err) {
  14694. case SSL_ERROR_WANT_READ:
  14695. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14696. continue;
  14697. }
  14698. break;
  14699. case SSL_ERROR_WANT_WRITE:
  14700. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14701. continue;
  14702. }
  14703. break;
  14704. default: break;
  14705. }
  14706. if (err) {
  14707. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14708. err->backend_code = ERR_get_error();
  14709. }
  14710. return false;
  14711. }
  14712. if (err) { err->code = ErrorCode::Success; }
  14713. return true;
  14714. }
  14715. inline bool accept_nonblocking(session_t session, socket_t sock,
  14716. time_t timeout_sec, time_t timeout_usec,
  14717. TlsError *err) {
  14718. if (!session) {
  14719. if (err) { err->code = ErrorCode::Fatal; }
  14720. return false;
  14721. }
  14722. auto ssl = static_cast<SSL *>(session);
  14723. auto bio = SSL_get_rbio(ssl);
  14724. // Set non-blocking mode for handshake
  14725. detail::set_nonblocking(sock, true);
  14726. if (bio) { BIO_set_nbio(bio, 1); }
  14727. auto cleanup = detail::scope_exit([&]() {
  14728. // Restore blocking mode after handshake
  14729. if (bio) { BIO_set_nbio(bio, 0); }
  14730. detail::set_nonblocking(sock, false);
  14731. });
  14732. auto res = 0;
  14733. while ((res = SSL_accept(ssl)) != 1) {
  14734. auto ssl_err = SSL_get_error(ssl, res);
  14735. switch (ssl_err) {
  14736. case SSL_ERROR_WANT_READ:
  14737. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  14738. continue;
  14739. }
  14740. break;
  14741. case SSL_ERROR_WANT_WRITE:
  14742. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  14743. continue;
  14744. }
  14745. break;
  14746. default: break;
  14747. }
  14748. if (err) {
  14749. err->code = impl::map_ssl_error(ssl_err, err->sys_errno);
  14750. err->backend_code = ERR_get_error();
  14751. }
  14752. return false;
  14753. }
  14754. if (err) { err->code = ErrorCode::Success; }
  14755. return true;
  14756. }
  14757. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  14758. if (!session || !buf) {
  14759. err.code = ErrorCode::Fatal;
  14760. return -1;
  14761. }
  14762. auto ssl = static_cast<SSL *>(session);
  14763. constexpr auto max_len =
  14764. static_cast<size_t>((std::numeric_limits<int>::max)());
  14765. if (len > max_len) { len = max_len; }
  14766. auto ret = SSL_read(ssl, buf, static_cast<int>(len));
  14767. if (ret > 0) {
  14768. err.code = ErrorCode::Success;
  14769. return ret;
  14770. }
  14771. auto ssl_err = SSL_get_error(ssl, ret);
  14772. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14773. if (err.code == ErrorCode::PeerClosed) {
  14774. return 0;
  14775. } // Gracefully handle the peer closed state.
  14776. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14777. return -1;
  14778. }
  14779. inline ssize_t write(session_t session, const void *buf, size_t len,
  14780. TlsError &err) {
  14781. if (!session || !buf) {
  14782. err.code = ErrorCode::Fatal;
  14783. return -1;
  14784. }
  14785. auto ssl = static_cast<SSL *>(session);
  14786. auto ret = SSL_write(ssl, buf, static_cast<int>(len));
  14787. if (ret > 0) {
  14788. err.code = ErrorCode::Success;
  14789. return ret;
  14790. }
  14791. auto ssl_err = SSL_get_error(ssl, ret);
  14792. err.code = impl::map_ssl_error(ssl_err, err.sys_errno);
  14793. if (err.code == ErrorCode::Fatal) { err.backend_code = ERR_get_error(); }
  14794. return -1;
  14795. }
  14796. inline int pending(const_session_t session) {
  14797. if (!session) return 0;
  14798. return SSL_pending(static_cast<SSL *>(const_cast<void *>(session)));
  14799. }
  14800. inline void shutdown(session_t session, bool graceful) {
  14801. if (!session) return;
  14802. auto ssl = static_cast<SSL *>(session);
  14803. if (graceful) {
  14804. // First call sends close_notify
  14805. if (SSL_shutdown(ssl) == 0) {
  14806. // Second call waits for peer's close_notify
  14807. SSL_shutdown(ssl);
  14808. }
  14809. }
  14810. }
  14811. inline bool is_peer_closed(session_t session, socket_t sock) {
  14812. if (!session) return true;
  14813. // Temporarily set socket to non-blocking to avoid blocking on SSL_peek
  14814. detail::set_nonblocking(sock, true);
  14815. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  14816. auto ssl = static_cast<SSL *>(session);
  14817. char buf;
  14818. auto ret = SSL_peek(ssl, &buf, 1);
  14819. if (ret > 0) return false;
  14820. auto err = SSL_get_error(ssl, ret);
  14821. return err == SSL_ERROR_ZERO_RETURN;
  14822. }
  14823. inline cert_t get_peer_cert(const_session_t session) {
  14824. if (!session) return nullptr;
  14825. return static_cast<cert_t>(SSL_get1_peer_certificate(
  14826. static_cast<SSL *>(const_cast<void *>(session))));
  14827. }
  14828. inline void free_cert(cert_t cert) {
  14829. if (cert) { X509_free(static_cast<X509 *>(cert)); }
  14830. }
  14831. inline bool verify_hostname(cert_t cert, const char *hostname) {
  14832. if (!cert || !hostname) return false;
  14833. auto x509 = static_cast<X509 *>(cert);
  14834. // Use X509_check_ip_asc for IP addresses, X509_check_host for DNS names
  14835. if (detail::is_ip_address(hostname)) {
  14836. return X509_check_ip_asc(x509, hostname, 0) == 1;
  14837. }
  14838. return X509_check_host(x509, hostname, strlen(hostname), 0, nullptr) == 1;
  14839. }
  14840. inline uint64_t hostname_mismatch_code() {
  14841. return static_cast<uint64_t>(X509_V_ERR_HOSTNAME_MISMATCH);
  14842. }
  14843. inline long get_verify_result(const_session_t session) {
  14844. if (!session) return X509_V_ERR_UNSPECIFIED;
  14845. return SSL_get_verify_result(static_cast<SSL *>(const_cast<void *>(session)));
  14846. }
  14847. inline std::string get_cert_subject_cn(cert_t cert) {
  14848. if (!cert) return "";
  14849. auto x509 = static_cast<X509 *>(cert);
  14850. auto subject_name = X509_get_subject_name(x509);
  14851. if (!subject_name) return "";
  14852. // X509_NAME_get_text_by_NID is deprecated since OpenSSL 4.0
  14853. auto idx = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1);
  14854. if (idx < 0) return "";
  14855. auto entry = X509_NAME_get_entry(subject_name, idx);
  14856. if (!entry) return "";
  14857. auto data = X509_NAME_ENTRY_get_data(entry);
  14858. if (!data) return "";
  14859. return std::string(
  14860. reinterpret_cast<const char *>(ASN1_STRING_get0_data(data)),
  14861. static_cast<size_t>(ASN1_STRING_length(data)));
  14862. }
  14863. inline std::string get_cert_issuer_name(cert_t cert) {
  14864. if (!cert) return "";
  14865. auto x509 = static_cast<X509 *>(cert);
  14866. auto issuer_name = X509_get_issuer_name(x509);
  14867. if (!issuer_name) return "";
  14868. char buf[256];
  14869. X509_NAME_oneline(issuer_name, buf, sizeof(buf));
  14870. return std::string(buf);
  14871. }
  14872. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  14873. sans.clear();
  14874. if (!cert) return false;
  14875. auto x509 = static_cast<X509 *>(cert);
  14876. auto names = static_cast<GENERAL_NAMES *>(
  14877. X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  14878. if (!names) return true; // No SANs is valid
  14879. auto count = sk_GENERAL_NAME_num(names);
  14880. for (decltype(count) i = 0; i < count; i++) {
  14881. auto gen = sk_GENERAL_NAME_value(names, i);
  14882. if (!gen) continue;
  14883. SanEntry entry;
  14884. switch (gen->type) {
  14885. case GEN_DNS:
  14886. entry.type = SanType::DNS;
  14887. if (gen->d.dNSName) {
  14888. entry.value = std::string(
  14889. reinterpret_cast<const char *>(
  14890. ASN1_STRING_get0_data(gen->d.dNSName)),
  14891. static_cast<size_t>(ASN1_STRING_length(gen->d.dNSName)));
  14892. }
  14893. break;
  14894. case GEN_IPADD:
  14895. entry.type = SanType::IP;
  14896. if (gen->d.iPAddress) {
  14897. auto data = ASN1_STRING_get0_data(gen->d.iPAddress);
  14898. auto len = ASN1_STRING_length(gen->d.iPAddress);
  14899. if (len == 4) {
  14900. // IPv4
  14901. char buf[INET_ADDRSTRLEN];
  14902. inet_ntop(AF_INET, data, buf, sizeof(buf));
  14903. entry.value = buf;
  14904. } else if (len == 16) {
  14905. // IPv6
  14906. char buf[INET6_ADDRSTRLEN];
  14907. inet_ntop(AF_INET6, data, buf, sizeof(buf));
  14908. entry.value = buf;
  14909. }
  14910. }
  14911. break;
  14912. case GEN_EMAIL:
  14913. entry.type = SanType::EMAIL;
  14914. if (gen->d.rfc822Name) {
  14915. entry.value = std::string(
  14916. reinterpret_cast<const char *>(
  14917. ASN1_STRING_get0_data(gen->d.rfc822Name)),
  14918. static_cast<size_t>(ASN1_STRING_length(gen->d.rfc822Name)));
  14919. }
  14920. break;
  14921. case GEN_URI:
  14922. entry.type = SanType::URI;
  14923. if (gen->d.uniformResourceIdentifier) {
  14924. entry.value = std::string(
  14925. reinterpret_cast<const char *>(
  14926. ASN1_STRING_get0_data(gen->d.uniformResourceIdentifier)),
  14927. static_cast<size_t>(
  14928. ASN1_STRING_length(gen->d.uniformResourceIdentifier)));
  14929. }
  14930. break;
  14931. default: entry.type = SanType::OTHER; break;
  14932. }
  14933. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  14934. }
  14935. GENERAL_NAMES_free(names);
  14936. return true;
  14937. }
  14938. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  14939. time_t &not_after) {
  14940. if (!cert) return false;
  14941. auto x509 = static_cast<X509 *>(cert);
  14942. auto nb = X509_get0_notBefore(x509);
  14943. auto na = X509_get0_notAfter(x509);
  14944. if (!nb || !na) return false;
  14945. ASN1_TIME *epoch = ASN1_TIME_new();
  14946. if (!epoch) return false;
  14947. auto se = detail::scope_exit([&] { ASN1_TIME_free(epoch); });
  14948. if (!ASN1_TIME_set(epoch, 0)) return false;
  14949. int pday, psec;
  14950. if (!ASN1_TIME_diff(&pday, &psec, epoch, nb)) return false;
  14951. not_before = 86400 * (time_t)pday + psec;
  14952. if (!ASN1_TIME_diff(&pday, &psec, epoch, na)) return false;
  14953. not_after = 86400 * (time_t)pday + psec;
  14954. return true;
  14955. }
  14956. inline std::string get_cert_serial(cert_t cert) {
  14957. if (!cert) return "";
  14958. auto x509 = static_cast<X509 *>(cert);
  14959. auto serial = X509_get_serialNumber(x509);
  14960. if (!serial) return "";
  14961. auto bn = ASN1_INTEGER_to_BN(serial, nullptr);
  14962. if (!bn) return "";
  14963. auto hex = BN_bn2hex(bn);
  14964. BN_free(bn);
  14965. if (!hex) return "";
  14966. std::string result(hex);
  14967. OPENSSL_free(hex);
  14968. return result;
  14969. }
  14970. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  14971. if (!cert) return false;
  14972. auto x509 = static_cast<X509 *>(cert);
  14973. auto len = i2d_X509(x509, nullptr);
  14974. if (len < 0) return false;
  14975. der.resize(static_cast<size_t>(len));
  14976. auto p = der.data();
  14977. i2d_X509(x509, &p);
  14978. return true;
  14979. }
  14980. inline const char *get_sni(const_session_t session) {
  14981. if (!session) return nullptr;
  14982. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  14983. return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
  14984. }
  14985. inline uint64_t peek_error() { return ERR_peek_last_error(); }
  14986. inline uint64_t get_error() { return ERR_get_error(); }
  14987. inline std::string error_string(uint64_t code) {
  14988. char buf[256];
  14989. ERR_error_string_n(static_cast<unsigned long>(code), buf, sizeof(buf));
  14990. return std::string(buf);
  14991. }
  14992. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  14993. auto mem = BIO_new_mem_buf(pem, static_cast<int>(len));
  14994. if (!mem) { return nullptr; }
  14995. auto mem_guard = detail::scope_exit([&] { BIO_free_all(mem); });
  14996. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  14997. if (!inf) { return nullptr; }
  14998. auto store = X509_STORE_new();
  14999. if (store) {
  15000. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  15001. auto itmp = sk_X509_INFO_value(inf, i);
  15002. if (!itmp) { continue; }
  15003. if (itmp->x509) { X509_STORE_add_cert(store, itmp->x509); }
  15004. if (itmp->crl) { X509_STORE_add_crl(store, itmp->crl); }
  15005. }
  15006. }
  15007. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  15008. return static_cast<ca_store_t>(store);
  15009. }
  15010. inline void free_ca_store(ca_store_t store) {
  15011. if (store) { X509_STORE_free(static_cast<X509_STORE *>(store)); }
  15012. }
  15013. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  15014. if (!ctx || !store) { return false; }
  15015. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15016. auto x509_store = static_cast<X509_STORE *>(store);
  15017. // Check if same store is already set
  15018. if (SSL_CTX_get_cert_store(ssl_ctx) == x509_store) { return true; }
  15019. // SSL_CTX_set_cert_store takes ownership and frees the old store
  15020. SSL_CTX_set_cert_store(ssl_ctx, x509_store);
  15021. return true;
  15022. }
  15023. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  15024. certs.clear();
  15025. if (!ctx) { return 0; }
  15026. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15027. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15028. if (!store) { return 0; }
  15029. auto objs = impl::get_store_objects(store);
  15030. if (!objs) { return 0; }
  15031. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15032. auto count = sk_X509_OBJECT_num(objs);
  15033. for (decltype(count) i = 0; i < count; i++) {
  15034. auto obj = sk_X509_OBJECT_value(objs, i);
  15035. if (!obj) { continue; }
  15036. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15037. auto x509 = X509_OBJECT_get0_X509(obj);
  15038. if (x509) {
  15039. // Increment reference count so caller can free it
  15040. X509_up_ref(x509);
  15041. certs.push_back(static_cast<cert_t>(x509));
  15042. }
  15043. }
  15044. }
  15045. return certs.size();
  15046. }
  15047. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  15048. std::vector<std::string> names;
  15049. if (!ctx) { return names; }
  15050. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15051. auto store = SSL_CTX_get_cert_store(ssl_ctx);
  15052. if (!store) { return names; }
  15053. auto objs = impl::get_store_objects(store);
  15054. if (!objs) { return names; }
  15055. auto se = detail::scope_exit([&] { impl::release_store_objects(objs); });
  15056. auto count = sk_X509_OBJECT_num(objs);
  15057. for (decltype(count) i = 0; i < count; i++) {
  15058. auto obj = sk_X509_OBJECT_value(objs, i);
  15059. if (!obj) { continue; }
  15060. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  15061. auto x509 = X509_OBJECT_get0_X509(obj);
  15062. if (x509) {
  15063. auto subject = X509_get_subject_name(x509);
  15064. if (subject) {
  15065. char buf[512];
  15066. X509_NAME_oneline(subject, buf, sizeof(buf));
  15067. names.push_back(buf);
  15068. }
  15069. }
  15070. }
  15071. }
  15072. return names;
  15073. }
  15074. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  15075. const char *key_pem, const char *password) {
  15076. if (!ctx || !cert_pem || !key_pem) { return false; }
  15077. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15078. // Load certificate from PEM
  15079. auto cert_bio = BIO_new_mem_buf(cert_pem, -1);
  15080. if (!cert_bio) { return false; }
  15081. auto cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  15082. BIO_free(cert_bio);
  15083. if (!cert) { return false; }
  15084. // Load private key from PEM
  15085. auto key_bio = BIO_new_mem_buf(key_pem, -1);
  15086. if (!key_bio) {
  15087. X509_free(cert);
  15088. return false;
  15089. }
  15090. auto key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr,
  15091. password ? const_cast<char *>(password)
  15092. : nullptr);
  15093. BIO_free(key_bio);
  15094. if (!key) {
  15095. X509_free(cert);
  15096. return false;
  15097. }
  15098. // Update certificate and key
  15099. auto ret = SSL_CTX_use_certificate(ssl_ctx, cert) == 1 &&
  15100. SSL_CTX_use_PrivateKey(ssl_ctx, key) == 1;
  15101. X509_free(cert);
  15102. EVP_PKEY_free(key);
  15103. return ret;
  15104. }
  15105. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  15106. if (!ctx || !ca_pem) { return false; }
  15107. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15108. // Create new X509_STORE from PEM
  15109. auto store = create_ca_store(ca_pem, strlen(ca_pem));
  15110. if (!store) { return false; }
  15111. // SSL_CTX_set_cert_store takes ownership
  15112. SSL_CTX_set_cert_store(ssl_ctx, static_cast<X509_STORE *>(store));
  15113. // Set client CA list for client certificate request
  15114. auto ca_list = impl::create_client_ca_list_from_pem(ca_pem);
  15115. if (ca_list) {
  15116. // SSL_CTX_set_client_CA_list takes ownership of ca_list
  15117. SSL_CTX_set_client_CA_list(ssl_ctx, ca_list);
  15118. }
  15119. return true;
  15120. }
  15121. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  15122. if (!ctx) { return false; }
  15123. auto ssl_ctx = static_cast<SSL_CTX *>(ctx);
  15124. impl::get_verify_callback() = std::move(callback);
  15125. if (impl::get_verify_callback()) {
  15126. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, impl::openssl_verify_callback);
  15127. } else {
  15128. SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
  15129. }
  15130. return true;
  15131. }
  15132. inline long get_verify_error(const_session_t session) {
  15133. if (!session) { return -1; }
  15134. auto ssl = static_cast<SSL *>(const_cast<void *>(session));
  15135. return SSL_get_verify_result(ssl);
  15136. }
  15137. inline std::string verify_error_string(long error_code) {
  15138. if (error_code == X509_V_OK) { return ""; }
  15139. const char *str = X509_verify_cert_error_string(static_cast<int>(error_code));
  15140. return str ? str : "unknown error";
  15141. }
  15142. } // namespace tls
  15143. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  15144. /*
  15145. * Group 9: TLS abstraction layer - Mbed TLS backend
  15146. */
  15147. /*
  15148. * Mbed TLS Backend Implementation
  15149. */
  15150. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  15151. namespace tls {
  15152. namespace impl {
  15153. // Mbed TLS session wrapper
  15154. struct MbedTlsSession {
  15155. mbedtls_ssl_context ssl;
  15156. socket_t sock = INVALID_SOCKET;
  15157. std::string hostname; // For client: set via set_sni
  15158. std::string sni_hostname; // For server: received from client via SNI callback
  15159. MbedTlsSession() { mbedtls_ssl_init(&ssl); }
  15160. ~MbedTlsSession() { mbedtls_ssl_free(&ssl); }
  15161. MbedTlsSession(const MbedTlsSession &) = delete;
  15162. MbedTlsSession &operator=(const MbedTlsSession &) = delete;
  15163. };
  15164. // Thread-local error code accessor for Mbed TLS (since it doesn't have an error
  15165. // queue)
  15166. inline int &mbedtls_last_error() {
  15167. static thread_local int err = 0;
  15168. return err;
  15169. }
  15170. // Helper to map Mbed TLS error to ErrorCode
  15171. inline ErrorCode map_mbedtls_error(int ret, int &out_errno) {
  15172. if (ret == 0) { return ErrorCode::Success; }
  15173. if (ret == MBEDTLS_ERR_SSL_WANT_READ) { return ErrorCode::WantRead; }
  15174. if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { return ErrorCode::WantWrite; }
  15175. if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
  15176. return ErrorCode::PeerClosed;
  15177. }
  15178. if (ret == MBEDTLS_ERR_NET_CONN_RESET || ret == MBEDTLS_ERR_NET_SEND_FAILED ||
  15179. ret == MBEDTLS_ERR_NET_RECV_FAILED) {
  15180. out_errno = errno;
  15181. return ErrorCode::SyscallError;
  15182. }
  15183. if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
  15184. return ErrorCode::CertVerifyFailed;
  15185. }
  15186. return ErrorCode::Fatal;
  15187. }
  15188. // BIO-like send callback for Mbed TLS
  15189. inline int mbedtls_net_send_cb(void *ctx, const unsigned char *buf,
  15190. size_t len) {
  15191. auto sock = *static_cast<socket_t *>(ctx);
  15192. #ifdef _WIN32
  15193. auto ret =
  15194. send(sock, reinterpret_cast<const char *>(buf), static_cast<int>(len), 0);
  15195. if (ret == SOCKET_ERROR) {
  15196. int err = WSAGetLastError();
  15197. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_WRITE; }
  15198. return MBEDTLS_ERR_NET_SEND_FAILED;
  15199. }
  15200. #else
  15201. auto ret = send(sock, buf, len, 0);
  15202. if (ret < 0) {
  15203. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15204. return MBEDTLS_ERR_SSL_WANT_WRITE;
  15205. }
  15206. return MBEDTLS_ERR_NET_SEND_FAILED;
  15207. }
  15208. #endif
  15209. return static_cast<int>(ret);
  15210. }
  15211. // BIO-like recv callback for Mbed TLS
  15212. inline int mbedtls_net_recv_cb(void *ctx, unsigned char *buf, size_t len) {
  15213. auto sock = *static_cast<socket_t *>(ctx);
  15214. #ifdef _WIN32
  15215. auto ret =
  15216. recv(sock, reinterpret_cast<char *>(buf), static_cast<int>(len), 0);
  15217. if (ret == SOCKET_ERROR) {
  15218. int err = WSAGetLastError();
  15219. if (err == WSAEWOULDBLOCK) { return MBEDTLS_ERR_SSL_WANT_READ; }
  15220. return MBEDTLS_ERR_NET_RECV_FAILED;
  15221. }
  15222. #else
  15223. auto ret = recv(sock, buf, len, 0);
  15224. if (ret < 0) {
  15225. if (errno == EAGAIN || errno == EWOULDBLOCK) {
  15226. return MBEDTLS_ERR_SSL_WANT_READ;
  15227. }
  15228. return MBEDTLS_ERR_NET_RECV_FAILED;
  15229. }
  15230. #endif
  15231. if (ret == 0) { return MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY; }
  15232. return static_cast<int>(ret);
  15233. }
  15234. // MbedTlsContext constructor/destructor implementations
  15235. inline MbedTlsContext::MbedTlsContext() {
  15236. mbedtls_ssl_config_init(&conf);
  15237. mbedtls_entropy_init(&entropy);
  15238. mbedtls_ctr_drbg_init(&ctr_drbg);
  15239. mbedtls_x509_crt_init(&ca_chain);
  15240. mbedtls_x509_crt_init(&own_cert);
  15241. mbedtls_pk_init(&own_key);
  15242. }
  15243. inline MbedTlsContext::~MbedTlsContext() {
  15244. mbedtls_pk_free(&own_key);
  15245. mbedtls_x509_crt_free(&own_cert);
  15246. mbedtls_x509_crt_free(&ca_chain);
  15247. mbedtls_ctr_drbg_free(&ctr_drbg);
  15248. mbedtls_entropy_free(&entropy);
  15249. mbedtls_ssl_config_free(&conf);
  15250. }
  15251. // Thread-local storage for SNI captured during handshake
  15252. // This is needed because the SNI callback doesn't have a way to pass
  15253. // session-specific data before the session is fully set up
  15254. inline std::string &mbedpending_sni() {
  15255. static thread_local std::string sni;
  15256. return sni;
  15257. }
  15258. // SNI callback for Mbed TLS server to capture client's SNI hostname
  15259. inline int mbedtls_sni_callback(void *p_ctx, mbedtls_ssl_context *ssl,
  15260. const unsigned char *name, size_t name_len) {
  15261. (void)p_ctx;
  15262. (void)ssl;
  15263. // Store SNI name in thread-local storage
  15264. // It will be retrieved and stored in the session after handshake
  15265. if (name && name_len > 0) {
  15266. mbedpending_sni().assign(reinterpret_cast<const char *>(name), name_len);
  15267. } else {
  15268. mbedpending_sni().clear();
  15269. }
  15270. return 0; // Accept any SNI
  15271. }
  15272. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15273. int cert_depth, uint32_t *flags);
  15274. // MbedTLS verify callback wrapper
  15275. inline int mbedtls_verify_callback(void *data, mbedtls_x509_crt *crt,
  15276. int cert_depth, uint32_t *flags) {
  15277. auto &callback = get_verify_callback();
  15278. if (!callback) { return 0; } // Continue with default verification
  15279. // data points to the MbedTlsSession
  15280. auto *session = static_cast<MbedTlsSession *>(data);
  15281. // Build context
  15282. VerifyContext verify_ctx;
  15283. verify_ctx.session = static_cast<session_t>(session);
  15284. verify_ctx.cert = static_cast<cert_t>(crt);
  15285. verify_ctx.depth = cert_depth;
  15286. verify_ctx.preverify_ok = (*flags == 0);
  15287. verify_ctx.error_code = static_cast<long>(*flags);
  15288. // Convert Mbed TLS flags to error string
  15289. static thread_local char error_buf[256];
  15290. if (*flags != 0) {
  15291. mbedtls_x509_crt_verify_info(error_buf, sizeof(error_buf), "", *flags);
  15292. verify_ctx.error_string = error_buf;
  15293. } else {
  15294. verify_ctx.error_string = nullptr;
  15295. }
  15296. bool accepted = callback(verify_ctx);
  15297. if (accepted) {
  15298. *flags = 0; // Clear all error flags
  15299. return 0;
  15300. }
  15301. return MBEDTLS_ERR_X509_CERT_VERIFY_FAILED;
  15302. }
  15303. } // namespace impl
  15304. inline ctx_t create_client_context() {
  15305. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15306. if (!ctx) { return nullptr; }
  15307. ctx->is_server = false;
  15308. // Seed the random number generator
  15309. const char *pers = "httplib_client";
  15310. int ret = mbedtls_ctr_drbg_seed(
  15311. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15312. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15313. if (ret != 0) {
  15314. impl::mbedtls_last_error() = ret;
  15315. delete ctx;
  15316. return nullptr;
  15317. }
  15318. // Set up SSL config for client
  15319. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_CLIENT,
  15320. MBEDTLS_SSL_TRANSPORT_STREAM,
  15321. MBEDTLS_SSL_PRESET_DEFAULT);
  15322. if (ret != 0) {
  15323. impl::mbedtls_last_error() = ret;
  15324. delete ctx;
  15325. return nullptr;
  15326. }
  15327. // Set random number generator
  15328. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15329. // Default: verify peer certificate
  15330. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15331. // Set minimum TLS version to 1.2
  15332. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15333. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15334. #else
  15335. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15336. MBEDTLS_SSL_MINOR_VERSION_3);
  15337. #endif
  15338. return static_cast<ctx_t>(ctx);
  15339. }
  15340. inline ctx_t create_server_context() {
  15341. auto ctx = new (std::nothrow) impl::MbedTlsContext();
  15342. if (!ctx) { return nullptr; }
  15343. ctx->is_server = true;
  15344. // Seed the random number generator
  15345. const char *pers = "httplib_server";
  15346. int ret = mbedtls_ctr_drbg_seed(
  15347. &ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy,
  15348. reinterpret_cast<const unsigned char *>(pers), strlen(pers));
  15349. if (ret != 0) {
  15350. impl::mbedtls_last_error() = ret;
  15351. delete ctx;
  15352. return nullptr;
  15353. }
  15354. // Set up SSL config for server
  15355. ret = mbedtls_ssl_config_defaults(&ctx->conf, MBEDTLS_SSL_IS_SERVER,
  15356. MBEDTLS_SSL_TRANSPORT_STREAM,
  15357. MBEDTLS_SSL_PRESET_DEFAULT);
  15358. if (ret != 0) {
  15359. impl::mbedtls_last_error() = ret;
  15360. delete ctx;
  15361. return nullptr;
  15362. }
  15363. // Set random number generator
  15364. mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg);
  15365. // Default: don't verify client
  15366. mbedtls_ssl_conf_authmode(&ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
  15367. // Set minimum TLS version to 1.2
  15368. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15369. mbedtls_ssl_conf_min_tls_version(&ctx->conf, MBEDTLS_SSL_VERSION_TLS1_2);
  15370. #else
  15371. mbedtls_ssl_conf_min_version(&ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  15372. MBEDTLS_SSL_MINOR_VERSION_3);
  15373. #endif
  15374. // Set SNI callback to capture client's SNI hostname
  15375. mbedtls_ssl_conf_sni(&ctx->conf, impl::mbedtls_sni_callback, nullptr);
  15376. return static_cast<ctx_t>(ctx);
  15377. }
  15378. inline void free_context(ctx_t ctx) {
  15379. if (ctx) { delete static_cast<impl::MbedTlsContext *>(ctx); }
  15380. }
  15381. inline bool set_min_version(ctx_t ctx, Version version) {
  15382. if (!ctx) { return false; }
  15383. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15384. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15385. // Mbed TLS 3.x uses mbedtls_ssl_protocol_version enum
  15386. mbedtls_ssl_protocol_version min_ver = MBEDTLS_SSL_VERSION_TLS1_2;
  15387. if (version >= Version::TLS1_3) {
  15388. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15389. min_ver = MBEDTLS_SSL_VERSION_TLS1_3;
  15390. #endif
  15391. }
  15392. mbedtls_ssl_conf_min_tls_version(&mctx->conf, min_ver);
  15393. #else
  15394. // Mbed TLS 2.x uses major/minor version numbers
  15395. int major = MBEDTLS_SSL_MAJOR_VERSION_3;
  15396. int minor = MBEDTLS_SSL_MINOR_VERSION_3; // TLS 1.2
  15397. if (version >= Version::TLS1_3) {
  15398. #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
  15399. minor = MBEDTLS_SSL_MINOR_VERSION_4; // TLS 1.3
  15400. #else
  15401. minor = MBEDTLS_SSL_MINOR_VERSION_3; // Fall back to TLS 1.2
  15402. #endif
  15403. }
  15404. mbedtls_ssl_conf_min_version(&mctx->conf, major, minor);
  15405. #endif
  15406. return true;
  15407. }
  15408. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  15409. if (!ctx || !pem) { return false; }
  15410. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15411. // mbedtls_x509_crt_parse expects null-terminated string for PEM
  15412. // Add null terminator if not present
  15413. std::string pem_str(pem, len);
  15414. int ret = mbedtls_x509_crt_parse(
  15415. &mctx->ca_chain, reinterpret_cast<const unsigned char *>(pem_str.c_str()),
  15416. pem_str.size() + 1);
  15417. if (ret != 0) {
  15418. impl::mbedtls_last_error() = ret;
  15419. return false;
  15420. }
  15421. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15422. return true;
  15423. }
  15424. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  15425. if (!ctx || !file_path) { return false; }
  15426. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15427. int ret = mbedtls_x509_crt_parse_file(&mctx->ca_chain, file_path);
  15428. if (ret != 0) {
  15429. impl::mbedtls_last_error() = ret;
  15430. return false;
  15431. }
  15432. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15433. return true;
  15434. }
  15435. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  15436. if (!ctx || !dir_path) { return false; }
  15437. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15438. int ret = mbedtls_x509_crt_parse_path(&mctx->ca_chain, dir_path);
  15439. if (ret < 0) { // Returns number of certs on success, negative on error
  15440. impl::mbedtls_last_error() = ret;
  15441. return false;
  15442. }
  15443. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15444. return true;
  15445. }
  15446. inline bool load_system_certs(ctx_t ctx) {
  15447. if (!ctx) { return false; }
  15448. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15449. bool loaded = false;
  15450. #ifdef _WIN32
  15451. loaded = impl::enumerate_windows_system_certs(
  15452. [&](const unsigned char *data, size_t len) {
  15453. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15454. });
  15455. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  15456. loaded = impl::enumerate_macos_keychain_certs(
  15457. [&](const unsigned char *data, size_t len) {
  15458. return mbedtls_x509_crt_parse_der(&mctx->ca_chain, data, len) == 0;
  15459. });
  15460. #else
  15461. for (auto path = impl::system_ca_paths(); *path; ++path) {
  15462. if (mbedtls_x509_crt_parse_file(&mctx->ca_chain, *path) >= 0) {
  15463. loaded = true;
  15464. break;
  15465. }
  15466. }
  15467. if (!loaded) {
  15468. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  15469. if (mbedtls_x509_crt_parse_path(&mctx->ca_chain, *dir) >= 0) {
  15470. loaded = true;
  15471. break;
  15472. }
  15473. }
  15474. }
  15475. #endif
  15476. if (loaded) {
  15477. mbedtls_ssl_conf_ca_chain(&mctx->conf, &mctx->ca_chain, nullptr);
  15478. }
  15479. return loaded;
  15480. }
  15481. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  15482. const char *password) {
  15483. if (!ctx || !cert || !key) { return false; }
  15484. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15485. // Parse certificate
  15486. std::string cert_str(cert);
  15487. int ret = mbedtls_x509_crt_parse(
  15488. &mctx->own_cert,
  15489. reinterpret_cast<const unsigned char *>(cert_str.c_str()),
  15490. cert_str.size() + 1);
  15491. if (ret != 0) {
  15492. impl::mbedtls_last_error() = ret;
  15493. return false;
  15494. }
  15495. // Parse private key
  15496. std::string key_str(key);
  15497. const unsigned char *pwd =
  15498. password ? reinterpret_cast<const unsigned char *>(password) : nullptr;
  15499. size_t pwd_len = password ? strlen(password) : 0;
  15500. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15501. ret = mbedtls_pk_parse_key(
  15502. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15503. key_str.size() + 1, pwd, pwd_len, mbedtls_ctr_drbg_random,
  15504. &mctx->ctr_drbg);
  15505. #else
  15506. ret = mbedtls_pk_parse_key(
  15507. &mctx->own_key, reinterpret_cast<const unsigned char *>(key_str.c_str()),
  15508. key_str.size() + 1, pwd, pwd_len);
  15509. #endif
  15510. if (ret != 0) {
  15511. impl::mbedtls_last_error() = ret;
  15512. return false;
  15513. }
  15514. // Verify that the certificate and private key match
  15515. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15516. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15517. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15518. #else
  15519. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15520. #endif
  15521. if (ret != 0) {
  15522. impl::mbedtls_last_error() = ret;
  15523. return false;
  15524. }
  15525. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15526. if (ret != 0) {
  15527. impl::mbedtls_last_error() = ret;
  15528. return false;
  15529. }
  15530. return true;
  15531. }
  15532. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  15533. const char *key_path, const char *password) {
  15534. if (!ctx || !cert_path || !key_path) { return false; }
  15535. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15536. // Parse certificate file
  15537. int ret = mbedtls_x509_crt_parse_file(&mctx->own_cert, cert_path);
  15538. if (ret != 0) {
  15539. impl::mbedtls_last_error() = ret;
  15540. return false;
  15541. }
  15542. // Parse private key file
  15543. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15544. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password,
  15545. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15546. #else
  15547. ret = mbedtls_pk_parse_keyfile(&mctx->own_key, key_path, password);
  15548. #endif
  15549. if (ret != 0) {
  15550. impl::mbedtls_last_error() = ret;
  15551. return false;
  15552. }
  15553. // Verify that the certificate and private key match
  15554. #ifdef CPPHTTPLIB_MBEDTLS_V3
  15555. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key,
  15556. mbedtls_ctr_drbg_random, &mctx->ctr_drbg);
  15557. #else
  15558. ret = mbedtls_pk_check_pair(&mctx->own_cert.pk, &mctx->own_key);
  15559. #endif
  15560. if (ret != 0) {
  15561. impl::mbedtls_last_error() = ret;
  15562. return false;
  15563. }
  15564. ret = mbedtls_ssl_conf_own_cert(&mctx->conf, &mctx->own_cert, &mctx->own_key);
  15565. if (ret != 0) {
  15566. impl::mbedtls_last_error() = ret;
  15567. return false;
  15568. }
  15569. return true;
  15570. }
  15571. inline void set_verify_client(ctx_t ctx, bool require) {
  15572. if (!ctx) { return; }
  15573. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15574. mctx->verify_client = require;
  15575. if (require) {
  15576. mbedtls_ssl_conf_authmode(&mctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  15577. } else {
  15578. // If a verify callback is set, use OPTIONAL mode to ensure the callback
  15579. // is called (matching OpenSSL behavior). Otherwise use NONE.
  15580. mbedtls_ssl_conf_authmode(&mctx->conf, mctx->has_verify_callback
  15581. ? MBEDTLS_SSL_VERIFY_OPTIONAL
  15582. : MBEDTLS_SSL_VERIFY_NONE);
  15583. }
  15584. }
  15585. inline session_t create_session(ctx_t ctx, socket_t sock) {
  15586. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  15587. auto mctx = static_cast<impl::MbedTlsContext *>(ctx);
  15588. auto session = new (std::nothrow) impl::MbedTlsSession();
  15589. if (!session) { return nullptr; }
  15590. session->sock = sock;
  15591. int ret = mbedtls_ssl_setup(&session->ssl, &mctx->conf);
  15592. if (ret != 0) {
  15593. impl::mbedtls_last_error() = ret;
  15594. delete session;
  15595. return nullptr;
  15596. }
  15597. // Explicitly opt out of in-handshake hostname verification by default;
  15598. // since Mbed TLS 3.6.4 a client handshake with certificate verification
  15599. // fails outright when no hostname was set. set_sni() installs the real
  15600. // hostname for DNS hosts; for IP hosts (where SNI must not be set) the
  15601. // caller verifies the certificate identity post-handshake via
  15602. // verify_hostname().
  15603. mbedtls_ssl_set_hostname(&session->ssl, nullptr);
  15604. // Set BIO callbacks
  15605. mbedtls_ssl_set_bio(&session->ssl, &session->sock, impl::mbedtls_net_send_cb,
  15606. impl::mbedtls_net_recv_cb, nullptr);
  15607. // Set per-session verify callback with session pointer if callback is
  15608. // registered
  15609. if (mctx->has_verify_callback) {
  15610. mbedtls_ssl_set_verify(&session->ssl, impl::mbedtls_verify_callback,
  15611. session);
  15612. }
  15613. return static_cast<session_t>(session);
  15614. }
  15615. inline void free_session(session_t session) {
  15616. if (session) { delete static_cast<impl::MbedTlsSession *>(session); }
  15617. }
  15618. inline bool set_sni(session_t session, const char *hostname) {
  15619. if (!session || !hostname) { return false; }
  15620. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15621. int ret = mbedtls_ssl_set_hostname(&msession->ssl, hostname);
  15622. if (ret != 0) {
  15623. impl::mbedtls_last_error() = ret;
  15624. return false;
  15625. }
  15626. msession->hostname = hostname;
  15627. return true;
  15628. }
  15629. inline bool set_hostname(session_t session, const char *hostname) {
  15630. // In Mbed TLS, set_hostname also sets up hostname verification
  15631. return set_sni(session, hostname);
  15632. }
  15633. inline TlsError connect(session_t session) {
  15634. TlsError err;
  15635. if (!session) {
  15636. err.code = ErrorCode::Fatal;
  15637. return err;
  15638. }
  15639. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15640. int ret = mbedtls_ssl_handshake(&msession->ssl);
  15641. if (ret == 0) {
  15642. err.code = ErrorCode::Success;
  15643. } else {
  15644. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15645. err.backend_code = static_cast<uint64_t>(-ret);
  15646. impl::mbedtls_last_error() = ret;
  15647. }
  15648. return err;
  15649. }
  15650. inline TlsError accept(session_t session) {
  15651. // Same as connect for Mbed TLS - handshake works for both client and server
  15652. auto result = connect(session);
  15653. // After successful handshake, capture SNI from thread-local storage
  15654. if (result.code == ErrorCode::Success && session) {
  15655. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15656. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15657. impl::mbedpending_sni().clear();
  15658. }
  15659. return result;
  15660. }
  15661. inline bool connect_nonblocking(session_t session, socket_t sock,
  15662. time_t timeout_sec, time_t timeout_usec,
  15663. TlsError *err) {
  15664. if (!session) {
  15665. if (err) { err->code = ErrorCode::Fatal; }
  15666. return false;
  15667. }
  15668. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15669. // Set socket to non-blocking mode
  15670. detail::set_nonblocking(sock, true);
  15671. auto cleanup =
  15672. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15673. int ret;
  15674. while ((ret = mbedtls_ssl_handshake(&msession->ssl)) != 0) {
  15675. if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
  15676. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  15677. continue;
  15678. }
  15679. } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
  15680. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  15681. continue;
  15682. }
  15683. }
  15684. // TlsError or timeout
  15685. if (err) {
  15686. err->code = impl::map_mbedtls_error(ret, err->sys_errno);
  15687. err->backend_code = static_cast<uint64_t>(-ret);
  15688. }
  15689. impl::mbedtls_last_error() = ret;
  15690. return false;
  15691. }
  15692. if (err) { err->code = ErrorCode::Success; }
  15693. return true;
  15694. }
  15695. inline bool accept_nonblocking(session_t session, socket_t sock,
  15696. time_t timeout_sec, time_t timeout_usec,
  15697. TlsError *err) {
  15698. // Same implementation as connect for Mbed TLS
  15699. bool result =
  15700. connect_nonblocking(session, sock, timeout_sec, timeout_usec, err);
  15701. // After successful handshake, capture SNI from thread-local storage
  15702. if (result && session) {
  15703. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15704. msession->sni_hostname = std::move(impl::mbedpending_sni());
  15705. impl::mbedpending_sni().clear();
  15706. }
  15707. return result;
  15708. }
  15709. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  15710. if (!session || !buf) {
  15711. err.code = ErrorCode::Fatal;
  15712. return -1;
  15713. }
  15714. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15715. int ret =
  15716. mbedtls_ssl_read(&msession->ssl, static_cast<unsigned char *>(buf), len);
  15717. if (ret > 0) {
  15718. err.code = ErrorCode::Success;
  15719. return static_cast<ssize_t>(ret);
  15720. }
  15721. if (ret == 0) {
  15722. err.code = ErrorCode::PeerClosed;
  15723. return 0;
  15724. }
  15725. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15726. err.backend_code = static_cast<uint64_t>(-ret);
  15727. impl::mbedtls_last_error() = ret;
  15728. // mbedTLS signals a clean close_notify via a negative error code rather
  15729. // than 0; surface it as a clean EOF the way OpenSSL/wolfSSL do.
  15730. if (err.code == ErrorCode::PeerClosed) { return 0; }
  15731. return -1;
  15732. }
  15733. inline ssize_t write(session_t session, const void *buf, size_t len,
  15734. TlsError &err) {
  15735. if (!session || !buf) {
  15736. err.code = ErrorCode::Fatal;
  15737. return -1;
  15738. }
  15739. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15740. int ret = mbedtls_ssl_write(&msession->ssl,
  15741. static_cast<const unsigned char *>(buf), len);
  15742. if (ret > 0) {
  15743. err.code = ErrorCode::Success;
  15744. return static_cast<ssize_t>(ret);
  15745. }
  15746. if (ret == 0) {
  15747. err.code = ErrorCode::PeerClosed;
  15748. return 0;
  15749. }
  15750. err.code = impl::map_mbedtls_error(ret, err.sys_errno);
  15751. err.backend_code = static_cast<uint64_t>(-ret);
  15752. impl::mbedtls_last_error() = ret;
  15753. return -1;
  15754. }
  15755. inline int pending(const_session_t session) {
  15756. if (!session) { return 0; }
  15757. auto msession =
  15758. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15759. return static_cast<int>(mbedtls_ssl_get_bytes_avail(&msession->ssl));
  15760. }
  15761. inline void shutdown(session_t session, bool graceful) {
  15762. if (!session) { return; }
  15763. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15764. if (graceful) {
  15765. // Try to send close_notify, but don't block forever
  15766. int ret;
  15767. int attempts = 0;
  15768. while ((ret = mbedtls_ssl_close_notify(&msession->ssl)) != 0 &&
  15769. attempts < 3) {
  15770. if (ret != MBEDTLS_ERR_SSL_WANT_READ &&
  15771. ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
  15772. break;
  15773. }
  15774. attempts++;
  15775. }
  15776. }
  15777. }
  15778. inline bool is_peer_closed(session_t session, socket_t sock) {
  15779. if (!session || sock == INVALID_SOCKET) { return true; }
  15780. auto msession = static_cast<impl::MbedTlsSession *>(session);
  15781. // Check if there's already decrypted data available in the TLS buffer
  15782. // If so, the connection is definitely alive
  15783. if (mbedtls_ssl_get_bytes_avail(&msession->ssl) > 0) { return false; }
  15784. // Set socket to non-blocking to avoid blocking on read
  15785. detail::set_nonblocking(sock, true);
  15786. auto cleanup =
  15787. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  15788. // Try a 1-byte read to check connection status
  15789. // Note: This will consume the byte if data is available, but for the
  15790. // purpose of checking if peer is closed, this should be acceptable
  15791. // since we're only called when we expect the connection might be closing
  15792. unsigned char buf;
  15793. int ret = mbedtls_ssl_read(&msession->ssl, &buf, 1);
  15794. // If we got data or WANT_READ (would block), connection is alive
  15795. if (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ) { return false; }
  15796. // If we get a peer close notify or a connection reset, the peer is closed
  15797. return ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY ||
  15798. ret == MBEDTLS_ERR_NET_CONN_RESET || ret == 0;
  15799. }
  15800. inline cert_t get_peer_cert(const_session_t session) {
  15801. if (!session) { return nullptr; }
  15802. auto msession =
  15803. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15804. // Mbed TLS returns a pointer to the internal peer cert chain.
  15805. // WARNING: This pointer is only valid while the session is active.
  15806. // Do not use the certificate after calling free_session().
  15807. const mbedtls_x509_crt *cert = mbedtls_ssl_get_peer_cert(&msession->ssl);
  15808. return const_cast<mbedtls_x509_crt *>(cert);
  15809. }
  15810. inline void free_cert(cert_t cert) {
  15811. // Mbed TLS: peer certificate is owned by the SSL context.
  15812. // No-op here, but callers should still call this for cross-backend
  15813. // portability.
  15814. (void)cert;
  15815. }
  15816. inline bool verify_hostname(cert_t cert, const char *hostname) {
  15817. if (!cert || !hostname) { return false; }
  15818. auto mcert = static_cast<const mbedtls_x509_crt *>(cert);
  15819. std::string host_str(hostname);
  15820. // Check if hostname is an IP address (IPv4 or IPv6)
  15821. unsigned char ip_bytes[16];
  15822. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  15823. auto is_ip = ip_len > 0;
  15824. // Check Subject Alternative Names (SAN)
  15825. // In Mbed TLS 3.x, subject_alt_names contains raw values without ASN.1 tags
  15826. // - DNS names: raw string bytes
  15827. // - IP addresses: raw IP bytes (4 for IPv4, 16 for IPv6)
  15828. const mbedtls_x509_sequence *san = &mcert->subject_alt_names;
  15829. while (san != nullptr && san->buf.p != nullptr && san->buf.len > 0) {
  15830. const unsigned char *p = san->buf.p;
  15831. size_t len = san->buf.len;
  15832. if (is_ip) {
  15833. // For an IP host, only a matching iPAddress SAN of the same family
  15834. // (4 bytes for IPv4, 16 bytes for IPv6) may authenticate it.
  15835. if (len == ip_len && memcmp(p, ip_bytes, ip_len) == 0) { return true; }
  15836. } else {
  15837. // Check if this SAN is a DNS name (printable ASCII string)
  15838. bool is_dns = len > 0;
  15839. for (size_t i = 0; i < len && is_dns; i++) {
  15840. if (p[i] < 32 || p[i] > 126) { is_dns = false; }
  15841. }
  15842. if (is_dns) {
  15843. std::string san_name(reinterpret_cast<const char *>(p), len);
  15844. if (detail::match_hostname(san_name, host_str)) { return true; }
  15845. }
  15846. }
  15847. san = san->next;
  15848. }
  15849. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  15850. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  15851. // the OpenSSL backend's X509_check_ip behaves the same way).
  15852. if (!is_ip) {
  15853. char cn[256];
  15854. int ret = mbedtls_x509_dn_gets(cn, sizeof(cn), &mcert->subject);
  15855. if (ret > 0) {
  15856. std::string cn_str(cn);
  15857. // Look for "CN=" in the DN string
  15858. size_t cn_pos = cn_str.find("CN=");
  15859. if (cn_pos != std::string::npos) {
  15860. size_t start = cn_pos + 3;
  15861. size_t end = cn_str.find(',', start);
  15862. std::string cn_value =
  15863. cn_str.substr(start, end == std::string::npos ? end : end - start);
  15864. if (detail::match_hostname(cn_value, host_str)) { return true; }
  15865. }
  15866. }
  15867. }
  15868. return false;
  15869. }
  15870. inline uint64_t hostname_mismatch_code() {
  15871. return static_cast<uint64_t>(MBEDTLS_X509_BADCERT_CN_MISMATCH);
  15872. }
  15873. inline long get_verify_result(const_session_t session) {
  15874. if (!session) { return -1; }
  15875. auto msession =
  15876. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  15877. uint32_t flags = mbedtls_ssl_get_verify_result(&msession->ssl);
  15878. // Return 0 (X509_V_OK equivalent) if verification passed
  15879. return flags == 0 ? 0 : static_cast<long>(flags);
  15880. }
  15881. inline std::string get_cert_subject_cn(cert_t cert) {
  15882. if (!cert) return "";
  15883. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15884. // Find the CN in the subject
  15885. const mbedtls_x509_name *name = &x509->subject;
  15886. while (name != nullptr) {
  15887. if (MBEDTLS_OID_CMP(MBEDTLS_OID_AT_CN, &name->oid) == 0) {
  15888. return std::string(reinterpret_cast<const char *>(name->val.p),
  15889. name->val.len);
  15890. }
  15891. name = name->next;
  15892. }
  15893. return "";
  15894. }
  15895. inline std::string get_cert_issuer_name(cert_t cert) {
  15896. if (!cert) return "";
  15897. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15898. // Build a human-readable issuer name string
  15899. char buf[512];
  15900. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &x509->issuer);
  15901. if (ret < 0) return "";
  15902. return std::string(buf);
  15903. }
  15904. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  15905. sans.clear();
  15906. if (!cert) return false;
  15907. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15908. // Parse the Subject Alternative Name extension
  15909. const mbedtls_x509_sequence *cur = &x509->subject_alt_names;
  15910. while (cur != nullptr) {
  15911. if (cur->buf.len > 0) {
  15912. // Mbed TLS stores SAN as ASN.1 sequences
  15913. // The tag byte indicates the type
  15914. const unsigned char *p = cur->buf.p;
  15915. size_t len = cur->buf.len;
  15916. // First byte is the tag
  15917. unsigned char tag = *p;
  15918. p++;
  15919. len--;
  15920. // Parse length (simple single-byte length assumed)
  15921. if (len > 0 && *p < 0x80) {
  15922. size_t value_len = *p;
  15923. p++;
  15924. len--;
  15925. if (value_len <= len) {
  15926. SanEntry entry;
  15927. // ASN.1 context tags for GeneralName
  15928. switch (tag & 0x1F) {
  15929. case 2: // dNSName
  15930. entry.type = SanType::DNS;
  15931. entry.value =
  15932. std::string(reinterpret_cast<const char *>(p), value_len);
  15933. break;
  15934. case 7: // iPAddress
  15935. entry.type = SanType::IP;
  15936. if (value_len == 4) {
  15937. // IPv4
  15938. char buf[16];
  15939. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
  15940. entry.value = buf;
  15941. } else if (value_len == 16) {
  15942. // IPv6
  15943. char buf[64];
  15944. snprintf(buf, sizeof(buf),
  15945. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  15946. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  15947. p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8],
  15948. p[9], p[10], p[11], p[12], p[13], p[14], p[15]);
  15949. entry.value = buf;
  15950. }
  15951. break;
  15952. case 1: // rfc822Name (email)
  15953. entry.type = SanType::EMAIL;
  15954. entry.value =
  15955. std::string(reinterpret_cast<const char *>(p), value_len);
  15956. break;
  15957. case 6: // uniformResourceIdentifier
  15958. entry.type = SanType::URI;
  15959. entry.value =
  15960. std::string(reinterpret_cast<const char *>(p), value_len);
  15961. break;
  15962. default: entry.type = SanType::OTHER; break;
  15963. }
  15964. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  15965. }
  15966. }
  15967. }
  15968. cur = cur->next;
  15969. }
  15970. return true;
  15971. }
  15972. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  15973. time_t &not_after) {
  15974. if (!cert) return false;
  15975. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15976. // Convert mbedtls_x509_time to time_t
  15977. auto to_time_t = [](const mbedtls_x509_time &t) -> time_t {
  15978. struct tm tm_time = {};
  15979. tm_time.tm_year = t.year - 1900;
  15980. tm_time.tm_mon = t.mon - 1;
  15981. tm_time.tm_mday = t.day;
  15982. tm_time.tm_hour = t.hour;
  15983. tm_time.tm_min = t.min;
  15984. tm_time.tm_sec = t.sec;
  15985. #ifdef _WIN32
  15986. return _mkgmtime(&tm_time);
  15987. #else
  15988. return timegm(&tm_time);
  15989. #endif
  15990. };
  15991. not_before = to_time_t(x509->valid_from);
  15992. not_after = to_time_t(x509->valid_to);
  15993. return true;
  15994. }
  15995. inline std::string get_cert_serial(cert_t cert) {
  15996. if (!cert) return "";
  15997. auto x509 = static_cast<mbedtls_x509_crt *>(cert);
  15998. // Convert serial number to hex string
  15999. std::string result;
  16000. result.reserve(x509->serial.len * 2);
  16001. for (size_t i = 0; i < x509->serial.len; i++) {
  16002. char hex[3];
  16003. snprintf(hex, sizeof(hex), "%02X", x509->serial.p[i]);
  16004. result += hex;
  16005. }
  16006. return result;
  16007. }
  16008. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16009. if (!cert) return false;
  16010. auto crt = static_cast<mbedtls_x509_crt *>(cert);
  16011. if (!crt->raw.p || crt->raw.len == 0) return false;
  16012. der.assign(crt->raw.p, crt->raw.p + crt->raw.len);
  16013. return true;
  16014. }
  16015. inline const char *get_sni(const_session_t session) {
  16016. if (!session) return nullptr;
  16017. auto msession = static_cast<const impl::MbedTlsSession *>(session);
  16018. // For server: return SNI received from client during handshake
  16019. if (!msession->sni_hostname.empty()) {
  16020. return msession->sni_hostname.c_str();
  16021. }
  16022. // For client: return the hostname set via set_sni
  16023. if (!msession->hostname.empty()) { return msession->hostname.c_str(); }
  16024. return nullptr;
  16025. }
  16026. inline uint64_t peek_error() {
  16027. // Mbed TLS doesn't have an error queue, return the last error
  16028. return static_cast<uint64_t>(-impl::mbedtls_last_error());
  16029. }
  16030. inline uint64_t get_error() {
  16031. // Mbed TLS doesn't have an error queue, return and clear the last error
  16032. uint64_t err = static_cast<uint64_t>(-impl::mbedtls_last_error());
  16033. impl::mbedtls_last_error() = 0;
  16034. return err;
  16035. }
  16036. inline std::string error_string(uint64_t code) {
  16037. char buf[256];
  16038. mbedtls_strerror(-static_cast<int>(code), buf, sizeof(buf));
  16039. return std::string(buf);
  16040. }
  16041. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  16042. auto *ca_chain = new (std::nothrow) mbedtls_x509_crt;
  16043. if (!ca_chain) { return nullptr; }
  16044. mbedtls_x509_crt_init(ca_chain);
  16045. // mbedtls_x509_crt_parse expects null-terminated PEM
  16046. int ret = mbedtls_x509_crt_parse(ca_chain,
  16047. reinterpret_cast<const unsigned char *>(pem),
  16048. len + 1); // +1 for null terminator
  16049. if (ret != 0) {
  16050. // Try without +1 in case PEM is already null-terminated
  16051. ret = mbedtls_x509_crt_parse(
  16052. ca_chain, reinterpret_cast<const unsigned char *>(pem), len);
  16053. if (ret != 0) {
  16054. mbedtls_x509_crt_free(ca_chain);
  16055. delete ca_chain;
  16056. return nullptr;
  16057. }
  16058. }
  16059. return static_cast<ca_store_t>(ca_chain);
  16060. }
  16061. inline void free_ca_store(ca_store_t store) {
  16062. if (store) {
  16063. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16064. mbedtls_x509_crt_free(ca_chain);
  16065. delete ca_chain;
  16066. }
  16067. }
  16068. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  16069. if (!ctx || !store) { return false; }
  16070. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16071. auto *ca_chain = static_cast<mbedtls_x509_crt *>(store);
  16072. // Free existing CA chain
  16073. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16074. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16075. // Copy the CA chain (deep copy)
  16076. // Parse from the raw data of the source cert
  16077. mbedtls_x509_crt *src = ca_chain;
  16078. while (src != nullptr) {
  16079. int ret = mbedtls_x509_crt_parse_der(&mbed_ctx->ca_chain, src->raw.p,
  16080. src->raw.len);
  16081. if (ret != 0) {
  16082. free_ca_store(store);
  16083. return false;
  16084. }
  16085. src = src->next;
  16086. }
  16087. // This function takes ownership of the store; the chain was deep-copied
  16088. // above, so release the source
  16089. free_ca_store(store);
  16090. // Update the SSL config to use the new CA chain
  16091. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16092. return true;
  16093. }
  16094. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  16095. certs.clear();
  16096. if (!ctx) { return 0; }
  16097. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16098. // Iterate through the CA chain
  16099. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16100. while (cert != nullptr && cert->raw.len > 0) {
  16101. // Create a copy of the certificate for the caller
  16102. auto *copy = new mbedtls_x509_crt;
  16103. mbedtls_x509_crt_init(copy);
  16104. int ret = mbedtls_x509_crt_parse_der(copy, cert->raw.p, cert->raw.len);
  16105. if (ret == 0) {
  16106. certs.push_back(static_cast<cert_t>(copy));
  16107. } else {
  16108. mbedtls_x509_crt_free(copy);
  16109. delete copy;
  16110. }
  16111. cert = cert->next;
  16112. }
  16113. return certs.size();
  16114. }
  16115. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  16116. std::vector<std::string> names;
  16117. if (!ctx) { return names; }
  16118. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16119. // Iterate through the CA chain
  16120. mbedtls_x509_crt *cert = &mbed_ctx->ca_chain;
  16121. while (cert != nullptr && cert->raw.len > 0) {
  16122. char buf[512];
  16123. int ret = mbedtls_x509_dn_gets(buf, sizeof(buf), &cert->subject);
  16124. if (ret > 0) { names.push_back(buf); }
  16125. cert = cert->next;
  16126. }
  16127. return names;
  16128. }
  16129. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  16130. const char *key_pem, const char *password) {
  16131. if (!ctx || !cert_pem || !key_pem) { return false; }
  16132. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16133. // Free existing certificate and key
  16134. mbedtls_x509_crt_free(&mbed_ctx->own_cert);
  16135. mbedtls_pk_free(&mbed_ctx->own_key);
  16136. mbedtls_x509_crt_init(&mbed_ctx->own_cert);
  16137. mbedtls_pk_init(&mbed_ctx->own_key);
  16138. // Parse certificate PEM
  16139. int ret = mbedtls_x509_crt_parse(
  16140. &mbed_ctx->own_cert, reinterpret_cast<const unsigned char *>(cert_pem),
  16141. strlen(cert_pem) + 1);
  16142. if (ret != 0) {
  16143. impl::mbedtls_last_error() = ret;
  16144. return false;
  16145. }
  16146. // Parse private key PEM
  16147. #ifdef CPPHTTPLIB_MBEDTLS_V3
  16148. ret = mbedtls_pk_parse_key(
  16149. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16150. strlen(key_pem) + 1,
  16151. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16152. password ? strlen(password) : 0, mbedtls_ctr_drbg_random,
  16153. &mbed_ctx->ctr_drbg);
  16154. #else
  16155. ret = mbedtls_pk_parse_key(
  16156. &mbed_ctx->own_key, reinterpret_cast<const unsigned char *>(key_pem),
  16157. strlen(key_pem) + 1,
  16158. password ? reinterpret_cast<const unsigned char *>(password) : nullptr,
  16159. password ? strlen(password) : 0);
  16160. #endif
  16161. if (ret != 0) {
  16162. impl::mbedtls_last_error() = ret;
  16163. return false;
  16164. }
  16165. // Configure SSL to use the new certificate and key
  16166. ret = mbedtls_ssl_conf_own_cert(&mbed_ctx->conf, &mbed_ctx->own_cert,
  16167. &mbed_ctx->own_key);
  16168. if (ret != 0) {
  16169. impl::mbedtls_last_error() = ret;
  16170. return false;
  16171. }
  16172. return true;
  16173. }
  16174. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  16175. if (!ctx || !ca_pem) { return false; }
  16176. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16177. // Free existing CA chain
  16178. mbedtls_x509_crt_free(&mbed_ctx->ca_chain);
  16179. mbedtls_x509_crt_init(&mbed_ctx->ca_chain);
  16180. // Parse CA PEM
  16181. int ret = mbedtls_x509_crt_parse(
  16182. &mbed_ctx->ca_chain, reinterpret_cast<const unsigned char *>(ca_pem),
  16183. strlen(ca_pem) + 1);
  16184. if (ret != 0) {
  16185. impl::mbedtls_last_error() = ret;
  16186. return false;
  16187. }
  16188. // Update SSL config to use new CA chain
  16189. mbedtls_ssl_conf_ca_chain(&mbed_ctx->conf, &mbed_ctx->ca_chain, nullptr);
  16190. return true;
  16191. }
  16192. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  16193. if (!ctx) { return false; }
  16194. auto *mbed_ctx = static_cast<impl::MbedTlsContext *>(ctx);
  16195. impl::get_verify_callback() = std::move(callback);
  16196. mbed_ctx->has_verify_callback =
  16197. static_cast<bool>(impl::get_verify_callback());
  16198. if (mbed_ctx->has_verify_callback) {
  16199. // Set OPTIONAL mode to ensure callback is called even when verification
  16200. // is disabled (matching OpenSSL behavior where SSL_VERIFY_PEER is set)
  16201. mbedtls_ssl_conf_authmode(&mbed_ctx->conf, MBEDTLS_SSL_VERIFY_OPTIONAL);
  16202. mbedtls_ssl_conf_verify(&mbed_ctx->conf, impl::mbedtls_verify_callback,
  16203. nullptr);
  16204. } else {
  16205. mbedtls_ssl_conf_verify(&mbed_ctx->conf, nullptr, nullptr);
  16206. }
  16207. return true;
  16208. }
  16209. inline long get_verify_error(const_session_t session) {
  16210. if (!session) { return -1; }
  16211. auto *msession =
  16212. static_cast<impl::MbedTlsSession *>(const_cast<void *>(session));
  16213. return static_cast<long>(mbedtls_ssl_get_verify_result(&msession->ssl));
  16214. }
  16215. inline std::string verify_error_string(long error_code) {
  16216. if (error_code == 0) { return ""; }
  16217. char buf[256];
  16218. mbedtls_x509_crt_verify_info(buf, sizeof(buf), "",
  16219. static_cast<uint32_t>(error_code));
  16220. // Remove trailing newline if present
  16221. std::string result(buf);
  16222. while (!result.empty() && (result.back() == '\n' || result.back() == ' ')) {
  16223. result.pop_back();
  16224. }
  16225. return result;
  16226. }
  16227. } // namespace tls
  16228. #endif // CPPHTTPLIB_MBEDTLS_SUPPORT
  16229. /*
  16230. * Group 10: TLS abstraction layer - wolfSSL backend
  16231. */
  16232. /*
  16233. * wolfSSL Backend Implementation
  16234. */
  16235. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  16236. namespace tls {
  16237. namespace impl {
  16238. // wolfSSL session wrapper
  16239. struct WolfSSLSession {
  16240. WOLFSSL *ssl = nullptr;
  16241. socket_t sock = INVALID_SOCKET;
  16242. std::string hostname; // For client: set via set_sni
  16243. std::string sni_hostname; // For server: received from client via SNI callback
  16244. WolfSSLSession() = default;
  16245. ~WolfSSLSession() {
  16246. if (ssl) { wolfSSL_free(ssl); }
  16247. }
  16248. WolfSSLSession(const WolfSSLSession &) = delete;
  16249. WolfSSLSession &operator=(const WolfSSLSession &) = delete;
  16250. };
  16251. // Thread-local error code accessor for wolfSSL
  16252. inline uint64_t &wolfssl_last_error() {
  16253. static thread_local uint64_t err = 0;
  16254. return err;
  16255. }
  16256. // Helper to map wolfSSL error to ErrorCode.
  16257. // ssl_error is the value from wolfSSL_get_error().
  16258. // raw_ret is the raw return value from the wolfSSL call (for low-level error).
  16259. inline ErrorCode map_wolfssl_error(WOLFSSL *ssl, int ssl_error,
  16260. int &out_errno) {
  16261. switch (ssl_error) {
  16262. case SSL_ERROR_NONE: return ErrorCode::Success;
  16263. case SSL_ERROR_WANT_READ: return ErrorCode::WantRead;
  16264. case SSL_ERROR_WANT_WRITE: return ErrorCode::WantWrite;
  16265. case SSL_ERROR_ZERO_RETURN: return ErrorCode::PeerClosed;
  16266. case SSL_ERROR_SYSCALL: out_errno = errno; return ErrorCode::SyscallError;
  16267. default:
  16268. if (ssl) {
  16269. // wolfSSL stores the low-level error code as a negative value.
  16270. // DOMAIN_NAME_MISMATCH (-322) indicates hostname verification failure.
  16271. int low_err = ssl_error; // wolfSSL_get_error returns the low-level code
  16272. if (low_err == DOMAIN_NAME_MISMATCH) {
  16273. return ErrorCode::HostnameMismatch;
  16274. }
  16275. // Check verify result to distinguish cert verification from generic SSL
  16276. // errors.
  16277. long vr = wolfSSL_get_verify_result(ssl);
  16278. if (vr != 0) { return ErrorCode::CertVerifyFailed; }
  16279. }
  16280. return ErrorCode::Fatal;
  16281. }
  16282. }
  16283. // WolfSSLContext constructor/destructor implementations
  16284. inline WolfSSLContext::WolfSSLContext() { wolfSSL_Init(); }
  16285. inline WolfSSLContext::~WolfSSLContext() {
  16286. if (ctx) { wolfSSL_CTX_free(ctx); }
  16287. }
  16288. // Thread-local storage for SNI captured during handshake
  16289. inline std::string &wolfssl_pending_sni() {
  16290. static thread_local std::string sni;
  16291. return sni;
  16292. }
  16293. // SNI callback for wolfSSL server to capture client's SNI hostname
  16294. inline int wolfssl_sni_callback(WOLFSSL *ssl, int *ret, void *exArg) {
  16295. (void)ret;
  16296. (void)exArg;
  16297. void *name_data = nullptr;
  16298. unsigned short name_len =
  16299. wolfSSL_SNI_GetRequest(ssl, WOLFSSL_SNI_HOST_NAME, &name_data);
  16300. if (name_data && name_len > 0) {
  16301. wolfssl_pending_sni().assign(static_cast<const char *>(name_data),
  16302. name_len);
  16303. } else {
  16304. wolfssl_pending_sni().clear();
  16305. }
  16306. return 0; // Continue regardless
  16307. }
  16308. // wolfSSL verify callback wrapper
  16309. inline int wolfssl_verify_callback(int preverify_ok,
  16310. WOLFSSL_X509_STORE_CTX *x509_ctx) {
  16311. auto &callback = get_verify_callback();
  16312. if (!callback) { return preverify_ok; }
  16313. WOLFSSL_X509 *cert = wolfSSL_X509_STORE_CTX_get_current_cert(x509_ctx);
  16314. int depth = wolfSSL_X509_STORE_CTX_get_error_depth(x509_ctx);
  16315. int err = wolfSSL_X509_STORE_CTX_get_error(x509_ctx);
  16316. // Get the WOLFSSL object from the X509_STORE_CTX
  16317. WOLFSSL *ssl = static_cast<WOLFSSL *>(wolfSSL_X509_STORE_CTX_get_ex_data(
  16318. x509_ctx, wolfSSL_get_ex_data_X509_STORE_CTX_idx()));
  16319. VerifyContext verify_ctx;
  16320. verify_ctx.session = static_cast<session_t>(ssl);
  16321. verify_ctx.cert = static_cast<cert_t>(cert);
  16322. verify_ctx.depth = depth;
  16323. verify_ctx.preverify_ok = (preverify_ok != 0);
  16324. verify_ctx.error_code = static_cast<long>(err);
  16325. if (err != 0) {
  16326. verify_ctx.error_string = wolfSSL_X509_verify_cert_error_string(err);
  16327. } else {
  16328. verify_ctx.error_string = nullptr;
  16329. }
  16330. bool accepted = callback(verify_ctx);
  16331. return accepted ? 1 : 0;
  16332. }
  16333. inline void set_wolfssl_password_cb(WOLFSSL_CTX *ctx, const char *password) {
  16334. wolfSSL_CTX_set_default_passwd_cb_userdata(ctx, const_cast<char *>(password));
  16335. wolfSSL_CTX_set_default_passwd_cb(
  16336. ctx, [](char *buf, int size, int /*rwflag*/, void *userdata) -> int {
  16337. auto *pwd = static_cast<const char *>(userdata);
  16338. if (!pwd) return 0;
  16339. auto len = static_cast<int>(strlen(pwd));
  16340. if (len > size) len = size;
  16341. memcpy(buf, pwd, static_cast<size_t>(len));
  16342. return len;
  16343. });
  16344. }
  16345. } // namespace impl
  16346. inline ctx_t create_client_context() {
  16347. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16348. if (!ctx) { return nullptr; }
  16349. ctx->is_server = false;
  16350. WOLFSSL_METHOD *method = wolfTLSv1_2_client_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: verify peer certificate
  16361. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_PEER, nullptr);
  16362. return static_cast<ctx_t>(ctx);
  16363. }
  16364. inline ctx_t create_server_context() {
  16365. auto ctx = new (std::nothrow) impl::WolfSSLContext();
  16366. if (!ctx) { return nullptr; }
  16367. ctx->is_server = true;
  16368. WOLFSSL_METHOD *method = wolfTLSv1_2_server_method();
  16369. if (!method) {
  16370. delete ctx;
  16371. return nullptr;
  16372. }
  16373. ctx->ctx = wolfSSL_CTX_new(method);
  16374. if (!ctx->ctx) {
  16375. delete ctx;
  16376. return nullptr;
  16377. }
  16378. // Default: don't verify client
  16379. wolfSSL_CTX_set_verify(ctx->ctx, SSL_VERIFY_NONE, nullptr);
  16380. // Enable SNI on server
  16381. wolfSSL_CTX_SNI_SetOptions(ctx->ctx, WOLFSSL_SNI_HOST_NAME,
  16382. WOLFSSL_SNI_CONTINUE_ON_MISMATCH);
  16383. wolfSSL_CTX_set_servername_callback(ctx->ctx, impl::wolfssl_sni_callback);
  16384. return static_cast<ctx_t>(ctx);
  16385. }
  16386. inline void free_context(ctx_t ctx) {
  16387. if (ctx) { delete static_cast<impl::WolfSSLContext *>(ctx); }
  16388. }
  16389. inline bool set_min_version(ctx_t ctx, Version version) {
  16390. if (!ctx) { return false; }
  16391. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16392. int min_ver = WOLFSSL_TLSV1_2;
  16393. if (version >= Version::TLS1_3) { min_ver = WOLFSSL_TLSV1_3; }
  16394. return wolfSSL_CTX_SetMinVersion(wctx->ctx, min_ver) == WOLFSSL_SUCCESS;
  16395. }
  16396. inline bool load_ca_pem(ctx_t ctx, const char *pem, size_t len) {
  16397. if (!ctx || !pem) { return false; }
  16398. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16399. int ret = wolfSSL_CTX_load_verify_buffer(
  16400. wctx->ctx, reinterpret_cast<const unsigned char *>(pem),
  16401. static_cast<long>(len), SSL_FILETYPE_PEM);
  16402. if (ret != SSL_SUCCESS) {
  16403. impl::wolfssl_last_error() =
  16404. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16405. return false;
  16406. }
  16407. wctx->ca_pem_data_.append(pem, len);
  16408. return true;
  16409. }
  16410. inline bool load_ca_file(ctx_t ctx, const char *file_path) {
  16411. if (!ctx || !file_path) { return false; }
  16412. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16413. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, file_path, nullptr);
  16414. if (ret != SSL_SUCCESS) {
  16415. impl::wolfssl_last_error() =
  16416. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16417. return false;
  16418. }
  16419. return true;
  16420. }
  16421. inline bool load_ca_dir(ctx_t ctx, const char *dir_path) {
  16422. if (!ctx || !dir_path) { return false; }
  16423. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16424. int ret = wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, dir_path);
  16425. // wolfSSL may fail if the directory doesn't contain properly hashed certs.
  16426. // Unlike OpenSSL which lazily loads certs from directories, wolfSSL scans
  16427. // immediately. Return true even on failure since the CA file may have
  16428. // already been loaded, matching OpenSSL's lenient behavior.
  16429. (void)ret;
  16430. return true;
  16431. }
  16432. inline bool load_system_certs(ctx_t ctx) {
  16433. if (!ctx) { return false; }
  16434. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16435. bool loaded = false;
  16436. #ifdef _WIN32
  16437. loaded = impl::enumerate_windows_system_certs(
  16438. [&](const unsigned char *data, size_t len) {
  16439. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16440. static_cast<long>(len),
  16441. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16442. });
  16443. #elif defined(__APPLE__) && defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  16444. loaded = impl::enumerate_macos_keychain_certs(
  16445. [&](const unsigned char *data, size_t len) {
  16446. return wolfSSL_CTX_load_verify_buffer(wctx->ctx, data,
  16447. static_cast<long>(len),
  16448. SSL_FILETYPE_ASN1) == SSL_SUCCESS;
  16449. });
  16450. #else
  16451. for (auto path = impl::system_ca_paths(); *path; ++path) {
  16452. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, *path, nullptr) ==
  16453. SSL_SUCCESS) {
  16454. loaded = true;
  16455. break;
  16456. }
  16457. }
  16458. if (!loaded) {
  16459. for (auto dir = impl::system_ca_dirs(); *dir; ++dir) {
  16460. if (wolfSSL_CTX_load_verify_locations(wctx->ctx, nullptr, *dir) ==
  16461. SSL_SUCCESS) {
  16462. loaded = true;
  16463. break;
  16464. }
  16465. }
  16466. }
  16467. #endif
  16468. return loaded;
  16469. }
  16470. inline bool set_client_cert_pem(ctx_t ctx, const char *cert, const char *key,
  16471. const char *password) {
  16472. if (!ctx || !cert || !key) { return false; }
  16473. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16474. // Load certificate
  16475. int ret = wolfSSL_CTX_use_certificate_buffer(
  16476. wctx->ctx, reinterpret_cast<const unsigned char *>(cert),
  16477. static_cast<long>(strlen(cert)), SSL_FILETYPE_PEM);
  16478. if (ret != SSL_SUCCESS) {
  16479. impl::wolfssl_last_error() =
  16480. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16481. return false;
  16482. }
  16483. // Set password callback if password is provided
  16484. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16485. // Load private key
  16486. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  16487. wctx->ctx, reinterpret_cast<const unsigned char *>(key),
  16488. static_cast<long>(strlen(key)), SSL_FILETYPE_PEM);
  16489. if (ret != SSL_SUCCESS) {
  16490. impl::wolfssl_last_error() =
  16491. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16492. return false;
  16493. }
  16494. // Verify that the certificate and private key match
  16495. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16496. }
  16497. inline bool set_client_cert_file(ctx_t ctx, const char *cert_path,
  16498. const char *key_path, const char *password) {
  16499. if (!ctx || !cert_path || !key_path) { return false; }
  16500. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16501. // Load certificate file
  16502. int ret =
  16503. wolfSSL_CTX_use_certificate_file(wctx->ctx, cert_path, SSL_FILETYPE_PEM);
  16504. if (ret != SSL_SUCCESS) {
  16505. impl::wolfssl_last_error() =
  16506. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16507. return false;
  16508. }
  16509. // Set password callback if password is provided
  16510. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  16511. // Load private key file
  16512. ret = wolfSSL_CTX_use_PrivateKey_file(wctx->ctx, key_path, SSL_FILETYPE_PEM);
  16513. if (ret != SSL_SUCCESS) {
  16514. impl::wolfssl_last_error() =
  16515. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16516. return false;
  16517. }
  16518. // Verify that the certificate and private key match
  16519. return wolfSSL_CTX_check_private_key(wctx->ctx) == SSL_SUCCESS;
  16520. }
  16521. inline void set_verify_client(ctx_t ctx, bool require) {
  16522. if (!ctx) { return; }
  16523. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16524. wctx->verify_client = require;
  16525. if (require) {
  16526. wolfSSL_CTX_set_verify(
  16527. wctx->ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
  16528. wctx->has_verify_callback ? impl::wolfssl_verify_callback : nullptr);
  16529. } else {
  16530. if (wctx->has_verify_callback) {
  16531. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  16532. impl::wolfssl_verify_callback);
  16533. } else {
  16534. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_NONE, nullptr);
  16535. }
  16536. }
  16537. }
  16538. inline session_t create_session(ctx_t ctx, socket_t sock) {
  16539. if (!ctx || sock == INVALID_SOCKET) { return nullptr; }
  16540. auto wctx = static_cast<impl::WolfSSLContext *>(ctx);
  16541. auto session = new (std::nothrow) impl::WolfSSLSession();
  16542. if (!session) { return nullptr; }
  16543. session->sock = sock;
  16544. session->ssl = wolfSSL_new(wctx->ctx);
  16545. if (!session->ssl) {
  16546. impl::wolfssl_last_error() =
  16547. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16548. delete session;
  16549. return nullptr;
  16550. }
  16551. wolfSSL_set_fd(session->ssl, static_cast<int>(sock));
  16552. return static_cast<session_t>(session);
  16553. }
  16554. inline void free_session(session_t session) {
  16555. if (session) { delete static_cast<impl::WolfSSLSession *>(session); }
  16556. }
  16557. inline bool set_sni(session_t session, const char *hostname) {
  16558. if (!session || !hostname) { return false; }
  16559. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16560. int ret = wolfSSL_UseSNI(wsession->ssl, WOLFSSL_SNI_HOST_NAME, hostname,
  16561. static_cast<word16>(strlen(hostname)));
  16562. if (ret != WOLFSSL_SUCCESS) {
  16563. impl::wolfssl_last_error() =
  16564. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  16565. return false;
  16566. }
  16567. // Also set hostname for verification
  16568. wolfSSL_check_domain_name(wsession->ssl, hostname);
  16569. wsession->hostname = hostname;
  16570. return true;
  16571. }
  16572. inline bool set_hostname(session_t session, const char *hostname) {
  16573. // In wolfSSL, set_hostname also sets up hostname verification
  16574. return set_sni(session, hostname);
  16575. }
  16576. inline TlsError connect(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_connect(wsession->ssl);
  16584. if (ret == SSL_SUCCESS) {
  16585. err.code = ErrorCode::Success;
  16586. } else {
  16587. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16588. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16589. err.backend_code = static_cast<uint64_t>(ssl_error);
  16590. impl::wolfssl_last_error() = err.backend_code;
  16591. }
  16592. return err;
  16593. }
  16594. inline TlsError accept(session_t session) {
  16595. TlsError err;
  16596. if (!session) {
  16597. err.code = ErrorCode::Fatal;
  16598. return err;
  16599. }
  16600. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16601. int ret = wolfSSL_accept(wsession->ssl);
  16602. if (ret == SSL_SUCCESS) {
  16603. err.code = ErrorCode::Success;
  16604. // Capture SNI from thread-local storage after successful handshake
  16605. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16606. impl::wolfssl_pending_sni().clear();
  16607. } else {
  16608. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16609. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16610. err.backend_code = static_cast<uint64_t>(ssl_error);
  16611. impl::wolfssl_last_error() = err.backend_code;
  16612. }
  16613. return err;
  16614. }
  16615. inline bool connect_nonblocking(session_t session, socket_t sock,
  16616. time_t timeout_sec, time_t timeout_usec,
  16617. TlsError *err) {
  16618. if (!session) {
  16619. if (err) { err->code = ErrorCode::Fatal; }
  16620. return false;
  16621. }
  16622. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16623. // Set socket to non-blocking mode
  16624. detail::set_nonblocking(sock, true);
  16625. auto cleanup =
  16626. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16627. int ret;
  16628. while ((ret = wolfSSL_connect(wsession->ssl)) != SSL_SUCCESS) {
  16629. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16630. if (ssl_error == SSL_ERROR_WANT_READ) {
  16631. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16632. continue;
  16633. }
  16634. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16635. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16636. continue;
  16637. }
  16638. }
  16639. // Error or timeout
  16640. if (err) {
  16641. err->code =
  16642. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16643. err->backend_code = static_cast<uint64_t>(ssl_error);
  16644. }
  16645. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16646. return false;
  16647. }
  16648. if (err) { err->code = ErrorCode::Success; }
  16649. return true;
  16650. }
  16651. inline bool accept_nonblocking(session_t session, socket_t sock,
  16652. time_t timeout_sec, time_t timeout_usec,
  16653. TlsError *err) {
  16654. if (!session) {
  16655. if (err) { err->code = ErrorCode::Fatal; }
  16656. return false;
  16657. }
  16658. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16659. // Set socket to non-blocking mode
  16660. detail::set_nonblocking(sock, true);
  16661. auto cleanup =
  16662. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16663. int ret;
  16664. while ((ret = wolfSSL_accept(wsession->ssl)) != SSL_SUCCESS) {
  16665. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16666. if (ssl_error == SSL_ERROR_WANT_READ) {
  16667. if (detail::select_read(sock, timeout_sec, timeout_usec) > 0) {
  16668. continue;
  16669. }
  16670. } else if (ssl_error == SSL_ERROR_WANT_WRITE) {
  16671. if (detail::select_write(sock, timeout_sec, timeout_usec) > 0) {
  16672. continue;
  16673. }
  16674. }
  16675. // Error or timeout
  16676. if (err) {
  16677. err->code =
  16678. impl::map_wolfssl_error(wsession->ssl, ssl_error, err->sys_errno);
  16679. err->backend_code = static_cast<uint64_t>(ssl_error);
  16680. }
  16681. impl::wolfssl_last_error() = static_cast<uint64_t>(ssl_error);
  16682. return false;
  16683. }
  16684. if (err) { err->code = ErrorCode::Success; }
  16685. // Capture SNI from thread-local storage after successful handshake
  16686. wsession->sni_hostname = std::move(impl::wolfssl_pending_sni());
  16687. impl::wolfssl_pending_sni().clear();
  16688. return true;
  16689. }
  16690. inline ssize_t read(session_t session, void *buf, size_t len, TlsError &err) {
  16691. if (!session || !buf) {
  16692. err.code = ErrorCode::Fatal;
  16693. return -1;
  16694. }
  16695. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16696. int ret = wolfSSL_read(wsession->ssl, buf, static_cast<int>(len));
  16697. if (ret > 0) {
  16698. err.code = ErrorCode::Success;
  16699. return static_cast<ssize_t>(ret);
  16700. }
  16701. if (ret == 0) {
  16702. err.code = ErrorCode::PeerClosed;
  16703. return 0;
  16704. }
  16705. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16706. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16707. err.backend_code = static_cast<uint64_t>(ssl_error);
  16708. impl::wolfssl_last_error() = err.backend_code;
  16709. return -1;
  16710. }
  16711. inline ssize_t write(session_t session, const void *buf, size_t len,
  16712. TlsError &err) {
  16713. if (!session || !buf) {
  16714. err.code = ErrorCode::Fatal;
  16715. return -1;
  16716. }
  16717. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16718. int ret = wolfSSL_write(wsession->ssl, buf, static_cast<int>(len));
  16719. if (ret > 0) {
  16720. err.code = ErrorCode::Success;
  16721. return static_cast<ssize_t>(ret);
  16722. }
  16723. // wolfSSL_write returns 0 when the peer has sent a close_notify.
  16724. // Treat this as an error (return -1) so callers don't spin in a
  16725. // write loop adding zero to the offset.
  16726. if (ret == 0) {
  16727. err.code = ErrorCode::PeerClosed;
  16728. return -1;
  16729. }
  16730. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16731. err.code = impl::map_wolfssl_error(wsession->ssl, ssl_error, err.sys_errno);
  16732. err.backend_code = static_cast<uint64_t>(ssl_error);
  16733. impl::wolfssl_last_error() = err.backend_code;
  16734. return -1;
  16735. }
  16736. inline int pending(const_session_t session) {
  16737. if (!session) { return 0; }
  16738. auto wsession =
  16739. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16740. return wolfSSL_pending(wsession->ssl);
  16741. }
  16742. inline void shutdown(session_t session, bool graceful) {
  16743. if (!session) { return; }
  16744. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16745. if (graceful) {
  16746. int ret;
  16747. int attempts = 0;
  16748. while ((ret = wolfSSL_shutdown(wsession->ssl)) != SSL_SUCCESS &&
  16749. attempts < 3) {
  16750. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16751. if (ssl_error != SSL_ERROR_WANT_READ &&
  16752. ssl_error != SSL_ERROR_WANT_WRITE) {
  16753. break;
  16754. }
  16755. attempts++;
  16756. }
  16757. } else {
  16758. wolfSSL_shutdown(wsession->ssl);
  16759. }
  16760. }
  16761. inline bool is_peer_closed(session_t session, socket_t sock) {
  16762. if (!session || sock == INVALID_SOCKET) { return true; }
  16763. auto wsession = static_cast<impl::WolfSSLSession *>(session);
  16764. // Check if there's already decrypted data available
  16765. if (wolfSSL_pending(wsession->ssl) > 0) { return false; }
  16766. // Set socket to non-blocking to avoid blocking on read
  16767. detail::set_nonblocking(sock, true);
  16768. auto cleanup =
  16769. detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  16770. // Peek 1 byte to check connection status without consuming data
  16771. unsigned char buf;
  16772. int ret = wolfSSL_peek(wsession->ssl, &buf, 1);
  16773. // If we got data or WANT_READ (would block), connection is alive
  16774. if (ret > 0) { return false; }
  16775. int ssl_error = wolfSSL_get_error(wsession->ssl, ret);
  16776. if (ssl_error == SSL_ERROR_WANT_READ) { return false; }
  16777. return ssl_error == SSL_ERROR_ZERO_RETURN || ssl_error == SSL_ERROR_SYSCALL ||
  16778. ret == 0;
  16779. }
  16780. inline cert_t get_peer_cert(const_session_t session) {
  16781. if (!session) { return nullptr; }
  16782. auto wsession =
  16783. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16784. WOLFSSL_X509 *cert = wolfSSL_get_peer_certificate(wsession->ssl);
  16785. return static_cast<cert_t>(cert);
  16786. }
  16787. inline void free_cert(cert_t cert) {
  16788. if (cert) { wolfSSL_X509_free(static_cast<WOLFSSL_X509 *>(cert)); }
  16789. }
  16790. inline bool verify_hostname(cert_t cert, const char *hostname) {
  16791. if (!cert || !hostname) { return false; }
  16792. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16793. std::string host_str(hostname);
  16794. // Check if hostname is an IP address (IPv4 or IPv6)
  16795. unsigned char ip_bytes[16];
  16796. auto ip_len = impl::parse_ip_address(host_str, ip_bytes);
  16797. auto is_ip = ip_len > 0;
  16798. // Check Subject Alternative Names
  16799. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16800. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16801. if (san_names) {
  16802. int san_count = wolfSSL_sk_num(san_names);
  16803. for (int i = 0; i < san_count; i++) {
  16804. auto *names =
  16805. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16806. if (!names) continue;
  16807. if (!is_ip && names->type == WOLFSSL_GEN_DNS) {
  16808. // DNS name
  16809. unsigned char *dns_name = nullptr;
  16810. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, names->d.dNSName);
  16811. if (dns_name && dns_len > 0) {
  16812. std::string san_name(reinterpret_cast<char *>(dns_name),
  16813. static_cast<size_t>(dns_len));
  16814. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16815. if (detail::match_hostname(san_name, host_str)) {
  16816. wolfSSL_sk_free(san_names);
  16817. return true;
  16818. }
  16819. }
  16820. } else if (is_ip && names->type == WOLFSSL_GEN_IPADD) {
  16821. // IP address: only an iPAddress SAN of the same family (4 bytes for
  16822. // IPv4, 16 bytes for IPv6) may authenticate the host.
  16823. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(names->d.iPAddress);
  16824. auto san_ip_len = wolfSSL_ASN1_STRING_length(names->d.iPAddress);
  16825. if (ip_data && san_ip_len == static_cast<int>(ip_len) &&
  16826. memcmp(ip_data, ip_bytes, ip_len) == 0) {
  16827. wolfSSL_sk_free(san_names);
  16828. return true;
  16829. }
  16830. }
  16831. }
  16832. wolfSSL_sk_free(san_names);
  16833. }
  16834. // Fallback: Check Common Name (CN) in subject. Skipped for IP-literal hosts:
  16835. // an IP identity is only valid via an iPAddress SAN, never the CN (RFC 9110;
  16836. // the OpenSSL backend's X509_check_ip behaves the same way).
  16837. auto subject = is_ip ? nullptr : wolfSSL_X509_get_subject_name(x509);
  16838. if (subject) {
  16839. char cn[256] = {};
  16840. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16841. sizeof(cn));
  16842. if (cn_len > 0) {
  16843. std::string cn_str(cn, static_cast<size_t>(cn_len));
  16844. if (detail::match_hostname(cn_str, host_str)) { return true; }
  16845. }
  16846. }
  16847. return false;
  16848. }
  16849. inline uint64_t hostname_mismatch_code() {
  16850. return static_cast<uint64_t>(DOMAIN_NAME_MISMATCH);
  16851. }
  16852. inline long get_verify_result(const_session_t session) {
  16853. if (!session) { return -1; }
  16854. auto wsession =
  16855. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  16856. long result = wolfSSL_get_verify_result(wsession->ssl);
  16857. return result;
  16858. }
  16859. inline std::string get_cert_subject_cn(cert_t cert) {
  16860. if (!cert) return "";
  16861. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16862. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  16863. if (!subject) return "";
  16864. char cn[256] = {};
  16865. int cn_len = wolfSSL_X509_NAME_get_text_by_NID(subject, NID_commonName, cn,
  16866. sizeof(cn));
  16867. if (cn_len <= 0) return "";
  16868. return std::string(cn, static_cast<size_t>(cn_len));
  16869. }
  16870. inline std::string get_cert_issuer_name(cert_t cert) {
  16871. if (!cert) return "";
  16872. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16873. WOLFSSL_X509_NAME *issuer = wolfSSL_X509_get_issuer_name(x509);
  16874. if (!issuer) return "";
  16875. char *name_str = wolfSSL_X509_NAME_oneline(issuer, nullptr, 0);
  16876. if (!name_str) return "";
  16877. std::string result(name_str);
  16878. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  16879. return result;
  16880. }
  16881. inline bool get_cert_sans(cert_t cert, std::vector<SanEntry> &sans) {
  16882. sans.clear();
  16883. if (!cert) return false;
  16884. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16885. auto *san_names = static_cast<WOLF_STACK_OF(WOLFSSL_GENERAL_NAME) *>(
  16886. wolfSSL_X509_get_ext_d2i(x509, NID_subject_alt_name, nullptr, nullptr));
  16887. if (!san_names) return true; // No SANs is not an error
  16888. int count = wolfSSL_sk_num(san_names);
  16889. for (int i = 0; i < count; i++) {
  16890. auto *name =
  16891. static_cast<WOLFSSL_GENERAL_NAME *>(wolfSSL_sk_value(san_names, i));
  16892. if (!name) continue;
  16893. SanEntry entry;
  16894. switch (name->type) {
  16895. case WOLFSSL_GEN_DNS: {
  16896. entry.type = SanType::DNS;
  16897. unsigned char *dns_name = nullptr;
  16898. int dns_len = wolfSSL_ASN1_STRING_to_UTF8(&dns_name, name->d.dNSName);
  16899. if (dns_name && dns_len > 0) {
  16900. entry.value = std::string(reinterpret_cast<char *>(dns_name),
  16901. static_cast<size_t>(dns_len));
  16902. XFREE(dns_name, nullptr, DYNAMIC_TYPE_OPENSSL);
  16903. }
  16904. break;
  16905. }
  16906. case WOLFSSL_GEN_IPADD: {
  16907. entry.type = SanType::IP;
  16908. unsigned char *ip_data = wolfSSL_ASN1_STRING_data(name->d.iPAddress);
  16909. int ip_len = wolfSSL_ASN1_STRING_length(name->d.iPAddress);
  16910. if (ip_data && ip_len == 4) {
  16911. char buf[16];
  16912. snprintf(buf, sizeof(buf), "%d.%d.%d.%d", ip_data[0], ip_data[1],
  16913. ip_data[2], ip_data[3]);
  16914. entry.value = buf;
  16915. } else if (ip_data && ip_len == 16) {
  16916. char buf[64];
  16917. snprintf(buf, sizeof(buf),
  16918. "%02x%02x:%02x%02x:%02x%02x:%02x%02x:"
  16919. "%02x%02x:%02x%02x:%02x%02x:%02x%02x",
  16920. ip_data[0], ip_data[1], ip_data[2], ip_data[3], ip_data[4],
  16921. ip_data[5], ip_data[6], ip_data[7], ip_data[8], ip_data[9],
  16922. ip_data[10], ip_data[11], ip_data[12], ip_data[13],
  16923. ip_data[14], ip_data[15]);
  16924. entry.value = buf;
  16925. }
  16926. break;
  16927. }
  16928. case WOLFSSL_GEN_EMAIL:
  16929. entry.type = SanType::EMAIL;
  16930. {
  16931. unsigned char *email = nullptr;
  16932. int email_len = wolfSSL_ASN1_STRING_to_UTF8(&email, name->d.rfc822Name);
  16933. if (email && email_len > 0) {
  16934. entry.value = std::string(reinterpret_cast<char *>(email),
  16935. static_cast<size_t>(email_len));
  16936. XFREE(email, nullptr, DYNAMIC_TYPE_OPENSSL);
  16937. }
  16938. }
  16939. break;
  16940. case WOLFSSL_GEN_URI:
  16941. entry.type = SanType::URI;
  16942. {
  16943. unsigned char *uri = nullptr;
  16944. int uri_len = wolfSSL_ASN1_STRING_to_UTF8(
  16945. &uri, name->d.uniformResourceIdentifier);
  16946. if (uri && uri_len > 0) {
  16947. entry.value = std::string(reinterpret_cast<char *>(uri),
  16948. static_cast<size_t>(uri_len));
  16949. XFREE(uri, nullptr, DYNAMIC_TYPE_OPENSSL);
  16950. }
  16951. }
  16952. break;
  16953. default: entry.type = SanType::OTHER; break;
  16954. }
  16955. if (!entry.value.empty()) { sans.push_back(std::move(entry)); }
  16956. }
  16957. wolfSSL_sk_free(san_names);
  16958. return true;
  16959. }
  16960. inline bool get_cert_validity(cert_t cert, time_t &not_before,
  16961. time_t &not_after) {
  16962. if (!cert) return false;
  16963. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16964. const WOLFSSL_ASN1_TIME *nb = wolfSSL_X509_get_notBefore(x509);
  16965. const WOLFSSL_ASN1_TIME *na = wolfSSL_X509_get_notAfter(x509);
  16966. if (!nb || !na) return false;
  16967. // wolfSSL_ASN1_TIME_to_tm is available
  16968. struct tm tm_nb = {}, tm_na = {};
  16969. if (wolfSSL_ASN1_TIME_to_tm(nb, &tm_nb) != WOLFSSL_SUCCESS) return false;
  16970. if (wolfSSL_ASN1_TIME_to_tm(na, &tm_na) != WOLFSSL_SUCCESS) return false;
  16971. #ifdef _WIN32
  16972. not_before = _mkgmtime(&tm_nb);
  16973. not_after = _mkgmtime(&tm_na);
  16974. #else
  16975. not_before = timegm(&tm_nb);
  16976. not_after = timegm(&tm_na);
  16977. #endif
  16978. return true;
  16979. }
  16980. inline std::string get_cert_serial(cert_t cert) {
  16981. if (!cert) return "";
  16982. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  16983. WOLFSSL_ASN1_INTEGER *serial_asn1 = wolfSSL_X509_get_serialNumber(x509);
  16984. if (!serial_asn1) return "";
  16985. // Get the serial number data
  16986. int len = serial_asn1->length;
  16987. unsigned char *data = serial_asn1->data;
  16988. if (!data || len <= 0) return "";
  16989. std::string result;
  16990. result.reserve(static_cast<size_t>(len) * 2);
  16991. for (int i = 0; i < len; i++) {
  16992. char hex[3];
  16993. snprintf(hex, sizeof(hex), "%02X", data[i]);
  16994. result += hex;
  16995. }
  16996. return result;
  16997. }
  16998. inline bool get_cert_der(cert_t cert, std::vector<unsigned char> &der) {
  16999. if (!cert) return false;
  17000. auto x509 = static_cast<WOLFSSL_X509 *>(cert);
  17001. int der_len = 0;
  17002. const unsigned char *der_data = wolfSSL_X509_get_der(x509, &der_len);
  17003. if (!der_data || der_len <= 0) return false;
  17004. der.assign(der_data, der_data + der_len);
  17005. return true;
  17006. }
  17007. inline const char *get_sni(const_session_t session) {
  17008. if (!session) return nullptr;
  17009. auto wsession = static_cast<const impl::WolfSSLSession *>(session);
  17010. // For server: return SNI received from client during handshake
  17011. if (!wsession->sni_hostname.empty()) {
  17012. return wsession->sni_hostname.c_str();
  17013. }
  17014. // For client: return the hostname set via set_sni
  17015. if (!wsession->hostname.empty()) { return wsession->hostname.c_str(); }
  17016. return nullptr;
  17017. }
  17018. inline uint64_t peek_error() {
  17019. return static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17020. }
  17021. inline uint64_t get_error() {
  17022. uint64_t err = impl::wolfssl_last_error();
  17023. impl::wolfssl_last_error() = 0;
  17024. return err;
  17025. }
  17026. inline std::string error_string(uint64_t code) {
  17027. char buf[256];
  17028. wolfSSL_ERR_error_string(static_cast<unsigned long>(code), buf);
  17029. return std::string(buf);
  17030. }
  17031. inline ca_store_t create_ca_store(const char *pem, size_t len) {
  17032. if (!pem || len == 0) { return nullptr; }
  17033. // Validate by attempting to load into a temporary ctx
  17034. WOLFSSL_CTX *tmp_ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  17035. if (!tmp_ctx) { return nullptr; }
  17036. int ret = wolfSSL_CTX_load_verify_buffer(
  17037. tmp_ctx, reinterpret_cast<const unsigned char *>(pem),
  17038. static_cast<long>(len), SSL_FILETYPE_PEM);
  17039. wolfSSL_CTX_free(tmp_ctx);
  17040. if (ret != SSL_SUCCESS) { return nullptr; }
  17041. return static_cast<ca_store_t>(
  17042. new impl::WolfSSLCAStore{std::string(pem, len)});
  17043. }
  17044. inline void free_ca_store(ca_store_t store) {
  17045. delete static_cast<impl::WolfSSLCAStore *>(store);
  17046. }
  17047. inline bool set_ca_store(ctx_t ctx, ca_store_t store) {
  17048. if (!ctx || !store) { return false; }
  17049. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17050. auto *ca = static_cast<impl::WolfSSLCAStore *>(store);
  17051. int ret = wolfSSL_CTX_load_verify_buffer(
  17052. wctx->ctx, reinterpret_cast<const unsigned char *>(ca->pem_data.data()),
  17053. static_cast<long>(ca->pem_data.size()), SSL_FILETYPE_PEM);
  17054. if (ret == SSL_SUCCESS) { wctx->ca_pem_data_ += ca->pem_data; }
  17055. // This function takes ownership of the store; the PEM data was copied into
  17056. // the context, so release the source
  17057. free_ca_store(store);
  17058. return ret == SSL_SUCCESS;
  17059. }
  17060. inline size_t get_ca_certs(ctx_t ctx, std::vector<cert_t> &certs) {
  17061. certs.clear();
  17062. if (!ctx) { return 0; }
  17063. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17064. if (wctx->ca_pem_data_.empty()) { return 0; }
  17065. const std::string &pem = wctx->ca_pem_data_;
  17066. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17067. const std::string end_marker = "-----END CERTIFICATE-----";
  17068. size_t pos = 0;
  17069. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17070. size_t end_pos = pem.find(end_marker, pos);
  17071. if (end_pos == std::string::npos) { break; }
  17072. end_pos += end_marker.size();
  17073. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17074. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17075. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17076. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17077. if (x509) { certs.push_back(static_cast<cert_t>(x509)); }
  17078. pos = end_pos;
  17079. }
  17080. return certs.size();
  17081. }
  17082. inline std::vector<std::string> get_ca_names(ctx_t ctx) {
  17083. std::vector<std::string> names;
  17084. if (!ctx) { return names; }
  17085. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17086. if (wctx->ca_pem_data_.empty()) { return names; }
  17087. const std::string &pem = wctx->ca_pem_data_;
  17088. const std::string begin_marker = "-----BEGIN CERTIFICATE-----";
  17089. const std::string end_marker = "-----END CERTIFICATE-----";
  17090. size_t pos = 0;
  17091. while ((pos = pem.find(begin_marker, pos)) != std::string::npos) {
  17092. size_t end_pos = pem.find(end_marker, pos);
  17093. if (end_pos == std::string::npos) { break; }
  17094. end_pos += end_marker.size();
  17095. std::string cert_pem = pem.substr(pos, end_pos - pos);
  17096. WOLFSSL_X509 *x509 = wolfSSL_X509_load_certificate_buffer(
  17097. reinterpret_cast<const unsigned char *>(cert_pem.data()),
  17098. static_cast<int>(cert_pem.size()), WOLFSSL_FILETYPE_PEM);
  17099. if (x509) {
  17100. WOLFSSL_X509_NAME *subject = wolfSSL_X509_get_subject_name(x509);
  17101. if (subject) {
  17102. char *name_str = wolfSSL_X509_NAME_oneline(subject, nullptr, 0);
  17103. if (name_str) {
  17104. names.push_back(name_str);
  17105. XFREE(name_str, nullptr, DYNAMIC_TYPE_OPENSSL);
  17106. }
  17107. }
  17108. wolfSSL_X509_free(x509);
  17109. }
  17110. pos = end_pos;
  17111. }
  17112. return names;
  17113. }
  17114. inline bool update_server_cert(ctx_t ctx, const char *cert_pem,
  17115. const char *key_pem, const char *password) {
  17116. if (!ctx || !cert_pem || !key_pem) { return false; }
  17117. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17118. // Load new certificate
  17119. int ret = wolfSSL_CTX_use_certificate_buffer(
  17120. wctx->ctx, reinterpret_cast<const unsigned char *>(cert_pem),
  17121. static_cast<long>(strlen(cert_pem)), SSL_FILETYPE_PEM);
  17122. if (ret != SSL_SUCCESS) {
  17123. impl::wolfssl_last_error() =
  17124. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17125. return false;
  17126. }
  17127. // Set password if provided
  17128. if (password) { impl::set_wolfssl_password_cb(wctx->ctx, password); }
  17129. // Load new private key
  17130. ret = wolfSSL_CTX_use_PrivateKey_buffer(
  17131. wctx->ctx, reinterpret_cast<const unsigned char *>(key_pem),
  17132. static_cast<long>(strlen(key_pem)), SSL_FILETYPE_PEM);
  17133. if (ret != SSL_SUCCESS) {
  17134. impl::wolfssl_last_error() =
  17135. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17136. return false;
  17137. }
  17138. return true;
  17139. }
  17140. inline bool update_server_client_ca(ctx_t ctx, const char *ca_pem) {
  17141. if (!ctx || !ca_pem) { return false; }
  17142. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17143. int ret = wolfSSL_CTX_load_verify_buffer(
  17144. wctx->ctx, reinterpret_cast<const unsigned char *>(ca_pem),
  17145. static_cast<long>(strlen(ca_pem)), SSL_FILETYPE_PEM);
  17146. if (ret != SSL_SUCCESS) {
  17147. impl::wolfssl_last_error() =
  17148. static_cast<uint64_t>(wolfSSL_ERR_peek_last_error());
  17149. return false;
  17150. }
  17151. return true;
  17152. }
  17153. inline bool set_verify_callback(ctx_t ctx, VerifyCallback callback) {
  17154. if (!ctx) { return false; }
  17155. auto *wctx = static_cast<impl::WolfSSLContext *>(ctx);
  17156. impl::get_verify_callback() = std::move(callback);
  17157. wctx->has_verify_callback = static_cast<bool>(impl::get_verify_callback());
  17158. if (wctx->has_verify_callback) {
  17159. wolfSSL_CTX_set_verify(wctx->ctx, SSL_VERIFY_PEER,
  17160. impl::wolfssl_verify_callback);
  17161. } else {
  17162. wolfSSL_CTX_set_verify(
  17163. wctx->ctx,
  17164. wctx->verify_client
  17165. ? (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
  17166. : SSL_VERIFY_NONE,
  17167. nullptr);
  17168. }
  17169. return true;
  17170. }
  17171. inline long get_verify_error(const_session_t session) {
  17172. if (!session) { return -1; }
  17173. auto *wsession =
  17174. static_cast<impl::WolfSSLSession *>(const_cast<void *>(session));
  17175. return wolfSSL_get_verify_result(wsession->ssl);
  17176. }
  17177. inline std::string verify_error_string(long error_code) {
  17178. if (error_code == 0) { return ""; }
  17179. const char *str =
  17180. wolfSSL_X509_verify_cert_error_string(static_cast<int>(error_code));
  17181. return str ? std::string(str) : std::string();
  17182. }
  17183. } // namespace tls
  17184. #endif // CPPHTTPLIB_WOLFSSL_SUPPORT
  17185. // WebSocket implementation
  17186. namespace ws {
  17187. inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
  17188. bool fin) {
  17189. std::lock_guard<std::mutex> lock(write_mutex_);
  17190. if (closed_) { return false; }
  17191. return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
  17192. }
  17193. inline ReadResult WebSocket::read(std::string &msg) {
  17194. while (!closed_) {
  17195. Opcode opcode;
  17196. std::string payload;
  17197. bool fin;
  17198. if (!impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
  17199. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17200. closed_ = true;
  17201. return Fail;
  17202. }
  17203. switch (opcode) {
  17204. case Opcode::Ping: {
  17205. std::lock_guard<std::mutex> lock(write_mutex_);
  17206. detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
  17207. payload.size(), true, !is_server_);
  17208. continue;
  17209. }
  17210. case Opcode::Pong: {
  17211. std::lock_guard<std::mutex> lock(ping_mutex_);
  17212. unacked_pings_ = 0;
  17213. continue;
  17214. }
  17215. case Opcode::Close: {
  17216. if (!closed_.exchange(true)) {
  17217. // Echo close frame back
  17218. std::lock_guard<std::mutex> lock(write_mutex_);
  17219. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17220. payload.size(), true, !is_server_);
  17221. }
  17222. return Fail;
  17223. }
  17224. case Opcode::Text:
  17225. case Opcode::Binary: {
  17226. auto result = opcode == Opcode::Text ? Text : Binary;
  17227. msg = std::move(payload);
  17228. // Handle fragmentation
  17229. if (!fin) {
  17230. while (true) {
  17231. Opcode cont_opcode;
  17232. std::string cont_payload;
  17233. bool cont_fin;
  17234. if (!impl::read_websocket_frame(
  17235. strm_, cont_opcode, cont_payload, cont_fin, is_server_,
  17236. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH)) {
  17237. closed_ = true;
  17238. return Fail;
  17239. }
  17240. if (cont_opcode == Opcode::Ping) {
  17241. std::lock_guard<std::mutex> lock(write_mutex_);
  17242. detail::write_websocket_frame(
  17243. strm_, Opcode::Pong, cont_payload.data(), cont_payload.size(),
  17244. true, !is_server_);
  17245. continue;
  17246. }
  17247. if (cont_opcode == Opcode::Pong) {
  17248. std::lock_guard<std::mutex> lock(ping_mutex_);
  17249. unacked_pings_ = 0;
  17250. continue;
  17251. }
  17252. if (cont_opcode == Opcode::Close) {
  17253. if (!closed_.exchange(true)) {
  17254. std::lock_guard<std::mutex> lock(write_mutex_);
  17255. detail::write_websocket_frame(
  17256. strm_, Opcode::Close, cont_payload.data(),
  17257. cont_payload.size(), true, !is_server_);
  17258. }
  17259. return Fail;
  17260. }
  17261. // RFC 6455: continuation frames must use opcode 0x0
  17262. if (cont_opcode != Opcode::Continuation) {
  17263. closed_ = true;
  17264. return Fail;
  17265. }
  17266. msg += cont_payload;
  17267. if (msg.size() > CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH) {
  17268. closed_ = true;
  17269. return Fail;
  17270. }
  17271. if (cont_fin) { break; }
  17272. }
  17273. }
  17274. // RFC 6455 Section 5.6: text frames must contain valid UTF-8
  17275. if (result == Text && !impl::is_valid_utf8(msg)) {
  17276. close(CloseStatus::InvalidPayload, "invalid UTF-8");
  17277. return Fail;
  17278. }
  17279. return result;
  17280. }
  17281. default: closed_ = true; return Fail;
  17282. }
  17283. }
  17284. return Fail;
  17285. }
  17286. inline bool WebSocket::send(const std::string &data) {
  17287. return send_frame(Opcode::Text, data.data(), data.size());
  17288. }
  17289. inline bool WebSocket::send(const char *data, size_t len) {
  17290. return send_frame(Opcode::Binary, data, len);
  17291. }
  17292. inline void WebSocket::close(CloseStatus status, const std::string &reason) {
  17293. if (closed_.exchange(true)) { return; }
  17294. ping_cv_.notify_all();
  17295. std::string payload;
  17296. auto code = static_cast<uint16_t>(status);
  17297. payload.push_back(static_cast<char>((code >> 8) & 0xFF));
  17298. payload.push_back(static_cast<char>(code & 0xFF));
  17299. // RFC 6455 Section 5.5: control frame payload must not exceed 125 bytes
  17300. // Close frame has 2-byte status code, so reason is limited to 123 bytes
  17301. payload += reason.substr(0, 123);
  17302. {
  17303. std::lock_guard<std::mutex> lock(write_mutex_);
  17304. detail::write_websocket_frame(strm_, Opcode::Close, payload.data(),
  17305. payload.size(), true, !is_server_);
  17306. }
  17307. // RFC 6455 Section 7.1.1: after sending a Close frame, wait for the peer's
  17308. // Close response before closing the TCP connection. Use a short timeout to
  17309. // avoid hanging if the peer doesn't respond.
  17310. strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
  17311. Opcode op;
  17312. std::string resp;
  17313. bool fin;
  17314. while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125)) {
  17315. if (op == Opcode::Close) { break; }
  17316. }
  17317. }
  17318. inline WebSocket::~WebSocket() {
  17319. {
  17320. std::lock_guard<std::mutex> lock(ping_mutex_);
  17321. closed_ = true;
  17322. }
  17323. ping_cv_.notify_all();
  17324. if (ping_thread_.joinable()) { ping_thread_.join(); }
  17325. }
  17326. inline void WebSocket::start_heartbeat() {
  17327. if (ping_interval_sec_ == 0) { return; }
  17328. ping_thread_ = std::thread([this]() {
  17329. std::unique_lock<std::mutex> lock(ping_mutex_);
  17330. while (!closed_) {
  17331. ping_cv_.wait_for(lock, std::chrono::seconds(ping_interval_sec_));
  17332. if (closed_) { break; }
  17333. // If the peer has failed to respond to the previous pings, give up.
  17334. // RFC 6455 does not define a pong-timeout mechanism; this is an
  17335. // opt-in liveness check controlled by max_missed_pongs_.
  17336. if (max_missed_pongs_ > 0 && unacked_pings_ >= max_missed_pongs_) {
  17337. lock.unlock();
  17338. close(CloseStatus::GoingAway, "pong timeout");
  17339. return;
  17340. }
  17341. lock.unlock();
  17342. if (!send_frame(Opcode::Ping, nullptr, 0)) {
  17343. lock.lock();
  17344. closed_ = true;
  17345. break;
  17346. }
  17347. lock.lock();
  17348. unacked_pings_++;
  17349. }
  17350. });
  17351. }
  17352. inline const Request &WebSocket::request() const { return req_; }
  17353. inline bool WebSocket::is_open() const { return !closed_; }
  17354. // WebSocketClient implementation
  17355. inline WebSocketClient::WebSocketClient(
  17356. const std::string &scheme_host_port_path, const Headers &headers)
  17357. : headers_(headers) {
  17358. detail::UrlComponents uc;
  17359. if (detail::parse_url(scheme_host_port_path, uc) && !uc.scheme.empty() &&
  17360. !uc.host.empty() && !uc.path.empty()) {
  17361. auto &scheme = uc.scheme;
  17362. #ifdef CPPHTTPLIB_SSL_ENABLED
  17363. if (scheme != "ws" && scheme != "wss") {
  17364. #else
  17365. if (scheme != "ws") {
  17366. #endif
  17367. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  17368. std::string msg = "'" + scheme + "' scheme is not supported.";
  17369. throw std::invalid_argument(msg);
  17370. #endif
  17371. return;
  17372. }
  17373. auto is_ssl = scheme == "wss";
  17374. host_ = std::move(uc.host);
  17375. port_ = is_ssl ? 443 : 80;
  17376. if (!uc.port.empty() && !detail::parse_port(uc.port, port_)) { return; }
  17377. path_ = std::move(uc.path);
  17378. if (!uc.query.empty()) { path_ += uc.query; }
  17379. #ifdef CPPHTTPLIB_SSL_ENABLED
  17380. is_ssl_ = is_ssl;
  17381. if (is_ssl_) {
  17382. // The context lives as long as the client so that CA configuration
  17383. // survives reconnects; sessions are created per connection.
  17384. tls_ctx_ = tls::create_client_context();
  17385. if (!tls_ctx_) { return; }
  17386. }
  17387. #else
  17388. if (is_ssl) { return; }
  17389. #endif
  17390. is_valid_ = true;
  17391. }
  17392. }
  17393. inline WebSocketClient::~WebSocketClient() {
  17394. shutdown_and_close();
  17395. #ifdef CPPHTTPLIB_SSL_ENABLED
  17396. if (tls_ctx_) {
  17397. tls::free_context(tls_ctx_);
  17398. tls_ctx_ = nullptr;
  17399. }
  17400. #endif
  17401. }
  17402. inline bool WebSocketClient::is_valid() const { return is_valid_; }
  17403. inline void WebSocketClient::shutdown_and_close() {
  17404. #ifdef CPPHTTPLIB_SSL_ENABLED
  17405. if (is_ssl_) {
  17406. if (tls_session_) {
  17407. tls::shutdown(tls_session_, true);
  17408. tls::free_session(tls_session_);
  17409. tls_session_ = nullptr;
  17410. }
  17411. }
  17412. #endif
  17413. if (ws_ && ws_->is_open()) { ws_->close(); }
  17414. ws_.reset();
  17415. if (sock_ != INVALID_SOCKET) {
  17416. detail::shutdown_socket(sock_);
  17417. detail::close_socket(sock_);
  17418. sock_ = INVALID_SOCKET;
  17419. }
  17420. }
  17421. inline bool WebSocketClient::create_stream(std::unique_ptr<Stream> &strm) {
  17422. #ifdef CPPHTTPLIB_SSL_ENABLED
  17423. if (is_ssl_) {
  17424. if (server_certificate_verification_ && !certs_loaded_) {
  17425. uint64_t backend_error = 0;
  17426. detail::load_client_ca_config(tls_ctx_, ca_cert_file_path_, std::string(),
  17427. custom_ca_loaded_, system_ca_mode_,
  17428. backend_error);
  17429. certs_loaded_ = true;
  17430. }
  17431. if (!detail::setup_client_tls_session(host_, tls_ctx_, tls_session_, sock_,
  17432. server_certificate_verification_,
  17433. read_timeout_sec_,
  17434. read_timeout_usec_)) {
  17435. return false;
  17436. }
  17437. strm = std::unique_ptr<Stream>(new detail::SSLSocketStream(
  17438. sock_, tls_session_, read_timeout_sec_, read_timeout_usec_,
  17439. write_timeout_sec_, write_timeout_usec_));
  17440. return true;
  17441. }
  17442. #endif
  17443. strm = std::unique_ptr<Stream>(
  17444. new detail::SocketStream(sock_, read_timeout_sec_, read_timeout_usec_,
  17445. write_timeout_sec_, write_timeout_usec_));
  17446. return true;
  17447. }
  17448. inline bool WebSocketClient::connect() {
  17449. if (!is_valid_) { return false; }
  17450. shutdown_and_close();
  17451. // Check is custom IP specified for host_
  17452. std::string ip;
  17453. auto it = addr_map_.find(host_);
  17454. if (it != addr_map_.end()) { ip = it->second; }
  17455. Error error;
  17456. sock_ = detail::create_client_socket(
  17457. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  17458. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  17459. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  17460. write_timeout_usec_, interface_, error);
  17461. if (sock_ == INVALID_SOCKET) { return false; }
  17462. std::unique_ptr<Stream> strm;
  17463. if (!create_stream(strm)) {
  17464. shutdown_and_close();
  17465. return false;
  17466. }
  17467. #ifdef CPPHTTPLIB_SSL_ENABLED
  17468. auto is_ssl = is_ssl_;
  17469. #else
  17470. auto is_ssl = false;
  17471. #endif
  17472. std::string selected_subprotocol;
  17473. if (!detail::perform_websocket_handshake(*strm, host_, port_, is_ssl, path_,
  17474. headers_, selected_subprotocol)) {
  17475. shutdown_and_close();
  17476. return false;
  17477. }
  17478. subprotocol_ = std::move(selected_subprotocol);
  17479. Request req;
  17480. req.method = "GET";
  17481. req.path = path_;
  17482. ws_ = std::unique_ptr<WebSocket>(new WebSocket(std::move(strm), req, false,
  17483. websocket_ping_interval_sec_,
  17484. websocket_max_missed_pongs_));
  17485. return true;
  17486. }
  17487. inline ReadResult WebSocketClient::read(std::string &msg) {
  17488. if (!ws_) { return Fail; }
  17489. return ws_->read(msg);
  17490. }
  17491. inline bool WebSocketClient::send(const std::string &data) {
  17492. if (!ws_) { return false; }
  17493. return ws_->send(data);
  17494. }
  17495. inline bool WebSocketClient::send(const char *data, size_t len) {
  17496. if (!ws_) { return false; }
  17497. return ws_->send(data, len);
  17498. }
  17499. inline void WebSocketClient::close(CloseStatus status,
  17500. const std::string &reason) {
  17501. if (ws_) { ws_->close(status, reason); }
  17502. }
  17503. inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
  17504. inline const std::string &WebSocketClient::subprotocol() const {
  17505. return subprotocol_;
  17506. }
  17507. inline void WebSocketClient::set_read_timeout(time_t sec, time_t usec) {
  17508. read_timeout_sec_ = sec;
  17509. read_timeout_usec_ = usec;
  17510. }
  17511. inline void WebSocketClient::set_write_timeout(time_t sec, time_t usec) {
  17512. write_timeout_sec_ = sec;
  17513. write_timeout_usec_ = usec;
  17514. }
  17515. inline void WebSocketClient::set_websocket_ping_interval(time_t sec) {
  17516. websocket_ping_interval_sec_ = sec;
  17517. }
  17518. inline void WebSocketClient::set_websocket_max_missed_pongs(int count) {
  17519. websocket_max_missed_pongs_ = count;
  17520. }
  17521. inline void WebSocketClient::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  17522. inline void WebSocketClient::set_address_family(int family) {
  17523. address_family_ = family;
  17524. }
  17525. inline void WebSocketClient::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  17526. inline void WebSocketClient::set_socket_options(SocketOptions socket_options) {
  17527. socket_options_ = std::move(socket_options);
  17528. }
  17529. inline void WebSocketClient::set_connection_timeout(time_t sec, time_t usec) {
  17530. connection_timeout_sec_ = sec;
  17531. connection_timeout_usec_ = usec;
  17532. }
  17533. inline void WebSocketClient::set_interface(const std::string &intf) {
  17534. interface_ = intf;
  17535. }
  17536. inline void WebSocketClient::set_hostname_addr_map(
  17537. std::map<std::string, std::string> addr_map) {
  17538. addr_map_ = std::move(addr_map);
  17539. }
  17540. #ifdef CPPHTTPLIB_SSL_ENABLED
  17541. inline void WebSocketClient::set_ca_cert_path(const std::string &path) {
  17542. ca_cert_file_path_ = path;
  17543. }
  17544. inline void WebSocketClient::set_ca_cert_store(tls::ca_store_t store) {
  17545. if (store && tls_ctx_) {
  17546. // set_ca_store takes ownership of store
  17547. tls::set_ca_store(tls_ctx_, store);
  17548. custom_ca_loaded_ = true;
  17549. } else if (store) {
  17550. tls::free_ca_store(store);
  17551. }
  17552. }
  17553. inline void WebSocketClient::load_ca_cert_store(const char *ca_cert,
  17554. std::size_t size) {
  17555. if (tls_ctx_ && ca_cert && size > 0) {
  17556. tls::load_ca_pem(tls_ctx_, ca_cert, size);
  17557. custom_ca_loaded_ = true;
  17558. }
  17559. }
  17560. inline void
  17561. WebSocketClient::enable_server_certificate_verification(bool enabled) {
  17562. server_certificate_verification_ = enabled;
  17563. }
  17564. inline void WebSocketClient::enable_system_ca(bool enabled) {
  17565. system_ca_mode_ = enabled ? SystemCAMode::Enabled : SystemCAMode::Disabled;
  17566. }
  17567. #endif // CPPHTTPLIB_SSL_ENABLED
  17568. } // namespace ws
  17569. // ----------------------------------------------------------------------------
  17570. } // namespace httplib
  17571. #endif // CPPHTTPLIB_HTTPLIB_H