httplib.h 396 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2025 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.26.0"
  10. #define CPPHTTPLIB_VERSION_NUM "0x001A00"
  11. /*
  12. * Platform compatibility check
  13. */
  14. #if defined(_WIN32) && !defined(_WIN64)
  15. #if defined(_MSC_VER)
  16. #pragma message( \
  17. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler.")
  18. #else
  19. #warning \
  20. "cpp-httplib doesn't support 32-bit Windows. Please use a 64-bit compiler."
  21. #endif
  22. #elif defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ < 8
  23. #warning \
  24. "cpp-httplib doesn't support 32-bit platforms. Please use a 64-bit compiler."
  25. #elif defined(__SIZEOF_SIZE_T__) && __SIZEOF_SIZE_T__ < 8
  26. #warning \
  27. "cpp-httplib doesn't support platforms where size_t is less than 64 bits."
  28. #endif
  29. #ifdef _WIN32
  30. #if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
  31. #error \
  32. "cpp-httplib doesn't support Windows 8 or lower. Please use Windows 10 or later."
  33. #endif
  34. #endif
  35. /*
  36. * Configuration
  37. */
  38. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  39. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  40. #endif
  41. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  42. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  43. #endif
  44. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  45. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  46. #endif
  47. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  48. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  49. #endif
  50. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  51. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  52. #endif
  53. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  54. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  55. #endif
  56. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  57. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  58. #endif
  59. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  60. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  61. #endif
  62. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  63. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  64. #endif
  65. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  66. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  67. #endif
  68. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  69. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  70. #endif
  71. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  72. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  73. #endif
  74. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  75. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  76. #endif
  77. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  78. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  79. #endif
  80. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  81. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  82. #endif
  83. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  84. #ifdef _WIN32
  85. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  86. #else
  87. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  88. #endif
  89. #endif
  90. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  91. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  92. #endif
  93. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  94. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  95. #endif
  96. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  97. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  98. #endif
  99. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  100. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  101. #endif
  102. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  103. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  104. #endif
  105. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  106. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  107. #endif
  108. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  109. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  110. #endif
  111. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  112. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  113. #endif
  114. #ifndef CPPHTTPLIB_TCP_NODELAY
  115. #define CPPHTTPLIB_TCP_NODELAY false
  116. #endif
  117. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  118. #define CPPHTTPLIB_IPV6_V6ONLY false
  119. #endif
  120. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  121. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  122. #endif
  123. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  124. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  125. #endif
  126. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  127. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  128. #endif
  129. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  130. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  131. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  132. ? std::thread::hardware_concurrency() - 1 \
  133. : 0))
  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. /*
  148. * Headers
  149. */
  150. #ifdef _WIN32
  151. #ifndef _CRT_SECURE_NO_WARNINGS
  152. #define _CRT_SECURE_NO_WARNINGS
  153. #endif //_CRT_SECURE_NO_WARNINGS
  154. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  155. #define _CRT_NONSTDC_NO_DEPRECATE
  156. #endif //_CRT_NONSTDC_NO_DEPRECATE
  157. #if defined(_MSC_VER)
  158. #if _MSC_VER < 1900
  159. #error Sorry, Visual Studio versions prior to 2015 are not supported
  160. #endif
  161. #pragma comment(lib, "ws2_32.lib")
  162. using ssize_t = __int64;
  163. #endif // _MSC_VER
  164. #ifndef S_ISREG
  165. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  166. #endif // S_ISREG
  167. #ifndef S_ISDIR
  168. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  169. #endif // S_ISDIR
  170. #ifndef NOMINMAX
  171. #define NOMINMAX
  172. #endif // NOMINMAX
  173. #include <io.h>
  174. #include <winsock2.h>
  175. #include <ws2tcpip.h>
  176. #if defined(__has_include)
  177. #if __has_include(<afunix.h>)
  178. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  179. #include <afunix.h>
  180. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  181. #endif
  182. #endif
  183. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  184. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  185. #endif
  186. using nfds_t = unsigned long;
  187. using socket_t = SOCKET;
  188. using socklen_t = int;
  189. #else // not _WIN32
  190. #include <arpa/inet.h>
  191. #if !defined(_AIX) && !defined(__MVS__)
  192. #include <ifaddrs.h>
  193. #endif
  194. #ifdef __MVS__
  195. #include <strings.h>
  196. #ifndef NI_MAXHOST
  197. #define NI_MAXHOST 1025
  198. #endif
  199. #endif
  200. #include <net/if.h>
  201. #include <netdb.h>
  202. #include <netinet/in.h>
  203. #ifdef __linux__
  204. #include <resolv.h>
  205. #endif
  206. #include <csignal>
  207. #include <netinet/tcp.h>
  208. #include <poll.h>
  209. #include <pthread.h>
  210. #include <sys/mman.h>
  211. #include <sys/socket.h>
  212. #include <sys/un.h>
  213. #include <unistd.h>
  214. using socket_t = int;
  215. #ifndef INVALID_SOCKET
  216. #define INVALID_SOCKET (-1)
  217. #endif
  218. #endif //_WIN32
  219. #if defined(__APPLE__)
  220. #include <TargetConditionals.h>
  221. #endif
  222. #include <algorithm>
  223. #include <array>
  224. #include <atomic>
  225. #include <cassert>
  226. #include <cctype>
  227. #include <climits>
  228. #include <condition_variable>
  229. #include <cstring>
  230. #include <errno.h>
  231. #include <exception>
  232. #include <fcntl.h>
  233. #include <functional>
  234. #include <iomanip>
  235. #include <iostream>
  236. #include <list>
  237. #include <map>
  238. #include <memory>
  239. #include <mutex>
  240. #include <random>
  241. #include <regex>
  242. #include <set>
  243. #include <sstream>
  244. #include <string>
  245. #include <sys/stat.h>
  246. #include <thread>
  247. #include <unordered_map>
  248. #include <unordered_set>
  249. #include <utility>
  250. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  251. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  252. #if TARGET_OS_MAC
  253. #include <CFNetwork/CFHost.h>
  254. #include <CoreFoundation/CoreFoundation.h>
  255. #endif
  256. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or
  257. // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  258. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  259. #ifdef _WIN32
  260. #include <wincrypt.h>
  261. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  262. // used
  263. #undef X509_NAME
  264. #undef X509_CERT_PAIR
  265. #undef X509_EXTENSIONS
  266. #undef PKCS7_SIGNER_INFO
  267. #ifdef _MSC_VER
  268. #pragma comment(lib, "crypt32.lib")
  269. #endif
  270. #endif // _WIN32
  271. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  272. #if TARGET_OS_MAC
  273. #include <Security/Security.h>
  274. #endif
  275. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  276. #include <openssl/err.h>
  277. #include <openssl/evp.h>
  278. #include <openssl/ssl.h>
  279. #include <openssl/x509v3.h>
  280. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  281. #include <openssl/applink.c>
  282. #endif
  283. #include <iostream>
  284. #include <sstream>
  285. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  286. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  287. #error Please use OpenSSL or a current version of BoringSSL
  288. #endif
  289. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  290. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  291. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  292. #endif
  293. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  294. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  295. #include <zlib.h>
  296. #endif
  297. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  298. #include <brotli/decode.h>
  299. #include <brotli/encode.h>
  300. #endif
  301. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  302. #include <zstd.h>
  303. #endif
  304. /*
  305. * Declaration
  306. */
  307. namespace httplib {
  308. namespace detail {
  309. /*
  310. * Backport std::make_unique from C++14.
  311. *
  312. * NOTE: This code came up with the following stackoverflow post:
  313. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  314. *
  315. */
  316. template <class T, class... Args>
  317. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  318. make_unique(Args &&...args) {
  319. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  320. }
  321. template <class T>
  322. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  323. make_unique(std::size_t n) {
  324. typedef typename std::remove_extent<T>::type RT;
  325. return std::unique_ptr<T>(new RT[n]);
  326. }
  327. namespace case_ignore {
  328. inline unsigned char to_lower(int c) {
  329. const static unsigned char table[256] = {
  330. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  331. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  332. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  333. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  334. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  335. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  336. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  337. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  338. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  339. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  340. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  341. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  342. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  343. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  344. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  345. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  346. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  347. 255,
  348. };
  349. return table[(unsigned char)(char)c];
  350. }
  351. inline bool equal(const std::string &a, const std::string &b) {
  352. return a.size() == b.size() &&
  353. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  354. return to_lower(ca) == to_lower(cb);
  355. });
  356. }
  357. struct equal_to {
  358. bool operator()(const std::string &a, const std::string &b) const {
  359. return equal(a, b);
  360. }
  361. };
  362. struct hash {
  363. size_t operator()(const std::string &key) const {
  364. return hash_core(key.data(), key.size(), 0);
  365. }
  366. size_t hash_core(const char *s, size_t l, size_t h) const {
  367. return (l == 0) ? h
  368. : hash_core(s + 1, l - 1,
  369. // Unsets the 6 high bits of h, therefore no
  370. // overflow happens
  371. (((std::numeric_limits<size_t>::max)() >> 6) &
  372. h * 33) ^
  373. static_cast<unsigned char>(to_lower(*s)));
  374. }
  375. };
  376. template <typename T>
  377. using unordered_set = std::unordered_set<T, detail::case_ignore::hash,
  378. detail::case_ignore::equal_to>;
  379. } // namespace case_ignore
  380. // This is based on
  381. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  382. struct scope_exit {
  383. explicit scope_exit(std::function<void(void)> &&f)
  384. : exit_function(std::move(f)), execute_on_destruction{true} {}
  385. scope_exit(scope_exit &&rhs) noexcept
  386. : exit_function(std::move(rhs.exit_function)),
  387. execute_on_destruction{rhs.execute_on_destruction} {
  388. rhs.release();
  389. }
  390. ~scope_exit() {
  391. if (execute_on_destruction) { this->exit_function(); }
  392. }
  393. void release() { this->execute_on_destruction = false; }
  394. private:
  395. scope_exit(const scope_exit &) = delete;
  396. void operator=(const scope_exit &) = delete;
  397. scope_exit &operator=(scope_exit &&) = delete;
  398. std::function<void(void)> exit_function;
  399. bool execute_on_destruction;
  400. };
  401. } // namespace detail
  402. enum SSLVerifierResponse {
  403. // no decision has been made, use the built-in certificate verifier
  404. NoDecisionMade,
  405. // connection certificate is verified and accepted
  406. CertificateAccepted,
  407. // connection certificate was processed but is rejected
  408. CertificateRejected
  409. };
  410. enum StatusCode {
  411. // Information responses
  412. Continue_100 = 100,
  413. SwitchingProtocol_101 = 101,
  414. Processing_102 = 102,
  415. EarlyHints_103 = 103,
  416. // Successful responses
  417. OK_200 = 200,
  418. Created_201 = 201,
  419. Accepted_202 = 202,
  420. NonAuthoritativeInformation_203 = 203,
  421. NoContent_204 = 204,
  422. ResetContent_205 = 205,
  423. PartialContent_206 = 206,
  424. MultiStatus_207 = 207,
  425. AlreadyReported_208 = 208,
  426. IMUsed_226 = 226,
  427. // Redirection messages
  428. MultipleChoices_300 = 300,
  429. MovedPermanently_301 = 301,
  430. Found_302 = 302,
  431. SeeOther_303 = 303,
  432. NotModified_304 = 304,
  433. UseProxy_305 = 305,
  434. unused_306 = 306,
  435. TemporaryRedirect_307 = 307,
  436. PermanentRedirect_308 = 308,
  437. // Client error responses
  438. BadRequest_400 = 400,
  439. Unauthorized_401 = 401,
  440. PaymentRequired_402 = 402,
  441. Forbidden_403 = 403,
  442. NotFound_404 = 404,
  443. MethodNotAllowed_405 = 405,
  444. NotAcceptable_406 = 406,
  445. ProxyAuthenticationRequired_407 = 407,
  446. RequestTimeout_408 = 408,
  447. Conflict_409 = 409,
  448. Gone_410 = 410,
  449. LengthRequired_411 = 411,
  450. PreconditionFailed_412 = 412,
  451. PayloadTooLarge_413 = 413,
  452. UriTooLong_414 = 414,
  453. UnsupportedMediaType_415 = 415,
  454. RangeNotSatisfiable_416 = 416,
  455. ExpectationFailed_417 = 417,
  456. ImATeapot_418 = 418,
  457. MisdirectedRequest_421 = 421,
  458. UnprocessableContent_422 = 422,
  459. Locked_423 = 423,
  460. FailedDependency_424 = 424,
  461. TooEarly_425 = 425,
  462. UpgradeRequired_426 = 426,
  463. PreconditionRequired_428 = 428,
  464. TooManyRequests_429 = 429,
  465. RequestHeaderFieldsTooLarge_431 = 431,
  466. UnavailableForLegalReasons_451 = 451,
  467. // Server error responses
  468. InternalServerError_500 = 500,
  469. NotImplemented_501 = 501,
  470. BadGateway_502 = 502,
  471. ServiceUnavailable_503 = 503,
  472. GatewayTimeout_504 = 504,
  473. HttpVersionNotSupported_505 = 505,
  474. VariantAlsoNegotiates_506 = 506,
  475. InsufficientStorage_507 = 507,
  476. LoopDetected_508 = 508,
  477. NotExtended_510 = 510,
  478. NetworkAuthenticationRequired_511 = 511,
  479. };
  480. using Headers =
  481. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  482. detail::case_ignore::equal_to>;
  483. using Params = std::multimap<std::string, std::string>;
  484. using Match = std::smatch;
  485. using DownloadProgress = std::function<bool(size_t current, size_t total)>;
  486. using UploadProgress = std::function<bool(size_t current, size_t total)>;
  487. struct Response;
  488. using ResponseHandler = std::function<bool(const Response &response)>;
  489. struct FormData {
  490. std::string name;
  491. std::string content;
  492. std::string filename;
  493. std::string content_type;
  494. Headers headers;
  495. };
  496. struct FormField {
  497. std::string name;
  498. std::string content;
  499. Headers headers;
  500. };
  501. using FormFields = std::multimap<std::string, FormField>;
  502. using FormFiles = std::multimap<std::string, FormData>;
  503. struct MultipartFormData {
  504. FormFields fields; // Text fields from multipart
  505. FormFiles files; // Files from multipart
  506. // Text field access
  507. std::string get_field(const std::string &key, size_t id = 0) const;
  508. std::vector<std::string> get_fields(const std::string &key) const;
  509. bool has_field(const std::string &key) const;
  510. size_t get_field_count(const std::string &key) const;
  511. // File access
  512. FormData get_file(const std::string &key, size_t id = 0) const;
  513. std::vector<FormData> get_files(const std::string &key) const;
  514. bool has_file(const std::string &key) const;
  515. size_t get_file_count(const std::string &key) const;
  516. };
  517. struct UploadFormData {
  518. std::string name;
  519. std::string content;
  520. std::string filename;
  521. std::string content_type;
  522. };
  523. using UploadFormDataItems = std::vector<UploadFormData>;
  524. class DataSink {
  525. public:
  526. DataSink() : os(&sb_), sb_(*this) {}
  527. DataSink(const DataSink &) = delete;
  528. DataSink &operator=(const DataSink &) = delete;
  529. DataSink(DataSink &&) = delete;
  530. DataSink &operator=(DataSink &&) = delete;
  531. std::function<bool(const char *data, size_t data_len)> write;
  532. std::function<bool()> is_writable;
  533. std::function<void()> done;
  534. std::function<void(const Headers &trailer)> done_with_trailer;
  535. std::ostream os;
  536. private:
  537. class data_sink_streambuf final : public std::streambuf {
  538. public:
  539. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  540. protected:
  541. std::streamsize xsputn(const char *s, std::streamsize n) override {
  542. sink_.write(s, static_cast<size_t>(n));
  543. return n;
  544. }
  545. private:
  546. DataSink &sink_;
  547. };
  548. data_sink_streambuf sb_;
  549. };
  550. using ContentProvider =
  551. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  552. using ContentProviderWithoutLength =
  553. std::function<bool(size_t offset, DataSink &sink)>;
  554. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  555. struct FormDataProvider {
  556. std::string name;
  557. ContentProviderWithoutLength provider;
  558. std::string filename;
  559. std::string content_type;
  560. };
  561. using FormDataProviderItems = std::vector<FormDataProvider>;
  562. using ContentReceiverWithProgress = std::function<bool(
  563. const char *data, size_t data_length, size_t offset, size_t total_length)>;
  564. using ContentReceiver =
  565. std::function<bool(const char *data, size_t data_length)>;
  566. using FormDataHeader = std::function<bool(const FormData &file)>;
  567. class ContentReader {
  568. public:
  569. using Reader = std::function<bool(ContentReceiver receiver)>;
  570. using FormDataReader =
  571. std::function<bool(FormDataHeader header, ContentReceiver receiver)>;
  572. ContentReader(Reader reader, FormDataReader multipart_reader)
  573. : reader_(std::move(reader)),
  574. formdata_reader_(std::move(multipart_reader)) {}
  575. bool operator()(FormDataHeader header, ContentReceiver receiver) const {
  576. return formdata_reader_(std::move(header), std::move(receiver));
  577. }
  578. bool operator()(ContentReceiver receiver) const {
  579. return reader_(std::move(receiver));
  580. }
  581. Reader reader_;
  582. FormDataReader formdata_reader_;
  583. };
  584. using Range = std::pair<ssize_t, ssize_t>;
  585. using Ranges = std::vector<Range>;
  586. struct Request {
  587. std::string method;
  588. std::string path;
  589. std::string matched_route;
  590. Params params;
  591. Headers headers;
  592. Headers trailers;
  593. std::string body;
  594. std::string remote_addr;
  595. int remote_port = -1;
  596. std::string local_addr;
  597. int local_port = -1;
  598. // for server
  599. std::string version;
  600. std::string target;
  601. MultipartFormData form;
  602. Ranges ranges;
  603. Match matches;
  604. std::unordered_map<std::string, std::string> path_params;
  605. std::function<bool()> is_connection_closed = []() { return true; };
  606. // for client
  607. std::vector<std::string> accept_content_types;
  608. ResponseHandler response_handler;
  609. ContentReceiverWithProgress content_receiver;
  610. DownloadProgress download_progress;
  611. UploadProgress upload_progress;
  612. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  613. const SSL *ssl = nullptr;
  614. #endif
  615. bool has_header(const std::string &key) const;
  616. std::string get_header_value(const std::string &key, const char *def = "",
  617. size_t id = 0) const;
  618. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  619. size_t id = 0) const;
  620. size_t get_header_value_count(const std::string &key) const;
  621. void set_header(const std::string &key, const std::string &val);
  622. bool has_trailer(const std::string &key) const;
  623. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  624. size_t get_trailer_value_count(const std::string &key) const;
  625. bool has_param(const std::string &key) const;
  626. std::string get_param_value(const std::string &key, size_t id = 0) const;
  627. size_t get_param_value_count(const std::string &key) const;
  628. bool is_multipart_form_data() const;
  629. // private members...
  630. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  631. size_t content_length_ = 0;
  632. ContentProvider content_provider_;
  633. bool is_chunked_content_provider_ = false;
  634. size_t authorization_count_ = 0;
  635. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  636. (std::chrono::steady_clock::time_point::min)();
  637. };
  638. struct Response {
  639. std::string version;
  640. int status = -1;
  641. std::string reason;
  642. Headers headers;
  643. Headers trailers;
  644. std::string body;
  645. std::string location; // Redirect location
  646. bool has_header(const std::string &key) const;
  647. std::string get_header_value(const std::string &key, const char *def = "",
  648. size_t id = 0) const;
  649. size_t get_header_value_u64(const std::string &key, size_t def = 0,
  650. size_t id = 0) const;
  651. size_t get_header_value_count(const std::string &key) const;
  652. void set_header(const std::string &key, const std::string &val);
  653. bool has_trailer(const std::string &key) const;
  654. std::string get_trailer_value(const std::string &key, size_t id = 0) const;
  655. size_t get_trailer_value_count(const std::string &key) const;
  656. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  657. void set_content(const char *s, size_t n, const std::string &content_type);
  658. void set_content(const std::string &s, const std::string &content_type);
  659. void set_content(std::string &&s, const std::string &content_type);
  660. void set_content_provider(
  661. size_t length, const std::string &content_type, ContentProvider provider,
  662. ContentProviderResourceReleaser resource_releaser = nullptr);
  663. void set_content_provider(
  664. const std::string &content_type, ContentProviderWithoutLength provider,
  665. ContentProviderResourceReleaser resource_releaser = nullptr);
  666. void set_chunked_content_provider(
  667. const std::string &content_type, ContentProviderWithoutLength provider,
  668. ContentProviderResourceReleaser resource_releaser = nullptr);
  669. void set_file_content(const std::string &path,
  670. const std::string &content_type);
  671. void set_file_content(const std::string &path);
  672. Response() = default;
  673. Response(const Response &) = default;
  674. Response &operator=(const Response &) = default;
  675. Response(Response &&) = default;
  676. Response &operator=(Response &&) = default;
  677. ~Response() {
  678. if (content_provider_resource_releaser_) {
  679. content_provider_resource_releaser_(content_provider_success_);
  680. }
  681. }
  682. // private members...
  683. size_t content_length_ = 0;
  684. ContentProvider content_provider_;
  685. ContentProviderResourceReleaser content_provider_resource_releaser_;
  686. bool is_chunked_content_provider_ = false;
  687. bool content_provider_success_ = false;
  688. std::string file_content_path_;
  689. std::string file_content_content_type_;
  690. };
  691. class Stream {
  692. public:
  693. virtual ~Stream() = default;
  694. virtual bool is_readable() const = 0;
  695. virtual bool wait_readable() const = 0;
  696. virtual bool wait_writable() const = 0;
  697. virtual ssize_t read(char *ptr, size_t size) = 0;
  698. virtual ssize_t write(const char *ptr, size_t size) = 0;
  699. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  700. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  701. virtual socket_t socket() const = 0;
  702. virtual time_t duration() const = 0;
  703. ssize_t write(const char *ptr);
  704. ssize_t write(const std::string &s);
  705. };
  706. class TaskQueue {
  707. public:
  708. TaskQueue() = default;
  709. virtual ~TaskQueue() = default;
  710. virtual bool enqueue(std::function<void()> fn) = 0;
  711. virtual void shutdown() = 0;
  712. virtual void on_idle() {}
  713. };
  714. class ThreadPool final : public TaskQueue {
  715. public:
  716. explicit ThreadPool(size_t n, size_t mqr = 0)
  717. : shutdown_(false), max_queued_requests_(mqr) {
  718. while (n) {
  719. threads_.emplace_back(worker(*this));
  720. n--;
  721. }
  722. }
  723. ThreadPool(const ThreadPool &) = delete;
  724. ~ThreadPool() override = default;
  725. bool enqueue(std::function<void()> fn) override {
  726. {
  727. std::unique_lock<std::mutex> lock(mutex_);
  728. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  729. return false;
  730. }
  731. jobs_.push_back(std::move(fn));
  732. }
  733. cond_.notify_one();
  734. return true;
  735. }
  736. void shutdown() override {
  737. // Stop all worker threads...
  738. {
  739. std::unique_lock<std::mutex> lock(mutex_);
  740. shutdown_ = true;
  741. }
  742. cond_.notify_all();
  743. // Join...
  744. for (auto &t : threads_) {
  745. t.join();
  746. }
  747. }
  748. private:
  749. struct worker {
  750. explicit worker(ThreadPool &pool) : pool_(pool) {}
  751. void operator()() {
  752. for (;;) {
  753. std::function<void()> fn;
  754. {
  755. std::unique_lock<std::mutex> lock(pool_.mutex_);
  756. pool_.cond_.wait(
  757. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  758. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  759. fn = pool_.jobs_.front();
  760. pool_.jobs_.pop_front();
  761. }
  762. assert(true == static_cast<bool>(fn));
  763. fn();
  764. }
  765. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  766. !defined(LIBRESSL_VERSION_NUMBER)
  767. OPENSSL_thread_stop();
  768. #endif
  769. }
  770. ThreadPool &pool_;
  771. };
  772. friend struct worker;
  773. std::vector<std::thread> threads_;
  774. std::list<std::function<void()>> jobs_;
  775. bool shutdown_;
  776. size_t max_queued_requests_ = 0;
  777. std::condition_variable cond_;
  778. std::mutex mutex_;
  779. };
  780. using Logger = std::function<void(const Request &, const Response &)>;
  781. // Forward declaration for Error type
  782. enum class Error;
  783. using ErrorLogger = std::function<void(const Error &, const Request *)>;
  784. using SocketOptions = std::function<void(socket_t sock)>;
  785. namespace detail {
  786. bool set_socket_opt_impl(socket_t sock, int level, int optname,
  787. const void *optval, socklen_t optlen);
  788. bool set_socket_opt(socket_t sock, int level, int optname, int opt);
  789. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  790. time_t usec);
  791. } // namespace detail
  792. void default_socket_options(socket_t sock);
  793. const char *status_message(int status);
  794. std::string get_bearer_token_auth(const Request &req);
  795. namespace detail {
  796. class MatcherBase {
  797. public:
  798. MatcherBase(std::string pattern) : pattern_(pattern) {}
  799. virtual ~MatcherBase() = default;
  800. const std::string &pattern() const { return pattern_; }
  801. // Match request path and populate its matches and
  802. virtual bool match(Request &request) const = 0;
  803. private:
  804. std::string pattern_;
  805. };
  806. /**
  807. * Captures parameters in request path and stores them in Request::path_params
  808. *
  809. * Capture name is a substring of a pattern from : to /.
  810. * The rest of the pattern is matched against the request path directly
  811. * Parameters are captured starting from the next character after
  812. * the end of the last matched static pattern fragment until the next /.
  813. *
  814. * Example pattern:
  815. * "/path/fragments/:capture/more/fragments/:second_capture"
  816. * Static fragments:
  817. * "/path/fragments/", "more/fragments/"
  818. *
  819. * Given the following request path:
  820. * "/path/fragments/:1/more/fragments/:2"
  821. * the resulting capture will be
  822. * {{"capture", "1"}, {"second_capture", "2"}}
  823. */
  824. class PathParamsMatcher final : public MatcherBase {
  825. public:
  826. PathParamsMatcher(const std::string &pattern);
  827. bool match(Request &request) const override;
  828. private:
  829. // Treat segment separators as the end of path parameter capture
  830. // Does not need to handle query parameters as they are parsed before path
  831. // matching
  832. static constexpr char separator = '/';
  833. // Contains static path fragments to match against, excluding the '/' after
  834. // path params
  835. // Fragments are separated by path params
  836. std::vector<std::string> static_fragments_;
  837. // Stores the names of the path parameters to be used as keys in the
  838. // Request::path_params map
  839. std::vector<std::string> param_names_;
  840. };
  841. /**
  842. * Performs std::regex_match on request path
  843. * and stores the result in Request::matches
  844. *
  845. * Note that regex match is performed directly on the whole request.
  846. * This means that wildcard patterns may match multiple path segments with /:
  847. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  848. */
  849. class RegexMatcher final : public MatcherBase {
  850. public:
  851. RegexMatcher(const std::string &pattern)
  852. : MatcherBase(pattern), regex_(pattern) {}
  853. bool match(Request &request) const override;
  854. private:
  855. std::regex regex_;
  856. };
  857. ssize_t write_headers(Stream &strm, const Headers &headers);
  858. } // namespace detail
  859. class Server {
  860. public:
  861. using Handler = std::function<void(const Request &, Response &)>;
  862. using ExceptionHandler =
  863. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  864. enum class HandlerResponse {
  865. Handled,
  866. Unhandled,
  867. };
  868. using HandlerWithResponse =
  869. std::function<HandlerResponse(const Request &, Response &)>;
  870. using HandlerWithContentReader = std::function<void(
  871. const Request &, Response &, const ContentReader &content_reader)>;
  872. using Expect100ContinueHandler =
  873. std::function<int(const Request &, Response &)>;
  874. Server();
  875. virtual ~Server();
  876. virtual bool is_valid() const;
  877. Server &Get(const std::string &pattern, Handler handler);
  878. Server &Post(const std::string &pattern, Handler handler);
  879. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  880. Server &Put(const std::string &pattern, Handler handler);
  881. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  882. Server &Patch(const std::string &pattern, Handler handler);
  883. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  884. Server &Delete(const std::string &pattern, Handler handler);
  885. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  886. Server &Options(const std::string &pattern, Handler handler);
  887. bool set_base_dir(const std::string &dir,
  888. const std::string &mount_point = std::string());
  889. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  890. Headers headers = Headers());
  891. bool remove_mount_point(const std::string &mount_point);
  892. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  893. const std::string &mime);
  894. Server &set_default_file_mimetype(const std::string &mime);
  895. Server &set_file_request_handler(Handler handler);
  896. template <class ErrorHandlerFunc>
  897. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  898. return set_error_handler_core(
  899. std::forward<ErrorHandlerFunc>(handler),
  900. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  901. }
  902. Server &set_exception_handler(ExceptionHandler handler);
  903. Server &set_pre_routing_handler(HandlerWithResponse handler);
  904. Server &set_post_routing_handler(Handler handler);
  905. Server &set_pre_request_handler(HandlerWithResponse handler);
  906. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  907. Server &set_logger(Logger logger);
  908. Server &set_pre_compression_logger(Logger logger);
  909. Server &set_error_logger(ErrorLogger error_logger);
  910. Server &set_address_family(int family);
  911. Server &set_tcp_nodelay(bool on);
  912. Server &set_ipv6_v6only(bool on);
  913. Server &set_socket_options(SocketOptions socket_options);
  914. Server &set_default_headers(Headers headers);
  915. Server &
  916. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  917. Server &set_keep_alive_max_count(size_t count);
  918. Server &set_keep_alive_timeout(time_t sec);
  919. Server &set_read_timeout(time_t sec, time_t usec = 0);
  920. template <class Rep, class Period>
  921. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  922. Server &set_write_timeout(time_t sec, time_t usec = 0);
  923. template <class Rep, class Period>
  924. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  925. Server &set_idle_interval(time_t sec, time_t usec = 0);
  926. template <class Rep, class Period>
  927. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  928. Server &set_payload_max_length(size_t length);
  929. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  930. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  931. bool listen_after_bind();
  932. bool listen(const std::string &host, int port, int socket_flags = 0);
  933. bool is_running() const;
  934. void wait_until_ready() const;
  935. void stop();
  936. void decommission();
  937. std::function<TaskQueue *(void)> new_task_queue;
  938. protected:
  939. bool process_request(Stream &strm, const std::string &remote_addr,
  940. int remote_port, const std::string &local_addr,
  941. int local_port, bool close_connection,
  942. bool &connection_closed,
  943. const std::function<void(Request &)> &setup_request);
  944. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  945. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  946. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  947. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  948. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  949. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  950. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  951. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  952. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  953. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  954. private:
  955. using Handlers =
  956. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  957. using HandlersForContentReader =
  958. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  959. HandlerWithContentReader>>;
  960. static std::unique_ptr<detail::MatcherBase>
  961. make_matcher(const std::string &pattern);
  962. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  963. Server &set_error_handler_core(Handler handler, std::false_type);
  964. socket_t create_server_socket(const std::string &host, int port,
  965. int socket_flags,
  966. SocketOptions socket_options) const;
  967. int bind_internal(const std::string &host, int port, int socket_flags);
  968. bool listen_internal();
  969. bool routing(Request &req, Response &res, Stream &strm);
  970. bool handle_file_request(const Request &req, Response &res);
  971. bool dispatch_request(Request &req, Response &res,
  972. const Handlers &handlers) const;
  973. bool dispatch_request_for_content_reader(
  974. Request &req, Response &res, ContentReader content_reader,
  975. const HandlersForContentReader &handlers) const;
  976. bool parse_request_line(const char *s, Request &req) const;
  977. void apply_ranges(const Request &req, Response &res,
  978. std::string &content_type, std::string &boundary) const;
  979. bool write_response(Stream &strm, bool close_connection, Request &req,
  980. Response &res);
  981. bool write_response_with_content(Stream &strm, bool close_connection,
  982. const Request &req, Response &res);
  983. bool write_response_core(Stream &strm, bool close_connection,
  984. const Request &req, Response &res,
  985. bool need_apply_ranges);
  986. bool write_content_with_provider(Stream &strm, const Request &req,
  987. Response &res, const std::string &boundary,
  988. const std::string &content_type);
  989. bool read_content(Stream &strm, Request &req, Response &res);
  990. bool read_content_with_content_receiver(Stream &strm, Request &req,
  991. Response &res,
  992. ContentReceiver receiver,
  993. FormDataHeader multipart_header,
  994. ContentReceiver multipart_receiver);
  995. bool read_content_core(Stream &strm, Request &req, Response &res,
  996. ContentReceiver receiver,
  997. FormDataHeader multipart_header,
  998. ContentReceiver multipart_receiver) const;
  999. virtual bool process_and_close_socket(socket_t sock);
  1000. void output_log(const Request &req, const Response &res) const;
  1001. void output_pre_compression_log(const Request &req,
  1002. const Response &res) const;
  1003. void output_error_log(const Error &err, const Request *req) const;
  1004. std::atomic<bool> is_running_{false};
  1005. std::atomic<bool> is_decommissioned{false};
  1006. struct MountPointEntry {
  1007. std::string mount_point;
  1008. std::string base_dir;
  1009. Headers headers;
  1010. };
  1011. std::vector<MountPointEntry> base_dirs_;
  1012. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  1013. std::string default_file_mimetype_ = "application/octet-stream";
  1014. Handler file_request_handler_;
  1015. Handlers get_handlers_;
  1016. Handlers post_handlers_;
  1017. HandlersForContentReader post_handlers_for_content_reader_;
  1018. Handlers put_handlers_;
  1019. HandlersForContentReader put_handlers_for_content_reader_;
  1020. Handlers patch_handlers_;
  1021. HandlersForContentReader patch_handlers_for_content_reader_;
  1022. Handlers delete_handlers_;
  1023. HandlersForContentReader delete_handlers_for_content_reader_;
  1024. Handlers options_handlers_;
  1025. HandlerWithResponse error_handler_;
  1026. ExceptionHandler exception_handler_;
  1027. HandlerWithResponse pre_routing_handler_;
  1028. Handler post_routing_handler_;
  1029. HandlerWithResponse pre_request_handler_;
  1030. Expect100ContinueHandler expect_100_continue_handler_;
  1031. mutable std::mutex logger_mutex_;
  1032. Logger logger_;
  1033. Logger pre_compression_logger_;
  1034. ErrorLogger error_logger_;
  1035. int address_family_ = AF_UNSPEC;
  1036. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1037. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1038. SocketOptions socket_options_ = default_socket_options;
  1039. Headers default_headers_;
  1040. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1041. detail::write_headers;
  1042. };
  1043. enum class Error {
  1044. Success = 0,
  1045. Unknown,
  1046. Connection,
  1047. BindIPAddress,
  1048. Read,
  1049. Write,
  1050. ExceedRedirectCount,
  1051. Canceled,
  1052. SSLConnection,
  1053. SSLLoadingCerts,
  1054. SSLServerVerification,
  1055. SSLServerHostnameVerification,
  1056. UnsupportedMultipartBoundaryChars,
  1057. Compression,
  1058. ConnectionTimeout,
  1059. ProxyConnection,
  1060. ResourceExhaustion,
  1061. TooManyFormDataFiles,
  1062. ExceedMaxPayloadSize,
  1063. ExceedUriMaxLength,
  1064. ExceedMaxSocketDescriptorCount,
  1065. InvalidRequestLine,
  1066. InvalidHTTPMethod,
  1067. InvalidHTTPVersion,
  1068. InvalidHeaders,
  1069. MultipartParsing,
  1070. OpenFile,
  1071. Listen,
  1072. GetSockName,
  1073. UnsupportedAddressFamily,
  1074. HTTPParsing,
  1075. InvalidRangeHeader,
  1076. // For internal use only
  1077. SSLPeerCouldBeClosed_,
  1078. };
  1079. std::string to_string(Error error);
  1080. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1081. class Result {
  1082. public:
  1083. Result() = default;
  1084. Result(std::unique_ptr<Response> &&res, Error err,
  1085. Headers &&request_headers = Headers{})
  1086. : res_(std::move(res)), err_(err),
  1087. request_headers_(std::move(request_headers)) {}
  1088. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1089. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1090. int ssl_error)
  1091. : res_(std::move(res)), err_(err),
  1092. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1093. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1094. int ssl_error, unsigned long ssl_openssl_error)
  1095. : res_(std::move(res)), err_(err),
  1096. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1097. ssl_openssl_error_(ssl_openssl_error) {}
  1098. #endif
  1099. // Response
  1100. operator bool() const { return res_ != nullptr; }
  1101. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1102. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1103. const Response &value() const { return *res_; }
  1104. Response &value() { return *res_; }
  1105. const Response &operator*() const { return *res_; }
  1106. Response &operator*() { return *res_; }
  1107. const Response *operator->() const { return res_.get(); }
  1108. Response *operator->() { return res_.get(); }
  1109. // Error
  1110. Error error() const { return err_; }
  1111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1112. // SSL Error
  1113. int ssl_error() const { return ssl_error_; }
  1114. // OpenSSL Error
  1115. unsigned long ssl_openssl_error() const { return ssl_openssl_error_; }
  1116. #endif
  1117. // Request Headers
  1118. bool has_request_header(const std::string &key) const;
  1119. std::string get_request_header_value(const std::string &key,
  1120. const char *def = "",
  1121. size_t id = 0) const;
  1122. size_t get_request_header_value_u64(const std::string &key, size_t def = 0,
  1123. size_t id = 0) const;
  1124. size_t get_request_header_value_count(const std::string &key) const;
  1125. private:
  1126. std::unique_ptr<Response> res_;
  1127. Error err_ = Error::Unknown;
  1128. Headers request_headers_;
  1129. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1130. int ssl_error_ = 0;
  1131. unsigned long ssl_openssl_error_ = 0;
  1132. #endif
  1133. };
  1134. class ClientImpl {
  1135. public:
  1136. explicit ClientImpl(const std::string &host);
  1137. explicit ClientImpl(const std::string &host, int port);
  1138. explicit ClientImpl(const std::string &host, int port,
  1139. const std::string &client_cert_path,
  1140. const std::string &client_key_path);
  1141. virtual ~ClientImpl();
  1142. virtual bool is_valid() const;
  1143. // clang-format off
  1144. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1145. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1146. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1147. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1148. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1149. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1150. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1151. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1152. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1153. Result Head(const std::string &path);
  1154. Result Head(const std::string &path, const Headers &headers);
  1155. Result Post(const std::string &path);
  1156. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1157. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1158. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1159. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1160. Result Post(const std::string &path, const Params &params);
  1161. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1162. Result Post(const std::string &path, const Headers &headers);
  1163. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1164. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1165. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1166. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1167. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1168. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1169. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1170. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1171. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1172. Result Put(const std::string &path);
  1173. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1174. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1175. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1176. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1177. Result Put(const std::string &path, const Params &params);
  1178. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1179. Result Put(const std::string &path, const Headers &headers);
  1180. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1181. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1182. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1183. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1184. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1185. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1186. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1187. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1188. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1189. Result Patch(const std::string &path);
  1190. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1191. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1192. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1193. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1194. Result Patch(const std::string &path, const Params &params);
  1195. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1196. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1197. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1198. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1199. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1200. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1201. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1202. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1203. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1204. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1205. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1206. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1207. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1208. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1209. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1210. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1211. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1212. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1213. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1214. Result Options(const std::string &path);
  1215. Result Options(const std::string &path, const Headers &headers);
  1216. // clang-format on
  1217. bool send(Request &req, Response &res, Error &error);
  1218. Result send(const Request &req);
  1219. void stop();
  1220. std::string host() const;
  1221. int port() const;
  1222. size_t is_socket_open() const;
  1223. socket_t socket() const;
  1224. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1225. void set_default_headers(Headers headers);
  1226. void
  1227. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1228. void set_address_family(int family);
  1229. void set_tcp_nodelay(bool on);
  1230. void set_ipv6_v6only(bool on);
  1231. void set_socket_options(SocketOptions socket_options);
  1232. void set_connection_timeout(time_t sec, time_t usec = 0);
  1233. template <class Rep, class Period>
  1234. void
  1235. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1236. void set_read_timeout(time_t sec, time_t usec = 0);
  1237. template <class Rep, class Period>
  1238. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1239. void set_write_timeout(time_t sec, time_t usec = 0);
  1240. template <class Rep, class Period>
  1241. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1242. void set_max_timeout(time_t msec);
  1243. template <class Rep, class Period>
  1244. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1245. void set_basic_auth(const std::string &username, const std::string &password);
  1246. void set_bearer_token_auth(const std::string &token);
  1247. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1248. void set_digest_auth(const std::string &username,
  1249. const std::string &password);
  1250. #endif
  1251. void set_keep_alive(bool on);
  1252. void set_follow_location(bool on);
  1253. void set_path_encode(bool on);
  1254. void set_compress(bool on);
  1255. void set_decompress(bool on);
  1256. void set_interface(const std::string &intf);
  1257. void set_proxy(const std::string &host, int port);
  1258. void set_proxy_basic_auth(const std::string &username,
  1259. const std::string &password);
  1260. void set_proxy_bearer_token_auth(const std::string &token);
  1261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1262. void set_proxy_digest_auth(const std::string &username,
  1263. const std::string &password);
  1264. #endif
  1265. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1266. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1267. const std::string &ca_cert_dir_path = std::string());
  1268. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1269. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1270. #endif
  1271. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1272. void enable_server_certificate_verification(bool enabled);
  1273. void enable_server_hostname_verification(bool enabled);
  1274. void set_server_certificate_verifier(
  1275. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1276. #endif
  1277. void set_logger(Logger logger);
  1278. void set_error_logger(ErrorLogger error_logger);
  1279. protected:
  1280. struct Socket {
  1281. socket_t sock = INVALID_SOCKET;
  1282. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1283. SSL *ssl = nullptr;
  1284. #endif
  1285. bool is_open() const { return sock != INVALID_SOCKET; }
  1286. };
  1287. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1288. // All of:
  1289. // shutdown_ssl
  1290. // shutdown_socket
  1291. // close_socket
  1292. // should ONLY be called when socket_mutex_ is locked.
  1293. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1294. // with a DIFFERENT thread sending requests using that socket.
  1295. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1296. void shutdown_socket(Socket &socket) const;
  1297. void close_socket(Socket &socket);
  1298. bool process_request(Stream &strm, Request &req, Response &res,
  1299. bool close_connection, Error &error);
  1300. bool write_content_with_provider(Stream &strm, const Request &req,
  1301. Error &error) const;
  1302. void copy_settings(const ClientImpl &rhs);
  1303. void output_log(const Request &req, const Response &res) const;
  1304. void output_error_log(const Error &err, const Request *req) const;
  1305. // Socket endpoint information
  1306. const std::string host_;
  1307. const int port_;
  1308. const std::string host_and_port_;
  1309. // Current open socket
  1310. Socket socket_;
  1311. mutable std::mutex socket_mutex_;
  1312. std::recursive_mutex request_mutex_;
  1313. // These are all protected under socket_mutex
  1314. size_t socket_requests_in_flight_ = 0;
  1315. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1316. bool socket_should_be_closed_when_request_is_done_ = false;
  1317. // Hostname-IP map
  1318. std::map<std::string, std::string> addr_map_;
  1319. // Default headers
  1320. Headers default_headers_;
  1321. // Header writer
  1322. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1323. detail::write_headers;
  1324. // Settings
  1325. std::string client_cert_path_;
  1326. std::string client_key_path_;
  1327. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1328. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1329. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1330. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1331. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1332. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1333. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1334. std::string basic_auth_username_;
  1335. std::string basic_auth_password_;
  1336. std::string bearer_token_auth_token_;
  1337. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1338. std::string digest_auth_username_;
  1339. std::string digest_auth_password_;
  1340. #endif
  1341. bool keep_alive_ = false;
  1342. bool follow_location_ = false;
  1343. bool path_encode_ = true;
  1344. int address_family_ = AF_UNSPEC;
  1345. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1346. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1347. SocketOptions socket_options_ = nullptr;
  1348. bool compress_ = false;
  1349. bool decompress_ = true;
  1350. std::string interface_;
  1351. std::string proxy_host_;
  1352. int proxy_port_ = -1;
  1353. std::string proxy_basic_auth_username_;
  1354. std::string proxy_basic_auth_password_;
  1355. std::string proxy_bearer_token_auth_token_;
  1356. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1357. std::string proxy_digest_auth_username_;
  1358. std::string proxy_digest_auth_password_;
  1359. #endif
  1360. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1361. std::string ca_cert_file_path_;
  1362. std::string ca_cert_dir_path_;
  1363. X509_STORE *ca_cert_store_ = nullptr;
  1364. #endif
  1365. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1366. bool server_certificate_verification_ = true;
  1367. bool server_hostname_verification_ = true;
  1368. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1369. #endif
  1370. mutable std::mutex logger_mutex_;
  1371. Logger logger_;
  1372. ErrorLogger error_logger_;
  1373. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1374. int last_ssl_error_ = 0;
  1375. unsigned long last_openssl_error_ = 0;
  1376. #endif
  1377. private:
  1378. bool send_(Request &req, Response &res, Error &error);
  1379. Result send_(Request &&req);
  1380. socket_t create_client_socket(Error &error) const;
  1381. bool read_response_line(Stream &strm, const Request &req,
  1382. Response &res) const;
  1383. bool write_request(Stream &strm, Request &req, bool close_connection,
  1384. Error &error);
  1385. bool redirect(Request &req, Response &res, Error &error);
  1386. bool create_redirect_client(const std::string &scheme,
  1387. const std::string &host, int port, Request &req,
  1388. Response &res, const std::string &path,
  1389. const std::string &location, Error &error);
  1390. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1391. bool handle_request(Stream &strm, Request &req, Response &res,
  1392. bool close_connection, Error &error);
  1393. std::unique_ptr<Response> send_with_content_provider(
  1394. Request &req, const char *body, size_t content_length,
  1395. ContentProvider content_provider,
  1396. ContentProviderWithoutLength content_provider_without_length,
  1397. const std::string &content_type, Error &error);
  1398. Result send_with_content_provider(
  1399. const std::string &method, const std::string &path,
  1400. const Headers &headers, const char *body, size_t content_length,
  1401. ContentProvider content_provider,
  1402. ContentProviderWithoutLength content_provider_without_length,
  1403. const std::string &content_type, UploadProgress progress);
  1404. ContentProviderWithoutLength get_multipart_content_provider(
  1405. const std::string &boundary, const UploadFormDataItems &items,
  1406. const FormDataProviderItems &provider_items) const;
  1407. std::string adjust_host_string(const std::string &host) const;
  1408. virtual bool
  1409. process_socket(const Socket &socket,
  1410. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1411. std::function<bool(Stream &strm)> callback);
  1412. virtual bool is_ssl() const;
  1413. };
  1414. class Client {
  1415. public:
  1416. // Universal interface
  1417. explicit Client(const std::string &scheme_host_port);
  1418. explicit Client(const std::string &scheme_host_port,
  1419. const std::string &client_cert_path,
  1420. const std::string &client_key_path);
  1421. // HTTP only interface
  1422. explicit Client(const std::string &host, int port);
  1423. explicit Client(const std::string &host, int port,
  1424. const std::string &client_cert_path,
  1425. const std::string &client_key_path);
  1426. Client(Client &&) = default;
  1427. Client &operator=(Client &&) = default;
  1428. ~Client();
  1429. bool is_valid() const;
  1430. // clang-format off
  1431. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1432. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1433. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1434. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1435. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1436. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1437. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1438. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1439. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1440. Result Head(const std::string &path);
  1441. Result Head(const std::string &path, const Headers &headers);
  1442. Result Post(const std::string &path);
  1443. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1444. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1445. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1446. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1447. Result Post(const std::string &path, const Params &params);
  1448. Result Post(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1449. Result Post(const std::string &path, const Headers &headers);
  1450. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1451. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1452. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1453. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1454. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1455. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1456. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1457. Result Post(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1458. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1459. Result Put(const std::string &path);
  1460. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1461. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1462. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1463. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1464. Result Put(const std::string &path, const Params &params);
  1465. Result Put(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1466. Result Put(const std::string &path, const Headers &headers);
  1467. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1468. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1469. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1470. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1471. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1472. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1473. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1474. Result Put(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1475. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1476. Result Patch(const std::string &path);
  1477. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1478. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1479. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1480. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1481. Result Patch(const std::string &path, const Params &params);
  1482. Result Patch(const std::string &path, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1483. Result Patch(const std::string &path, const Headers &headers);
  1484. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1485. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1486. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1487. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1488. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1489. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, UploadProgress progress = nullptr);
  1490. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const std::string &boundary, UploadProgress progress = nullptr);
  1491. Result Patch(const std::string &path, const Headers &headers, const UploadFormDataItems &items, const FormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1492. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1493. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1494. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1495. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1496. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1497. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1498. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1499. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1500. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1501. Result Options(const std::string &path);
  1502. Result Options(const std::string &path, const Headers &headers);
  1503. // clang-format on
  1504. bool send(Request &req, Response &res, Error &error);
  1505. Result send(const Request &req);
  1506. void stop();
  1507. std::string host() const;
  1508. int port() const;
  1509. size_t is_socket_open() const;
  1510. socket_t socket() const;
  1511. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1512. void set_default_headers(Headers headers);
  1513. void
  1514. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1515. void set_address_family(int family);
  1516. void set_tcp_nodelay(bool on);
  1517. void set_socket_options(SocketOptions socket_options);
  1518. void set_connection_timeout(time_t sec, time_t usec = 0);
  1519. template <class Rep, class Period>
  1520. void
  1521. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1522. void set_read_timeout(time_t sec, time_t usec = 0);
  1523. template <class Rep, class Period>
  1524. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1525. void set_write_timeout(time_t sec, time_t usec = 0);
  1526. template <class Rep, class Period>
  1527. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1528. void set_max_timeout(time_t msec);
  1529. template <class Rep, class Period>
  1530. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1531. void set_basic_auth(const std::string &username, const std::string &password);
  1532. void set_bearer_token_auth(const std::string &token);
  1533. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1534. void set_digest_auth(const std::string &username,
  1535. const std::string &password);
  1536. #endif
  1537. void set_keep_alive(bool on);
  1538. void set_follow_location(bool on);
  1539. void set_path_encode(bool on);
  1540. void set_url_encode(bool on);
  1541. void set_compress(bool on);
  1542. void set_decompress(bool on);
  1543. void set_interface(const std::string &intf);
  1544. void set_proxy(const std::string &host, int port);
  1545. void set_proxy_basic_auth(const std::string &username,
  1546. const std::string &password);
  1547. void set_proxy_bearer_token_auth(const std::string &token);
  1548. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1549. void set_proxy_digest_auth(const std::string &username,
  1550. const std::string &password);
  1551. #endif
  1552. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1553. void enable_server_certificate_verification(bool enabled);
  1554. void enable_server_hostname_verification(bool enabled);
  1555. void set_server_certificate_verifier(
  1556. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1557. #endif
  1558. void set_logger(Logger logger);
  1559. void set_error_logger(ErrorLogger error_logger);
  1560. // SSL
  1561. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1562. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1563. const std::string &ca_cert_dir_path = std::string());
  1564. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1565. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1566. long get_openssl_verify_result() const;
  1567. SSL_CTX *ssl_context() const;
  1568. #endif
  1569. private:
  1570. std::unique_ptr<ClientImpl> cli_;
  1571. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1572. bool is_ssl_ = false;
  1573. #endif
  1574. };
  1575. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1576. class SSLServer : public Server {
  1577. public:
  1578. SSLServer(const char *cert_path, const char *private_key_path,
  1579. const char *client_ca_cert_file_path = nullptr,
  1580. const char *client_ca_cert_dir_path = nullptr,
  1581. const char *private_key_password = nullptr);
  1582. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1583. X509_STORE *client_ca_cert_store = nullptr);
  1584. SSLServer(
  1585. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1586. ~SSLServer() override;
  1587. bool is_valid() const override;
  1588. SSL_CTX *ssl_context() const;
  1589. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1590. X509_STORE *client_ca_cert_store = nullptr);
  1591. private:
  1592. bool process_and_close_socket(socket_t sock) override;
  1593. SSL_CTX *ctx_;
  1594. std::mutex ctx_mutex_;
  1595. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1596. int last_ssl_error_ = 0;
  1597. #endif
  1598. };
  1599. class SSLClient final : public ClientImpl {
  1600. public:
  1601. explicit SSLClient(const std::string &host);
  1602. explicit SSLClient(const std::string &host, int port);
  1603. explicit SSLClient(const std::string &host, int port,
  1604. const std::string &client_cert_path,
  1605. const std::string &client_key_path,
  1606. const std::string &private_key_password = std::string());
  1607. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1608. EVP_PKEY *client_key,
  1609. const std::string &private_key_password = std::string());
  1610. ~SSLClient() override;
  1611. bool is_valid() const override;
  1612. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1613. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1614. long get_openssl_verify_result() const;
  1615. SSL_CTX *ssl_context() const;
  1616. private:
  1617. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1618. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1619. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1620. bool
  1621. process_socket(const Socket &socket,
  1622. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1623. std::function<bool(Stream &strm)> callback) override;
  1624. bool is_ssl() const override;
  1625. bool connect_with_proxy(
  1626. Socket &sock,
  1627. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1628. Response &res, bool &success, Error &error);
  1629. bool initialize_ssl(Socket &socket, Error &error);
  1630. bool load_certs();
  1631. bool verify_host(X509 *server_cert) const;
  1632. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1633. bool verify_host_with_common_name(X509 *server_cert) const;
  1634. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1635. SSL_CTX *ctx_;
  1636. std::mutex ctx_mutex_;
  1637. std::once_flag initialize_cert_;
  1638. std::vector<std::string> host_components_;
  1639. long verify_result_ = 0;
  1640. friend class ClientImpl;
  1641. };
  1642. #endif
  1643. /*
  1644. * Implementation of template methods.
  1645. */
  1646. namespace detail {
  1647. template <typename T, typename U>
  1648. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1649. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1650. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1651. duration - std::chrono::seconds(sec))
  1652. .count();
  1653. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1654. }
  1655. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1656. return N - 1;
  1657. }
  1658. inline bool is_numeric(const std::string &str) {
  1659. return !str.empty() &&
  1660. std::all_of(str.cbegin(), str.cend(),
  1661. [](unsigned char c) { return std::isdigit(c); });
  1662. }
  1663. inline size_t get_header_value_u64(const Headers &headers,
  1664. const std::string &key, size_t def,
  1665. size_t id, bool &is_invalid_value) {
  1666. is_invalid_value = false;
  1667. auto rng = headers.equal_range(key);
  1668. auto it = rng.first;
  1669. std::advance(it, static_cast<ssize_t>(id));
  1670. if (it != rng.second) {
  1671. if (is_numeric(it->second)) {
  1672. return std::strtoull(it->second.data(), nullptr, 10);
  1673. } else {
  1674. is_invalid_value = true;
  1675. }
  1676. }
  1677. return def;
  1678. }
  1679. inline size_t get_header_value_u64(const Headers &headers,
  1680. const std::string &key, size_t def,
  1681. size_t id) {
  1682. auto dummy = false;
  1683. return get_header_value_u64(headers, key, def, id, dummy);
  1684. }
  1685. } // namespace detail
  1686. inline size_t Request::get_header_value_u64(const std::string &key, size_t def,
  1687. size_t id) const {
  1688. return detail::get_header_value_u64(headers, key, def, id);
  1689. }
  1690. inline size_t Response::get_header_value_u64(const std::string &key, size_t def,
  1691. size_t id) const {
  1692. return detail::get_header_value_u64(headers, key, def, id);
  1693. }
  1694. namespace detail {
  1695. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1696. const void *optval, socklen_t optlen) {
  1697. return setsockopt(sock, level, optname,
  1698. #ifdef _WIN32
  1699. reinterpret_cast<const char *>(optval),
  1700. #else
  1701. optval,
  1702. #endif
  1703. optlen) == 0;
  1704. }
  1705. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1706. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1707. }
  1708. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1709. time_t sec, time_t usec) {
  1710. #ifdef _WIN32
  1711. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1712. #else
  1713. timeval timeout;
  1714. timeout.tv_sec = static_cast<long>(sec);
  1715. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1716. #endif
  1717. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1718. }
  1719. } // namespace detail
  1720. inline void default_socket_options(socket_t sock) {
  1721. detail::set_socket_opt(sock, SOL_SOCKET,
  1722. #ifdef SO_REUSEPORT
  1723. SO_REUSEPORT,
  1724. #else
  1725. SO_REUSEADDR,
  1726. #endif
  1727. 1);
  1728. }
  1729. inline const char *status_message(int status) {
  1730. switch (status) {
  1731. case StatusCode::Continue_100: return "Continue";
  1732. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  1733. case StatusCode::Processing_102: return "Processing";
  1734. case StatusCode::EarlyHints_103: return "Early Hints";
  1735. case StatusCode::OK_200: return "OK";
  1736. case StatusCode::Created_201: return "Created";
  1737. case StatusCode::Accepted_202: return "Accepted";
  1738. case StatusCode::NonAuthoritativeInformation_203:
  1739. return "Non-Authoritative Information";
  1740. case StatusCode::NoContent_204: return "No Content";
  1741. case StatusCode::ResetContent_205: return "Reset Content";
  1742. case StatusCode::PartialContent_206: return "Partial Content";
  1743. case StatusCode::MultiStatus_207: return "Multi-Status";
  1744. case StatusCode::AlreadyReported_208: return "Already Reported";
  1745. case StatusCode::IMUsed_226: return "IM Used";
  1746. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  1747. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  1748. case StatusCode::Found_302: return "Found";
  1749. case StatusCode::SeeOther_303: return "See Other";
  1750. case StatusCode::NotModified_304: return "Not Modified";
  1751. case StatusCode::UseProxy_305: return "Use Proxy";
  1752. case StatusCode::unused_306: return "unused";
  1753. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  1754. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  1755. case StatusCode::BadRequest_400: return "Bad Request";
  1756. case StatusCode::Unauthorized_401: return "Unauthorized";
  1757. case StatusCode::PaymentRequired_402: return "Payment Required";
  1758. case StatusCode::Forbidden_403: return "Forbidden";
  1759. case StatusCode::NotFound_404: return "Not Found";
  1760. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  1761. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  1762. case StatusCode::ProxyAuthenticationRequired_407:
  1763. return "Proxy Authentication Required";
  1764. case StatusCode::RequestTimeout_408: return "Request Timeout";
  1765. case StatusCode::Conflict_409: return "Conflict";
  1766. case StatusCode::Gone_410: return "Gone";
  1767. case StatusCode::LengthRequired_411: return "Length Required";
  1768. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  1769. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  1770. case StatusCode::UriTooLong_414: return "URI Too Long";
  1771. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  1772. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  1773. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  1774. case StatusCode::ImATeapot_418: return "I'm a teapot";
  1775. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  1776. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  1777. case StatusCode::Locked_423: return "Locked";
  1778. case StatusCode::FailedDependency_424: return "Failed Dependency";
  1779. case StatusCode::TooEarly_425: return "Too Early";
  1780. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  1781. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  1782. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  1783. case StatusCode::RequestHeaderFieldsTooLarge_431:
  1784. return "Request Header Fields Too Large";
  1785. case StatusCode::UnavailableForLegalReasons_451:
  1786. return "Unavailable For Legal Reasons";
  1787. case StatusCode::NotImplemented_501: return "Not Implemented";
  1788. case StatusCode::BadGateway_502: return "Bad Gateway";
  1789. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  1790. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  1791. case StatusCode::HttpVersionNotSupported_505:
  1792. return "HTTP Version Not Supported";
  1793. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  1794. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  1795. case StatusCode::LoopDetected_508: return "Loop Detected";
  1796. case StatusCode::NotExtended_510: return "Not Extended";
  1797. case StatusCode::NetworkAuthenticationRequired_511:
  1798. return "Network Authentication Required";
  1799. default:
  1800. case StatusCode::InternalServerError_500: return "Internal Server Error";
  1801. }
  1802. }
  1803. inline std::string get_bearer_token_auth(const Request &req) {
  1804. if (req.has_header("Authorization")) {
  1805. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1806. return req.get_header_value("Authorization")
  1807. .substr(bearer_header_prefix_len);
  1808. }
  1809. return "";
  1810. }
  1811. template <class Rep, class Period>
  1812. inline Server &
  1813. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1814. detail::duration_to_sec_and_usec(
  1815. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1816. return *this;
  1817. }
  1818. template <class Rep, class Period>
  1819. inline Server &
  1820. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1821. detail::duration_to_sec_and_usec(
  1822. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1823. return *this;
  1824. }
  1825. template <class Rep, class Period>
  1826. inline Server &
  1827. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1828. detail::duration_to_sec_and_usec(
  1829. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1830. return *this;
  1831. }
  1832. inline std::string to_string(const Error error) {
  1833. switch (error) {
  1834. case Error::Success: return "Success (no error)";
  1835. case Error::Unknown: return "Unknown";
  1836. case Error::Connection: return "Could not establish connection";
  1837. case Error::BindIPAddress: return "Failed to bind IP address";
  1838. case Error::Read: return "Failed to read connection";
  1839. case Error::Write: return "Failed to write connection";
  1840. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  1841. case Error::Canceled: return "Connection handling canceled";
  1842. case Error::SSLConnection: return "SSL connection failed";
  1843. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  1844. case Error::SSLServerVerification: return "SSL server verification failed";
  1845. case Error::SSLServerHostnameVerification:
  1846. return "SSL server hostname verification failed";
  1847. case Error::UnsupportedMultipartBoundaryChars:
  1848. return "Unsupported HTTP multipart boundary characters";
  1849. case Error::Compression: return "Compression failed";
  1850. case Error::ConnectionTimeout: return "Connection timed out";
  1851. case Error::ProxyConnection: return "Proxy connection failed";
  1852. case Error::ResourceExhaustion: return "Resource exhaustion";
  1853. case Error::TooManyFormDataFiles: return "Too many form data files";
  1854. case Error::ExceedMaxPayloadSize: return "Exceeded maximum payload size";
  1855. case Error::ExceedUriMaxLength: return "Exceeded maximum URI length";
  1856. case Error::ExceedMaxSocketDescriptorCount:
  1857. return "Exceeded maximum socket descriptor count";
  1858. case Error::InvalidRequestLine: return "Invalid request line";
  1859. case Error::InvalidHTTPMethod: return "Invalid HTTP method";
  1860. case Error::InvalidHTTPVersion: return "Invalid HTTP version";
  1861. case Error::InvalidHeaders: return "Invalid headers";
  1862. case Error::MultipartParsing: return "Multipart parsing failed";
  1863. case Error::OpenFile: return "Failed to open file";
  1864. case Error::Listen: return "Failed to listen on socket";
  1865. case Error::GetSockName: return "Failed to get socket name";
  1866. case Error::UnsupportedAddressFamily: return "Unsupported address family";
  1867. case Error::HTTPParsing: return "HTTP parsing failed";
  1868. case Error::InvalidRangeHeader: return "Invalid Range header";
  1869. default: break;
  1870. }
  1871. return "Invalid";
  1872. }
  1873. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  1874. os << to_string(obj);
  1875. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  1876. return os;
  1877. }
  1878. inline size_t Result::get_request_header_value_u64(const std::string &key,
  1879. size_t def,
  1880. size_t id) const {
  1881. return detail::get_header_value_u64(request_headers_, key, def, id);
  1882. }
  1883. template <class Rep, class Period>
  1884. inline void ClientImpl::set_connection_timeout(
  1885. const std::chrono::duration<Rep, Period> &duration) {
  1886. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1887. set_connection_timeout(sec, usec);
  1888. });
  1889. }
  1890. template <class Rep, class Period>
  1891. inline void ClientImpl::set_read_timeout(
  1892. const std::chrono::duration<Rep, Period> &duration) {
  1893. detail::duration_to_sec_and_usec(
  1894. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1895. }
  1896. template <class Rep, class Period>
  1897. inline void ClientImpl::set_write_timeout(
  1898. const std::chrono::duration<Rep, Period> &duration) {
  1899. detail::duration_to_sec_and_usec(
  1900. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1901. }
  1902. template <class Rep, class Period>
  1903. inline void ClientImpl::set_max_timeout(
  1904. const std::chrono::duration<Rep, Period> &duration) {
  1905. auto msec =
  1906. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  1907. set_max_timeout(msec);
  1908. }
  1909. template <class Rep, class Period>
  1910. inline void Client::set_connection_timeout(
  1911. const std::chrono::duration<Rep, Period> &duration) {
  1912. cli_->set_connection_timeout(duration);
  1913. }
  1914. template <class Rep, class Period>
  1915. inline void
  1916. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1917. cli_->set_read_timeout(duration);
  1918. }
  1919. template <class Rep, class Period>
  1920. inline void
  1921. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1922. cli_->set_write_timeout(duration);
  1923. }
  1924. inline void Client::set_max_timeout(time_t msec) {
  1925. cli_->set_max_timeout(msec);
  1926. }
  1927. template <class Rep, class Period>
  1928. inline void
  1929. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1930. cli_->set_max_timeout(duration);
  1931. }
  1932. /*
  1933. * Forward declarations and types that will be part of the .h file if split into
  1934. * .h + .cc.
  1935. */
  1936. std::string hosted_at(const std::string &hostname);
  1937. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  1938. // JavaScript-style URL encoding/decoding functions
  1939. std::string encode_uri_component(const std::string &value);
  1940. std::string encode_uri(const std::string &value);
  1941. std::string decode_uri_component(const std::string &value);
  1942. std::string decode_uri(const std::string &value);
  1943. // RFC 3986 compliant URL component encoding/decoding functions
  1944. std::string encode_path_component(const std::string &component);
  1945. std::string decode_path_component(const std::string &component);
  1946. std::string encode_query_component(const std::string &component,
  1947. bool space_as_plus = true);
  1948. std::string decode_query_component(const std::string &component,
  1949. bool plus_as_space = true);
  1950. std::string append_query_params(const std::string &path, const Params &params);
  1951. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  1952. std::pair<std::string, std::string>
  1953. make_basic_authentication_header(const std::string &username,
  1954. const std::string &password,
  1955. bool is_proxy = false);
  1956. namespace detail {
  1957. #if defined(_WIN32)
  1958. inline std::wstring u8string_to_wstring(const char *s) {
  1959. std::wstring ws;
  1960. auto len = static_cast<int>(strlen(s));
  1961. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  1962. if (wlen > 0) {
  1963. ws.resize(wlen);
  1964. wlen = ::MultiByteToWideChar(
  1965. CP_UTF8, 0, s, len,
  1966. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  1967. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  1968. }
  1969. return ws;
  1970. }
  1971. #endif
  1972. struct FileStat {
  1973. FileStat(const std::string &path);
  1974. bool is_file() const;
  1975. bool is_dir() const;
  1976. private:
  1977. #if defined(_WIN32)
  1978. struct _stat st_;
  1979. #else
  1980. struct stat st_;
  1981. #endif
  1982. int ret_ = -1;
  1983. };
  1984. std::string trim_copy(const std::string &s);
  1985. void divide(
  1986. const char *data, std::size_t size, char d,
  1987. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1988. fn);
  1989. void divide(
  1990. const std::string &str, char d,
  1991. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1992. fn);
  1993. void split(const char *b, const char *e, char d,
  1994. std::function<void(const char *, const char *)> fn);
  1995. void split(const char *b, const char *e, char d, size_t m,
  1996. std::function<void(const char *, const char *)> fn);
  1997. bool process_client_socket(
  1998. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  1999. time_t write_timeout_sec, time_t write_timeout_usec,
  2000. time_t max_timeout_msec,
  2001. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2002. std::function<bool(Stream &)> callback);
  2003. socket_t create_client_socket(const std::string &host, const std::string &ip,
  2004. int port, int address_family, bool tcp_nodelay,
  2005. bool ipv6_v6only, SocketOptions socket_options,
  2006. time_t connection_timeout_sec,
  2007. time_t connection_timeout_usec,
  2008. time_t read_timeout_sec, time_t read_timeout_usec,
  2009. time_t write_timeout_sec,
  2010. time_t write_timeout_usec,
  2011. const std::string &intf, Error &error);
  2012. const char *get_header_value(const Headers &headers, const std::string &key,
  2013. const char *def, size_t id);
  2014. std::string params_to_query_str(const Params &params);
  2015. void parse_query_text(const char *data, std::size_t size, Params &params);
  2016. void parse_query_text(const std::string &s, Params &params);
  2017. bool parse_multipart_boundary(const std::string &content_type,
  2018. std::string &boundary);
  2019. bool parse_range_header(const std::string &s, Ranges &ranges);
  2020. bool parse_accept_header(const std::string &s,
  2021. std::vector<std::string> &content_types);
  2022. int close_socket(socket_t sock);
  2023. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  2024. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  2025. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  2026. EncodingType encoding_type(const Request &req, const Response &res);
  2027. class BufferStream final : public Stream {
  2028. public:
  2029. BufferStream() = default;
  2030. ~BufferStream() override = default;
  2031. bool is_readable() const override;
  2032. bool wait_readable() const override;
  2033. bool wait_writable() const override;
  2034. ssize_t read(char *ptr, size_t size) override;
  2035. ssize_t write(const char *ptr, size_t size) override;
  2036. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2037. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2038. socket_t socket() const override;
  2039. time_t duration() const override;
  2040. const std::string &get_buffer() const;
  2041. private:
  2042. std::string buffer;
  2043. size_t position = 0;
  2044. };
  2045. class compressor {
  2046. public:
  2047. virtual ~compressor() = default;
  2048. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2049. virtual bool compress(const char *data, size_t data_length, bool last,
  2050. Callback callback) = 0;
  2051. };
  2052. class decompressor {
  2053. public:
  2054. virtual ~decompressor() = default;
  2055. virtual bool is_valid() const = 0;
  2056. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  2057. virtual bool decompress(const char *data, size_t data_length,
  2058. Callback callback) = 0;
  2059. };
  2060. class nocompressor final : public compressor {
  2061. public:
  2062. ~nocompressor() override = default;
  2063. bool compress(const char *data, size_t data_length, bool /*last*/,
  2064. Callback callback) override;
  2065. };
  2066. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2067. class gzip_compressor final : public compressor {
  2068. public:
  2069. gzip_compressor();
  2070. ~gzip_compressor() override;
  2071. bool compress(const char *data, size_t data_length, bool last,
  2072. Callback callback) override;
  2073. private:
  2074. bool is_valid_ = false;
  2075. z_stream strm_;
  2076. };
  2077. class gzip_decompressor final : public decompressor {
  2078. public:
  2079. gzip_decompressor();
  2080. ~gzip_decompressor() override;
  2081. bool is_valid() const override;
  2082. bool decompress(const char *data, size_t data_length,
  2083. Callback callback) override;
  2084. private:
  2085. bool is_valid_ = false;
  2086. z_stream strm_;
  2087. };
  2088. #endif
  2089. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2090. class brotli_compressor final : public compressor {
  2091. public:
  2092. brotli_compressor();
  2093. ~brotli_compressor();
  2094. bool compress(const char *data, size_t data_length, bool last,
  2095. Callback callback) override;
  2096. private:
  2097. BrotliEncoderState *state_ = nullptr;
  2098. };
  2099. class brotli_decompressor final : public decompressor {
  2100. public:
  2101. brotli_decompressor();
  2102. ~brotli_decompressor();
  2103. bool is_valid() const override;
  2104. bool decompress(const char *data, size_t data_length,
  2105. Callback callback) override;
  2106. private:
  2107. BrotliDecoderResult decoder_r;
  2108. BrotliDecoderState *decoder_s = nullptr;
  2109. };
  2110. #endif
  2111. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2112. class zstd_compressor : public compressor {
  2113. public:
  2114. zstd_compressor();
  2115. ~zstd_compressor();
  2116. bool compress(const char *data, size_t data_length, bool last,
  2117. Callback callback) override;
  2118. private:
  2119. ZSTD_CCtx *ctx_ = nullptr;
  2120. };
  2121. class zstd_decompressor : public decompressor {
  2122. public:
  2123. zstd_decompressor();
  2124. ~zstd_decompressor();
  2125. bool is_valid() const override;
  2126. bool decompress(const char *data, size_t data_length,
  2127. Callback callback) override;
  2128. private:
  2129. ZSTD_DCtx *ctx_ = nullptr;
  2130. };
  2131. #endif
  2132. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2133. // to store data. The call can set memory on stack for performance.
  2134. class stream_line_reader {
  2135. public:
  2136. stream_line_reader(Stream &strm, char *fixed_buffer,
  2137. size_t fixed_buffer_size);
  2138. const char *ptr() const;
  2139. size_t size() const;
  2140. bool end_with_crlf() const;
  2141. bool getline();
  2142. private:
  2143. void append(char c);
  2144. Stream &strm_;
  2145. char *fixed_buffer_;
  2146. const size_t fixed_buffer_size_;
  2147. size_t fixed_buffer_used_size_ = 0;
  2148. std::string growable_buffer_;
  2149. };
  2150. class mmap {
  2151. public:
  2152. mmap(const char *path);
  2153. ~mmap();
  2154. bool open(const char *path);
  2155. void close();
  2156. bool is_open() const;
  2157. size_t size() const;
  2158. const char *data() const;
  2159. private:
  2160. #if defined(_WIN32)
  2161. HANDLE hFile_ = NULL;
  2162. HANDLE hMapping_ = NULL;
  2163. #else
  2164. int fd_ = -1;
  2165. #endif
  2166. size_t size_ = 0;
  2167. void *addr_ = nullptr;
  2168. bool is_open_empty_file = false;
  2169. };
  2170. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2171. namespace fields {
  2172. inline bool is_token_char(char c) {
  2173. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  2174. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  2175. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  2176. }
  2177. inline bool is_token(const std::string &s) {
  2178. if (s.empty()) { return false; }
  2179. for (auto c : s) {
  2180. if (!is_token_char(c)) { return false; }
  2181. }
  2182. return true;
  2183. }
  2184. inline bool is_field_name(const std::string &s) { return is_token(s); }
  2185. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  2186. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  2187. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  2188. inline bool is_field_content(const std::string &s) {
  2189. if (s.empty()) { return true; }
  2190. if (s.size() == 1) {
  2191. return is_field_vchar(s[0]);
  2192. } else if (s.size() == 2) {
  2193. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  2194. } else {
  2195. size_t i = 0;
  2196. if (!is_field_vchar(s[i])) { return false; }
  2197. i++;
  2198. while (i < s.size() - 1) {
  2199. auto c = s[i++];
  2200. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  2201. } else {
  2202. return false;
  2203. }
  2204. }
  2205. return is_field_vchar(s[i]);
  2206. }
  2207. }
  2208. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  2209. } // namespace fields
  2210. } // namespace detail
  2211. // ----------------------------------------------------------------------------
  2212. /*
  2213. * Implementation that will be part of the .cc file if split into .h + .cc.
  2214. */
  2215. namespace detail {
  2216. inline bool is_hex(char c, int &v) {
  2217. if (0x20 <= c && isdigit(c)) {
  2218. v = c - '0';
  2219. return true;
  2220. } else if ('A' <= c && c <= 'F') {
  2221. v = c - 'A' + 10;
  2222. return true;
  2223. } else if ('a' <= c && c <= 'f') {
  2224. v = c - 'a' + 10;
  2225. return true;
  2226. }
  2227. return false;
  2228. }
  2229. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  2230. int &val) {
  2231. if (i >= s.size()) { return false; }
  2232. val = 0;
  2233. for (; cnt; i++, cnt--) {
  2234. if (!s[i]) { return false; }
  2235. auto v = 0;
  2236. if (is_hex(s[i], v)) {
  2237. val = val * 16 + v;
  2238. } else {
  2239. return false;
  2240. }
  2241. }
  2242. return true;
  2243. }
  2244. inline std::string from_i_to_hex(size_t n) {
  2245. static const auto charset = "0123456789abcdef";
  2246. std::string ret;
  2247. do {
  2248. ret = charset[n & 15] + ret;
  2249. n >>= 4;
  2250. } while (n > 0);
  2251. return ret;
  2252. }
  2253. inline size_t to_utf8(int code, char *buff) {
  2254. if (code < 0x0080) {
  2255. buff[0] = static_cast<char>(code & 0x7F);
  2256. return 1;
  2257. } else if (code < 0x0800) {
  2258. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  2259. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  2260. return 2;
  2261. } else if (code < 0xD800) {
  2262. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2263. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2264. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2265. return 3;
  2266. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  2267. return 0;
  2268. } else if (code < 0x10000) {
  2269. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2270. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2271. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2272. return 3;
  2273. } else if (code < 0x110000) {
  2274. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  2275. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  2276. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2277. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  2278. return 4;
  2279. }
  2280. // NOTREACHED
  2281. return 0;
  2282. }
  2283. // NOTE: This code came up with the following stackoverflow post:
  2284. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  2285. inline std::string base64_encode(const std::string &in) {
  2286. static const auto lookup =
  2287. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2288. std::string out;
  2289. out.reserve(in.size());
  2290. auto val = 0;
  2291. auto valb = -6;
  2292. for (auto c : in) {
  2293. val = (val << 8) + static_cast<uint8_t>(c);
  2294. valb += 8;
  2295. while (valb >= 0) {
  2296. out.push_back(lookup[(val >> valb) & 0x3F]);
  2297. valb -= 6;
  2298. }
  2299. }
  2300. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  2301. while (out.size() % 4) {
  2302. out.push_back('=');
  2303. }
  2304. return out;
  2305. }
  2306. inline bool is_valid_path(const std::string &path) {
  2307. size_t level = 0;
  2308. size_t i = 0;
  2309. // Skip slash
  2310. while (i < path.size() && path[i] == '/') {
  2311. i++;
  2312. }
  2313. while (i < path.size()) {
  2314. // Read component
  2315. auto beg = i;
  2316. while (i < path.size() && path[i] != '/') {
  2317. if (path[i] == '\0') {
  2318. return false;
  2319. } else if (path[i] == '\\') {
  2320. return false;
  2321. }
  2322. i++;
  2323. }
  2324. auto len = i - beg;
  2325. assert(len > 0);
  2326. if (!path.compare(beg, len, ".")) {
  2327. ;
  2328. } else if (!path.compare(beg, len, "..")) {
  2329. if (level == 0) { return false; }
  2330. level--;
  2331. } else {
  2332. level++;
  2333. }
  2334. // Skip slash
  2335. while (i < path.size() && path[i] == '/') {
  2336. i++;
  2337. }
  2338. }
  2339. return true;
  2340. }
  2341. inline FileStat::FileStat(const std::string &path) {
  2342. #if defined(_WIN32)
  2343. auto wpath = u8string_to_wstring(path.c_str());
  2344. ret_ = _wstat(wpath.c_str(), &st_);
  2345. #else
  2346. ret_ = stat(path.c_str(), &st_);
  2347. #endif
  2348. }
  2349. inline bool FileStat::is_file() const {
  2350. return ret_ >= 0 && S_ISREG(st_.st_mode);
  2351. }
  2352. inline bool FileStat::is_dir() const {
  2353. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  2354. }
  2355. inline std::string encode_path(const std::string &s) {
  2356. std::string result;
  2357. result.reserve(s.size());
  2358. for (size_t i = 0; s[i]; i++) {
  2359. switch (s[i]) {
  2360. case ' ': result += "%20"; break;
  2361. case '+': result += "%2B"; break;
  2362. case '\r': result += "%0D"; break;
  2363. case '\n': result += "%0A"; break;
  2364. case '\'': result += "%27"; break;
  2365. case ',': result += "%2C"; break;
  2366. // case ':': result += "%3A"; break; // ok? probably...
  2367. case ';': result += "%3B"; break;
  2368. default:
  2369. auto c = static_cast<uint8_t>(s[i]);
  2370. if (c >= 0x80) {
  2371. result += '%';
  2372. char hex[4];
  2373. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  2374. assert(len == 2);
  2375. result.append(hex, static_cast<size_t>(len));
  2376. } else {
  2377. result += s[i];
  2378. }
  2379. break;
  2380. }
  2381. }
  2382. return result;
  2383. }
  2384. inline std::string file_extension(const std::string &path) {
  2385. std::smatch m;
  2386. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  2387. if (std::regex_search(path, m, re)) { return m[1].str(); }
  2388. return std::string();
  2389. }
  2390. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  2391. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  2392. size_t right) {
  2393. while (b + left < e && is_space_or_tab(b[left])) {
  2394. left++;
  2395. }
  2396. while (right > 0 && is_space_or_tab(b[right - 1])) {
  2397. right--;
  2398. }
  2399. return std::make_pair(left, right);
  2400. }
  2401. inline std::string trim_copy(const std::string &s) {
  2402. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  2403. return s.substr(r.first, r.second - r.first);
  2404. }
  2405. inline std::string trim_double_quotes_copy(const std::string &s) {
  2406. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  2407. return s.substr(1, s.size() - 2);
  2408. }
  2409. return s;
  2410. }
  2411. inline void
  2412. divide(const char *data, std::size_t size, char d,
  2413. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2414. fn) {
  2415. const auto it = std::find(data, data + size, d);
  2416. const auto found = static_cast<std::size_t>(it != data + size);
  2417. const auto lhs_data = data;
  2418. const auto lhs_size = static_cast<std::size_t>(it - data);
  2419. const auto rhs_data = it + found;
  2420. const auto rhs_size = size - lhs_size - found;
  2421. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  2422. }
  2423. inline void
  2424. divide(const std::string &str, char d,
  2425. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2426. fn) {
  2427. divide(str.data(), str.size(), d, std::move(fn));
  2428. }
  2429. inline void split(const char *b, const char *e, char d,
  2430. std::function<void(const char *, const char *)> fn) {
  2431. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  2432. }
  2433. inline void split(const char *b, const char *e, char d, size_t m,
  2434. std::function<void(const char *, const char *)> fn) {
  2435. size_t i = 0;
  2436. size_t beg = 0;
  2437. size_t count = 1;
  2438. while (e ? (b + i < e) : (b[i] != '\0')) {
  2439. if (b[i] == d && count < m) {
  2440. auto r = trim(b, e, beg, i);
  2441. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2442. beg = i + 1;
  2443. count++;
  2444. }
  2445. i++;
  2446. }
  2447. if (i) {
  2448. auto r = trim(b, e, beg, i);
  2449. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2450. }
  2451. }
  2452. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  2453. size_t fixed_buffer_size)
  2454. : strm_(strm), fixed_buffer_(fixed_buffer),
  2455. fixed_buffer_size_(fixed_buffer_size) {}
  2456. inline const char *stream_line_reader::ptr() const {
  2457. if (growable_buffer_.empty()) {
  2458. return fixed_buffer_;
  2459. } else {
  2460. return growable_buffer_.data();
  2461. }
  2462. }
  2463. inline size_t stream_line_reader::size() const {
  2464. if (growable_buffer_.empty()) {
  2465. return fixed_buffer_used_size_;
  2466. } else {
  2467. return growable_buffer_.size();
  2468. }
  2469. }
  2470. inline bool stream_line_reader::end_with_crlf() const {
  2471. auto end = ptr() + size();
  2472. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  2473. }
  2474. inline bool stream_line_reader::getline() {
  2475. fixed_buffer_used_size_ = 0;
  2476. growable_buffer_.clear();
  2477. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2478. char prev_byte = 0;
  2479. #endif
  2480. for (size_t i = 0;; i++) {
  2481. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  2482. // Treat exceptionally long lines as an error to
  2483. // prevent infinite loops/memory exhaustion
  2484. return false;
  2485. }
  2486. char byte;
  2487. auto n = strm_.read(&byte, 1);
  2488. if (n < 0) {
  2489. return false;
  2490. } else if (n == 0) {
  2491. if (i == 0) {
  2492. return false;
  2493. } else {
  2494. break;
  2495. }
  2496. }
  2497. append(byte);
  2498. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2499. if (byte == '\n') { break; }
  2500. #else
  2501. if (prev_byte == '\r' && byte == '\n') { break; }
  2502. prev_byte = byte;
  2503. #endif
  2504. }
  2505. return true;
  2506. }
  2507. inline void stream_line_reader::append(char c) {
  2508. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  2509. fixed_buffer_[fixed_buffer_used_size_++] = c;
  2510. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  2511. } else {
  2512. if (growable_buffer_.empty()) {
  2513. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  2514. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  2515. }
  2516. growable_buffer_ += c;
  2517. }
  2518. }
  2519. inline mmap::mmap(const char *path) { open(path); }
  2520. inline mmap::~mmap() { close(); }
  2521. inline bool mmap::open(const char *path) {
  2522. close();
  2523. #if defined(_WIN32)
  2524. auto wpath = u8string_to_wstring(path);
  2525. if (wpath.empty()) { return false; }
  2526. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  2527. OPEN_EXISTING, NULL);
  2528. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  2529. LARGE_INTEGER size{};
  2530. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  2531. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  2532. // See:
  2533. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  2534. if (static_cast<ULONGLONG>(size.QuadPart) >
  2535. (std::numeric_limits<decltype(size_)>::max)()) {
  2536. // `size_t` might be 32-bits, on 32-bits Windows.
  2537. return false;
  2538. }
  2539. size_ = static_cast<size_t>(size.QuadPart);
  2540. hMapping_ =
  2541. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  2542. // Special treatment for an empty file...
  2543. if (hMapping_ == NULL && size_ == 0) {
  2544. close();
  2545. is_open_empty_file = true;
  2546. return true;
  2547. }
  2548. if (hMapping_ == NULL) {
  2549. close();
  2550. return false;
  2551. }
  2552. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  2553. if (addr_ == nullptr) {
  2554. close();
  2555. return false;
  2556. }
  2557. #else
  2558. fd_ = ::open(path, O_RDONLY);
  2559. if (fd_ == -1) { return false; }
  2560. struct stat sb;
  2561. if (fstat(fd_, &sb) == -1) {
  2562. close();
  2563. return false;
  2564. }
  2565. size_ = static_cast<size_t>(sb.st_size);
  2566. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  2567. // Special treatment for an empty file...
  2568. if (addr_ == MAP_FAILED && size_ == 0) {
  2569. close();
  2570. is_open_empty_file = true;
  2571. return false;
  2572. }
  2573. #endif
  2574. return true;
  2575. }
  2576. inline bool mmap::is_open() const {
  2577. return is_open_empty_file ? true : addr_ != nullptr;
  2578. }
  2579. inline size_t mmap::size() const { return size_; }
  2580. inline const char *mmap::data() const {
  2581. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  2582. }
  2583. inline void mmap::close() {
  2584. #if defined(_WIN32)
  2585. if (addr_) {
  2586. ::UnmapViewOfFile(addr_);
  2587. addr_ = nullptr;
  2588. }
  2589. if (hMapping_) {
  2590. ::CloseHandle(hMapping_);
  2591. hMapping_ = NULL;
  2592. }
  2593. if (hFile_ != INVALID_HANDLE_VALUE) {
  2594. ::CloseHandle(hFile_);
  2595. hFile_ = INVALID_HANDLE_VALUE;
  2596. }
  2597. is_open_empty_file = false;
  2598. #else
  2599. if (addr_ != nullptr) {
  2600. munmap(addr_, size_);
  2601. addr_ = nullptr;
  2602. }
  2603. if (fd_ != -1) {
  2604. ::close(fd_);
  2605. fd_ = -1;
  2606. }
  2607. #endif
  2608. size_ = 0;
  2609. }
  2610. inline int close_socket(socket_t sock) {
  2611. #ifdef _WIN32
  2612. return closesocket(sock);
  2613. #else
  2614. return close(sock);
  2615. #endif
  2616. }
  2617. template <typename T> inline ssize_t handle_EINTR(T fn) {
  2618. ssize_t res = 0;
  2619. while (true) {
  2620. res = fn();
  2621. if (res < 0 && errno == EINTR) {
  2622. std::this_thread::sleep_for(std::chrono::microseconds{1});
  2623. continue;
  2624. }
  2625. break;
  2626. }
  2627. return res;
  2628. }
  2629. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  2630. return handle_EINTR([&]() {
  2631. return recv(sock,
  2632. #ifdef _WIN32
  2633. static_cast<char *>(ptr), static_cast<int>(size),
  2634. #else
  2635. ptr, size,
  2636. #endif
  2637. flags);
  2638. });
  2639. }
  2640. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  2641. int flags) {
  2642. return handle_EINTR([&]() {
  2643. return send(sock,
  2644. #ifdef _WIN32
  2645. static_cast<const char *>(ptr), static_cast<int>(size),
  2646. #else
  2647. ptr, size,
  2648. #endif
  2649. flags);
  2650. });
  2651. }
  2652. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  2653. #ifdef _WIN32
  2654. return ::WSAPoll(fds, nfds, timeout);
  2655. #else
  2656. return ::poll(fds, nfds, timeout);
  2657. #endif
  2658. }
  2659. template <bool Read>
  2660. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  2661. #ifdef __APPLE__
  2662. if (sock >= FD_SETSIZE) { return -1; }
  2663. fd_set fds, *rfds, *wfds;
  2664. FD_ZERO(&fds);
  2665. FD_SET(sock, &fds);
  2666. rfds = (Read ? &fds : nullptr);
  2667. wfds = (Read ? nullptr : &fds);
  2668. timeval tv;
  2669. tv.tv_sec = static_cast<long>(sec);
  2670. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  2671. return handle_EINTR([&]() {
  2672. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  2673. });
  2674. #else
  2675. struct pollfd pfd;
  2676. pfd.fd = sock;
  2677. pfd.events = (Read ? POLLIN : POLLOUT);
  2678. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2679. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  2680. #endif
  2681. }
  2682. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  2683. return select_impl<true>(sock, sec, usec);
  2684. }
  2685. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  2686. return select_impl<false>(sock, sec, usec);
  2687. }
  2688. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  2689. time_t usec) {
  2690. #ifdef __APPLE__
  2691. if (sock >= FD_SETSIZE) { return Error::Connection; }
  2692. fd_set fdsr, fdsw;
  2693. FD_ZERO(&fdsr);
  2694. FD_ZERO(&fdsw);
  2695. FD_SET(sock, &fdsr);
  2696. FD_SET(sock, &fdsw);
  2697. timeval tv;
  2698. tv.tv_sec = static_cast<long>(sec);
  2699. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  2700. auto ret = handle_EINTR([&]() {
  2701. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  2702. });
  2703. if (ret == 0) { return Error::ConnectionTimeout; }
  2704. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  2705. auto error = 0;
  2706. socklen_t len = sizeof(error);
  2707. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2708. reinterpret_cast<char *>(&error), &len);
  2709. auto successful = res >= 0 && !error;
  2710. return successful ? Error::Success : Error::Connection;
  2711. }
  2712. return Error::Connection;
  2713. #else
  2714. struct pollfd pfd_read;
  2715. pfd_read.fd = sock;
  2716. pfd_read.events = POLLIN | POLLOUT;
  2717. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2718. auto poll_res =
  2719. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  2720. if (poll_res == 0) { return Error::ConnectionTimeout; }
  2721. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  2722. auto error = 0;
  2723. socklen_t len = sizeof(error);
  2724. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2725. reinterpret_cast<char *>(&error), &len);
  2726. auto successful = res >= 0 && !error;
  2727. return successful ? Error::Success : Error::Connection;
  2728. }
  2729. return Error::Connection;
  2730. #endif
  2731. }
  2732. inline bool is_socket_alive(socket_t sock) {
  2733. const auto val = detail::select_read(sock, 0, 0);
  2734. if (val == 0) {
  2735. return true;
  2736. } else if (val < 0 && errno == EBADF) {
  2737. return false;
  2738. }
  2739. char buf[1];
  2740. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  2741. }
  2742. class SocketStream final : public Stream {
  2743. public:
  2744. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2745. time_t write_timeout_sec, time_t write_timeout_usec,
  2746. time_t max_timeout_msec = 0,
  2747. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2748. (std::chrono::steady_clock::time_point::min)());
  2749. ~SocketStream() override;
  2750. bool is_readable() const override;
  2751. bool wait_readable() const override;
  2752. bool wait_writable() const override;
  2753. ssize_t read(char *ptr, size_t size) override;
  2754. ssize_t write(const char *ptr, size_t size) override;
  2755. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2756. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2757. socket_t socket() const override;
  2758. time_t duration() const override;
  2759. private:
  2760. socket_t sock_;
  2761. time_t read_timeout_sec_;
  2762. time_t read_timeout_usec_;
  2763. time_t write_timeout_sec_;
  2764. time_t write_timeout_usec_;
  2765. time_t max_timeout_msec_;
  2766. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2767. std::vector<char> read_buff_;
  2768. size_t read_buff_off_ = 0;
  2769. size_t read_buff_content_size_ = 0;
  2770. static const size_t read_buff_size_ = 1024l * 4;
  2771. };
  2772. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2773. class SSLSocketStream final : public Stream {
  2774. public:
  2775. SSLSocketStream(
  2776. socket_t sock, SSL *ssl, time_t read_timeout_sec,
  2777. time_t read_timeout_usec, time_t write_timeout_sec,
  2778. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  2779. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2780. (std::chrono::steady_clock::time_point::min)());
  2781. ~SSLSocketStream() override;
  2782. bool is_readable() const override;
  2783. bool wait_readable() const override;
  2784. bool wait_writable() const override;
  2785. ssize_t read(char *ptr, size_t size) override;
  2786. ssize_t write(const char *ptr, size_t size) override;
  2787. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2788. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2789. socket_t socket() const override;
  2790. time_t duration() const override;
  2791. private:
  2792. socket_t sock_;
  2793. SSL *ssl_;
  2794. time_t read_timeout_sec_;
  2795. time_t read_timeout_usec_;
  2796. time_t write_timeout_sec_;
  2797. time_t write_timeout_usec_;
  2798. time_t max_timeout_msec_;
  2799. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2800. };
  2801. #endif
  2802. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2803. time_t keep_alive_timeout_sec) {
  2804. using namespace std::chrono;
  2805. const auto interval_usec =
  2806. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  2807. // Avoid expensive `steady_clock::now()` call for the first time
  2808. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  2809. const auto start = steady_clock::now() - microseconds{interval_usec};
  2810. const auto timeout = seconds{keep_alive_timeout_sec};
  2811. while (true) {
  2812. if (svr_sock == INVALID_SOCKET) {
  2813. break; // Server socket is closed
  2814. }
  2815. auto val = select_read(sock, 0, interval_usec);
  2816. if (val < 0) {
  2817. break; // Ssocket error
  2818. } else if (val == 0) {
  2819. if (steady_clock::now() - start > timeout) {
  2820. break; // Timeout
  2821. }
  2822. } else {
  2823. return true; // Ready for read
  2824. }
  2825. }
  2826. return false;
  2827. }
  2828. template <typename T>
  2829. inline bool
  2830. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2831. size_t keep_alive_max_count,
  2832. time_t keep_alive_timeout_sec, T callback) {
  2833. assert(keep_alive_max_count > 0);
  2834. auto ret = false;
  2835. auto count = keep_alive_max_count;
  2836. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  2837. auto close_connection = count == 1;
  2838. auto connection_closed = false;
  2839. ret = callback(close_connection, connection_closed);
  2840. if (!ret || connection_closed) { break; }
  2841. count--;
  2842. }
  2843. return ret;
  2844. }
  2845. template <typename T>
  2846. inline bool
  2847. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2848. size_t keep_alive_max_count,
  2849. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  2850. time_t read_timeout_usec, time_t write_timeout_sec,
  2851. time_t write_timeout_usec, T callback) {
  2852. return process_server_socket_core(
  2853. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  2854. [&](bool close_connection, bool &connection_closed) {
  2855. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2856. write_timeout_sec, write_timeout_usec);
  2857. return callback(strm, close_connection, connection_closed);
  2858. });
  2859. }
  2860. inline bool process_client_socket(
  2861. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2862. time_t write_timeout_sec, time_t write_timeout_usec,
  2863. time_t max_timeout_msec,
  2864. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2865. std::function<bool(Stream &)> callback) {
  2866. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2867. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  2868. start_time);
  2869. return callback(strm);
  2870. }
  2871. inline int shutdown_socket(socket_t sock) {
  2872. #ifdef _WIN32
  2873. return shutdown(sock, SD_BOTH);
  2874. #else
  2875. return shutdown(sock, SHUT_RDWR);
  2876. #endif
  2877. }
  2878. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  2879. if (s.size() > 1 && s[0] == '\0') {
  2880. auto ret = s;
  2881. ret[0] = '@';
  2882. return ret;
  2883. }
  2884. return s;
  2885. }
  2886. inline std::string
  2887. unescape_abstract_namespace_unix_domain(const std::string &s) {
  2888. if (s.size() > 1 && s[0] == '@') {
  2889. auto ret = s;
  2890. ret[0] = '\0';
  2891. return ret;
  2892. }
  2893. return s;
  2894. }
  2895. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  2896. const struct addrinfo *hints,
  2897. struct addrinfo **res, time_t timeout_sec) {
  2898. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2899. if (timeout_sec <= 0) {
  2900. // No timeout specified, use standard getaddrinfo
  2901. return getaddrinfo(node, service, hints, res);
  2902. }
  2903. #ifdef _WIN32
  2904. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  2905. OVERLAPPED overlapped = {0};
  2906. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  2907. if (!event) { return EAI_FAIL; }
  2908. overlapped.hEvent = event;
  2909. PADDRINFOEXW result_addrinfo = nullptr;
  2910. HANDLE cancel_handle = nullptr;
  2911. ADDRINFOEXW hints_ex = {0};
  2912. if (hints) {
  2913. hints_ex.ai_flags = hints->ai_flags;
  2914. hints_ex.ai_family = hints->ai_family;
  2915. hints_ex.ai_socktype = hints->ai_socktype;
  2916. hints_ex.ai_protocol = hints->ai_protocol;
  2917. }
  2918. auto wnode = u8string_to_wstring(node);
  2919. auto wservice = u8string_to_wstring(service);
  2920. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  2921. hints ? &hints_ex : nullptr, &result_addrinfo,
  2922. nullptr, &overlapped, nullptr, &cancel_handle);
  2923. if (ret == WSA_IO_PENDING) {
  2924. auto wait_result =
  2925. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  2926. if (wait_result == WAIT_TIMEOUT) {
  2927. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  2928. ::CloseHandle(event);
  2929. return EAI_AGAIN;
  2930. }
  2931. DWORD bytes_returned;
  2932. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  2933. &bytes_returned, FALSE)) {
  2934. ::CloseHandle(event);
  2935. return ::WSAGetLastError();
  2936. }
  2937. }
  2938. ::CloseHandle(event);
  2939. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  2940. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  2941. return 0;
  2942. }
  2943. return ret;
  2944. #elif TARGET_OS_MAC
  2945. // macOS implementation using CFHost API for asynchronous DNS resolution
  2946. CFStringRef hostname_ref = CFStringCreateWithCString(
  2947. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  2948. if (!hostname_ref) { return EAI_MEMORY; }
  2949. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  2950. CFRelease(hostname_ref);
  2951. if (!host_ref) { return EAI_MEMORY; }
  2952. // Set up context for callback
  2953. struct CFHostContext {
  2954. bool completed = false;
  2955. bool success = false;
  2956. CFArrayRef addresses = nullptr;
  2957. std::mutex mutex;
  2958. std::condition_variable cv;
  2959. } context;
  2960. CFHostClientContext client_context;
  2961. memset(&client_context, 0, sizeof(client_context));
  2962. client_context.info = &context;
  2963. // Set callback
  2964. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  2965. const CFStreamError *error, void *info) {
  2966. auto ctx = static_cast<CFHostContext *>(info);
  2967. std::lock_guard<std::mutex> lock(ctx->mutex);
  2968. if (error && error->error != 0) {
  2969. ctx->success = false;
  2970. } else {
  2971. Boolean hasBeenResolved;
  2972. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  2973. if (ctx->addresses && hasBeenResolved) {
  2974. CFRetain(ctx->addresses);
  2975. ctx->success = true;
  2976. } else {
  2977. ctx->success = false;
  2978. }
  2979. }
  2980. ctx->completed = true;
  2981. ctx->cv.notify_one();
  2982. };
  2983. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  2984. CFRelease(host_ref);
  2985. return EAI_SYSTEM;
  2986. }
  2987. // Schedule on run loop
  2988. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  2989. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2990. // Start resolution
  2991. CFStreamError stream_error;
  2992. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  2993. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2994. CFRelease(host_ref);
  2995. return EAI_FAIL;
  2996. }
  2997. // Wait for completion with timeout
  2998. auto timeout_time =
  2999. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  3000. bool timed_out = false;
  3001. {
  3002. std::unique_lock<std::mutex> lock(context.mutex);
  3003. while (!context.completed) {
  3004. auto now = std::chrono::steady_clock::now();
  3005. if (now >= timeout_time) {
  3006. timed_out = true;
  3007. break;
  3008. }
  3009. // Run the runloop for a short time
  3010. lock.unlock();
  3011. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  3012. lock.lock();
  3013. }
  3014. }
  3015. // Clean up
  3016. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  3017. CFHostSetClient(host_ref, nullptr, nullptr);
  3018. if (timed_out || !context.completed) {
  3019. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  3020. CFRelease(host_ref);
  3021. return EAI_AGAIN;
  3022. }
  3023. if (!context.success || !context.addresses) {
  3024. CFRelease(host_ref);
  3025. return EAI_NODATA;
  3026. }
  3027. // Convert CFArray to addrinfo
  3028. CFIndex count = CFArrayGetCount(context.addresses);
  3029. if (count == 0) {
  3030. CFRelease(context.addresses);
  3031. CFRelease(host_ref);
  3032. return EAI_NODATA;
  3033. }
  3034. struct addrinfo *result_addrinfo = nullptr;
  3035. struct addrinfo **current = &result_addrinfo;
  3036. for (CFIndex i = 0; i < count; i++) {
  3037. CFDataRef addr_data =
  3038. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  3039. if (!addr_data) continue;
  3040. const struct sockaddr *sockaddr_ptr =
  3041. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  3042. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  3043. // Allocate addrinfo structure
  3044. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  3045. if (!*current) {
  3046. freeaddrinfo(result_addrinfo);
  3047. CFRelease(context.addresses);
  3048. CFRelease(host_ref);
  3049. return EAI_MEMORY;
  3050. }
  3051. memset(*current, 0, sizeof(struct addrinfo));
  3052. // Set up addrinfo fields
  3053. (*current)->ai_family = sockaddr_ptr->sa_family;
  3054. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  3055. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  3056. (*current)->ai_addrlen = sockaddr_len;
  3057. // Copy sockaddr
  3058. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  3059. if (!(*current)->ai_addr) {
  3060. freeaddrinfo(result_addrinfo);
  3061. CFRelease(context.addresses);
  3062. CFRelease(host_ref);
  3063. return EAI_MEMORY;
  3064. }
  3065. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  3066. // Set port if service is specified
  3067. if (service && strlen(service) > 0) {
  3068. int port = atoi(service);
  3069. if (port > 0) {
  3070. if (sockaddr_ptr->sa_family == AF_INET) {
  3071. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  3072. ->sin_port = htons(static_cast<uint16_t>(port));
  3073. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  3074. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  3075. ->sin6_port = htons(static_cast<uint16_t>(port));
  3076. }
  3077. }
  3078. }
  3079. current = &((*current)->ai_next);
  3080. }
  3081. CFRelease(context.addresses);
  3082. CFRelease(host_ref);
  3083. *res = result_addrinfo;
  3084. return 0;
  3085. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  3086. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  3087. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  3088. struct gaicb request;
  3089. struct gaicb *requests[1] = {&request};
  3090. struct sigevent sevp;
  3091. struct timespec timeout;
  3092. // Initialize the request structure
  3093. memset(&request, 0, sizeof(request));
  3094. request.ar_name = node;
  3095. request.ar_service = service;
  3096. request.ar_request = hints;
  3097. // Set up timeout
  3098. timeout.tv_sec = timeout_sec;
  3099. timeout.tv_nsec = 0;
  3100. // Initialize sigevent structure (not used, but required)
  3101. memset(&sevp, 0, sizeof(sevp));
  3102. sevp.sigev_notify = SIGEV_NONE;
  3103. // Start asynchronous resolution
  3104. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  3105. if (start_result != 0) { return start_result; }
  3106. // Wait for completion with timeout
  3107. int wait_result =
  3108. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  3109. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  3110. // Completed successfully, get the result
  3111. int gai_result = gai_error(&request);
  3112. if (gai_result == 0) {
  3113. *res = request.ar_result;
  3114. return 0;
  3115. } else {
  3116. // Clean up on error
  3117. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  3118. return gai_result;
  3119. }
  3120. } else if (wait_result == EAI_AGAIN) {
  3121. // Timeout occurred, cancel the request
  3122. gai_cancel(&request);
  3123. return EAI_AGAIN;
  3124. } else {
  3125. // Other error occurred
  3126. gai_cancel(&request);
  3127. return wait_result;
  3128. }
  3129. #else
  3130. // Fallback implementation using thread-based timeout for other Unix systems
  3131. struct GetAddrInfoState {
  3132. std::mutex mutex;
  3133. std::condition_variable result_cv;
  3134. bool completed = false;
  3135. int result = EAI_SYSTEM;
  3136. std::string node = node;
  3137. std::string service = service;
  3138. struct addrinfo hints = hints;
  3139. struct addrinfo *info = nullptr;
  3140. };
  3141. // Allocate on the heap, so the resolver thread can keep using the data.
  3142. auto state = std::make_shared<GetAddrInfoState>();
  3143. std::thread resolve_thread([=]() {
  3144. auto thread_result = getaddrinfo(
  3145. state->node.c_str(), state->service.c_str(), hints, &state->info);
  3146. std::lock_guard<std::mutex> lock(state->mutex);
  3147. state->result = thread_result;
  3148. state->completed = true;
  3149. state->result_cv.notify_one();
  3150. });
  3151. // Wait for completion or timeout
  3152. std::unique_lock<std::mutex> lock(state->mutex);
  3153. auto finished =
  3154. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  3155. [&] { return state->completed; });
  3156. if (finished) {
  3157. // Operation completed within timeout
  3158. resolve_thread.join();
  3159. *res = state->info;
  3160. return state->result;
  3161. } else {
  3162. // Timeout occurred
  3163. resolve_thread.detach(); // Let the thread finish in background
  3164. return EAI_AGAIN; // Return timeout error
  3165. }
  3166. #endif
  3167. #else
  3168. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  3169. return getaddrinfo(node, service, hints, res);
  3170. #endif
  3171. }
  3172. template <typename BindOrConnect>
  3173. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  3174. int address_family, int socket_flags, bool tcp_nodelay,
  3175. bool ipv6_v6only, SocketOptions socket_options,
  3176. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  3177. // Get address info
  3178. const char *node = nullptr;
  3179. struct addrinfo hints;
  3180. struct addrinfo *result;
  3181. memset(&hints, 0, sizeof(struct addrinfo));
  3182. hints.ai_socktype = SOCK_STREAM;
  3183. hints.ai_protocol = IPPROTO_IP;
  3184. if (!ip.empty()) {
  3185. node = ip.c_str();
  3186. // Ask getaddrinfo to convert IP in c-string to address
  3187. hints.ai_family = AF_UNSPEC;
  3188. hints.ai_flags = AI_NUMERICHOST;
  3189. } else {
  3190. if (!host.empty()) { node = host.c_str(); }
  3191. hints.ai_family = address_family;
  3192. hints.ai_flags = socket_flags;
  3193. }
  3194. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  3195. if (hints.ai_family == AF_UNIX) {
  3196. const auto addrlen = host.length();
  3197. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  3198. #ifdef SOCK_CLOEXEC
  3199. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  3200. hints.ai_protocol);
  3201. #else
  3202. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  3203. #endif
  3204. if (sock != INVALID_SOCKET) {
  3205. sockaddr_un addr{};
  3206. addr.sun_family = AF_UNIX;
  3207. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  3208. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  3209. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  3210. hints.ai_addrlen = static_cast<socklen_t>(
  3211. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  3212. #ifndef SOCK_CLOEXEC
  3213. #ifndef _WIN32
  3214. fcntl(sock, F_SETFD, FD_CLOEXEC);
  3215. #endif
  3216. #endif
  3217. if (socket_options) { socket_options(sock); }
  3218. #ifdef _WIN32
  3219. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  3220. // remove the option.
  3221. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  3222. #endif
  3223. bool dummy;
  3224. if (!bind_or_connect(sock, hints, dummy)) {
  3225. close_socket(sock);
  3226. sock = INVALID_SOCKET;
  3227. }
  3228. }
  3229. return sock;
  3230. }
  3231. #endif
  3232. auto service = std::to_string(port);
  3233. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  3234. timeout_sec)) {
  3235. #if defined __linux__ && !defined __ANDROID__
  3236. res_init();
  3237. #endif
  3238. return INVALID_SOCKET;
  3239. }
  3240. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  3241. for (auto rp = result; rp; rp = rp->ai_next) {
  3242. // Create a socket
  3243. #ifdef _WIN32
  3244. auto sock =
  3245. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  3246. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  3247. /**
  3248. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  3249. * and above the socket creation fails on older Windows Systems.
  3250. *
  3251. * Let's try to create a socket the old way in this case.
  3252. *
  3253. * Reference:
  3254. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  3255. *
  3256. * WSA_FLAG_NO_HANDLE_INHERIT:
  3257. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  3258. * SP1, and later
  3259. *
  3260. */
  3261. if (sock == INVALID_SOCKET) {
  3262. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  3263. }
  3264. #else
  3265. #ifdef SOCK_CLOEXEC
  3266. auto sock =
  3267. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  3268. #else
  3269. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  3270. #endif
  3271. #endif
  3272. if (sock == INVALID_SOCKET) { continue; }
  3273. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  3274. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  3275. close_socket(sock);
  3276. continue;
  3277. }
  3278. #endif
  3279. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  3280. if (rp->ai_family == AF_INET6) {
  3281. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  3282. }
  3283. if (socket_options) { socket_options(sock); }
  3284. // bind or connect
  3285. auto quit = false;
  3286. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  3287. close_socket(sock);
  3288. if (quit) { break; }
  3289. }
  3290. return INVALID_SOCKET;
  3291. }
  3292. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  3293. #ifdef _WIN32
  3294. auto flags = nonblocking ? 1UL : 0UL;
  3295. ioctlsocket(sock, FIONBIO, &flags);
  3296. #else
  3297. auto flags = fcntl(sock, F_GETFL, 0);
  3298. fcntl(sock, F_SETFL,
  3299. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  3300. #endif
  3301. }
  3302. inline bool is_connection_error() {
  3303. #ifdef _WIN32
  3304. return WSAGetLastError() != WSAEWOULDBLOCK;
  3305. #else
  3306. return errno != EINPROGRESS;
  3307. #endif
  3308. }
  3309. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  3310. struct addrinfo hints;
  3311. struct addrinfo *result;
  3312. memset(&hints, 0, sizeof(struct addrinfo));
  3313. hints.ai_family = AF_UNSPEC;
  3314. hints.ai_socktype = SOCK_STREAM;
  3315. hints.ai_protocol = 0;
  3316. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  3317. return false;
  3318. }
  3319. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  3320. auto ret = false;
  3321. for (auto rp = result; rp; rp = rp->ai_next) {
  3322. const auto &ai = *rp;
  3323. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  3324. ret = true;
  3325. break;
  3326. }
  3327. }
  3328. return ret;
  3329. }
  3330. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  3331. #define USE_IF2IP
  3332. #endif
  3333. #ifdef USE_IF2IP
  3334. inline std::string if2ip(int address_family, const std::string &ifn) {
  3335. struct ifaddrs *ifap;
  3336. getifaddrs(&ifap);
  3337. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  3338. std::string addr_candidate;
  3339. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  3340. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  3341. (AF_UNSPEC == address_family ||
  3342. ifa->ifa_addr->sa_family == address_family)) {
  3343. if (ifa->ifa_addr->sa_family == AF_INET) {
  3344. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  3345. char buf[INET_ADDRSTRLEN];
  3346. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  3347. return std::string(buf, INET_ADDRSTRLEN);
  3348. }
  3349. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  3350. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  3351. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  3352. char buf[INET6_ADDRSTRLEN] = {};
  3353. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  3354. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  3355. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  3356. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  3357. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  3358. } else {
  3359. return std::string(buf, INET6_ADDRSTRLEN);
  3360. }
  3361. }
  3362. }
  3363. }
  3364. }
  3365. }
  3366. return addr_candidate;
  3367. }
  3368. #endif
  3369. inline socket_t create_client_socket(
  3370. const std::string &host, const std::string &ip, int port,
  3371. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  3372. SocketOptions socket_options, time_t connection_timeout_sec,
  3373. time_t connection_timeout_usec, time_t read_timeout_sec,
  3374. time_t read_timeout_usec, time_t write_timeout_sec,
  3375. time_t write_timeout_usec, const std::string &intf, Error &error) {
  3376. auto sock = create_socket(
  3377. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  3378. std::move(socket_options),
  3379. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  3380. if (!intf.empty()) {
  3381. #ifdef USE_IF2IP
  3382. auto ip_from_if = if2ip(address_family, intf);
  3383. if (ip_from_if.empty()) { ip_from_if = intf; }
  3384. if (!bind_ip_address(sock2, ip_from_if)) {
  3385. error = Error::BindIPAddress;
  3386. return false;
  3387. }
  3388. #endif
  3389. }
  3390. set_nonblocking(sock2, true);
  3391. auto ret =
  3392. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  3393. if (ret < 0) {
  3394. if (is_connection_error()) {
  3395. error = Error::Connection;
  3396. return false;
  3397. }
  3398. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  3399. connection_timeout_usec);
  3400. if (error != Error::Success) {
  3401. if (error == Error::ConnectionTimeout) { quit = true; }
  3402. return false;
  3403. }
  3404. }
  3405. set_nonblocking(sock2, false);
  3406. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  3407. read_timeout_usec);
  3408. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  3409. write_timeout_usec);
  3410. error = Error::Success;
  3411. return true;
  3412. },
  3413. connection_timeout_sec); // Pass DNS timeout
  3414. if (sock != INVALID_SOCKET) {
  3415. error = Error::Success;
  3416. } else {
  3417. if (error == Error::Success) { error = Error::Connection; }
  3418. }
  3419. return sock;
  3420. }
  3421. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  3422. socklen_t addr_len, std::string &ip, int &port) {
  3423. if (addr.ss_family == AF_INET) {
  3424. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  3425. } else if (addr.ss_family == AF_INET6) {
  3426. port =
  3427. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  3428. } else {
  3429. return false;
  3430. }
  3431. std::array<char, NI_MAXHOST> ipstr{};
  3432. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  3433. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  3434. 0, NI_NUMERICHOST)) {
  3435. return false;
  3436. }
  3437. ip = ipstr.data();
  3438. return true;
  3439. }
  3440. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3441. struct sockaddr_storage addr;
  3442. socklen_t addr_len = sizeof(addr);
  3443. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3444. &addr_len)) {
  3445. get_ip_and_port(addr, addr_len, ip, port);
  3446. }
  3447. }
  3448. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3449. struct sockaddr_storage addr;
  3450. socklen_t addr_len = sizeof(addr);
  3451. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3452. &addr_len)) {
  3453. #ifndef _WIN32
  3454. if (addr.ss_family == AF_UNIX) {
  3455. #if defined(__linux__)
  3456. struct ucred ucred;
  3457. socklen_t len = sizeof(ucred);
  3458. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  3459. port = ucred.pid;
  3460. }
  3461. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  3462. pid_t pid;
  3463. socklen_t len = sizeof(pid);
  3464. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  3465. port = pid;
  3466. }
  3467. #endif
  3468. return;
  3469. }
  3470. #endif
  3471. get_ip_and_port(addr, addr_len, ip, port);
  3472. }
  3473. }
  3474. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  3475. unsigned int h) {
  3476. return (l == 0)
  3477. ? h
  3478. : str2tag_core(
  3479. s + 1, l - 1,
  3480. // Unsets the 6 high bits of h, therefore no overflow happens
  3481. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  3482. h * 33) ^
  3483. static_cast<unsigned char>(*s));
  3484. }
  3485. inline unsigned int str2tag(const std::string &s) {
  3486. return str2tag_core(s.data(), s.size(), 0);
  3487. }
  3488. namespace udl {
  3489. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  3490. return str2tag_core(s, l, 0);
  3491. }
  3492. } // namespace udl
  3493. inline std::string
  3494. find_content_type(const std::string &path,
  3495. const std::map<std::string, std::string> &user_data,
  3496. const std::string &default_content_type) {
  3497. auto ext = file_extension(path);
  3498. auto it = user_data.find(ext);
  3499. if (it != user_data.end()) { return it->second; }
  3500. using udl::operator""_t;
  3501. switch (str2tag(ext)) {
  3502. default: return default_content_type;
  3503. case "css"_t: return "text/css";
  3504. case "csv"_t: return "text/csv";
  3505. case "htm"_t:
  3506. case "html"_t: return "text/html";
  3507. case "js"_t:
  3508. case "mjs"_t: return "text/javascript";
  3509. case "txt"_t: return "text/plain";
  3510. case "vtt"_t: return "text/vtt";
  3511. case "apng"_t: return "image/apng";
  3512. case "avif"_t: return "image/avif";
  3513. case "bmp"_t: return "image/bmp";
  3514. case "gif"_t: return "image/gif";
  3515. case "png"_t: return "image/png";
  3516. case "svg"_t: return "image/svg+xml";
  3517. case "webp"_t: return "image/webp";
  3518. case "ico"_t: return "image/x-icon";
  3519. case "tif"_t: return "image/tiff";
  3520. case "tiff"_t: return "image/tiff";
  3521. case "jpg"_t:
  3522. case "jpeg"_t: return "image/jpeg";
  3523. case "mp4"_t: return "video/mp4";
  3524. case "mpeg"_t: return "video/mpeg";
  3525. case "webm"_t: return "video/webm";
  3526. case "mp3"_t: return "audio/mp3";
  3527. case "mpga"_t: return "audio/mpeg";
  3528. case "weba"_t: return "audio/webm";
  3529. case "wav"_t: return "audio/wave";
  3530. case "otf"_t: return "font/otf";
  3531. case "ttf"_t: return "font/ttf";
  3532. case "woff"_t: return "font/woff";
  3533. case "woff2"_t: return "font/woff2";
  3534. case "7z"_t: return "application/x-7z-compressed";
  3535. case "atom"_t: return "application/atom+xml";
  3536. case "pdf"_t: return "application/pdf";
  3537. case "json"_t: return "application/json";
  3538. case "rss"_t: return "application/rss+xml";
  3539. case "tar"_t: return "application/x-tar";
  3540. case "xht"_t:
  3541. case "xhtml"_t: return "application/xhtml+xml";
  3542. case "xslt"_t: return "application/xslt+xml";
  3543. case "xml"_t: return "application/xml";
  3544. case "gz"_t: return "application/gzip";
  3545. case "zip"_t: return "application/zip";
  3546. case "wasm"_t: return "application/wasm";
  3547. }
  3548. }
  3549. inline bool can_compress_content_type(const std::string &content_type) {
  3550. using udl::operator""_t;
  3551. auto tag = str2tag(content_type);
  3552. switch (tag) {
  3553. case "image/svg+xml"_t:
  3554. case "application/javascript"_t:
  3555. case "application/json"_t:
  3556. case "application/xml"_t:
  3557. case "application/protobuf"_t:
  3558. case "application/xhtml+xml"_t: return true;
  3559. case "text/event-stream"_t: return false;
  3560. default: return !content_type.rfind("text/", 0);
  3561. }
  3562. }
  3563. inline EncodingType encoding_type(const Request &req, const Response &res) {
  3564. auto ret =
  3565. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  3566. if (!ret) { return EncodingType::None; }
  3567. const auto &s = req.get_header_value("Accept-Encoding");
  3568. (void)(s);
  3569. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3570. // TODO: 'Accept-Encoding' has br, not br;q=0
  3571. ret = s.find("br") != std::string::npos;
  3572. if (ret) { return EncodingType::Brotli; }
  3573. #endif
  3574. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3575. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  3576. ret = s.find("gzip") != std::string::npos;
  3577. if (ret) { return EncodingType::Gzip; }
  3578. #endif
  3579. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3580. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  3581. ret = s.find("zstd") != std::string::npos;
  3582. if (ret) { return EncodingType::Zstd; }
  3583. #endif
  3584. return EncodingType::None;
  3585. }
  3586. inline bool nocompressor::compress(const char *data, size_t data_length,
  3587. bool /*last*/, Callback callback) {
  3588. if (!data_length) { return true; }
  3589. return callback(data, data_length);
  3590. }
  3591. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3592. inline gzip_compressor::gzip_compressor() {
  3593. std::memset(&strm_, 0, sizeof(strm_));
  3594. strm_.zalloc = Z_NULL;
  3595. strm_.zfree = Z_NULL;
  3596. strm_.opaque = Z_NULL;
  3597. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  3598. Z_DEFAULT_STRATEGY) == Z_OK;
  3599. }
  3600. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  3601. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  3602. bool last, Callback callback) {
  3603. assert(is_valid_);
  3604. do {
  3605. constexpr size_t max_avail_in =
  3606. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3607. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3608. (std::min)(data_length, max_avail_in));
  3609. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3610. data_length -= strm_.avail_in;
  3611. data += strm_.avail_in;
  3612. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  3613. auto ret = Z_OK;
  3614. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3615. do {
  3616. strm_.avail_out = static_cast<uInt>(buff.size());
  3617. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3618. ret = deflate(&strm_, flush);
  3619. if (ret == Z_STREAM_ERROR) { return false; }
  3620. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3621. return false;
  3622. }
  3623. } while (strm_.avail_out == 0);
  3624. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  3625. (flush == Z_NO_FLUSH && ret == Z_OK));
  3626. assert(strm_.avail_in == 0);
  3627. } while (data_length > 0);
  3628. return true;
  3629. }
  3630. inline gzip_decompressor::gzip_decompressor() {
  3631. std::memset(&strm_, 0, sizeof(strm_));
  3632. strm_.zalloc = Z_NULL;
  3633. strm_.zfree = Z_NULL;
  3634. strm_.opaque = Z_NULL;
  3635. // 15 is the value of wbits, which should be at the maximum possible value
  3636. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  3637. // that the stream type should be automatically detected either gzip or
  3638. // deflate.
  3639. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  3640. }
  3641. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  3642. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  3643. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  3644. Callback callback) {
  3645. assert(is_valid_);
  3646. auto ret = Z_OK;
  3647. do {
  3648. constexpr size_t max_avail_in =
  3649. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3650. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3651. (std::min)(data_length, max_avail_in));
  3652. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3653. data_length -= strm_.avail_in;
  3654. data += strm_.avail_in;
  3655. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3656. while (strm_.avail_in > 0 && ret == Z_OK) {
  3657. strm_.avail_out = static_cast<uInt>(buff.size());
  3658. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3659. ret = inflate(&strm_, Z_NO_FLUSH);
  3660. assert(ret != Z_STREAM_ERROR);
  3661. switch (ret) {
  3662. case Z_NEED_DICT:
  3663. case Z_DATA_ERROR:
  3664. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  3665. }
  3666. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3667. return false;
  3668. }
  3669. }
  3670. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  3671. } while (data_length > 0);
  3672. return true;
  3673. }
  3674. #endif
  3675. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3676. inline brotli_compressor::brotli_compressor() {
  3677. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  3678. }
  3679. inline brotli_compressor::~brotli_compressor() {
  3680. BrotliEncoderDestroyInstance(state_);
  3681. }
  3682. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  3683. bool last, Callback callback) {
  3684. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3685. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  3686. auto available_in = data_length;
  3687. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3688. for (;;) {
  3689. if (last) {
  3690. if (BrotliEncoderIsFinished(state_)) { break; }
  3691. } else {
  3692. if (!available_in) { break; }
  3693. }
  3694. auto available_out = buff.size();
  3695. auto next_out = buff.data();
  3696. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  3697. &available_out, &next_out, nullptr)) {
  3698. return false;
  3699. }
  3700. auto output_bytes = buff.size() - available_out;
  3701. if (output_bytes) {
  3702. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  3703. }
  3704. }
  3705. return true;
  3706. }
  3707. inline brotli_decompressor::brotli_decompressor() {
  3708. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  3709. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  3710. : BROTLI_DECODER_RESULT_ERROR;
  3711. }
  3712. inline brotli_decompressor::~brotli_decompressor() {
  3713. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  3714. }
  3715. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  3716. inline bool brotli_decompressor::decompress(const char *data,
  3717. size_t data_length,
  3718. Callback callback) {
  3719. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3720. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  3721. return 0;
  3722. }
  3723. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3724. size_t avail_in = data_length;
  3725. size_t total_out;
  3726. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  3727. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3728. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  3729. char *next_out = buff.data();
  3730. size_t avail_out = buff.size();
  3731. decoder_r = BrotliDecoderDecompressStream(
  3732. decoder_s, &avail_in, &next_in, &avail_out,
  3733. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  3734. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  3735. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  3736. }
  3737. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3738. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  3739. }
  3740. #endif
  3741. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3742. inline zstd_compressor::zstd_compressor() {
  3743. ctx_ = ZSTD_createCCtx();
  3744. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  3745. }
  3746. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  3747. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  3748. bool last, Callback callback) {
  3749. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3750. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  3751. ZSTD_inBuffer input = {data, data_length, 0};
  3752. bool finished;
  3753. do {
  3754. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3755. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  3756. if (ZSTD_isError(remaining)) { return false; }
  3757. if (!callback(buff.data(), output.pos)) { return false; }
  3758. finished = last ? (remaining == 0) : (input.pos == input.size);
  3759. } while (!finished);
  3760. return true;
  3761. }
  3762. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  3763. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  3764. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  3765. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  3766. Callback callback) {
  3767. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3768. ZSTD_inBuffer input = {data, data_length, 0};
  3769. while (input.pos < input.size) {
  3770. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3771. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  3772. if (ZSTD_isError(remaining)) { return false; }
  3773. if (!callback(buff.data(), output.pos)) { return false; }
  3774. }
  3775. return true;
  3776. }
  3777. #endif
  3778. inline bool has_header(const Headers &headers, const std::string &key) {
  3779. return headers.find(key) != headers.end();
  3780. }
  3781. inline const char *get_header_value(const Headers &headers,
  3782. const std::string &key, const char *def,
  3783. size_t id) {
  3784. auto rng = headers.equal_range(key);
  3785. auto it = rng.first;
  3786. std::advance(it, static_cast<ssize_t>(id));
  3787. if (it != rng.second) { return it->second.c_str(); }
  3788. return def;
  3789. }
  3790. template <typename T>
  3791. inline bool parse_header(const char *beg, const char *end, T fn) {
  3792. // Skip trailing spaces and tabs.
  3793. while (beg < end && is_space_or_tab(end[-1])) {
  3794. end--;
  3795. }
  3796. auto p = beg;
  3797. while (p < end && *p != ':') {
  3798. p++;
  3799. }
  3800. auto name = std::string(beg, p);
  3801. if (!detail::fields::is_field_name(name)) { return false; }
  3802. if (p == end) { return false; }
  3803. auto key_end = p;
  3804. if (*p++ != ':') { return false; }
  3805. while (p < end && is_space_or_tab(*p)) {
  3806. p++;
  3807. }
  3808. if (p <= end) {
  3809. auto key_len = key_end - beg;
  3810. if (!key_len) { return false; }
  3811. auto key = std::string(beg, key_end);
  3812. auto val = std::string(p, end);
  3813. if (!detail::fields::is_field_value(val)) { return false; }
  3814. if (case_ignore::equal(key, "Location") ||
  3815. case_ignore::equal(key, "Referer")) {
  3816. fn(key, val);
  3817. } else {
  3818. fn(key, decode_path_component(val));
  3819. }
  3820. return true;
  3821. }
  3822. return false;
  3823. }
  3824. inline bool read_headers(Stream &strm, Headers &headers) {
  3825. const auto bufsiz = 2048;
  3826. char buf[bufsiz];
  3827. stream_line_reader line_reader(strm, buf, bufsiz);
  3828. size_t header_count = 0;
  3829. for (;;) {
  3830. if (!line_reader.getline()) { return false; }
  3831. // Check if the line ends with CRLF.
  3832. auto line_terminator_len = 2;
  3833. if (line_reader.end_with_crlf()) {
  3834. // Blank line indicates end of headers.
  3835. if (line_reader.size() == 2) { break; }
  3836. } else {
  3837. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3838. // Blank line indicates end of headers.
  3839. if (line_reader.size() == 1) { break; }
  3840. line_terminator_len = 1;
  3841. #else
  3842. continue; // Skip invalid line.
  3843. #endif
  3844. }
  3845. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3846. // Check header count limit
  3847. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3848. // Exclude line terminator
  3849. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3850. if (!parse_header(line_reader.ptr(), end,
  3851. [&](const std::string &key, const std::string &val) {
  3852. headers.emplace(key, val);
  3853. })) {
  3854. return false;
  3855. }
  3856. header_count++;
  3857. }
  3858. return true;
  3859. }
  3860. inline bool read_content_with_length(Stream &strm, size_t len,
  3861. DownloadProgress progress,
  3862. ContentReceiverWithProgress out) {
  3863. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3864. size_t r = 0;
  3865. while (r < len) {
  3866. auto read_len = static_cast<size_t>(len - r);
  3867. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3868. if (n <= 0) { return false; }
  3869. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  3870. r += static_cast<size_t>(n);
  3871. if (progress) {
  3872. if (!progress(r, len)) { return false; }
  3873. }
  3874. }
  3875. return true;
  3876. }
  3877. inline void skip_content_with_length(Stream &strm, size_t len) {
  3878. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3879. size_t r = 0;
  3880. while (r < len) {
  3881. auto read_len = static_cast<size_t>(len - r);
  3882. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3883. if (n <= 0) { return; }
  3884. r += static_cast<size_t>(n);
  3885. }
  3886. }
  3887. enum class ReadContentResult {
  3888. Success, // Successfully read the content
  3889. PayloadTooLarge, // The content exceeds the specified payload limit
  3890. Error // An error occurred while reading the content
  3891. };
  3892. inline ReadContentResult
  3893. read_content_without_length(Stream &strm, size_t payload_max_length,
  3894. ContentReceiverWithProgress out) {
  3895. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3896. size_t r = 0;
  3897. for (;;) {
  3898. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  3899. if (n == 0) { return ReadContentResult::Success; }
  3900. if (n < 0) { return ReadContentResult::Error; }
  3901. // Check if adding this data would exceed the payload limit
  3902. if (r > payload_max_length ||
  3903. payload_max_length - r < static_cast<size_t>(n)) {
  3904. return ReadContentResult::PayloadTooLarge;
  3905. }
  3906. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  3907. return ReadContentResult::Error;
  3908. }
  3909. r += static_cast<size_t>(n);
  3910. }
  3911. return ReadContentResult::Success;
  3912. }
  3913. template <typename T>
  3914. inline ReadContentResult read_content_chunked(Stream &strm, T &x,
  3915. size_t payload_max_length,
  3916. ContentReceiverWithProgress out) {
  3917. const auto bufsiz = 16;
  3918. char buf[bufsiz];
  3919. stream_line_reader line_reader(strm, buf, bufsiz);
  3920. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3921. unsigned long chunk_len;
  3922. size_t total_len = 0;
  3923. while (true) {
  3924. char *end_ptr;
  3925. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  3926. if (end_ptr == line_reader.ptr()) { return ReadContentResult::Error; }
  3927. if (chunk_len == ULONG_MAX) { return ReadContentResult::Error; }
  3928. if (chunk_len == 0) { break; }
  3929. // Check if adding this chunk would exceed the payload limit
  3930. if (total_len > payload_max_length ||
  3931. payload_max_length - total_len < chunk_len) {
  3932. return ReadContentResult::PayloadTooLarge;
  3933. }
  3934. total_len += chunk_len;
  3935. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  3936. return ReadContentResult::Error;
  3937. }
  3938. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3939. if (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3940. return ReadContentResult::Error;
  3941. }
  3942. if (!line_reader.getline()) { return ReadContentResult::Error; }
  3943. }
  3944. assert(chunk_len == 0);
  3945. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3946. // transfer coding is complete when a chunk with a chunk-size of zero is
  3947. // received, possibly followed by a trailer section, and finally terminated by
  3948. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3949. //
  3950. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3951. // does't care for the existence of the final CRLF. In other words, it seems
  3952. // to be ok whether the final CRLF exists or not in the chunked data.
  3953. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3954. //
  3955. // According to the reference code in RFC 9112, cpp-httplib now allows
  3956. // chunked transfer coding data without the final CRLF.
  3957. if (!line_reader.getline()) { return ReadContentResult::Success; }
  3958. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  3959. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  3960. // Message framing
  3961. "transfer-encoding", "content-length",
  3962. // Routing
  3963. "host",
  3964. // Authentication
  3965. "authorization", "www-authenticate", "proxy-authenticate",
  3966. "proxy-authorization", "cookie", "set-cookie",
  3967. // Request modifiers
  3968. "cache-control", "expect", "max-forwards", "pragma", "range", "te",
  3969. // Response control
  3970. "age", "expires", "date", "location", "retry-after", "vary", "warning",
  3971. // Payload processing
  3972. "content-encoding", "content-type", "content-range", "trailer"};
  3973. // Parse declared trailer headers once for performance
  3974. case_ignore::unordered_set<std::string> declared_trailers;
  3975. if (has_header(x.headers, "Trailer")) {
  3976. auto trailer_header = get_header_value(x.headers, "Trailer", "", 0);
  3977. auto len = std::strlen(trailer_header);
  3978. split(trailer_header, trailer_header + len, ',',
  3979. [&](const char *b, const char *e) {
  3980. std::string key(b, e);
  3981. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  3982. declared_trailers.insert(key);
  3983. }
  3984. });
  3985. }
  3986. size_t trailer_header_count = 0;
  3987. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3988. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) {
  3989. return ReadContentResult::Error;
  3990. }
  3991. // Check trailer header count limit
  3992. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  3993. return ReadContentResult::Error;
  3994. }
  3995. // Exclude line terminator
  3996. constexpr auto line_terminator_len = 2;
  3997. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3998. parse_header(line_reader.ptr(), end,
  3999. [&](const std::string &key, const std::string &val) {
  4000. if (declared_trailers.find(key) != declared_trailers.end()) {
  4001. x.trailers.emplace(key, val);
  4002. trailer_header_count++;
  4003. }
  4004. });
  4005. if (!line_reader.getline()) { return ReadContentResult::Error; }
  4006. }
  4007. return ReadContentResult::Success;
  4008. }
  4009. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  4010. return case_ignore::equal(
  4011. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  4012. }
  4013. template <typename T, typename U>
  4014. bool prepare_content_receiver(T &x, int &status,
  4015. ContentReceiverWithProgress receiver,
  4016. bool decompress, U callback) {
  4017. if (decompress) {
  4018. std::string encoding = x.get_header_value("Content-Encoding");
  4019. std::unique_ptr<decompressor> decompressor;
  4020. if (encoding == "gzip" || encoding == "deflate") {
  4021. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4022. decompressor = detail::make_unique<gzip_decompressor>();
  4023. #else
  4024. status = StatusCode::UnsupportedMediaType_415;
  4025. return false;
  4026. #endif
  4027. } else if (encoding.find("br") != std::string::npos) {
  4028. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4029. decompressor = detail::make_unique<brotli_decompressor>();
  4030. #else
  4031. status = StatusCode::UnsupportedMediaType_415;
  4032. return false;
  4033. #endif
  4034. } else if (encoding == "zstd") {
  4035. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4036. decompressor = detail::make_unique<zstd_decompressor>();
  4037. #else
  4038. status = StatusCode::UnsupportedMediaType_415;
  4039. return false;
  4040. #endif
  4041. }
  4042. if (decompressor) {
  4043. if (decompressor->is_valid()) {
  4044. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  4045. size_t off, size_t len) {
  4046. return decompressor->decompress(buf, n,
  4047. [&](const char *buf2, size_t n2) {
  4048. return receiver(buf2, n2, off, len);
  4049. });
  4050. };
  4051. return callback(std::move(out));
  4052. } else {
  4053. status = StatusCode::InternalServerError_500;
  4054. return false;
  4055. }
  4056. }
  4057. }
  4058. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  4059. size_t len) {
  4060. return receiver(buf, n, off, len);
  4061. };
  4062. return callback(std::move(out));
  4063. }
  4064. template <typename T>
  4065. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  4066. DownloadProgress progress,
  4067. ContentReceiverWithProgress receiver, bool decompress) {
  4068. return prepare_content_receiver(
  4069. x, status, std::move(receiver), decompress,
  4070. [&](const ContentReceiverWithProgress &out) {
  4071. auto ret = true;
  4072. auto exceed_payload_max_length = false;
  4073. if (is_chunked_transfer_encoding(x.headers)) {
  4074. auto result = read_content_chunked(strm, x, payload_max_length, out);
  4075. if (result == ReadContentResult::Success) {
  4076. ret = true;
  4077. } else if (result == ReadContentResult::PayloadTooLarge) {
  4078. exceed_payload_max_length = true;
  4079. ret = false;
  4080. } else {
  4081. ret = false;
  4082. }
  4083. } else if (!has_header(x.headers, "Content-Length")) {
  4084. auto result =
  4085. read_content_without_length(strm, payload_max_length, out);
  4086. if (result == ReadContentResult::Success) {
  4087. ret = true;
  4088. } else if (result == ReadContentResult::PayloadTooLarge) {
  4089. exceed_payload_max_length = true;
  4090. ret = false;
  4091. } else {
  4092. ret = false;
  4093. }
  4094. } else {
  4095. auto is_invalid_value = false;
  4096. auto len = get_header_value_u64(x.headers, "Content-Length",
  4097. (std::numeric_limits<size_t>::max)(),
  4098. 0, is_invalid_value);
  4099. if (is_invalid_value) {
  4100. ret = false;
  4101. } else if (len > payload_max_length) {
  4102. exceed_payload_max_length = true;
  4103. skip_content_with_length(strm, len);
  4104. ret = false;
  4105. } else if (len > 0) {
  4106. ret = read_content_with_length(strm, len, std::move(progress), out);
  4107. }
  4108. }
  4109. if (!ret) {
  4110. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  4111. : StatusCode::BadRequest_400;
  4112. }
  4113. return ret;
  4114. });
  4115. }
  4116. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  4117. const std::string &path) {
  4118. std::string s = method;
  4119. s += " ";
  4120. s += path;
  4121. s += " HTTP/1.1\r\n";
  4122. return strm.write(s.data(), s.size());
  4123. }
  4124. inline ssize_t write_response_line(Stream &strm, int status) {
  4125. std::string s = "HTTP/1.1 ";
  4126. s += std::to_string(status);
  4127. s += " ";
  4128. s += httplib::status_message(status);
  4129. s += "\r\n";
  4130. return strm.write(s.data(), s.size());
  4131. }
  4132. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  4133. ssize_t write_len = 0;
  4134. for (const auto &x : headers) {
  4135. std::string s;
  4136. s = x.first;
  4137. s += ": ";
  4138. s += x.second;
  4139. s += "\r\n";
  4140. auto len = strm.write(s.data(), s.size());
  4141. if (len < 0) { return len; }
  4142. write_len += len;
  4143. }
  4144. auto len = strm.write("\r\n");
  4145. if (len < 0) { return len; }
  4146. write_len += len;
  4147. return write_len;
  4148. }
  4149. inline bool write_data(Stream &strm, const char *d, size_t l) {
  4150. size_t offset = 0;
  4151. while (offset < l) {
  4152. auto length = strm.write(d + offset, l - offset);
  4153. if (length < 0) { return false; }
  4154. offset += static_cast<size_t>(length);
  4155. }
  4156. return true;
  4157. }
  4158. template <typename T>
  4159. inline bool write_content_with_progress(Stream &strm,
  4160. const ContentProvider &content_provider,
  4161. size_t offset, size_t length,
  4162. T is_shutting_down,
  4163. const UploadProgress &upload_progress,
  4164. Error &error) {
  4165. size_t end_offset = offset + length;
  4166. size_t start_offset = offset;
  4167. auto ok = true;
  4168. DataSink data_sink;
  4169. data_sink.write = [&](const char *d, size_t l) -> bool {
  4170. if (ok) {
  4171. if (write_data(strm, d, l)) {
  4172. offset += l;
  4173. if (upload_progress && length > 0) {
  4174. size_t current_written = offset - start_offset;
  4175. if (!upload_progress(current_written, length)) {
  4176. ok = false;
  4177. return false;
  4178. }
  4179. }
  4180. } else {
  4181. ok = false;
  4182. }
  4183. }
  4184. return ok;
  4185. };
  4186. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4187. while (offset < end_offset && !is_shutting_down()) {
  4188. if (!strm.wait_writable()) {
  4189. error = Error::Write;
  4190. return false;
  4191. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  4192. error = Error::Canceled;
  4193. return false;
  4194. } else if (!ok) {
  4195. error = Error::Write;
  4196. return false;
  4197. }
  4198. }
  4199. error = Error::Success;
  4200. return true;
  4201. }
  4202. template <typename T>
  4203. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4204. size_t offset, size_t length, T is_shutting_down,
  4205. Error &error) {
  4206. return write_content_with_progress<T>(strm, content_provider, offset, length,
  4207. is_shutting_down, nullptr, error);
  4208. }
  4209. template <typename T>
  4210. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4211. size_t offset, size_t length,
  4212. const T &is_shutting_down) {
  4213. auto error = Error::Success;
  4214. return write_content(strm, content_provider, offset, length, is_shutting_down,
  4215. error);
  4216. }
  4217. template <typename T>
  4218. inline bool
  4219. write_content_without_length(Stream &strm,
  4220. const ContentProvider &content_provider,
  4221. const T &is_shutting_down) {
  4222. size_t offset = 0;
  4223. auto data_available = true;
  4224. auto ok = true;
  4225. DataSink data_sink;
  4226. data_sink.write = [&](const char *d, size_t l) -> bool {
  4227. if (ok) {
  4228. offset += l;
  4229. if (!write_data(strm, d, l)) { ok = false; }
  4230. }
  4231. return ok;
  4232. };
  4233. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4234. data_sink.done = [&](void) { data_available = false; };
  4235. while (data_available && !is_shutting_down()) {
  4236. if (!strm.wait_writable()) {
  4237. return false;
  4238. } else if (!content_provider(offset, 0, data_sink)) {
  4239. return false;
  4240. } else if (!ok) {
  4241. return false;
  4242. }
  4243. }
  4244. return true;
  4245. }
  4246. template <typename T, typename U>
  4247. inline bool
  4248. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  4249. const T &is_shutting_down, U &compressor, Error &error) {
  4250. size_t offset = 0;
  4251. auto data_available = true;
  4252. auto ok = true;
  4253. DataSink data_sink;
  4254. data_sink.write = [&](const char *d, size_t l) -> bool {
  4255. if (ok) {
  4256. data_available = l > 0;
  4257. offset += l;
  4258. std::string payload;
  4259. if (compressor.compress(d, l, false,
  4260. [&](const char *data, size_t data_len) {
  4261. payload.append(data, data_len);
  4262. return true;
  4263. })) {
  4264. if (!payload.empty()) {
  4265. // Emit chunked response header and footer for each chunk
  4266. auto chunk =
  4267. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  4268. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  4269. }
  4270. } else {
  4271. ok = false;
  4272. }
  4273. }
  4274. return ok;
  4275. };
  4276. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4277. auto done_with_trailer = [&](const Headers *trailer) {
  4278. if (!ok) { return; }
  4279. data_available = false;
  4280. std::string payload;
  4281. if (!compressor.compress(nullptr, 0, true,
  4282. [&](const char *data, size_t data_len) {
  4283. payload.append(data, data_len);
  4284. return true;
  4285. })) {
  4286. ok = false;
  4287. return;
  4288. }
  4289. if (!payload.empty()) {
  4290. // Emit chunked response header and footer for each chunk
  4291. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  4292. if (!write_data(strm, chunk.data(), chunk.size())) {
  4293. ok = false;
  4294. return;
  4295. }
  4296. }
  4297. constexpr const char done_marker[] = "0\r\n";
  4298. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  4299. // Trailer
  4300. if (trailer) {
  4301. for (const auto &kv : *trailer) {
  4302. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  4303. if (!write_data(strm, field_line.data(), field_line.size())) {
  4304. ok = false;
  4305. }
  4306. }
  4307. }
  4308. constexpr const char crlf[] = "\r\n";
  4309. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  4310. };
  4311. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  4312. data_sink.done_with_trailer = [&](const Headers &trailer) {
  4313. done_with_trailer(&trailer);
  4314. };
  4315. while (data_available && !is_shutting_down()) {
  4316. if (!strm.wait_writable()) {
  4317. error = Error::Write;
  4318. return false;
  4319. } else if (!content_provider(offset, 0, data_sink)) {
  4320. error = Error::Canceled;
  4321. return false;
  4322. } else if (!ok) {
  4323. error = Error::Write;
  4324. return false;
  4325. }
  4326. }
  4327. error = Error::Success;
  4328. return true;
  4329. }
  4330. template <typename T, typename U>
  4331. inline bool write_content_chunked(Stream &strm,
  4332. const ContentProvider &content_provider,
  4333. const T &is_shutting_down, U &compressor) {
  4334. auto error = Error::Success;
  4335. return write_content_chunked(strm, content_provider, is_shutting_down,
  4336. compressor, error);
  4337. }
  4338. template <typename T>
  4339. inline bool redirect(T &cli, Request &req, Response &res,
  4340. const std::string &path, const std::string &location,
  4341. Error &error) {
  4342. Request new_req = req;
  4343. new_req.path = path;
  4344. new_req.redirect_count_ -= 1;
  4345. if (res.status == StatusCode::SeeOther_303 &&
  4346. (req.method != "GET" && req.method != "HEAD")) {
  4347. new_req.method = "GET";
  4348. new_req.body.clear();
  4349. new_req.headers.clear();
  4350. }
  4351. Response new_res;
  4352. auto ret = cli.send(new_req, new_res, error);
  4353. if (ret) {
  4354. req = new_req;
  4355. res = new_res;
  4356. if (res.location.empty()) { res.location = location; }
  4357. }
  4358. return ret;
  4359. }
  4360. inline std::string params_to_query_str(const Params &params) {
  4361. std::string query;
  4362. for (auto it = params.begin(); it != params.end(); ++it) {
  4363. if (it != params.begin()) { query += "&"; }
  4364. query += encode_query_component(it->first);
  4365. query += "=";
  4366. query += encode_query_component(it->second);
  4367. }
  4368. return query;
  4369. }
  4370. inline void parse_query_text(const char *data, std::size_t size,
  4371. Params &params) {
  4372. std::set<std::string> cache;
  4373. split(data, data + size, '&', [&](const char *b, const char *e) {
  4374. std::string kv(b, e);
  4375. if (cache.find(kv) != cache.end()) { return; }
  4376. cache.insert(std::move(kv));
  4377. std::string key;
  4378. std::string val;
  4379. divide(b, static_cast<std::size_t>(e - b), '=',
  4380. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  4381. std::size_t rhs_size) {
  4382. key.assign(lhs_data, lhs_size);
  4383. val.assign(rhs_data, rhs_size);
  4384. });
  4385. if (!key.empty()) {
  4386. params.emplace(decode_query_component(key), decode_query_component(val));
  4387. }
  4388. });
  4389. }
  4390. inline void parse_query_text(const std::string &s, Params &params) {
  4391. parse_query_text(s.data(), s.size(), params);
  4392. }
  4393. inline bool parse_multipart_boundary(const std::string &content_type,
  4394. std::string &boundary) {
  4395. auto boundary_keyword = "boundary=";
  4396. auto pos = content_type.find(boundary_keyword);
  4397. if (pos == std::string::npos) { return false; }
  4398. auto end = content_type.find(';', pos);
  4399. auto beg = pos + strlen(boundary_keyword);
  4400. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  4401. return !boundary.empty();
  4402. }
  4403. inline void parse_disposition_params(const std::string &s, Params &params) {
  4404. std::set<std::string> cache;
  4405. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  4406. std::string kv(b, e);
  4407. if (cache.find(kv) != cache.end()) { return; }
  4408. cache.insert(kv);
  4409. std::string key;
  4410. std::string val;
  4411. split(b, e, '=', [&](const char *b2, const char *e2) {
  4412. if (key.empty()) {
  4413. key.assign(b2, e2);
  4414. } else {
  4415. val.assign(b2, e2);
  4416. }
  4417. });
  4418. if (!key.empty()) {
  4419. params.emplace(trim_double_quotes_copy((key)),
  4420. trim_double_quotes_copy((val)));
  4421. }
  4422. });
  4423. }
  4424. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4425. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  4426. #else
  4427. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  4428. #endif
  4429. auto is_valid = [](const std::string &str) {
  4430. return std::all_of(str.cbegin(), str.cend(),
  4431. [](unsigned char c) { return std::isdigit(c); });
  4432. };
  4433. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  4434. const auto pos = static_cast<size_t>(6);
  4435. const auto len = static_cast<size_t>(s.size() - 6);
  4436. auto all_valid_ranges = true;
  4437. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  4438. if (!all_valid_ranges) { return; }
  4439. const auto it = std::find(b, e, '-');
  4440. if (it == e) {
  4441. all_valid_ranges = false;
  4442. return;
  4443. }
  4444. const auto lhs = std::string(b, it);
  4445. const auto rhs = std::string(it + 1, e);
  4446. if (!is_valid(lhs) || !is_valid(rhs)) {
  4447. all_valid_ranges = false;
  4448. return;
  4449. }
  4450. const auto first =
  4451. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  4452. const auto last =
  4453. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  4454. if ((first == -1 && last == -1) ||
  4455. (first != -1 && last != -1 && first > last)) {
  4456. all_valid_ranges = false;
  4457. return;
  4458. }
  4459. ranges.emplace_back(first, last);
  4460. });
  4461. return all_valid_ranges && !ranges.empty();
  4462. }
  4463. return false;
  4464. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4465. }
  4466. #else
  4467. } catch (...) { return false; }
  4468. #endif
  4469. inline bool parse_accept_header(const std::string &s,
  4470. std::vector<std::string> &content_types) {
  4471. content_types.clear();
  4472. // Empty string is considered valid (no preference)
  4473. if (s.empty()) { return true; }
  4474. // Check for invalid patterns: leading/trailing commas or consecutive commas
  4475. if (s.front() == ',' || s.back() == ',' ||
  4476. s.find(",,") != std::string::npos) {
  4477. return false;
  4478. }
  4479. struct AcceptEntry {
  4480. std::string media_type;
  4481. double quality;
  4482. int order; // Original order in header
  4483. };
  4484. std::vector<AcceptEntry> entries;
  4485. int order = 0;
  4486. bool has_invalid_entry = false;
  4487. // Split by comma and parse each entry
  4488. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  4489. std::string entry(b, e);
  4490. entry = trim_copy(entry);
  4491. if (entry.empty()) {
  4492. has_invalid_entry = true;
  4493. return;
  4494. }
  4495. AcceptEntry accept_entry;
  4496. accept_entry.quality = 1.0; // Default quality
  4497. accept_entry.order = order++;
  4498. // Find q= parameter
  4499. auto q_pos = entry.find(";q=");
  4500. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  4501. if (q_pos != std::string::npos) {
  4502. // Extract media type (before q parameter)
  4503. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  4504. // Extract quality value
  4505. auto q_start = entry.find('=', q_pos) + 1;
  4506. auto q_end = entry.find(';', q_start);
  4507. if (q_end == std::string::npos) { q_end = entry.length(); }
  4508. std::string quality_str =
  4509. trim_copy(entry.substr(q_start, q_end - q_start));
  4510. if (quality_str.empty()) {
  4511. has_invalid_entry = true;
  4512. return;
  4513. }
  4514. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4515. {
  4516. std::istringstream iss(quality_str);
  4517. iss >> accept_entry.quality;
  4518. // Check if conversion was successful and entire string was consumed
  4519. if (iss.fail() || !iss.eof()) {
  4520. has_invalid_entry = true;
  4521. return;
  4522. }
  4523. }
  4524. #else
  4525. try {
  4526. accept_entry.quality = std::stod(quality_str);
  4527. } catch (...) {
  4528. has_invalid_entry = true;
  4529. return;
  4530. }
  4531. #endif
  4532. // Check if quality is in valid range [0.0, 1.0]
  4533. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  4534. has_invalid_entry = true;
  4535. return;
  4536. }
  4537. } else {
  4538. // No quality parameter, use entire entry as media type
  4539. accept_entry.media_type = entry;
  4540. }
  4541. // Remove additional parameters from media type
  4542. auto param_pos = accept_entry.media_type.find(';');
  4543. if (param_pos != std::string::npos) {
  4544. accept_entry.media_type =
  4545. trim_copy(accept_entry.media_type.substr(0, param_pos));
  4546. }
  4547. // Basic validation of media type format
  4548. if (accept_entry.media_type.empty()) {
  4549. has_invalid_entry = true;
  4550. return;
  4551. }
  4552. // Check for basic media type format (should contain '/' or be '*')
  4553. if (accept_entry.media_type != "*" &&
  4554. accept_entry.media_type.find('/') == std::string::npos) {
  4555. has_invalid_entry = true;
  4556. return;
  4557. }
  4558. entries.push_back(accept_entry);
  4559. });
  4560. // Return false if any invalid entry was found
  4561. if (has_invalid_entry) { return false; }
  4562. // Sort by quality (descending), then by original order (ascending)
  4563. std::sort(entries.begin(), entries.end(),
  4564. [](const AcceptEntry &a, const AcceptEntry &b) {
  4565. if (a.quality != b.quality) {
  4566. return a.quality > b.quality; // Higher quality first
  4567. }
  4568. return a.order < b.order; // Earlier order first for same quality
  4569. });
  4570. // Extract sorted media types
  4571. content_types.reserve(entries.size());
  4572. for (const auto &entry : entries) {
  4573. content_types.push_back(entry.media_type);
  4574. }
  4575. return true;
  4576. }
  4577. class FormDataParser {
  4578. public:
  4579. FormDataParser() = default;
  4580. void set_boundary(std::string &&boundary) {
  4581. boundary_ = boundary;
  4582. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  4583. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  4584. }
  4585. bool is_valid() const { return is_valid_; }
  4586. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  4587. const ContentReceiver &content_callback) {
  4588. buf_append(buf, n);
  4589. while (buf_size() > 0) {
  4590. switch (state_) {
  4591. case 0: { // Initial boundary
  4592. auto pos = buf_find(dash_boundary_crlf_);
  4593. if (pos == buf_size()) { return true; }
  4594. buf_erase(pos + dash_boundary_crlf_.size());
  4595. state_ = 1;
  4596. break;
  4597. }
  4598. case 1: { // New entry
  4599. clear_file_info();
  4600. state_ = 2;
  4601. break;
  4602. }
  4603. case 2: { // Headers
  4604. auto pos = buf_find(crlf_);
  4605. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4606. while (pos < buf_size()) {
  4607. // Empty line
  4608. if (pos == 0) {
  4609. if (!header_callback(file_)) {
  4610. is_valid_ = false;
  4611. return false;
  4612. }
  4613. buf_erase(crlf_.size());
  4614. state_ = 3;
  4615. break;
  4616. }
  4617. const auto header = buf_head(pos);
  4618. if (!parse_header(header.data(), header.data() + header.size(),
  4619. [&](const std::string &, const std::string &) {})) {
  4620. is_valid_ = false;
  4621. return false;
  4622. }
  4623. // Parse and emplace space trimmed headers into a map
  4624. if (!parse_header(
  4625. header.data(), header.data() + header.size(),
  4626. [&](const std::string &key, const std::string &val) {
  4627. file_.headers.emplace(key, val);
  4628. })) {
  4629. is_valid_ = false;
  4630. return false;
  4631. }
  4632. constexpr const char header_content_type[] = "Content-Type:";
  4633. if (start_with_case_ignore(header, header_content_type)) {
  4634. file_.content_type =
  4635. trim_copy(header.substr(str_len(header_content_type)));
  4636. } else {
  4637. thread_local const std::regex re_content_disposition(
  4638. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  4639. std::regex_constants::icase);
  4640. std::smatch m;
  4641. if (std::regex_match(header, m, re_content_disposition)) {
  4642. Params params;
  4643. parse_disposition_params(m[1], params);
  4644. auto it = params.find("name");
  4645. if (it != params.end()) {
  4646. file_.name = it->second;
  4647. } else {
  4648. is_valid_ = false;
  4649. return false;
  4650. }
  4651. it = params.find("filename");
  4652. if (it != params.end()) { file_.filename = it->second; }
  4653. it = params.find("filename*");
  4654. if (it != params.end()) {
  4655. // Only allow UTF-8 encoding...
  4656. thread_local const std::regex re_rfc5987_encoding(
  4657. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  4658. std::smatch m2;
  4659. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  4660. file_.filename = decode_path_component(m2[1]); // override...
  4661. } else {
  4662. is_valid_ = false;
  4663. return false;
  4664. }
  4665. }
  4666. }
  4667. }
  4668. buf_erase(pos + crlf_.size());
  4669. pos = buf_find(crlf_);
  4670. }
  4671. if (state_ != 3) { return true; }
  4672. break;
  4673. }
  4674. case 3: { // Body
  4675. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  4676. auto pos = buf_find(crlf_dash_boundary_);
  4677. if (pos < buf_size()) {
  4678. if (!content_callback(buf_data(), pos)) {
  4679. is_valid_ = false;
  4680. return false;
  4681. }
  4682. buf_erase(pos + crlf_dash_boundary_.size());
  4683. state_ = 4;
  4684. } else {
  4685. auto len = buf_size() - crlf_dash_boundary_.size();
  4686. if (len > 0) {
  4687. if (!content_callback(buf_data(), len)) {
  4688. is_valid_ = false;
  4689. return false;
  4690. }
  4691. buf_erase(len);
  4692. }
  4693. return true;
  4694. }
  4695. break;
  4696. }
  4697. case 4: { // Boundary
  4698. if (crlf_.size() > buf_size()) { return true; }
  4699. if (buf_start_with(crlf_)) {
  4700. buf_erase(crlf_.size());
  4701. state_ = 1;
  4702. } else {
  4703. if (dash_.size() > buf_size()) { return true; }
  4704. if (buf_start_with(dash_)) {
  4705. buf_erase(dash_.size());
  4706. is_valid_ = true;
  4707. buf_erase(buf_size()); // Remove epilogue
  4708. } else {
  4709. return true;
  4710. }
  4711. }
  4712. break;
  4713. }
  4714. }
  4715. }
  4716. return true;
  4717. }
  4718. private:
  4719. void clear_file_info() {
  4720. file_.name.clear();
  4721. file_.filename.clear();
  4722. file_.content_type.clear();
  4723. file_.headers.clear();
  4724. }
  4725. bool start_with_case_ignore(const std::string &a, const char *b) const {
  4726. const auto b_len = strlen(b);
  4727. if (a.size() < b_len) { return false; }
  4728. for (size_t i = 0; i < b_len; i++) {
  4729. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  4730. return false;
  4731. }
  4732. }
  4733. return true;
  4734. }
  4735. const std::string dash_ = "--";
  4736. const std::string crlf_ = "\r\n";
  4737. std::string boundary_;
  4738. std::string dash_boundary_crlf_;
  4739. std::string crlf_dash_boundary_;
  4740. size_t state_ = 0;
  4741. bool is_valid_ = false;
  4742. FormData file_;
  4743. // Buffer
  4744. bool start_with(const std::string &a, size_t spos, size_t epos,
  4745. const std::string &b) const {
  4746. if (epos - spos < b.size()) { return false; }
  4747. for (size_t i = 0; i < b.size(); i++) {
  4748. if (a[i + spos] != b[i]) { return false; }
  4749. }
  4750. return true;
  4751. }
  4752. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  4753. const char *buf_data() const { return &buf_[buf_spos_]; }
  4754. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  4755. bool buf_start_with(const std::string &s) const {
  4756. return start_with(buf_, buf_spos_, buf_epos_, s);
  4757. }
  4758. size_t buf_find(const std::string &s) const {
  4759. auto c = s.front();
  4760. size_t off = buf_spos_;
  4761. while (off < buf_epos_) {
  4762. auto pos = off;
  4763. while (true) {
  4764. if (pos == buf_epos_) { return buf_size(); }
  4765. if (buf_[pos] == c) { break; }
  4766. pos++;
  4767. }
  4768. auto remaining_size = buf_epos_ - pos;
  4769. if (s.size() > remaining_size) { return buf_size(); }
  4770. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  4771. off = pos + 1;
  4772. }
  4773. return buf_size();
  4774. }
  4775. void buf_append(const char *data, size_t n) {
  4776. auto remaining_size = buf_size();
  4777. if (remaining_size > 0 && buf_spos_ > 0) {
  4778. for (size_t i = 0; i < remaining_size; i++) {
  4779. buf_[i] = buf_[buf_spos_ + i];
  4780. }
  4781. }
  4782. buf_spos_ = 0;
  4783. buf_epos_ = remaining_size;
  4784. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  4785. for (size_t i = 0; i < n; i++) {
  4786. buf_[buf_epos_ + i] = data[i];
  4787. }
  4788. buf_epos_ += n;
  4789. }
  4790. void buf_erase(size_t size) { buf_spos_ += size; }
  4791. std::string buf_;
  4792. size_t buf_spos_ = 0;
  4793. size_t buf_epos_ = 0;
  4794. };
  4795. inline std::string random_string(size_t length) {
  4796. constexpr const char data[] =
  4797. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  4798. thread_local auto engine([]() {
  4799. // std::random_device might actually be deterministic on some
  4800. // platforms, but due to lack of support in the c++ standard library,
  4801. // doing better requires either some ugly hacks or breaking portability.
  4802. std::random_device seed_gen;
  4803. // Request 128 bits of entropy for initialization
  4804. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  4805. return std::mt19937(seed_sequence);
  4806. }());
  4807. std::string result;
  4808. for (size_t i = 0; i < length; i++) {
  4809. result += data[engine() % (sizeof(data) - 1)];
  4810. }
  4811. return result;
  4812. }
  4813. inline std::string make_multipart_data_boundary() {
  4814. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  4815. }
  4816. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  4817. auto valid = true;
  4818. for (size_t i = 0; i < boundary.size(); i++) {
  4819. auto c = boundary[i];
  4820. if (!std::isalnum(c) && c != '-' && c != '_') {
  4821. valid = false;
  4822. break;
  4823. }
  4824. }
  4825. return valid;
  4826. }
  4827. template <typename T>
  4828. inline std::string
  4829. serialize_multipart_formdata_item_begin(const T &item,
  4830. const std::string &boundary) {
  4831. std::string body = "--" + boundary + "\r\n";
  4832. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4833. if (!item.filename.empty()) {
  4834. body += "; filename=\"" + item.filename + "\"";
  4835. }
  4836. body += "\r\n";
  4837. if (!item.content_type.empty()) {
  4838. body += "Content-Type: " + item.content_type + "\r\n";
  4839. }
  4840. body += "\r\n";
  4841. return body;
  4842. }
  4843. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  4844. inline std::string
  4845. serialize_multipart_formdata_finish(const std::string &boundary) {
  4846. return "--" + boundary + "--\r\n";
  4847. }
  4848. inline std::string
  4849. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  4850. return "multipart/form-data; boundary=" + boundary;
  4851. }
  4852. inline std::string
  4853. serialize_multipart_formdata(const UploadFormDataItems &items,
  4854. const std::string &boundary, bool finish = true) {
  4855. std::string body;
  4856. for (const auto &item : items) {
  4857. body += serialize_multipart_formdata_item_begin(item, boundary);
  4858. body += item.content + serialize_multipart_formdata_item_end();
  4859. }
  4860. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  4861. return body;
  4862. }
  4863. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  4864. if (ranges.size() <= 1) return;
  4865. // Sort ranges by start position
  4866. std::sort(ranges.begin(), ranges.end(),
  4867. [](const Range &a, const Range &b) { return a.first < b.first; });
  4868. Ranges coalesced;
  4869. coalesced.reserve(ranges.size());
  4870. for (auto &r : ranges) {
  4871. auto first_pos = r.first;
  4872. auto last_pos = r.second;
  4873. // Handle special cases like in range_error
  4874. if (first_pos == -1 && last_pos == -1) {
  4875. first_pos = 0;
  4876. last_pos = static_cast<ssize_t>(content_length);
  4877. }
  4878. if (first_pos == -1) {
  4879. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  4880. last_pos = static_cast<ssize_t>(content_length) - 1;
  4881. }
  4882. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  4883. last_pos = static_cast<ssize_t>(content_length) - 1;
  4884. }
  4885. // Skip invalid ranges
  4886. if (!(0 <= first_pos && first_pos <= last_pos &&
  4887. last_pos < static_cast<ssize_t>(content_length))) {
  4888. continue;
  4889. }
  4890. // Coalesce with previous range if overlapping or adjacent (but not
  4891. // identical)
  4892. if (!coalesced.empty()) {
  4893. auto &prev = coalesced.back();
  4894. // Check if current range overlaps or is adjacent to previous range
  4895. // but don't coalesce identical ranges (allow duplicates)
  4896. if (first_pos <= prev.second + 1 &&
  4897. !(first_pos == prev.first && last_pos == prev.second)) {
  4898. // Extend the previous range
  4899. prev.second = (std::max)(prev.second, last_pos);
  4900. continue;
  4901. }
  4902. }
  4903. // Add new range
  4904. coalesced.emplace_back(first_pos, last_pos);
  4905. }
  4906. ranges = std::move(coalesced);
  4907. }
  4908. inline bool range_error(Request &req, Response &res) {
  4909. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  4910. ssize_t content_len = static_cast<ssize_t>(
  4911. res.content_length_ ? res.content_length_ : res.body.size());
  4912. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  4913. size_t overwrapping_count = 0;
  4914. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  4915. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  4916. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  4917. // Too many ranges
  4918. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  4919. for (auto &r : req.ranges) {
  4920. auto &first_pos = r.first;
  4921. auto &last_pos = r.second;
  4922. if (first_pos == -1 && last_pos == -1) {
  4923. first_pos = 0;
  4924. last_pos = content_len;
  4925. }
  4926. if (first_pos == -1) {
  4927. first_pos = content_len - last_pos;
  4928. last_pos = content_len - 1;
  4929. }
  4930. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  4931. // A client can limit the number of bytes requested without knowing the
  4932. // size of the selected representation. If the last-pos value is absent,
  4933. // or if the value is greater than or equal to the current length of the
  4934. // representation data, the byte range is interpreted as the remainder of
  4935. // the representation (i.e., the server replaces the value of last-pos
  4936. // with a value that is one less than the current length of the selected
  4937. // representation).
  4938. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  4939. if (last_pos == -1 || last_pos >= content_len) {
  4940. last_pos = content_len - 1;
  4941. }
  4942. // Range must be within content length
  4943. if (!(0 <= first_pos && first_pos <= last_pos &&
  4944. last_pos <= content_len - 1)) {
  4945. return true;
  4946. }
  4947. // Request must not have more than two overlapping ranges
  4948. for (const auto &processed_range : processed_ranges) {
  4949. if (!(last_pos < processed_range.first ||
  4950. first_pos > processed_range.second)) {
  4951. overwrapping_count++;
  4952. if (overwrapping_count > 2) { return true; }
  4953. break; // Only count once per range
  4954. }
  4955. }
  4956. processed_ranges.emplace_back(first_pos, last_pos);
  4957. }
  4958. // After validation, coalesce overlapping ranges as per RFC 9110
  4959. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  4960. }
  4961. return false;
  4962. }
  4963. inline std::pair<size_t, size_t>
  4964. get_range_offset_and_length(Range r, size_t content_length) {
  4965. assert(r.first != -1 && r.second != -1);
  4966. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  4967. assert(r.first <= r.second &&
  4968. r.second < static_cast<ssize_t>(content_length));
  4969. (void)(content_length);
  4970. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  4971. }
  4972. inline std::string make_content_range_header_field(
  4973. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  4974. auto st = offset_and_length.first;
  4975. auto ed = st + offset_and_length.second - 1;
  4976. std::string field = "bytes ";
  4977. field += std::to_string(st);
  4978. field += "-";
  4979. field += std::to_string(ed);
  4980. field += "/";
  4981. field += std::to_string(content_length);
  4982. return field;
  4983. }
  4984. template <typename SToken, typename CToken, typename Content>
  4985. bool process_multipart_ranges_data(const Request &req,
  4986. const std::string &boundary,
  4987. const std::string &content_type,
  4988. size_t content_length, SToken stoken,
  4989. CToken ctoken, Content content) {
  4990. for (size_t i = 0; i < req.ranges.size(); i++) {
  4991. ctoken("--");
  4992. stoken(boundary);
  4993. ctoken("\r\n");
  4994. if (!content_type.empty()) {
  4995. ctoken("Content-Type: ");
  4996. stoken(content_type);
  4997. ctoken("\r\n");
  4998. }
  4999. auto offset_and_length =
  5000. get_range_offset_and_length(req.ranges[i], content_length);
  5001. ctoken("Content-Range: ");
  5002. stoken(make_content_range_header_field(offset_and_length, content_length));
  5003. ctoken("\r\n");
  5004. ctoken("\r\n");
  5005. if (!content(offset_and_length.first, offset_and_length.second)) {
  5006. return false;
  5007. }
  5008. ctoken("\r\n");
  5009. }
  5010. ctoken("--");
  5011. stoken(boundary);
  5012. ctoken("--");
  5013. return true;
  5014. }
  5015. inline void make_multipart_ranges_data(const Request &req, Response &res,
  5016. const std::string &boundary,
  5017. const std::string &content_type,
  5018. size_t content_length,
  5019. std::string &data) {
  5020. process_multipart_ranges_data(
  5021. req, boundary, content_type, content_length,
  5022. [&](const std::string &token) { data += token; },
  5023. [&](const std::string &token) { data += token; },
  5024. [&](size_t offset, size_t length) {
  5025. assert(offset + length <= content_length);
  5026. data += res.body.substr(offset, length);
  5027. return true;
  5028. });
  5029. }
  5030. inline size_t get_multipart_ranges_data_length(const Request &req,
  5031. const std::string &boundary,
  5032. const std::string &content_type,
  5033. size_t content_length) {
  5034. size_t data_length = 0;
  5035. process_multipart_ranges_data(
  5036. req, boundary, content_type, content_length,
  5037. [&](const std::string &token) { data_length += token.size(); },
  5038. [&](const std::string &token) { data_length += token.size(); },
  5039. [&](size_t /*offset*/, size_t length) {
  5040. data_length += length;
  5041. return true;
  5042. });
  5043. return data_length;
  5044. }
  5045. template <typename T>
  5046. inline bool
  5047. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  5048. const std::string &boundary,
  5049. const std::string &content_type,
  5050. size_t content_length, const T &is_shutting_down) {
  5051. return process_multipart_ranges_data(
  5052. req, boundary, content_type, content_length,
  5053. [&](const std::string &token) { strm.write(token); },
  5054. [&](const std::string &token) { strm.write(token); },
  5055. [&](size_t offset, size_t length) {
  5056. return write_content(strm, res.content_provider_, offset, length,
  5057. is_shutting_down);
  5058. });
  5059. }
  5060. inline bool expect_content(const Request &req) {
  5061. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  5062. req.method == "DELETE") {
  5063. return true;
  5064. }
  5065. if (req.has_header("Content-Length") &&
  5066. req.get_header_value_u64("Content-Length") > 0) {
  5067. return true;
  5068. }
  5069. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  5070. return false;
  5071. }
  5072. inline bool has_crlf(const std::string &s) {
  5073. auto p = s.c_str();
  5074. while (*p) {
  5075. if (*p == '\r' || *p == '\n') { return true; }
  5076. p++;
  5077. }
  5078. return false;
  5079. }
  5080. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5081. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  5082. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  5083. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  5084. unsigned int hash_length = 0;
  5085. unsigned char hash[EVP_MAX_MD_SIZE];
  5086. EVP_DigestInit_ex(context.get(), algo, nullptr);
  5087. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  5088. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  5089. std::stringstream ss;
  5090. for (auto i = 0u; i < hash_length; ++i) {
  5091. ss << std::hex << std::setw(2) << std::setfill('0')
  5092. << static_cast<unsigned int>(hash[i]);
  5093. }
  5094. return ss.str();
  5095. }
  5096. inline std::string MD5(const std::string &s) {
  5097. return message_digest(s, EVP_md5());
  5098. }
  5099. inline std::string SHA_256(const std::string &s) {
  5100. return message_digest(s, EVP_sha256());
  5101. }
  5102. inline std::string SHA_512(const std::string &s) {
  5103. return message_digest(s, EVP_sha512());
  5104. }
  5105. inline std::pair<std::string, std::string> make_digest_authentication_header(
  5106. const Request &req, const std::map<std::string, std::string> &auth,
  5107. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  5108. const std::string &password, bool is_proxy = false) {
  5109. std::string nc;
  5110. {
  5111. std::stringstream ss;
  5112. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  5113. nc = ss.str();
  5114. }
  5115. std::string qop;
  5116. if (auth.find("qop") != auth.end()) {
  5117. qop = auth.at("qop");
  5118. if (qop.find("auth-int") != std::string::npos) {
  5119. qop = "auth-int";
  5120. } else if (qop.find("auth") != std::string::npos) {
  5121. qop = "auth";
  5122. } else {
  5123. qop.clear();
  5124. }
  5125. }
  5126. std::string algo = "MD5";
  5127. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  5128. std::string response;
  5129. {
  5130. auto H = algo == "SHA-256" ? detail::SHA_256
  5131. : algo == "SHA-512" ? detail::SHA_512
  5132. : detail::MD5;
  5133. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  5134. auto A2 = req.method + ":" + req.path;
  5135. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  5136. if (qop.empty()) {
  5137. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  5138. } else {
  5139. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  5140. ":" + qop + ":" + H(A2));
  5141. }
  5142. }
  5143. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  5144. auto field = "Digest username=\"" + username + "\", realm=\"" +
  5145. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  5146. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  5147. (qop.empty() ? ", response=\""
  5148. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  5149. cnonce + "\", response=\"") +
  5150. response + "\"" +
  5151. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  5152. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5153. return std::make_pair(key, field);
  5154. }
  5155. inline bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) {
  5156. detail::set_nonblocking(sock, true);
  5157. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  5158. char buf[1];
  5159. return !SSL_peek(ssl, buf, 1) &&
  5160. SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
  5161. }
  5162. #ifdef _WIN32
  5163. // NOTE: This code came up with the following stackoverflow post:
  5164. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  5165. inline bool load_system_certs_on_windows(X509_STORE *store) {
  5166. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  5167. if (!hStore) { return false; }
  5168. auto result = false;
  5169. PCCERT_CONTEXT pContext = NULL;
  5170. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  5171. nullptr) {
  5172. auto encoded_cert =
  5173. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  5174. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  5175. if (x509) {
  5176. X509_STORE_add_cert(store, x509);
  5177. X509_free(x509);
  5178. result = true;
  5179. }
  5180. }
  5181. CertFreeCertificateContext(pContext);
  5182. CertCloseStore(hStore, 0);
  5183. return result;
  5184. }
  5185. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  5186. template <typename T>
  5187. using CFObjectPtr =
  5188. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  5189. inline void cf_object_ptr_deleter(CFTypeRef obj) {
  5190. if (obj) { CFRelease(obj); }
  5191. }
  5192. inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5193. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  5194. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  5195. kCFBooleanTrue};
  5196. CFObjectPtr<CFDictionaryRef> query(
  5197. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  5198. sizeof(keys) / sizeof(keys[0]),
  5199. &kCFTypeDictionaryKeyCallBacks,
  5200. &kCFTypeDictionaryValueCallBacks),
  5201. cf_object_ptr_deleter);
  5202. if (!query) { return false; }
  5203. CFTypeRef security_items = nullptr;
  5204. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  5205. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  5206. return false;
  5207. }
  5208. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  5209. return true;
  5210. }
  5211. inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5212. CFArrayRef root_security_items = nullptr;
  5213. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  5214. return false;
  5215. }
  5216. certs.reset(root_security_items);
  5217. return true;
  5218. }
  5219. inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  5220. auto result = false;
  5221. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  5222. const auto cert = reinterpret_cast<const __SecCertificate *>(
  5223. CFArrayGetValueAtIndex(certs, i));
  5224. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  5225. CFDataRef cert_data = nullptr;
  5226. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  5227. errSecSuccess) {
  5228. continue;
  5229. }
  5230. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  5231. auto encoded_cert = static_cast<const unsigned char *>(
  5232. CFDataGetBytePtr(cert_data_ptr.get()));
  5233. auto x509 =
  5234. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  5235. if (x509) {
  5236. X509_STORE_add_cert(store, x509);
  5237. X509_free(x509);
  5238. result = true;
  5239. }
  5240. }
  5241. return result;
  5242. }
  5243. inline bool load_system_certs_on_macos(X509_STORE *store) {
  5244. auto result = false;
  5245. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  5246. if (retrieve_certs_from_keychain(certs) && certs) {
  5247. result = add_certs_to_x509_store(certs.get(), store);
  5248. }
  5249. if (retrieve_root_certs_from_keychain(certs) && certs) {
  5250. result = add_certs_to_x509_store(certs.get(), store) || result;
  5251. }
  5252. return result;
  5253. }
  5254. #endif // _WIN32
  5255. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  5256. #ifdef _WIN32
  5257. class WSInit {
  5258. public:
  5259. WSInit() {
  5260. WSADATA wsaData;
  5261. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  5262. }
  5263. ~WSInit() {
  5264. if (is_valid_) WSACleanup();
  5265. }
  5266. bool is_valid_ = false;
  5267. };
  5268. static WSInit wsinit_;
  5269. #endif
  5270. inline bool parse_www_authenticate(const Response &res,
  5271. std::map<std::string, std::string> &auth,
  5272. bool is_proxy) {
  5273. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  5274. if (res.has_header(auth_key)) {
  5275. thread_local auto re =
  5276. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  5277. auto s = res.get_header_value(auth_key);
  5278. auto pos = s.find(' ');
  5279. if (pos != std::string::npos) {
  5280. auto type = s.substr(0, pos);
  5281. if (type == "Basic") {
  5282. return false;
  5283. } else if (type == "Digest") {
  5284. s = s.substr(pos + 1);
  5285. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  5286. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  5287. const auto &m = *i;
  5288. auto key = s.substr(static_cast<size_t>(m.position(1)),
  5289. static_cast<size_t>(m.length(1)));
  5290. auto val = m.length(2) > 0
  5291. ? s.substr(static_cast<size_t>(m.position(2)),
  5292. static_cast<size_t>(m.length(2)))
  5293. : s.substr(static_cast<size_t>(m.position(3)),
  5294. static_cast<size_t>(m.length(3)));
  5295. auth[key] = val;
  5296. }
  5297. return true;
  5298. }
  5299. }
  5300. }
  5301. return false;
  5302. }
  5303. class ContentProviderAdapter {
  5304. public:
  5305. explicit ContentProviderAdapter(
  5306. ContentProviderWithoutLength &&content_provider)
  5307. : content_provider_(content_provider) {}
  5308. bool operator()(size_t offset, size_t, DataSink &sink) {
  5309. return content_provider_(offset, sink);
  5310. }
  5311. private:
  5312. ContentProviderWithoutLength content_provider_;
  5313. };
  5314. } // namespace detail
  5315. inline std::string hosted_at(const std::string &hostname) {
  5316. std::vector<std::string> addrs;
  5317. hosted_at(hostname, addrs);
  5318. if (addrs.empty()) { return std::string(); }
  5319. return addrs[0];
  5320. }
  5321. inline void hosted_at(const std::string &hostname,
  5322. std::vector<std::string> &addrs) {
  5323. struct addrinfo hints;
  5324. struct addrinfo *result;
  5325. memset(&hints, 0, sizeof(struct addrinfo));
  5326. hints.ai_family = AF_UNSPEC;
  5327. hints.ai_socktype = SOCK_STREAM;
  5328. hints.ai_protocol = 0;
  5329. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  5330. &result, 0)) {
  5331. #if defined __linux__ && !defined __ANDROID__
  5332. res_init();
  5333. #endif
  5334. return;
  5335. }
  5336. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5337. for (auto rp = result; rp; rp = rp->ai_next) {
  5338. const auto &addr =
  5339. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  5340. std::string ip;
  5341. auto dummy = -1;
  5342. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  5343. dummy)) {
  5344. addrs.push_back(ip);
  5345. }
  5346. }
  5347. }
  5348. inline std::string encode_uri_component(const std::string &value) {
  5349. std::ostringstream escaped;
  5350. escaped.fill('0');
  5351. escaped << std::hex;
  5352. for (auto c : value) {
  5353. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  5354. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  5355. c == ')') {
  5356. escaped << c;
  5357. } else {
  5358. escaped << std::uppercase;
  5359. escaped << '%' << std::setw(2)
  5360. << static_cast<int>(static_cast<unsigned char>(c));
  5361. escaped << std::nouppercase;
  5362. }
  5363. }
  5364. return escaped.str();
  5365. }
  5366. inline std::string encode_uri(const std::string &value) {
  5367. std::ostringstream escaped;
  5368. escaped.fill('0');
  5369. escaped << std::hex;
  5370. for (auto c : value) {
  5371. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  5372. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  5373. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  5374. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  5375. escaped << c;
  5376. } else {
  5377. escaped << std::uppercase;
  5378. escaped << '%' << std::setw(2)
  5379. << static_cast<int>(static_cast<unsigned char>(c));
  5380. escaped << std::nouppercase;
  5381. }
  5382. }
  5383. return escaped.str();
  5384. }
  5385. inline std::string decode_uri_component(const std::string &value) {
  5386. std::string result;
  5387. for (size_t i = 0; i < value.size(); i++) {
  5388. if (value[i] == '%' && i + 2 < value.size()) {
  5389. auto val = 0;
  5390. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  5391. result += static_cast<char>(val);
  5392. i += 2;
  5393. } else {
  5394. result += value[i];
  5395. }
  5396. } else {
  5397. result += value[i];
  5398. }
  5399. }
  5400. return result;
  5401. }
  5402. inline std::string decode_uri(const std::string &value) {
  5403. std::string result;
  5404. for (size_t i = 0; i < value.size(); i++) {
  5405. if (value[i] == '%' && i + 2 < value.size()) {
  5406. auto val = 0;
  5407. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  5408. result += static_cast<char>(val);
  5409. i += 2;
  5410. } else {
  5411. result += value[i];
  5412. }
  5413. } else {
  5414. result += value[i];
  5415. }
  5416. }
  5417. return result;
  5418. }
  5419. inline std::string encode_path_component(const std::string &component) {
  5420. std::string result;
  5421. result.reserve(component.size() * 3);
  5422. for (size_t i = 0; i < component.size(); i++) {
  5423. auto c = static_cast<unsigned char>(component[i]);
  5424. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  5425. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  5426. result += static_cast<char>(c);
  5427. }
  5428. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  5429. // "," / ";" / "="
  5430. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  5431. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  5432. c == '=') {
  5433. result += static_cast<char>(c);
  5434. }
  5435. // Colon is allowed in path segments except first segment
  5436. else if (c == ':') {
  5437. result += static_cast<char>(c);
  5438. }
  5439. // @ is allowed in path
  5440. else if (c == '@') {
  5441. result += static_cast<char>(c);
  5442. } else {
  5443. result += '%';
  5444. char hex[3];
  5445. snprintf(hex, sizeof(hex), "%02X", c);
  5446. result.append(hex, 2);
  5447. }
  5448. }
  5449. return result;
  5450. }
  5451. inline std::string decode_path_component(const std::string &component) {
  5452. std::string result;
  5453. result.reserve(component.size());
  5454. for (size_t i = 0; i < component.size(); i++) {
  5455. if (component[i] == '%' && i + 1 < component.size()) {
  5456. if (component[i + 1] == 'u') {
  5457. // Unicode %uXXXX encoding
  5458. auto val = 0;
  5459. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  5460. // 4 digits Unicode codes
  5461. char buff[4];
  5462. size_t len = detail::to_utf8(val, buff);
  5463. if (len > 0) { result.append(buff, len); }
  5464. i += 5; // 'u0000'
  5465. } else {
  5466. result += component[i];
  5467. }
  5468. } else {
  5469. // Standard %XX encoding
  5470. auto val = 0;
  5471. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  5472. // 2 digits hex codes
  5473. result += static_cast<char>(val);
  5474. i += 2; // 'XX'
  5475. } else {
  5476. result += component[i];
  5477. }
  5478. }
  5479. } else {
  5480. result += component[i];
  5481. }
  5482. }
  5483. return result;
  5484. }
  5485. inline std::string encode_query_component(const std::string &component,
  5486. bool space_as_plus) {
  5487. std::string result;
  5488. result.reserve(component.size() * 3);
  5489. for (size_t i = 0; i < component.size(); i++) {
  5490. auto c = static_cast<unsigned char>(component[i]);
  5491. // Unreserved characters per RFC 3986
  5492. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  5493. result += static_cast<char>(c);
  5494. }
  5495. // Space handling
  5496. else if (c == ' ') {
  5497. if (space_as_plus) {
  5498. result += '+';
  5499. } else {
  5500. result += "%20";
  5501. }
  5502. }
  5503. // Plus sign handling
  5504. else if (c == '+') {
  5505. if (space_as_plus) {
  5506. result += "%2B";
  5507. } else {
  5508. result += static_cast<char>(c);
  5509. }
  5510. }
  5511. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  5512. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  5513. c == '*' || c == ',' || c == ';') {
  5514. result += static_cast<char>(c);
  5515. }
  5516. // Colon and @ are allowed in query
  5517. else if (c == ':' || c == '@') {
  5518. result += static_cast<char>(c);
  5519. }
  5520. // Forward slash is allowed in query values
  5521. else if (c == '/') {
  5522. result += static_cast<char>(c);
  5523. }
  5524. // Question mark is allowed in query values (after first ?)
  5525. else if (c == '?') {
  5526. result += static_cast<char>(c);
  5527. } else {
  5528. result += '%';
  5529. char hex[3];
  5530. snprintf(hex, sizeof(hex), "%02X", c);
  5531. result.append(hex, 2);
  5532. }
  5533. }
  5534. return result;
  5535. }
  5536. inline std::string decode_query_component(const std::string &component,
  5537. bool plus_as_space) {
  5538. std::string result;
  5539. result.reserve(component.size());
  5540. for (size_t i = 0; i < component.size(); i++) {
  5541. if (component[i] == '%' && i + 2 < component.size()) {
  5542. std::string hex = component.substr(i + 1, 2);
  5543. char *end;
  5544. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  5545. if (end == hex.c_str() + 2) {
  5546. result += static_cast<char>(value);
  5547. i += 2;
  5548. } else {
  5549. result += component[i];
  5550. }
  5551. } else if (component[i] == '+' && plus_as_space) {
  5552. result += ' '; // + becomes space in form-urlencoded
  5553. } else {
  5554. result += component[i];
  5555. }
  5556. }
  5557. return result;
  5558. }
  5559. inline std::string append_query_params(const std::string &path,
  5560. const Params &params) {
  5561. std::string path_with_query = path;
  5562. thread_local const std::regex re("[^?]+\\?.*");
  5563. auto delm = std::regex_match(path, re) ? '&' : '?';
  5564. path_with_query += delm + detail::params_to_query_str(params);
  5565. return path_with_query;
  5566. }
  5567. // Header utilities
  5568. inline std::pair<std::string, std::string>
  5569. make_range_header(const Ranges &ranges) {
  5570. std::string field = "bytes=";
  5571. auto i = 0;
  5572. for (const auto &r : ranges) {
  5573. if (i != 0) { field += ", "; }
  5574. if (r.first != -1) { field += std::to_string(r.first); }
  5575. field += '-';
  5576. if (r.second != -1) { field += std::to_string(r.second); }
  5577. i++;
  5578. }
  5579. return std::make_pair("Range", std::move(field));
  5580. }
  5581. inline std::pair<std::string, std::string>
  5582. make_basic_authentication_header(const std::string &username,
  5583. const std::string &password, bool is_proxy) {
  5584. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  5585. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5586. return std::make_pair(key, std::move(field));
  5587. }
  5588. inline std::pair<std::string, std::string>
  5589. make_bearer_token_authentication_header(const std::string &token,
  5590. bool is_proxy = false) {
  5591. auto field = "Bearer " + token;
  5592. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5593. return std::make_pair(key, std::move(field));
  5594. }
  5595. // Request implementation
  5596. inline bool Request::has_header(const std::string &key) const {
  5597. return detail::has_header(headers, key);
  5598. }
  5599. inline std::string Request::get_header_value(const std::string &key,
  5600. const char *def, size_t id) const {
  5601. return detail::get_header_value(headers, key, def, id);
  5602. }
  5603. inline size_t Request::get_header_value_count(const std::string &key) const {
  5604. auto r = headers.equal_range(key);
  5605. return static_cast<size_t>(std::distance(r.first, r.second));
  5606. }
  5607. inline void Request::set_header(const std::string &key,
  5608. const std::string &val) {
  5609. if (detail::fields::is_field_name(key) &&
  5610. detail::fields::is_field_value(val)) {
  5611. headers.emplace(key, val);
  5612. }
  5613. }
  5614. inline bool Request::has_trailer(const std::string &key) const {
  5615. return trailers.find(key) != trailers.end();
  5616. }
  5617. inline std::string Request::get_trailer_value(const std::string &key,
  5618. size_t id) const {
  5619. auto rng = trailers.equal_range(key);
  5620. auto it = rng.first;
  5621. std::advance(it, static_cast<ssize_t>(id));
  5622. if (it != rng.second) { return it->second; }
  5623. return std::string();
  5624. }
  5625. inline size_t Request::get_trailer_value_count(const std::string &key) const {
  5626. auto r = trailers.equal_range(key);
  5627. return static_cast<size_t>(std::distance(r.first, r.second));
  5628. }
  5629. inline bool Request::has_param(const std::string &key) const {
  5630. return params.find(key) != params.end();
  5631. }
  5632. inline std::string Request::get_param_value(const std::string &key,
  5633. size_t id) const {
  5634. auto rng = params.equal_range(key);
  5635. auto it = rng.first;
  5636. std::advance(it, static_cast<ssize_t>(id));
  5637. if (it != rng.second) { return it->second; }
  5638. return std::string();
  5639. }
  5640. inline size_t Request::get_param_value_count(const std::string &key) const {
  5641. auto r = params.equal_range(key);
  5642. return static_cast<size_t>(std::distance(r.first, r.second));
  5643. }
  5644. inline bool Request::is_multipart_form_data() const {
  5645. const auto &content_type = get_header_value("Content-Type");
  5646. return !content_type.rfind("multipart/form-data", 0);
  5647. }
  5648. // Multipart FormData implementation
  5649. inline std::string MultipartFormData::get_field(const std::string &key,
  5650. size_t id) const {
  5651. auto rng = fields.equal_range(key);
  5652. auto it = rng.first;
  5653. std::advance(it, static_cast<ssize_t>(id));
  5654. if (it != rng.second) { return it->second.content; }
  5655. return std::string();
  5656. }
  5657. inline std::vector<std::string>
  5658. MultipartFormData::get_fields(const std::string &key) const {
  5659. std::vector<std::string> values;
  5660. auto rng = fields.equal_range(key);
  5661. for (auto it = rng.first; it != rng.second; it++) {
  5662. values.push_back(it->second.content);
  5663. }
  5664. return values;
  5665. }
  5666. inline bool MultipartFormData::has_field(const std::string &key) const {
  5667. return fields.find(key) != fields.end();
  5668. }
  5669. inline size_t MultipartFormData::get_field_count(const std::string &key) const {
  5670. auto r = fields.equal_range(key);
  5671. return static_cast<size_t>(std::distance(r.first, r.second));
  5672. }
  5673. inline FormData MultipartFormData::get_file(const std::string &key,
  5674. size_t id) const {
  5675. auto rng = files.equal_range(key);
  5676. auto it = rng.first;
  5677. std::advance(it, static_cast<ssize_t>(id));
  5678. if (it != rng.second) { return it->second; }
  5679. return FormData();
  5680. }
  5681. inline std::vector<FormData>
  5682. MultipartFormData::get_files(const std::string &key) const {
  5683. std::vector<FormData> values;
  5684. auto rng = files.equal_range(key);
  5685. for (auto it = rng.first; it != rng.second; it++) {
  5686. values.push_back(it->second);
  5687. }
  5688. return values;
  5689. }
  5690. inline bool MultipartFormData::has_file(const std::string &key) const {
  5691. return files.find(key) != files.end();
  5692. }
  5693. inline size_t MultipartFormData::get_file_count(const std::string &key) const {
  5694. auto r = files.equal_range(key);
  5695. return static_cast<size_t>(std::distance(r.first, r.second));
  5696. }
  5697. // Response implementation
  5698. inline bool Response::has_header(const std::string &key) const {
  5699. return headers.find(key) != headers.end();
  5700. }
  5701. inline std::string Response::get_header_value(const std::string &key,
  5702. const char *def,
  5703. size_t id) const {
  5704. return detail::get_header_value(headers, key, def, id);
  5705. }
  5706. inline size_t Response::get_header_value_count(const std::string &key) const {
  5707. auto r = headers.equal_range(key);
  5708. return static_cast<size_t>(std::distance(r.first, r.second));
  5709. }
  5710. inline void Response::set_header(const std::string &key,
  5711. const std::string &val) {
  5712. if (detail::fields::is_field_name(key) &&
  5713. detail::fields::is_field_value(val)) {
  5714. headers.emplace(key, val);
  5715. }
  5716. }
  5717. inline bool Response::has_trailer(const std::string &key) const {
  5718. return trailers.find(key) != trailers.end();
  5719. }
  5720. inline std::string Response::get_trailer_value(const std::string &key,
  5721. size_t id) const {
  5722. auto rng = trailers.equal_range(key);
  5723. auto it = rng.first;
  5724. std::advance(it, static_cast<ssize_t>(id));
  5725. if (it != rng.second) { return it->second; }
  5726. return std::string();
  5727. }
  5728. inline size_t Response::get_trailer_value_count(const std::string &key) const {
  5729. auto r = trailers.equal_range(key);
  5730. return static_cast<size_t>(std::distance(r.first, r.second));
  5731. }
  5732. inline void Response::set_redirect(const std::string &url, int stat) {
  5733. if (detail::fields::is_field_value(url)) {
  5734. set_header("Location", url);
  5735. if (300 <= stat && stat < 400) {
  5736. this->status = stat;
  5737. } else {
  5738. this->status = StatusCode::Found_302;
  5739. }
  5740. }
  5741. }
  5742. inline void Response::set_content(const char *s, size_t n,
  5743. const std::string &content_type) {
  5744. body.assign(s, n);
  5745. auto rng = headers.equal_range("Content-Type");
  5746. headers.erase(rng.first, rng.second);
  5747. set_header("Content-Type", content_type);
  5748. }
  5749. inline void Response::set_content(const std::string &s,
  5750. const std::string &content_type) {
  5751. set_content(s.data(), s.size(), content_type);
  5752. }
  5753. inline void Response::set_content(std::string &&s,
  5754. const std::string &content_type) {
  5755. body = std::move(s);
  5756. auto rng = headers.equal_range("Content-Type");
  5757. headers.erase(rng.first, rng.second);
  5758. set_header("Content-Type", content_type);
  5759. }
  5760. inline void Response::set_content_provider(
  5761. size_t in_length, const std::string &content_type, ContentProvider provider,
  5762. ContentProviderResourceReleaser resource_releaser) {
  5763. set_header("Content-Type", content_type);
  5764. content_length_ = in_length;
  5765. if (in_length > 0) { content_provider_ = std::move(provider); }
  5766. content_provider_resource_releaser_ = std::move(resource_releaser);
  5767. is_chunked_content_provider_ = false;
  5768. }
  5769. inline void Response::set_content_provider(
  5770. const std::string &content_type, ContentProviderWithoutLength provider,
  5771. ContentProviderResourceReleaser resource_releaser) {
  5772. set_header("Content-Type", content_type);
  5773. content_length_ = 0;
  5774. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5775. content_provider_resource_releaser_ = std::move(resource_releaser);
  5776. is_chunked_content_provider_ = false;
  5777. }
  5778. inline void Response::set_chunked_content_provider(
  5779. const std::string &content_type, ContentProviderWithoutLength provider,
  5780. ContentProviderResourceReleaser resource_releaser) {
  5781. set_header("Content-Type", content_type);
  5782. content_length_ = 0;
  5783. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5784. content_provider_resource_releaser_ = std::move(resource_releaser);
  5785. is_chunked_content_provider_ = true;
  5786. }
  5787. inline void Response::set_file_content(const std::string &path,
  5788. const std::string &content_type) {
  5789. file_content_path_ = path;
  5790. file_content_content_type_ = content_type;
  5791. }
  5792. inline void Response::set_file_content(const std::string &path) {
  5793. file_content_path_ = path;
  5794. }
  5795. // Result implementation
  5796. inline bool Result::has_request_header(const std::string &key) const {
  5797. return request_headers_.find(key) != request_headers_.end();
  5798. }
  5799. inline std::string Result::get_request_header_value(const std::string &key,
  5800. const char *def,
  5801. size_t id) const {
  5802. return detail::get_header_value(request_headers_, key, def, id);
  5803. }
  5804. inline size_t
  5805. Result::get_request_header_value_count(const std::string &key) const {
  5806. auto r = request_headers_.equal_range(key);
  5807. return static_cast<size_t>(std::distance(r.first, r.second));
  5808. }
  5809. // Stream implementation
  5810. inline ssize_t Stream::write(const char *ptr) {
  5811. return write(ptr, strlen(ptr));
  5812. }
  5813. inline ssize_t Stream::write(const std::string &s) {
  5814. return write(s.data(), s.size());
  5815. }
  5816. namespace detail {
  5817. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  5818. time_t timeout_sec, time_t timeout_usec,
  5819. time_t &actual_timeout_sec,
  5820. time_t &actual_timeout_usec) {
  5821. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  5822. auto actual_timeout_msec =
  5823. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  5824. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  5825. actual_timeout_sec = actual_timeout_msec / 1000;
  5826. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  5827. }
  5828. // Socket stream implementation
  5829. inline SocketStream::SocketStream(
  5830. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5831. time_t write_timeout_sec, time_t write_timeout_usec,
  5832. time_t max_timeout_msec,
  5833. std::chrono::time_point<std::chrono::steady_clock> start_time)
  5834. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  5835. read_timeout_usec_(read_timeout_usec),
  5836. write_timeout_sec_(write_timeout_sec),
  5837. write_timeout_usec_(write_timeout_usec),
  5838. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  5839. read_buff_(read_buff_size_, 0) {}
  5840. inline SocketStream::~SocketStream() = default;
  5841. inline bool SocketStream::is_readable() const {
  5842. return read_buff_off_ < read_buff_content_size_;
  5843. }
  5844. inline bool SocketStream::wait_readable() const {
  5845. if (max_timeout_msec_ <= 0) {
  5846. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  5847. }
  5848. time_t read_timeout_sec;
  5849. time_t read_timeout_usec;
  5850. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  5851. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  5852. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  5853. }
  5854. inline bool SocketStream::wait_writable() const {
  5855. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  5856. is_socket_alive(sock_);
  5857. }
  5858. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  5859. #ifdef _WIN32
  5860. size =
  5861. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5862. #else
  5863. size = (std::min)(size,
  5864. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  5865. #endif
  5866. if (read_buff_off_ < read_buff_content_size_) {
  5867. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  5868. if (size <= remaining_size) {
  5869. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  5870. read_buff_off_ += size;
  5871. return static_cast<ssize_t>(size);
  5872. } else {
  5873. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  5874. read_buff_off_ += remaining_size;
  5875. return static_cast<ssize_t>(remaining_size);
  5876. }
  5877. }
  5878. if (!wait_readable()) { return -1; }
  5879. read_buff_off_ = 0;
  5880. read_buff_content_size_ = 0;
  5881. if (size < read_buff_size_) {
  5882. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  5883. CPPHTTPLIB_RECV_FLAGS);
  5884. if (n <= 0) {
  5885. return n;
  5886. } else if (n <= static_cast<ssize_t>(size)) {
  5887. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  5888. return n;
  5889. } else {
  5890. memcpy(ptr, read_buff_.data(), size);
  5891. read_buff_off_ = size;
  5892. read_buff_content_size_ = static_cast<size_t>(n);
  5893. return static_cast<ssize_t>(size);
  5894. }
  5895. } else {
  5896. return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  5897. }
  5898. }
  5899. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  5900. if (!wait_writable()) { return -1; }
  5901. #if defined(_WIN32) && !defined(_WIN64)
  5902. size =
  5903. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5904. #endif
  5905. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  5906. }
  5907. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  5908. int &port) const {
  5909. return detail::get_remote_ip_and_port(sock_, ip, port);
  5910. }
  5911. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  5912. int &port) const {
  5913. return detail::get_local_ip_and_port(sock_, ip, port);
  5914. }
  5915. inline socket_t SocketStream::socket() const { return sock_; }
  5916. inline time_t SocketStream::duration() const {
  5917. return std::chrono::duration_cast<std::chrono::milliseconds>(
  5918. std::chrono::steady_clock::now() - start_time_)
  5919. .count();
  5920. }
  5921. // Buffer stream implementation
  5922. inline bool BufferStream::is_readable() const { return true; }
  5923. inline bool BufferStream::wait_readable() const { return true; }
  5924. inline bool BufferStream::wait_writable() const { return true; }
  5925. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  5926. #if defined(_MSC_VER) && _MSC_VER < 1910
  5927. auto len_read = buffer._Copy_s(ptr, size, size, position);
  5928. #else
  5929. auto len_read = buffer.copy(ptr, size, position);
  5930. #endif
  5931. position += static_cast<size_t>(len_read);
  5932. return static_cast<ssize_t>(len_read);
  5933. }
  5934. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  5935. buffer.append(ptr, size);
  5936. return static_cast<ssize_t>(size);
  5937. }
  5938. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  5939. int & /*port*/) const {}
  5940. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  5941. int & /*port*/) const {}
  5942. inline socket_t BufferStream::socket() const { return 0; }
  5943. inline time_t BufferStream::duration() const { return 0; }
  5944. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  5945. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  5946. : MatcherBase(pattern) {
  5947. constexpr const char marker[] = "/:";
  5948. // One past the last ending position of a path param substring
  5949. std::size_t last_param_end = 0;
  5950. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5951. // Needed to ensure that parameter names are unique during matcher
  5952. // construction
  5953. // If exceptions are disabled, only last duplicate path
  5954. // parameter will be set
  5955. std::unordered_set<std::string> param_name_set;
  5956. #endif
  5957. while (true) {
  5958. const auto marker_pos = pattern.find(
  5959. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  5960. if (marker_pos == std::string::npos) { break; }
  5961. static_fragments_.push_back(
  5962. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  5963. const auto param_name_start = marker_pos + str_len(marker);
  5964. auto sep_pos = pattern.find(separator, param_name_start);
  5965. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  5966. auto param_name =
  5967. pattern.substr(param_name_start, sep_pos - param_name_start);
  5968. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5969. if (param_name_set.find(param_name) != param_name_set.cend()) {
  5970. std::string msg = "Encountered path parameter '" + param_name +
  5971. "' multiple times in route pattern '" + pattern + "'.";
  5972. throw std::invalid_argument(msg);
  5973. }
  5974. #endif
  5975. param_names_.push_back(std::move(param_name));
  5976. last_param_end = sep_pos + 1;
  5977. }
  5978. if (last_param_end < pattern.length()) {
  5979. static_fragments_.push_back(pattern.substr(last_param_end));
  5980. }
  5981. }
  5982. inline bool PathParamsMatcher::match(Request &request) const {
  5983. request.matches = std::smatch();
  5984. request.path_params.clear();
  5985. request.path_params.reserve(param_names_.size());
  5986. // One past the position at which the path matched the pattern last time
  5987. std::size_t starting_pos = 0;
  5988. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  5989. const auto &fragment = static_fragments_[i];
  5990. if (starting_pos + fragment.length() > request.path.length()) {
  5991. return false;
  5992. }
  5993. // Avoid unnecessary allocation by using strncmp instead of substr +
  5994. // comparison
  5995. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  5996. fragment.length()) != 0) {
  5997. return false;
  5998. }
  5999. starting_pos += fragment.length();
  6000. // Should only happen when we have a static fragment after a param
  6001. // Example: '/users/:id/subscriptions'
  6002. // The 'subscriptions' fragment here does not have a corresponding param
  6003. if (i >= param_names_.size()) { continue; }
  6004. auto sep_pos = request.path.find(separator, starting_pos);
  6005. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  6006. const auto &param_name = param_names_[i];
  6007. request.path_params.emplace(
  6008. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  6009. // Mark everything up to '/' as matched
  6010. starting_pos = sep_pos + 1;
  6011. }
  6012. // Returns false if the path is longer than the pattern
  6013. return starting_pos >= request.path.length();
  6014. }
  6015. inline bool RegexMatcher::match(Request &request) const {
  6016. request.path_params.clear();
  6017. return std::regex_match(request.path, request.matches, regex_);
  6018. }
  6019. } // namespace detail
  6020. // HTTP server implementation
  6021. inline Server::Server()
  6022. : new_task_queue(
  6023. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  6024. #ifndef _WIN32
  6025. signal(SIGPIPE, SIG_IGN);
  6026. #endif
  6027. }
  6028. inline Server::~Server() = default;
  6029. inline std::unique_ptr<detail::MatcherBase>
  6030. Server::make_matcher(const std::string &pattern) {
  6031. if (pattern.find("/:") != std::string::npos) {
  6032. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  6033. } else {
  6034. return detail::make_unique<detail::RegexMatcher>(pattern);
  6035. }
  6036. }
  6037. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  6038. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6039. return *this;
  6040. }
  6041. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  6042. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6043. return *this;
  6044. }
  6045. inline Server &Server::Post(const std::string &pattern,
  6046. HandlerWithContentReader handler) {
  6047. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  6048. std::move(handler));
  6049. return *this;
  6050. }
  6051. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  6052. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6053. return *this;
  6054. }
  6055. inline Server &Server::Put(const std::string &pattern,
  6056. HandlerWithContentReader handler) {
  6057. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  6058. std::move(handler));
  6059. return *this;
  6060. }
  6061. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  6062. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6063. return *this;
  6064. }
  6065. inline Server &Server::Patch(const std::string &pattern,
  6066. HandlerWithContentReader handler) {
  6067. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  6068. std::move(handler));
  6069. return *this;
  6070. }
  6071. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  6072. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6073. return *this;
  6074. }
  6075. inline Server &Server::Delete(const std::string &pattern,
  6076. HandlerWithContentReader handler) {
  6077. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  6078. std::move(handler));
  6079. return *this;
  6080. }
  6081. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  6082. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  6083. return *this;
  6084. }
  6085. inline bool Server::set_base_dir(const std::string &dir,
  6086. const std::string &mount_point) {
  6087. return set_mount_point(mount_point, dir);
  6088. }
  6089. inline bool Server::set_mount_point(const std::string &mount_point,
  6090. const std::string &dir, Headers headers) {
  6091. detail::FileStat stat(dir);
  6092. if (stat.is_dir()) {
  6093. std::string mnt = !mount_point.empty() ? mount_point : "/";
  6094. if (!mnt.empty() && mnt[0] == '/') {
  6095. base_dirs_.push_back({mnt, dir, std::move(headers)});
  6096. return true;
  6097. }
  6098. }
  6099. return false;
  6100. }
  6101. inline bool Server::remove_mount_point(const std::string &mount_point) {
  6102. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  6103. if (it->mount_point == mount_point) {
  6104. base_dirs_.erase(it);
  6105. return true;
  6106. }
  6107. }
  6108. return false;
  6109. }
  6110. inline Server &
  6111. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  6112. const std::string &mime) {
  6113. file_extension_and_mimetype_map_[ext] = mime;
  6114. return *this;
  6115. }
  6116. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  6117. default_file_mimetype_ = mime;
  6118. return *this;
  6119. }
  6120. inline Server &Server::set_file_request_handler(Handler handler) {
  6121. file_request_handler_ = std::move(handler);
  6122. return *this;
  6123. }
  6124. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  6125. std::true_type) {
  6126. error_handler_ = std::move(handler);
  6127. return *this;
  6128. }
  6129. inline Server &Server::set_error_handler_core(Handler handler,
  6130. std::false_type) {
  6131. error_handler_ = [handler](const Request &req, Response &res) {
  6132. handler(req, res);
  6133. return HandlerResponse::Handled;
  6134. };
  6135. return *this;
  6136. }
  6137. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  6138. exception_handler_ = std::move(handler);
  6139. return *this;
  6140. }
  6141. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  6142. pre_routing_handler_ = std::move(handler);
  6143. return *this;
  6144. }
  6145. inline Server &Server::set_post_routing_handler(Handler handler) {
  6146. post_routing_handler_ = std::move(handler);
  6147. return *this;
  6148. }
  6149. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  6150. pre_request_handler_ = std::move(handler);
  6151. return *this;
  6152. }
  6153. inline Server &Server::set_logger(Logger logger) {
  6154. logger_ = std::move(logger);
  6155. return *this;
  6156. }
  6157. inline Server &Server::set_error_logger(ErrorLogger error_logger) {
  6158. error_logger_ = std::move(error_logger);
  6159. return *this;
  6160. }
  6161. inline Server &Server::set_pre_compression_logger(Logger logger) {
  6162. pre_compression_logger_ = std::move(logger);
  6163. return *this;
  6164. }
  6165. inline Server &
  6166. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  6167. expect_100_continue_handler_ = std::move(handler);
  6168. return *this;
  6169. }
  6170. inline Server &Server::set_address_family(int family) {
  6171. address_family_ = family;
  6172. return *this;
  6173. }
  6174. inline Server &Server::set_tcp_nodelay(bool on) {
  6175. tcp_nodelay_ = on;
  6176. return *this;
  6177. }
  6178. inline Server &Server::set_ipv6_v6only(bool on) {
  6179. ipv6_v6only_ = on;
  6180. return *this;
  6181. }
  6182. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  6183. socket_options_ = std::move(socket_options);
  6184. return *this;
  6185. }
  6186. inline Server &Server::set_default_headers(Headers headers) {
  6187. default_headers_ = std::move(headers);
  6188. return *this;
  6189. }
  6190. inline Server &Server::set_header_writer(
  6191. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  6192. header_writer_ = writer;
  6193. return *this;
  6194. }
  6195. inline Server &Server::set_keep_alive_max_count(size_t count) {
  6196. keep_alive_max_count_ = count;
  6197. return *this;
  6198. }
  6199. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  6200. keep_alive_timeout_sec_ = sec;
  6201. return *this;
  6202. }
  6203. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  6204. read_timeout_sec_ = sec;
  6205. read_timeout_usec_ = usec;
  6206. return *this;
  6207. }
  6208. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  6209. write_timeout_sec_ = sec;
  6210. write_timeout_usec_ = usec;
  6211. return *this;
  6212. }
  6213. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  6214. idle_interval_sec_ = sec;
  6215. idle_interval_usec_ = usec;
  6216. return *this;
  6217. }
  6218. inline Server &Server::set_payload_max_length(size_t length) {
  6219. payload_max_length_ = length;
  6220. return *this;
  6221. }
  6222. inline bool Server::bind_to_port(const std::string &host, int port,
  6223. int socket_flags) {
  6224. auto ret = bind_internal(host, port, socket_flags);
  6225. if (ret == -1) { is_decommissioned = true; }
  6226. return ret >= 0;
  6227. }
  6228. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  6229. auto ret = bind_internal(host, 0, socket_flags);
  6230. if (ret == -1) { is_decommissioned = true; }
  6231. return ret;
  6232. }
  6233. inline bool Server::listen_after_bind() { return listen_internal(); }
  6234. inline bool Server::listen(const std::string &host, int port,
  6235. int socket_flags) {
  6236. return bind_to_port(host, port, socket_flags) && listen_internal();
  6237. }
  6238. inline bool Server::is_running() const { return is_running_; }
  6239. inline void Server::wait_until_ready() const {
  6240. while (!is_running_ && !is_decommissioned) {
  6241. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  6242. }
  6243. }
  6244. inline void Server::stop() {
  6245. if (is_running_) {
  6246. assert(svr_sock_ != INVALID_SOCKET);
  6247. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  6248. detail::shutdown_socket(sock);
  6249. detail::close_socket(sock);
  6250. }
  6251. is_decommissioned = false;
  6252. }
  6253. inline void Server::decommission() { is_decommissioned = true; }
  6254. inline bool Server::parse_request_line(const char *s, Request &req) const {
  6255. auto len = strlen(s);
  6256. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  6257. len -= 2;
  6258. {
  6259. size_t count = 0;
  6260. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  6261. switch (count) {
  6262. case 0: req.method = std::string(b, e); break;
  6263. case 1: req.target = std::string(b, e); break;
  6264. case 2: req.version = std::string(b, e); break;
  6265. default: break;
  6266. }
  6267. count++;
  6268. });
  6269. if (count != 3) { return false; }
  6270. }
  6271. thread_local const std::set<std::string> methods{
  6272. "GET", "HEAD", "POST", "PUT", "DELETE",
  6273. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  6274. if (methods.find(req.method) == methods.end()) {
  6275. output_error_log(Error::InvalidHTTPMethod, &req);
  6276. return false;
  6277. }
  6278. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  6279. output_error_log(Error::InvalidHTTPVersion, &req);
  6280. return false;
  6281. }
  6282. {
  6283. // Skip URL fragment
  6284. for (size_t i = 0; i < req.target.size(); i++) {
  6285. if (req.target[i] == '#') {
  6286. req.target.erase(i);
  6287. break;
  6288. }
  6289. }
  6290. detail::divide(req.target, '?',
  6291. [&](const char *lhs_data, std::size_t lhs_size,
  6292. const char *rhs_data, std::size_t rhs_size) {
  6293. req.path =
  6294. decode_path_component(std::string(lhs_data, lhs_size));
  6295. detail::parse_query_text(rhs_data, rhs_size, req.params);
  6296. });
  6297. }
  6298. return true;
  6299. }
  6300. inline bool Server::write_response(Stream &strm, bool close_connection,
  6301. Request &req, Response &res) {
  6302. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  6303. // incorrectly to the error content.
  6304. req.ranges.clear();
  6305. return write_response_core(strm, close_connection, req, res, false);
  6306. }
  6307. inline bool Server::write_response_with_content(Stream &strm,
  6308. bool close_connection,
  6309. const Request &req,
  6310. Response &res) {
  6311. return write_response_core(strm, close_connection, req, res, true);
  6312. }
  6313. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  6314. const Request &req, Response &res,
  6315. bool need_apply_ranges) {
  6316. assert(res.status != -1);
  6317. if (400 <= res.status && error_handler_ &&
  6318. error_handler_(req, res) == HandlerResponse::Handled) {
  6319. need_apply_ranges = true;
  6320. }
  6321. std::string content_type;
  6322. std::string boundary;
  6323. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  6324. // Prepare additional headers
  6325. if (close_connection || req.get_header_value("Connection") == "close") {
  6326. res.set_header("Connection", "close");
  6327. } else {
  6328. std::string s = "timeout=";
  6329. s += std::to_string(keep_alive_timeout_sec_);
  6330. s += ", max=";
  6331. s += std::to_string(keep_alive_max_count_);
  6332. res.set_header("Keep-Alive", s);
  6333. }
  6334. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  6335. !res.has_header("Content-Type")) {
  6336. res.set_header("Content-Type", "text/plain");
  6337. }
  6338. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  6339. !res.has_header("Content-Length")) {
  6340. res.set_header("Content-Length", "0");
  6341. }
  6342. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  6343. res.set_header("Accept-Ranges", "bytes");
  6344. }
  6345. if (post_routing_handler_) { post_routing_handler_(req, res); }
  6346. // Response line and headers
  6347. {
  6348. detail::BufferStream bstrm;
  6349. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  6350. if (!header_writer_(bstrm, res.headers)) { return false; }
  6351. // Flush buffer
  6352. auto &data = bstrm.get_buffer();
  6353. detail::write_data(strm, data.data(), data.size());
  6354. }
  6355. // Body
  6356. auto ret = true;
  6357. if (req.method != "HEAD") {
  6358. if (!res.body.empty()) {
  6359. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  6360. ret = false;
  6361. }
  6362. } else if (res.content_provider_) {
  6363. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  6364. res.content_provider_success_ = true;
  6365. } else {
  6366. ret = false;
  6367. }
  6368. }
  6369. }
  6370. // Log
  6371. output_log(req, res);
  6372. return ret;
  6373. }
  6374. inline bool
  6375. Server::write_content_with_provider(Stream &strm, const Request &req,
  6376. Response &res, const std::string &boundary,
  6377. const std::string &content_type) {
  6378. auto is_shutting_down = [this]() {
  6379. return this->svr_sock_ == INVALID_SOCKET;
  6380. };
  6381. if (res.content_length_ > 0) {
  6382. if (req.ranges.empty()) {
  6383. return detail::write_content(strm, res.content_provider_, 0,
  6384. res.content_length_, is_shutting_down);
  6385. } else if (req.ranges.size() == 1) {
  6386. auto offset_and_length = detail::get_range_offset_and_length(
  6387. req.ranges[0], res.content_length_);
  6388. return detail::write_content(strm, res.content_provider_,
  6389. offset_and_length.first,
  6390. offset_and_length.second, is_shutting_down);
  6391. } else {
  6392. return detail::write_multipart_ranges_data(
  6393. strm, req, res, boundary, content_type, res.content_length_,
  6394. is_shutting_down);
  6395. }
  6396. } else {
  6397. if (res.is_chunked_content_provider_) {
  6398. auto type = detail::encoding_type(req, res);
  6399. std::unique_ptr<detail::compressor> compressor;
  6400. if (type == detail::EncodingType::Gzip) {
  6401. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6402. compressor = detail::make_unique<detail::gzip_compressor>();
  6403. #endif
  6404. } else if (type == detail::EncodingType::Brotli) {
  6405. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6406. compressor = detail::make_unique<detail::brotli_compressor>();
  6407. #endif
  6408. } else if (type == detail::EncodingType::Zstd) {
  6409. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6410. compressor = detail::make_unique<detail::zstd_compressor>();
  6411. #endif
  6412. } else {
  6413. compressor = detail::make_unique<detail::nocompressor>();
  6414. }
  6415. assert(compressor != nullptr);
  6416. return detail::write_content_chunked(strm, res.content_provider_,
  6417. is_shutting_down, *compressor);
  6418. } else {
  6419. return detail::write_content_without_length(strm, res.content_provider_,
  6420. is_shutting_down);
  6421. }
  6422. }
  6423. }
  6424. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  6425. FormFields::iterator cur_field;
  6426. FormFiles::iterator cur_file;
  6427. auto is_text_field = false;
  6428. size_t count = 0;
  6429. if (read_content_core(
  6430. strm, req, res,
  6431. // Regular
  6432. [&](const char *buf, size_t n) {
  6433. if (req.body.size() + n > req.body.max_size()) { return false; }
  6434. req.body.append(buf, n);
  6435. return true;
  6436. },
  6437. // Multipart FormData
  6438. [&](const FormData &file) {
  6439. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  6440. output_error_log(Error::TooManyFormDataFiles, &req);
  6441. return false;
  6442. }
  6443. if (file.filename.empty()) {
  6444. cur_field = req.form.fields.emplace(
  6445. file.name, FormField{file.name, file.content, file.headers});
  6446. is_text_field = true;
  6447. } else {
  6448. cur_file = req.form.files.emplace(file.name, file);
  6449. is_text_field = false;
  6450. }
  6451. return true;
  6452. },
  6453. [&](const char *buf, size_t n) {
  6454. if (is_text_field) {
  6455. auto &content = cur_field->second.content;
  6456. if (content.size() + n > content.max_size()) { return false; }
  6457. content.append(buf, n);
  6458. } else {
  6459. auto &content = cur_file->second.content;
  6460. if (content.size() + n > content.max_size()) { return false; }
  6461. content.append(buf, n);
  6462. }
  6463. return true;
  6464. })) {
  6465. const auto &content_type = req.get_header_value("Content-Type");
  6466. if (!content_type.find("application/x-www-form-urlencoded")) {
  6467. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  6468. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  6469. output_error_log(Error::ExceedMaxPayloadSize, &req);
  6470. return false;
  6471. }
  6472. detail::parse_query_text(req.body, req.params);
  6473. }
  6474. return true;
  6475. }
  6476. return false;
  6477. }
  6478. inline bool Server::read_content_with_content_receiver(
  6479. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  6480. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  6481. return read_content_core(strm, req, res, std::move(receiver),
  6482. std::move(multipart_header),
  6483. std::move(multipart_receiver));
  6484. }
  6485. inline bool Server::read_content_core(
  6486. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  6487. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  6488. detail::FormDataParser multipart_form_data_parser;
  6489. ContentReceiverWithProgress out;
  6490. if (req.is_multipart_form_data()) {
  6491. const auto &content_type = req.get_header_value("Content-Type");
  6492. std::string boundary;
  6493. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  6494. res.status = StatusCode::BadRequest_400;
  6495. output_error_log(Error::MultipartParsing, &req);
  6496. return false;
  6497. }
  6498. multipart_form_data_parser.set_boundary(std::move(boundary));
  6499. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  6500. return multipart_form_data_parser.parse(buf, n, multipart_header,
  6501. multipart_receiver);
  6502. };
  6503. } else {
  6504. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  6505. size_t /*len*/) { return receiver(buf, n); };
  6506. }
  6507. if (req.method == "DELETE" && !req.has_header("Content-Length")) {
  6508. return true;
  6509. }
  6510. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  6511. out, true)) {
  6512. return false;
  6513. }
  6514. if (req.is_multipart_form_data()) {
  6515. if (!multipart_form_data_parser.is_valid()) {
  6516. res.status = StatusCode::BadRequest_400;
  6517. output_error_log(Error::MultipartParsing, &req);
  6518. return false;
  6519. }
  6520. }
  6521. return true;
  6522. }
  6523. inline bool Server::handle_file_request(const Request &req, Response &res) {
  6524. for (const auto &entry : base_dirs_) {
  6525. // Prefix match
  6526. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  6527. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  6528. if (detail::is_valid_path(sub_path)) {
  6529. auto path = entry.base_dir + sub_path;
  6530. if (path.back() == '/') { path += "index.html"; }
  6531. detail::FileStat stat(path);
  6532. if (stat.is_dir()) {
  6533. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  6534. return true;
  6535. }
  6536. if (stat.is_file()) {
  6537. for (const auto &kv : entry.headers) {
  6538. res.set_header(kv.first, kv.second);
  6539. }
  6540. auto mm = std::make_shared<detail::mmap>(path.c_str());
  6541. if (!mm->is_open()) {
  6542. output_error_log(Error::OpenFile, &req);
  6543. return false;
  6544. }
  6545. res.set_content_provider(
  6546. mm->size(),
  6547. detail::find_content_type(path, file_extension_and_mimetype_map_,
  6548. default_file_mimetype_),
  6549. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  6550. sink.write(mm->data() + offset, length);
  6551. return true;
  6552. });
  6553. if (req.method != "HEAD" && file_request_handler_) {
  6554. file_request_handler_(req, res);
  6555. }
  6556. return true;
  6557. } else {
  6558. output_error_log(Error::OpenFile, &req);
  6559. }
  6560. }
  6561. }
  6562. }
  6563. return false;
  6564. }
  6565. inline socket_t
  6566. Server::create_server_socket(const std::string &host, int port,
  6567. int socket_flags,
  6568. SocketOptions socket_options) const {
  6569. return detail::create_socket(
  6570. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  6571. ipv6_v6only_, std::move(socket_options),
  6572. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  6573. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  6574. output_error_log(Error::BindIPAddress, nullptr);
  6575. return false;
  6576. }
  6577. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  6578. output_error_log(Error::Listen, nullptr);
  6579. return false;
  6580. }
  6581. return true;
  6582. });
  6583. }
  6584. inline int Server::bind_internal(const std::string &host, int port,
  6585. int socket_flags) {
  6586. if (is_decommissioned) { return -1; }
  6587. if (!is_valid()) { return -1; }
  6588. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  6589. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  6590. if (port == 0) {
  6591. struct sockaddr_storage addr;
  6592. socklen_t addr_len = sizeof(addr);
  6593. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  6594. &addr_len) == -1) {
  6595. output_error_log(Error::GetSockName, nullptr);
  6596. return -1;
  6597. }
  6598. if (addr.ss_family == AF_INET) {
  6599. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  6600. } else if (addr.ss_family == AF_INET6) {
  6601. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  6602. } else {
  6603. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  6604. return -1;
  6605. }
  6606. } else {
  6607. return port;
  6608. }
  6609. }
  6610. inline bool Server::listen_internal() {
  6611. if (is_decommissioned) { return false; }
  6612. auto ret = true;
  6613. is_running_ = true;
  6614. auto se = detail::scope_exit([&]() { is_running_ = false; });
  6615. {
  6616. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  6617. while (svr_sock_ != INVALID_SOCKET) {
  6618. #ifndef _WIN32
  6619. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  6620. #endif
  6621. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  6622. idle_interval_usec_);
  6623. if (val == 0) { // Timeout
  6624. task_queue->on_idle();
  6625. continue;
  6626. }
  6627. #ifndef _WIN32
  6628. }
  6629. #endif
  6630. #if defined _WIN32
  6631. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  6632. // OVERLAPPED
  6633. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  6634. #elif defined SOCK_CLOEXEC
  6635. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  6636. #else
  6637. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  6638. #endif
  6639. if (sock == INVALID_SOCKET) {
  6640. if (errno == EMFILE) {
  6641. // The per-process limit of open file descriptors has been reached.
  6642. // Try to accept new connections after a short sleep.
  6643. std::this_thread::sleep_for(std::chrono::microseconds{1});
  6644. continue;
  6645. } else if (errno == EINTR || errno == EAGAIN) {
  6646. continue;
  6647. }
  6648. if (svr_sock_ != INVALID_SOCKET) {
  6649. detail::close_socket(svr_sock_);
  6650. ret = false;
  6651. output_error_log(Error::Connection, nullptr);
  6652. } else {
  6653. ; // The server socket was closed by user.
  6654. }
  6655. break;
  6656. }
  6657. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  6658. read_timeout_sec_, read_timeout_usec_);
  6659. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  6660. write_timeout_sec_, write_timeout_usec_);
  6661. if (!task_queue->enqueue(
  6662. [this, sock]() { process_and_close_socket(sock); })) {
  6663. output_error_log(Error::ResourceExhaustion, nullptr);
  6664. detail::shutdown_socket(sock);
  6665. detail::close_socket(sock);
  6666. }
  6667. }
  6668. task_queue->shutdown();
  6669. }
  6670. is_decommissioned = !ret;
  6671. return ret;
  6672. }
  6673. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  6674. if (pre_routing_handler_ &&
  6675. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  6676. return true;
  6677. }
  6678. // File handler
  6679. if ((req.method == "GET" || req.method == "HEAD") &&
  6680. handle_file_request(req, res)) {
  6681. return true;
  6682. }
  6683. if (detail::expect_content(req)) {
  6684. // Content reader handler
  6685. {
  6686. ContentReader reader(
  6687. [&](ContentReceiver receiver) {
  6688. auto result = read_content_with_content_receiver(
  6689. strm, req, res, std::move(receiver), nullptr, nullptr);
  6690. if (!result) { output_error_log(Error::Read, &req); }
  6691. return result;
  6692. },
  6693. [&](FormDataHeader header, ContentReceiver receiver) {
  6694. auto result = read_content_with_content_receiver(
  6695. strm, req, res, nullptr, std::move(header),
  6696. std::move(receiver));
  6697. if (!result) { output_error_log(Error::Read, &req); }
  6698. return result;
  6699. });
  6700. if (req.method == "POST") {
  6701. if (dispatch_request_for_content_reader(
  6702. req, res, std::move(reader),
  6703. post_handlers_for_content_reader_)) {
  6704. return true;
  6705. }
  6706. } else if (req.method == "PUT") {
  6707. if (dispatch_request_for_content_reader(
  6708. req, res, std::move(reader),
  6709. put_handlers_for_content_reader_)) {
  6710. return true;
  6711. }
  6712. } else if (req.method == "PATCH") {
  6713. if (dispatch_request_for_content_reader(
  6714. req, res, std::move(reader),
  6715. patch_handlers_for_content_reader_)) {
  6716. return true;
  6717. }
  6718. } else if (req.method == "DELETE") {
  6719. if (dispatch_request_for_content_reader(
  6720. req, res, std::move(reader),
  6721. delete_handlers_for_content_reader_)) {
  6722. return true;
  6723. }
  6724. }
  6725. }
  6726. // Read content into `req.body`
  6727. if (!read_content(strm, req, res)) {
  6728. output_error_log(Error::Read, &req);
  6729. return false;
  6730. }
  6731. }
  6732. // Regular handler
  6733. if (req.method == "GET" || req.method == "HEAD") {
  6734. return dispatch_request(req, res, get_handlers_);
  6735. } else if (req.method == "POST") {
  6736. return dispatch_request(req, res, post_handlers_);
  6737. } else if (req.method == "PUT") {
  6738. return dispatch_request(req, res, put_handlers_);
  6739. } else if (req.method == "DELETE") {
  6740. return dispatch_request(req, res, delete_handlers_);
  6741. } else if (req.method == "OPTIONS") {
  6742. return dispatch_request(req, res, options_handlers_);
  6743. } else if (req.method == "PATCH") {
  6744. return dispatch_request(req, res, patch_handlers_);
  6745. }
  6746. res.status = StatusCode::BadRequest_400;
  6747. return false;
  6748. }
  6749. inline bool Server::dispatch_request(Request &req, Response &res,
  6750. const Handlers &handlers) const {
  6751. for (const auto &x : handlers) {
  6752. const auto &matcher = x.first;
  6753. const auto &handler = x.second;
  6754. if (matcher->match(req)) {
  6755. req.matched_route = matcher->pattern();
  6756. if (!pre_request_handler_ ||
  6757. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  6758. handler(req, res);
  6759. }
  6760. return true;
  6761. }
  6762. }
  6763. return false;
  6764. }
  6765. inline void Server::apply_ranges(const Request &req, Response &res,
  6766. std::string &content_type,
  6767. std::string &boundary) const {
  6768. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  6769. auto it = res.headers.find("Content-Type");
  6770. if (it != res.headers.end()) {
  6771. content_type = it->second;
  6772. res.headers.erase(it);
  6773. }
  6774. boundary = detail::make_multipart_data_boundary();
  6775. res.set_header("Content-Type",
  6776. "multipart/byteranges; boundary=" + boundary);
  6777. }
  6778. auto type = detail::encoding_type(req, res);
  6779. if (res.body.empty()) {
  6780. if (res.content_length_ > 0) {
  6781. size_t length = 0;
  6782. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  6783. length = res.content_length_;
  6784. } else if (req.ranges.size() == 1) {
  6785. auto offset_and_length = detail::get_range_offset_and_length(
  6786. req.ranges[0], res.content_length_);
  6787. length = offset_and_length.second;
  6788. auto content_range = detail::make_content_range_header_field(
  6789. offset_and_length, res.content_length_);
  6790. res.set_header("Content-Range", content_range);
  6791. } else {
  6792. length = detail::get_multipart_ranges_data_length(
  6793. req, boundary, content_type, res.content_length_);
  6794. }
  6795. res.set_header("Content-Length", std::to_string(length));
  6796. } else {
  6797. if (res.content_provider_) {
  6798. if (res.is_chunked_content_provider_) {
  6799. res.set_header("Transfer-Encoding", "chunked");
  6800. if (type == detail::EncodingType::Gzip) {
  6801. res.set_header("Content-Encoding", "gzip");
  6802. } else if (type == detail::EncodingType::Brotli) {
  6803. res.set_header("Content-Encoding", "br");
  6804. } else if (type == detail::EncodingType::Zstd) {
  6805. res.set_header("Content-Encoding", "zstd");
  6806. }
  6807. }
  6808. }
  6809. }
  6810. } else {
  6811. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  6812. ;
  6813. } else if (req.ranges.size() == 1) {
  6814. auto offset_and_length =
  6815. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  6816. auto offset = offset_and_length.first;
  6817. auto length = offset_and_length.second;
  6818. auto content_range = detail::make_content_range_header_field(
  6819. offset_and_length, res.body.size());
  6820. res.set_header("Content-Range", content_range);
  6821. assert(offset + length <= res.body.size());
  6822. res.body = res.body.substr(offset, length);
  6823. } else {
  6824. std::string data;
  6825. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  6826. res.body.size(), data);
  6827. res.body.swap(data);
  6828. }
  6829. if (type != detail::EncodingType::None) {
  6830. output_pre_compression_log(req, res);
  6831. std::unique_ptr<detail::compressor> compressor;
  6832. std::string content_encoding;
  6833. if (type == detail::EncodingType::Gzip) {
  6834. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6835. compressor = detail::make_unique<detail::gzip_compressor>();
  6836. content_encoding = "gzip";
  6837. #endif
  6838. } else if (type == detail::EncodingType::Brotli) {
  6839. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6840. compressor = detail::make_unique<detail::brotli_compressor>();
  6841. content_encoding = "br";
  6842. #endif
  6843. } else if (type == detail::EncodingType::Zstd) {
  6844. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6845. compressor = detail::make_unique<detail::zstd_compressor>();
  6846. content_encoding = "zstd";
  6847. #endif
  6848. }
  6849. if (compressor) {
  6850. std::string compressed;
  6851. if (compressor->compress(res.body.data(), res.body.size(), true,
  6852. [&](const char *data, size_t data_len) {
  6853. compressed.append(data, data_len);
  6854. return true;
  6855. })) {
  6856. res.body.swap(compressed);
  6857. res.set_header("Content-Encoding", content_encoding);
  6858. }
  6859. }
  6860. }
  6861. auto length = std::to_string(res.body.size());
  6862. res.set_header("Content-Length", length);
  6863. }
  6864. }
  6865. inline bool Server::dispatch_request_for_content_reader(
  6866. Request &req, Response &res, ContentReader content_reader,
  6867. const HandlersForContentReader &handlers) const {
  6868. for (const auto &x : handlers) {
  6869. const auto &matcher = x.first;
  6870. const auto &handler = x.second;
  6871. if (matcher->match(req)) {
  6872. req.matched_route = matcher->pattern();
  6873. if (!pre_request_handler_ ||
  6874. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  6875. handler(req, res, content_reader);
  6876. }
  6877. return true;
  6878. }
  6879. }
  6880. return false;
  6881. }
  6882. inline bool
  6883. Server::process_request(Stream &strm, const std::string &remote_addr,
  6884. int remote_port, const std::string &local_addr,
  6885. int local_port, bool close_connection,
  6886. bool &connection_closed,
  6887. const std::function<void(Request &)> &setup_request) {
  6888. std::array<char, 2048> buf{};
  6889. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  6890. // Connection has been closed on client
  6891. if (!line_reader.getline()) { return false; }
  6892. Request req;
  6893. req.start_time_ = std::chrono::steady_clock::now();
  6894. Response res;
  6895. res.version = "HTTP/1.1";
  6896. res.headers = default_headers_;
  6897. #ifdef __APPLE__
  6898. // Socket file descriptor exceeded FD_SETSIZE...
  6899. if (strm.socket() >= FD_SETSIZE) {
  6900. Headers dummy;
  6901. detail::read_headers(strm, dummy);
  6902. res.status = StatusCode::InternalServerError_500;
  6903. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  6904. return write_response(strm, close_connection, req, res);
  6905. }
  6906. #endif
  6907. // Request line and headers
  6908. if (!parse_request_line(line_reader.ptr(), req)) {
  6909. res.status = StatusCode::BadRequest_400;
  6910. output_error_log(Error::InvalidRequestLine, &req);
  6911. return write_response(strm, close_connection, req, res);
  6912. }
  6913. // Request headers
  6914. if (!detail::read_headers(strm, req.headers)) {
  6915. res.status = StatusCode::BadRequest_400;
  6916. output_error_log(Error::InvalidHeaders, &req);
  6917. return write_response(strm, close_connection, req, res);
  6918. }
  6919. // Check if the request URI doesn't exceed the limit
  6920. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  6921. Headers dummy;
  6922. detail::read_headers(strm, dummy);
  6923. res.status = StatusCode::UriTooLong_414;
  6924. output_error_log(Error::ExceedUriMaxLength, &req);
  6925. return write_response(strm, close_connection, req, res);
  6926. }
  6927. if (req.get_header_value("Connection") == "close") {
  6928. connection_closed = true;
  6929. }
  6930. if (req.version == "HTTP/1.0" &&
  6931. req.get_header_value("Connection") != "Keep-Alive") {
  6932. connection_closed = true;
  6933. }
  6934. req.remote_addr = remote_addr;
  6935. req.remote_port = remote_port;
  6936. req.set_header("REMOTE_ADDR", req.remote_addr);
  6937. req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
  6938. req.local_addr = local_addr;
  6939. req.local_port = local_port;
  6940. req.set_header("LOCAL_ADDR", req.local_addr);
  6941. req.set_header("LOCAL_PORT", std::to_string(req.local_port));
  6942. if (req.has_header("Accept")) {
  6943. const auto &accept_header = req.get_header_value("Accept");
  6944. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  6945. res.status = StatusCode::BadRequest_400;
  6946. output_error_log(Error::HTTPParsing, &req);
  6947. return write_response(strm, close_connection, req, res);
  6948. }
  6949. }
  6950. if (req.has_header("Range")) {
  6951. const auto &range_header_value = req.get_header_value("Range");
  6952. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  6953. res.status = StatusCode::RangeNotSatisfiable_416;
  6954. output_error_log(Error::InvalidRangeHeader, &req);
  6955. return write_response(strm, close_connection, req, res);
  6956. }
  6957. }
  6958. if (setup_request) { setup_request(req); }
  6959. if (req.get_header_value("Expect") == "100-continue") {
  6960. int status = StatusCode::Continue_100;
  6961. if (expect_100_continue_handler_) {
  6962. status = expect_100_continue_handler_(req, res);
  6963. }
  6964. switch (status) {
  6965. case StatusCode::Continue_100:
  6966. case StatusCode::ExpectationFailed_417:
  6967. detail::write_response_line(strm, status);
  6968. strm.write("\r\n");
  6969. break;
  6970. default:
  6971. connection_closed = true;
  6972. return write_response(strm, true, req, res);
  6973. }
  6974. }
  6975. // Setup `is_connection_closed` method
  6976. auto sock = strm.socket();
  6977. req.is_connection_closed = [sock]() {
  6978. return !detail::is_socket_alive(sock);
  6979. };
  6980. // Routing
  6981. auto routed = false;
  6982. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6983. routed = routing(req, res, strm);
  6984. #else
  6985. try {
  6986. routed = routing(req, res, strm);
  6987. } catch (std::exception &e) {
  6988. if (exception_handler_) {
  6989. auto ep = std::current_exception();
  6990. exception_handler_(req, res, ep);
  6991. routed = true;
  6992. } else {
  6993. res.status = StatusCode::InternalServerError_500;
  6994. std::string val;
  6995. auto s = e.what();
  6996. for (size_t i = 0; s[i]; i++) {
  6997. switch (s[i]) {
  6998. case '\r': val += "\\r"; break;
  6999. case '\n': val += "\\n"; break;
  7000. default: val += s[i]; break;
  7001. }
  7002. }
  7003. res.set_header("EXCEPTION_WHAT", val);
  7004. }
  7005. } catch (...) {
  7006. if (exception_handler_) {
  7007. auto ep = std::current_exception();
  7008. exception_handler_(req, res, ep);
  7009. routed = true;
  7010. } else {
  7011. res.status = StatusCode::InternalServerError_500;
  7012. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  7013. }
  7014. }
  7015. #endif
  7016. if (routed) {
  7017. if (res.status == -1) {
  7018. res.status = req.ranges.empty() ? StatusCode::OK_200
  7019. : StatusCode::PartialContent_206;
  7020. }
  7021. // Serve file content by using a content provider
  7022. if (!res.file_content_path_.empty()) {
  7023. const auto &path = res.file_content_path_;
  7024. auto mm = std::make_shared<detail::mmap>(path.c_str());
  7025. if (!mm->is_open()) {
  7026. res.body.clear();
  7027. res.content_length_ = 0;
  7028. res.content_provider_ = nullptr;
  7029. res.status = StatusCode::NotFound_404;
  7030. output_error_log(Error::OpenFile, &req);
  7031. return write_response(strm, close_connection, req, res);
  7032. }
  7033. auto content_type = res.file_content_content_type_;
  7034. if (content_type.empty()) {
  7035. content_type = detail::find_content_type(
  7036. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  7037. }
  7038. res.set_content_provider(
  7039. mm->size(), content_type,
  7040. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  7041. sink.write(mm->data() + offset, length);
  7042. return true;
  7043. });
  7044. }
  7045. if (detail::range_error(req, res)) {
  7046. res.body.clear();
  7047. res.content_length_ = 0;
  7048. res.content_provider_ = nullptr;
  7049. res.status = StatusCode::RangeNotSatisfiable_416;
  7050. return write_response(strm, close_connection, req, res);
  7051. }
  7052. return write_response_with_content(strm, close_connection, req, res);
  7053. } else {
  7054. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  7055. return write_response(strm, close_connection, req, res);
  7056. }
  7057. }
  7058. inline bool Server::is_valid() const { return true; }
  7059. inline bool Server::process_and_close_socket(socket_t sock) {
  7060. std::string remote_addr;
  7061. int remote_port = 0;
  7062. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  7063. std::string local_addr;
  7064. int local_port = 0;
  7065. detail::get_local_ip_and_port(sock, local_addr, local_port);
  7066. auto ret = detail::process_server_socket(
  7067. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  7068. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  7069. write_timeout_usec_,
  7070. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  7071. return process_request(strm, remote_addr, remote_port, local_addr,
  7072. local_port, close_connection, connection_closed,
  7073. nullptr);
  7074. });
  7075. detail::shutdown_socket(sock);
  7076. detail::close_socket(sock);
  7077. return ret;
  7078. }
  7079. inline void Server::output_log(const Request &req, const Response &res) const {
  7080. if (logger_) {
  7081. std::lock_guard<std::mutex> guard(logger_mutex_);
  7082. logger_(req, res);
  7083. }
  7084. }
  7085. inline void Server::output_pre_compression_log(const Request &req,
  7086. const Response &res) const {
  7087. if (pre_compression_logger_) {
  7088. std::lock_guard<std::mutex> guard(logger_mutex_);
  7089. pre_compression_logger_(req, res);
  7090. }
  7091. }
  7092. inline void Server::output_error_log(const Error &err,
  7093. const Request *req) const {
  7094. if (error_logger_) {
  7095. std::lock_guard<std::mutex> guard(logger_mutex_);
  7096. error_logger_(err, req);
  7097. }
  7098. }
  7099. // HTTP client implementation
  7100. inline ClientImpl::ClientImpl(const std::string &host)
  7101. : ClientImpl(host, 80, std::string(), std::string()) {}
  7102. inline ClientImpl::ClientImpl(const std::string &host, int port)
  7103. : ClientImpl(host, port, std::string(), std::string()) {}
  7104. inline ClientImpl::ClientImpl(const std::string &host, int port,
  7105. const std::string &client_cert_path,
  7106. const std::string &client_key_path)
  7107. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  7108. host_and_port_(adjust_host_string(host_) + ":" + std::to_string(port)),
  7109. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  7110. inline ClientImpl::~ClientImpl() {
  7111. // Wait until all the requests in flight are handled.
  7112. size_t retry_count = 10;
  7113. while (retry_count-- > 0) {
  7114. {
  7115. std::lock_guard<std::mutex> guard(socket_mutex_);
  7116. if (socket_requests_in_flight_ == 0) { break; }
  7117. }
  7118. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  7119. }
  7120. std::lock_guard<std::mutex> guard(socket_mutex_);
  7121. shutdown_socket(socket_);
  7122. close_socket(socket_);
  7123. }
  7124. inline bool ClientImpl::is_valid() const { return true; }
  7125. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  7126. client_cert_path_ = rhs.client_cert_path_;
  7127. client_key_path_ = rhs.client_key_path_;
  7128. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  7129. read_timeout_sec_ = rhs.read_timeout_sec_;
  7130. read_timeout_usec_ = rhs.read_timeout_usec_;
  7131. write_timeout_sec_ = rhs.write_timeout_sec_;
  7132. write_timeout_usec_ = rhs.write_timeout_usec_;
  7133. max_timeout_msec_ = rhs.max_timeout_msec_;
  7134. basic_auth_username_ = rhs.basic_auth_username_;
  7135. basic_auth_password_ = rhs.basic_auth_password_;
  7136. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  7137. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7138. digest_auth_username_ = rhs.digest_auth_username_;
  7139. digest_auth_password_ = rhs.digest_auth_password_;
  7140. #endif
  7141. keep_alive_ = rhs.keep_alive_;
  7142. follow_location_ = rhs.follow_location_;
  7143. path_encode_ = rhs.path_encode_;
  7144. address_family_ = rhs.address_family_;
  7145. tcp_nodelay_ = rhs.tcp_nodelay_;
  7146. ipv6_v6only_ = rhs.ipv6_v6only_;
  7147. socket_options_ = rhs.socket_options_;
  7148. compress_ = rhs.compress_;
  7149. decompress_ = rhs.decompress_;
  7150. interface_ = rhs.interface_;
  7151. proxy_host_ = rhs.proxy_host_;
  7152. proxy_port_ = rhs.proxy_port_;
  7153. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  7154. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  7155. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  7156. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7157. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  7158. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  7159. #endif
  7160. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7161. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  7162. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  7163. ca_cert_store_ = rhs.ca_cert_store_;
  7164. #endif
  7165. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7166. server_certificate_verification_ = rhs.server_certificate_verification_;
  7167. server_hostname_verification_ = rhs.server_hostname_verification_;
  7168. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  7169. #endif
  7170. logger_ = rhs.logger_;
  7171. error_logger_ = rhs.error_logger_;
  7172. }
  7173. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  7174. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7175. return detail::create_client_socket(
  7176. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  7177. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  7178. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  7179. write_timeout_sec_, write_timeout_usec_, interface_, error);
  7180. }
  7181. // Check is custom IP specified for host_
  7182. std::string ip;
  7183. auto it = addr_map_.find(host_);
  7184. if (it != addr_map_.end()) { ip = it->second; }
  7185. return detail::create_client_socket(
  7186. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  7187. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  7188. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  7189. write_timeout_usec_, interface_, error);
  7190. }
  7191. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  7192. Error &error) {
  7193. auto sock = create_client_socket(error);
  7194. if (sock == INVALID_SOCKET) { return false; }
  7195. socket.sock = sock;
  7196. return true;
  7197. }
  7198. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  7199. bool /*shutdown_gracefully*/) {
  7200. // If there are any requests in flight from threads other than us, then it's
  7201. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  7202. assert(socket_requests_in_flight_ == 0 ||
  7203. socket_requests_are_from_thread_ == std::this_thread::get_id());
  7204. }
  7205. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  7206. if (socket.sock == INVALID_SOCKET) { return; }
  7207. detail::shutdown_socket(socket.sock);
  7208. }
  7209. inline void ClientImpl::close_socket(Socket &socket) {
  7210. // If there are requests in flight in another thread, usually closing
  7211. // the socket will be fine and they will simply receive an error when
  7212. // using the closed socket, but it is still a bug since rarely the OS
  7213. // may reassign the socket id to be used for a new socket, and then
  7214. // suddenly they will be operating on a live socket that is different
  7215. // than the one they intended!
  7216. assert(socket_requests_in_flight_ == 0 ||
  7217. socket_requests_are_from_thread_ == std::this_thread::get_id());
  7218. // It is also a bug if this happens while SSL is still active
  7219. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7220. assert(socket.ssl == nullptr);
  7221. #endif
  7222. if (socket.sock == INVALID_SOCKET) { return; }
  7223. detail::close_socket(socket.sock);
  7224. socket.sock = INVALID_SOCKET;
  7225. }
  7226. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  7227. Response &res) const {
  7228. std::array<char, 2048> buf{};
  7229. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  7230. if (!line_reader.getline()) { return false; }
  7231. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  7232. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  7233. #else
  7234. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  7235. #endif
  7236. std::cmatch m;
  7237. if (!std::regex_match(line_reader.ptr(), m, re)) {
  7238. return req.method == "CONNECT";
  7239. }
  7240. res.version = std::string(m[1]);
  7241. res.status = std::stoi(std::string(m[2]));
  7242. res.reason = std::string(m[3]);
  7243. // Ignore '100 Continue'
  7244. while (res.status == StatusCode::Continue_100) {
  7245. if (!line_reader.getline()) { return false; } // CRLF
  7246. if (!line_reader.getline()) { return false; } // next response line
  7247. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  7248. res.version = std::string(m[1]);
  7249. res.status = std::stoi(std::string(m[2]));
  7250. res.reason = std::string(m[3]);
  7251. }
  7252. return true;
  7253. }
  7254. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  7255. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  7256. auto ret = send_(req, res, error);
  7257. if (error == Error::SSLPeerCouldBeClosed_) {
  7258. assert(!ret);
  7259. ret = send_(req, res, error);
  7260. }
  7261. return ret;
  7262. }
  7263. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  7264. {
  7265. std::lock_guard<std::mutex> guard(socket_mutex_);
  7266. // Set this to false immediately - if it ever gets set to true by the end of
  7267. // the request, we know another thread instructed us to close the socket.
  7268. socket_should_be_closed_when_request_is_done_ = false;
  7269. auto is_alive = false;
  7270. if (socket_.is_open()) {
  7271. is_alive = detail::is_socket_alive(socket_.sock);
  7272. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7273. if (is_alive && is_ssl()) {
  7274. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  7275. is_alive = false;
  7276. }
  7277. }
  7278. #endif
  7279. if (!is_alive) {
  7280. // Attempt to avoid sigpipe by shutting down non-gracefully if it seems
  7281. // like the other side has already closed the connection Also, there
  7282. // cannot be any requests in flight from other threads since we locked
  7283. // request_mutex_, so safe to close everything immediately
  7284. const bool shutdown_gracefully = false;
  7285. shutdown_ssl(socket_, shutdown_gracefully);
  7286. shutdown_socket(socket_);
  7287. close_socket(socket_);
  7288. }
  7289. }
  7290. if (!is_alive) {
  7291. if (!create_and_connect_socket(socket_, error)) {
  7292. output_error_log(error, &req);
  7293. return false;
  7294. }
  7295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7296. // TODO: refactoring
  7297. if (is_ssl()) {
  7298. auto &scli = static_cast<SSLClient &>(*this);
  7299. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7300. auto success = false;
  7301. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  7302. error)) {
  7303. if (!success) { output_error_log(error, &req); }
  7304. return success;
  7305. }
  7306. }
  7307. if (!scli.initialize_ssl(socket_, error)) {
  7308. output_error_log(error, &req);
  7309. return false;
  7310. }
  7311. }
  7312. #endif
  7313. }
  7314. // Mark the current socket as being in use so that it cannot be closed by
  7315. // anyone else while this request is ongoing, even though we will be
  7316. // releasing the mutex.
  7317. if (socket_requests_in_flight_ > 1) {
  7318. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  7319. }
  7320. socket_requests_in_flight_ += 1;
  7321. socket_requests_are_from_thread_ = std::this_thread::get_id();
  7322. }
  7323. for (const auto &header : default_headers_) {
  7324. if (req.headers.find(header.first) == req.headers.end()) {
  7325. req.headers.insert(header);
  7326. }
  7327. }
  7328. auto ret = false;
  7329. auto close_connection = !keep_alive_;
  7330. auto se = detail::scope_exit([&]() {
  7331. // Briefly lock mutex in order to mark that a request is no longer ongoing
  7332. std::lock_guard<std::mutex> guard(socket_mutex_);
  7333. socket_requests_in_flight_ -= 1;
  7334. if (socket_requests_in_flight_ <= 0) {
  7335. assert(socket_requests_in_flight_ == 0);
  7336. socket_requests_are_from_thread_ = std::thread::id();
  7337. }
  7338. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  7339. !ret) {
  7340. shutdown_ssl(socket_, true);
  7341. shutdown_socket(socket_);
  7342. close_socket(socket_);
  7343. }
  7344. });
  7345. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  7346. return handle_request(strm, req, res, close_connection, error);
  7347. });
  7348. if (!ret) {
  7349. if (error == Error::Success) {
  7350. error = Error::Unknown;
  7351. output_error_log(error, &req);
  7352. }
  7353. }
  7354. return ret;
  7355. }
  7356. inline Result ClientImpl::send(const Request &req) {
  7357. auto req2 = req;
  7358. return send_(std::move(req2));
  7359. }
  7360. inline Result ClientImpl::send_(Request &&req) {
  7361. auto res = detail::make_unique<Response>();
  7362. auto error = Error::Success;
  7363. auto ret = send(req, *res, error);
  7364. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7365. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  7366. last_ssl_error_, last_openssl_error_};
  7367. #else
  7368. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  7369. #endif
  7370. }
  7371. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  7372. Response &res, bool close_connection,
  7373. Error &error) {
  7374. if (req.path.empty()) {
  7375. error = Error::Connection;
  7376. output_error_log(error, &req);
  7377. return false;
  7378. }
  7379. auto req_save = req;
  7380. bool ret;
  7381. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  7382. auto req2 = req;
  7383. req2.path = "http://" + host_and_port_ + req.path;
  7384. ret = process_request(strm, req2, res, close_connection, error);
  7385. req = req2;
  7386. req.path = req_save.path;
  7387. } else {
  7388. ret = process_request(strm, req, res, close_connection, error);
  7389. }
  7390. if (!ret) { return false; }
  7391. if (res.get_header_value("Connection") == "close" ||
  7392. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  7393. // TODO this requires a not-entirely-obvious chain of calls to be correct
  7394. // for this to be safe.
  7395. // This is safe to call because handle_request is only called by send_
  7396. // which locks the request mutex during the process. It would be a bug
  7397. // to call it from a different thread since it's a thread-safety issue
  7398. // to do these things to the socket if another thread is using the socket.
  7399. std::lock_guard<std::mutex> guard(socket_mutex_);
  7400. shutdown_ssl(socket_, true);
  7401. shutdown_socket(socket_);
  7402. close_socket(socket_);
  7403. }
  7404. if (300 < res.status && res.status < 400 && follow_location_) {
  7405. req = req_save;
  7406. ret = redirect(req, res, error);
  7407. }
  7408. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7409. if ((res.status == StatusCode::Unauthorized_401 ||
  7410. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  7411. req.authorization_count_ < 5) {
  7412. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  7413. const auto &username =
  7414. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  7415. const auto &password =
  7416. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  7417. if (!username.empty() && !password.empty()) {
  7418. std::map<std::string, std::string> auth;
  7419. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  7420. Request new_req = req;
  7421. new_req.authorization_count_ += 1;
  7422. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  7423. : "Authorization");
  7424. new_req.headers.insert(detail::make_digest_authentication_header(
  7425. req, auth, new_req.authorization_count_, detail::random_string(10),
  7426. username, password, is_proxy));
  7427. Response new_res;
  7428. ret = send(new_req, new_res, error);
  7429. if (ret) { res = new_res; }
  7430. }
  7431. }
  7432. }
  7433. #endif
  7434. return ret;
  7435. }
  7436. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  7437. if (req.redirect_count_ == 0) {
  7438. error = Error::ExceedRedirectCount;
  7439. output_error_log(error, &req);
  7440. return false;
  7441. }
  7442. auto location = res.get_header_value("location");
  7443. if (location.empty()) { return false; }
  7444. thread_local const std::regex re(
  7445. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  7446. std::smatch m;
  7447. if (!std::regex_match(location, m, re)) { return false; }
  7448. auto scheme = is_ssl() ? "https" : "http";
  7449. auto next_scheme = m[1].str();
  7450. auto next_host = m[2].str();
  7451. if (next_host.empty()) { next_host = m[3].str(); }
  7452. auto port_str = m[4].str();
  7453. auto next_path = m[5].str();
  7454. auto next_query = m[6].str();
  7455. auto next_port = port_;
  7456. if (!port_str.empty()) {
  7457. next_port = std::stoi(port_str);
  7458. } else if (!next_scheme.empty()) {
  7459. next_port = next_scheme == "https" ? 443 : 80;
  7460. }
  7461. if (next_scheme.empty()) { next_scheme = scheme; }
  7462. if (next_host.empty()) { next_host = host_; }
  7463. if (next_path.empty()) { next_path = "/"; }
  7464. auto path = decode_query_component(next_path, true) + next_query;
  7465. // Same host redirect - use current client
  7466. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  7467. return detail::redirect(*this, req, res, path, location, error);
  7468. }
  7469. // Cross-host/scheme redirect - create new client with robust setup
  7470. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  7471. path, location, error);
  7472. }
  7473. // New method for robust redirect client creation
  7474. inline bool ClientImpl::create_redirect_client(
  7475. const std::string &scheme, const std::string &host, int port, Request &req,
  7476. Response &res, const std::string &path, const std::string &location,
  7477. Error &error) {
  7478. // Determine if we need SSL
  7479. auto need_ssl = (scheme == "https");
  7480. // Clean up request headers that are host/client specific
  7481. // Remove headers that should not be carried over to new host
  7482. auto headers_to_remove =
  7483. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  7484. for (const auto &header_name : headers_to_remove) {
  7485. auto it = req.headers.find(header_name);
  7486. while (it != req.headers.end()) {
  7487. it = req.headers.erase(it);
  7488. it = req.headers.find(header_name);
  7489. }
  7490. }
  7491. // Create appropriate client type and handle redirect
  7492. if (need_ssl) {
  7493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7494. // Create SSL client for HTTPS redirect
  7495. SSLClient redirect_client(host, port);
  7496. // Setup basic client configuration first
  7497. setup_redirect_client(redirect_client);
  7498. // SSL-specific configuration for proxy environments
  7499. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7500. // Critical: Disable SSL verification for proxy environments
  7501. redirect_client.enable_server_certificate_verification(false);
  7502. redirect_client.enable_server_hostname_verification(false);
  7503. } else {
  7504. // For direct SSL connections, copy SSL verification settings
  7505. redirect_client.enable_server_certificate_verification(
  7506. server_certificate_verification_);
  7507. redirect_client.enable_server_hostname_verification(
  7508. server_hostname_verification_);
  7509. }
  7510. // Handle CA certificate store and paths if available
  7511. if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) {
  7512. redirect_client.set_ca_cert_store(ca_cert_store_);
  7513. }
  7514. if (!ca_cert_file_path_.empty()) {
  7515. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  7516. }
  7517. // Client certificates are set through constructor for SSLClient
  7518. // NOTE: SSLClient constructor already takes client_cert_path and
  7519. // client_key_path so we need to create it properly if client certs are
  7520. // needed
  7521. // Execute the redirect
  7522. return detail::redirect(redirect_client, req, res, path, location, error);
  7523. #else
  7524. // SSL not supported - set appropriate error
  7525. error = Error::SSLConnection;
  7526. output_error_log(error, &req);
  7527. return false;
  7528. #endif
  7529. } else {
  7530. // HTTP redirect
  7531. ClientImpl redirect_client(host, port);
  7532. // Setup client with robust configuration
  7533. setup_redirect_client(redirect_client);
  7534. // Execute the redirect
  7535. return detail::redirect(redirect_client, req, res, path, location, error);
  7536. }
  7537. }
  7538. // New method for robust client setup (based on basic_manual_redirect.cpp logic)
  7539. template <typename ClientType>
  7540. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  7541. // Copy basic settings first
  7542. client.set_connection_timeout(connection_timeout_sec_);
  7543. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  7544. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  7545. client.set_keep_alive(keep_alive_);
  7546. client.set_follow_location(
  7547. true); // Enable redirects to handle multi-step redirects
  7548. client.set_path_encode(path_encode_);
  7549. client.set_compress(compress_);
  7550. client.set_decompress(decompress_);
  7551. // Copy authentication settings BEFORE proxy setup
  7552. if (!basic_auth_username_.empty()) {
  7553. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  7554. }
  7555. if (!bearer_token_auth_token_.empty()) {
  7556. client.set_bearer_token_auth(bearer_token_auth_token_);
  7557. }
  7558. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7559. if (!digest_auth_username_.empty()) {
  7560. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  7561. }
  7562. #endif
  7563. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  7564. // before proxy auth)
  7565. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7566. // First set proxy host and port
  7567. client.set_proxy(proxy_host_, proxy_port_);
  7568. // Then set proxy authentication (order matters!)
  7569. if (!proxy_basic_auth_username_.empty()) {
  7570. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  7571. proxy_basic_auth_password_);
  7572. }
  7573. if (!proxy_bearer_token_auth_token_.empty()) {
  7574. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  7575. }
  7576. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7577. if (!proxy_digest_auth_username_.empty()) {
  7578. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  7579. proxy_digest_auth_password_);
  7580. }
  7581. #endif
  7582. }
  7583. // Copy network and socket settings
  7584. client.set_address_family(address_family_);
  7585. client.set_tcp_nodelay(tcp_nodelay_);
  7586. client.set_ipv6_v6only(ipv6_v6only_);
  7587. if (socket_options_) { client.set_socket_options(socket_options_); }
  7588. if (!interface_.empty()) { client.set_interface(interface_); }
  7589. // Copy logging and headers
  7590. if (logger_) { client.set_logger(logger_); }
  7591. if (error_logger_) { client.set_error_logger(error_logger_); }
  7592. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  7593. // Each new client should generate its own headers based on its target host
  7594. }
  7595. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  7596. const Request &req,
  7597. Error &error) const {
  7598. auto is_shutting_down = []() { return false; };
  7599. if (req.is_chunked_content_provider_) {
  7600. // TODO: Brotli support
  7601. std::unique_ptr<detail::compressor> compressor;
  7602. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7603. if (compress_) {
  7604. compressor = detail::make_unique<detail::gzip_compressor>();
  7605. } else
  7606. #endif
  7607. {
  7608. compressor = detail::make_unique<detail::nocompressor>();
  7609. }
  7610. return detail::write_content_chunked(strm, req.content_provider_,
  7611. is_shutting_down, *compressor, error);
  7612. } else {
  7613. return detail::write_content_with_progress(
  7614. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  7615. req.upload_progress, error);
  7616. }
  7617. }
  7618. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  7619. bool close_connection, Error &error) {
  7620. // Prepare additional headers
  7621. if (close_connection) {
  7622. if (!req.has_header("Connection")) {
  7623. req.set_header("Connection", "close");
  7624. }
  7625. }
  7626. if (!req.has_header("Host")) {
  7627. // For Unix socket connections, use "localhost" as Host header (similar to
  7628. // curl behavior)
  7629. if (address_family_ == AF_UNIX) {
  7630. req.set_header("Host", "localhost");
  7631. } else if (is_ssl()) {
  7632. if (port_ == 443) {
  7633. req.set_header("Host", host_);
  7634. } else {
  7635. req.set_header("Host", host_and_port_);
  7636. }
  7637. } else {
  7638. if (port_ == 80) {
  7639. req.set_header("Host", host_);
  7640. } else {
  7641. req.set_header("Host", host_and_port_);
  7642. }
  7643. }
  7644. }
  7645. if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); }
  7646. if (!req.content_receiver) {
  7647. if (!req.has_header("Accept-Encoding")) {
  7648. std::string accept_encoding;
  7649. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7650. accept_encoding = "br";
  7651. #endif
  7652. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7653. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  7654. accept_encoding += "gzip, deflate";
  7655. #endif
  7656. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7657. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  7658. accept_encoding += "zstd";
  7659. #endif
  7660. req.set_header("Accept-Encoding", accept_encoding);
  7661. }
  7662. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  7663. if (!req.has_header("User-Agent")) {
  7664. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  7665. req.set_header("User-Agent", agent);
  7666. }
  7667. #endif
  7668. };
  7669. if (req.body.empty()) {
  7670. if (req.content_provider_) {
  7671. if (!req.is_chunked_content_provider_) {
  7672. if (!req.has_header("Content-Length")) {
  7673. auto length = std::to_string(req.content_length_);
  7674. req.set_header("Content-Length", length);
  7675. }
  7676. }
  7677. } else {
  7678. if (req.method == "POST" || req.method == "PUT" ||
  7679. req.method == "PATCH") {
  7680. req.set_header("Content-Length", "0");
  7681. }
  7682. }
  7683. } else {
  7684. if (!req.has_header("Content-Type")) {
  7685. req.set_header("Content-Type", "text/plain");
  7686. }
  7687. if (!req.has_header("Content-Length")) {
  7688. auto length = std::to_string(req.body.size());
  7689. req.set_header("Content-Length", length);
  7690. }
  7691. }
  7692. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  7693. if (!req.has_header("Authorization")) {
  7694. req.headers.insert(make_basic_authentication_header(
  7695. basic_auth_username_, basic_auth_password_, false));
  7696. }
  7697. }
  7698. if (!proxy_basic_auth_username_.empty() &&
  7699. !proxy_basic_auth_password_.empty()) {
  7700. if (!req.has_header("Proxy-Authorization")) {
  7701. req.headers.insert(make_basic_authentication_header(
  7702. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  7703. }
  7704. }
  7705. if (!bearer_token_auth_token_.empty()) {
  7706. if (!req.has_header("Authorization")) {
  7707. req.headers.insert(make_bearer_token_authentication_header(
  7708. bearer_token_auth_token_, false));
  7709. }
  7710. }
  7711. if (!proxy_bearer_token_auth_token_.empty()) {
  7712. if (!req.has_header("Proxy-Authorization")) {
  7713. req.headers.insert(make_bearer_token_authentication_header(
  7714. proxy_bearer_token_auth_token_, true));
  7715. }
  7716. }
  7717. // Request line and headers
  7718. {
  7719. detail::BufferStream bstrm;
  7720. // Extract path and query from req.path
  7721. std::string path_part, query_part;
  7722. auto query_pos = req.path.find('?');
  7723. if (query_pos != std::string::npos) {
  7724. path_part = req.path.substr(0, query_pos);
  7725. query_part = req.path.substr(query_pos + 1);
  7726. } else {
  7727. path_part = req.path;
  7728. query_part = "";
  7729. }
  7730. // Encode path and query
  7731. auto path_with_query =
  7732. path_encode_ ? detail::encode_path(path_part) : path_part;
  7733. detail::parse_query_text(query_part, req.params);
  7734. if (!req.params.empty()) {
  7735. path_with_query = append_query_params(path_with_query, req.params);
  7736. }
  7737. // Write request line and headers
  7738. detail::write_request_line(bstrm, req.method, path_with_query);
  7739. header_writer_(bstrm, req.headers);
  7740. // Flush buffer
  7741. auto &data = bstrm.get_buffer();
  7742. if (!detail::write_data(strm, data.data(), data.size())) {
  7743. error = Error::Write;
  7744. output_error_log(error, &req);
  7745. return false;
  7746. }
  7747. }
  7748. // Body
  7749. if (req.body.empty()) {
  7750. return write_content_with_provider(strm, req, error);
  7751. }
  7752. if (req.upload_progress) {
  7753. auto body_size = req.body.size();
  7754. size_t written = 0;
  7755. auto data = req.body.data();
  7756. while (written < body_size) {
  7757. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  7758. if (!detail::write_data(strm, data + written, to_write)) {
  7759. error = Error::Write;
  7760. output_error_log(error, &req);
  7761. return false;
  7762. }
  7763. written += to_write;
  7764. if (!req.upload_progress(written, body_size)) {
  7765. error = Error::Canceled;
  7766. output_error_log(error, &req);
  7767. return false;
  7768. }
  7769. }
  7770. } else {
  7771. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  7772. error = Error::Write;
  7773. output_error_log(error, &req);
  7774. return false;
  7775. }
  7776. }
  7777. return true;
  7778. }
  7779. inline std::unique_ptr<Response> ClientImpl::send_with_content_provider(
  7780. Request &req, const char *body, size_t content_length,
  7781. ContentProvider content_provider,
  7782. ContentProviderWithoutLength content_provider_without_length,
  7783. const std::string &content_type, Error &error) {
  7784. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7785. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7786. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  7787. #endif
  7788. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7789. if (compress_ && !content_provider_without_length) {
  7790. // TODO: Brotli support
  7791. detail::gzip_compressor compressor;
  7792. if (content_provider) {
  7793. auto ok = true;
  7794. size_t offset = 0;
  7795. DataSink data_sink;
  7796. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  7797. if (ok) {
  7798. auto last = offset + data_len == content_length;
  7799. auto ret = compressor.compress(
  7800. data, data_len, last,
  7801. [&](const char *compressed_data, size_t compressed_data_len) {
  7802. req.body.append(compressed_data, compressed_data_len);
  7803. return true;
  7804. });
  7805. if (ret) {
  7806. offset += data_len;
  7807. } else {
  7808. ok = false;
  7809. }
  7810. }
  7811. return ok;
  7812. };
  7813. while (ok && offset < content_length) {
  7814. if (!content_provider(offset, content_length - offset, data_sink)) {
  7815. error = Error::Canceled;
  7816. output_error_log(error, &req);
  7817. return nullptr;
  7818. }
  7819. }
  7820. } else {
  7821. if (!compressor.compress(body, content_length, true,
  7822. [&](const char *data, size_t data_len) {
  7823. req.body.append(data, data_len);
  7824. return true;
  7825. })) {
  7826. error = Error::Compression;
  7827. output_error_log(error, &req);
  7828. return nullptr;
  7829. }
  7830. }
  7831. } else
  7832. #endif
  7833. {
  7834. if (content_provider) {
  7835. req.content_length_ = content_length;
  7836. req.content_provider_ = std::move(content_provider);
  7837. req.is_chunked_content_provider_ = false;
  7838. } else if (content_provider_without_length) {
  7839. req.content_length_ = 0;
  7840. req.content_provider_ = detail::ContentProviderAdapter(
  7841. std::move(content_provider_without_length));
  7842. req.is_chunked_content_provider_ = true;
  7843. req.set_header("Transfer-Encoding", "chunked");
  7844. } else {
  7845. req.body.assign(body, content_length);
  7846. }
  7847. }
  7848. auto res = detail::make_unique<Response>();
  7849. return send(req, *res, error) ? std::move(res) : nullptr;
  7850. }
  7851. inline Result ClientImpl::send_with_content_provider(
  7852. const std::string &method, const std::string &path, const Headers &headers,
  7853. const char *body, size_t content_length, ContentProvider content_provider,
  7854. ContentProviderWithoutLength content_provider_without_length,
  7855. const std::string &content_type, UploadProgress progress) {
  7856. Request req;
  7857. req.method = method;
  7858. req.headers = headers;
  7859. req.path = path;
  7860. req.upload_progress = std::move(progress);
  7861. if (max_timeout_msec_ > 0) {
  7862. req.start_time_ = std::chrono::steady_clock::now();
  7863. }
  7864. auto error = Error::Success;
  7865. auto res = send_with_content_provider(
  7866. req, body, content_length, std::move(content_provider),
  7867. std::move(content_provider_without_length), content_type, error);
  7868. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7869. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  7870. last_openssl_error_};
  7871. #else
  7872. return Result{std::move(res), error, std::move(req.headers)};
  7873. #endif
  7874. }
  7875. inline std::string
  7876. ClientImpl::adjust_host_string(const std::string &host) const {
  7877. if (host.find(':') != std::string::npos) { return "[" + host + "]"; }
  7878. return host;
  7879. }
  7880. inline void ClientImpl::output_log(const Request &req,
  7881. const Response &res) const {
  7882. if (logger_) {
  7883. std::lock_guard<std::mutex> guard(logger_mutex_);
  7884. logger_(req, res);
  7885. }
  7886. }
  7887. inline void ClientImpl::output_error_log(const Error &err,
  7888. const Request *req) const {
  7889. if (error_logger_) {
  7890. std::lock_guard<std::mutex> guard(logger_mutex_);
  7891. error_logger_(err, req);
  7892. }
  7893. }
  7894. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  7895. Response &res, bool close_connection,
  7896. Error &error) {
  7897. // Send request
  7898. if (!write_request(strm, req, close_connection, error)) { return false; }
  7899. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7900. if (is_ssl()) {
  7901. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  7902. if (!is_proxy_enabled) {
  7903. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  7904. error = Error::SSLPeerCouldBeClosed_;
  7905. output_error_log(error, &req);
  7906. return false;
  7907. }
  7908. }
  7909. }
  7910. #endif
  7911. // Receive response and headers
  7912. if (!read_response_line(strm, req, res) ||
  7913. !detail::read_headers(strm, res.headers)) {
  7914. error = Error::Read;
  7915. output_error_log(error, &req);
  7916. return false;
  7917. }
  7918. // Body
  7919. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  7920. req.method != "CONNECT") {
  7921. auto redirect = 300 < res.status && res.status < 400 &&
  7922. res.status != StatusCode::NotModified_304 &&
  7923. follow_location_;
  7924. if (req.response_handler && !redirect) {
  7925. if (!req.response_handler(res)) {
  7926. error = Error::Canceled;
  7927. output_error_log(error, &req);
  7928. return false;
  7929. }
  7930. }
  7931. auto out =
  7932. req.content_receiver
  7933. ? static_cast<ContentReceiverWithProgress>(
  7934. [&](const char *buf, size_t n, size_t off, size_t len) {
  7935. if (redirect) { return true; }
  7936. auto ret = req.content_receiver(buf, n, off, len);
  7937. if (!ret) {
  7938. error = Error::Canceled;
  7939. output_error_log(error, &req);
  7940. }
  7941. return ret;
  7942. })
  7943. : static_cast<ContentReceiverWithProgress>(
  7944. [&](const char *buf, size_t n, size_t /*off*/,
  7945. size_t /*len*/) {
  7946. assert(res.body.size() + n <= res.body.max_size());
  7947. res.body.append(buf, n);
  7948. return true;
  7949. });
  7950. auto progress = [&](size_t current, size_t total) {
  7951. if (!req.download_progress || redirect) { return true; }
  7952. auto ret = req.download_progress(current, total);
  7953. if (!ret) {
  7954. error = Error::Canceled;
  7955. output_error_log(error, &req);
  7956. }
  7957. return ret;
  7958. };
  7959. if (res.has_header("Content-Length")) {
  7960. if (!req.content_receiver) {
  7961. auto len = res.get_header_value_u64("Content-Length");
  7962. if (len > res.body.max_size()) {
  7963. error = Error::Read;
  7964. output_error_log(error, &req);
  7965. return false;
  7966. }
  7967. res.body.reserve(static_cast<size_t>(len));
  7968. }
  7969. }
  7970. if (res.status != StatusCode::NotModified_304) {
  7971. int dummy_status;
  7972. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  7973. dummy_status, std::move(progress),
  7974. std::move(out), decompress_)) {
  7975. if (error != Error::Canceled) { error = Error::Read; }
  7976. output_error_log(error, &req);
  7977. return false;
  7978. }
  7979. }
  7980. }
  7981. // Log
  7982. output_log(req, res);
  7983. return true;
  7984. }
  7985. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  7986. const std::string &boundary, const UploadFormDataItems &items,
  7987. const FormDataProviderItems &provider_items) const {
  7988. size_t cur_item = 0;
  7989. size_t cur_start = 0;
  7990. // cur_item and cur_start are copied to within the std::function and maintain
  7991. // state between successive calls
  7992. return [&, cur_item, cur_start](size_t offset,
  7993. DataSink &sink) mutable -> bool {
  7994. if (!offset && !items.empty()) {
  7995. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  7996. return true;
  7997. } else if (cur_item < provider_items.size()) {
  7998. if (!cur_start) {
  7999. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  8000. provider_items[cur_item], boundary);
  8001. offset += begin.size();
  8002. cur_start = offset;
  8003. sink.os << begin;
  8004. }
  8005. DataSink cur_sink;
  8006. auto has_data = true;
  8007. cur_sink.write = sink.write;
  8008. cur_sink.done = [&]() { has_data = false; };
  8009. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  8010. return false;
  8011. }
  8012. if (!has_data) {
  8013. sink.os << detail::serialize_multipart_formdata_item_end();
  8014. cur_item++;
  8015. cur_start = 0;
  8016. }
  8017. return true;
  8018. } else {
  8019. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  8020. sink.done();
  8021. return true;
  8022. }
  8023. };
  8024. }
  8025. inline bool ClientImpl::process_socket(
  8026. const Socket &socket,
  8027. std::chrono::time_point<std::chrono::steady_clock> start_time,
  8028. std::function<bool(Stream &strm)> callback) {
  8029. return detail::process_client_socket(
  8030. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8031. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  8032. }
  8033. inline bool ClientImpl::is_ssl() const { return false; }
  8034. inline Result ClientImpl::Get(const std::string &path,
  8035. DownloadProgress progress) {
  8036. return Get(path, Headers(), std::move(progress));
  8037. }
  8038. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  8039. const Headers &headers,
  8040. DownloadProgress progress) {
  8041. if (params.empty()) { return Get(path, headers); }
  8042. std::string path_with_query = append_query_params(path, params);
  8043. return Get(path_with_query, headers, std::move(progress));
  8044. }
  8045. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  8046. DownloadProgress progress) {
  8047. Request req;
  8048. req.method = "GET";
  8049. req.path = path;
  8050. req.headers = headers;
  8051. req.download_progress = std::move(progress);
  8052. if (max_timeout_msec_ > 0) {
  8053. req.start_time_ = std::chrono::steady_clock::now();
  8054. }
  8055. return send_(std::move(req));
  8056. }
  8057. inline Result ClientImpl::Get(const std::string &path,
  8058. ContentReceiver content_receiver,
  8059. DownloadProgress progress) {
  8060. return Get(path, Headers(), nullptr, std::move(content_receiver),
  8061. std::move(progress));
  8062. }
  8063. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  8064. ContentReceiver content_receiver,
  8065. DownloadProgress progress) {
  8066. return Get(path, headers, nullptr, std::move(content_receiver),
  8067. std::move(progress));
  8068. }
  8069. inline Result ClientImpl::Get(const std::string &path,
  8070. ResponseHandler response_handler,
  8071. ContentReceiver content_receiver,
  8072. DownloadProgress progress) {
  8073. return Get(path, Headers(), std::move(response_handler),
  8074. std::move(content_receiver), std::move(progress));
  8075. }
  8076. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  8077. ResponseHandler response_handler,
  8078. ContentReceiver content_receiver,
  8079. DownloadProgress progress) {
  8080. Request req;
  8081. req.method = "GET";
  8082. req.path = path;
  8083. req.headers = headers;
  8084. req.response_handler = std::move(response_handler);
  8085. req.content_receiver =
  8086. [content_receiver](const char *data, size_t data_length,
  8087. size_t /*offset*/, size_t /*total_length*/) {
  8088. return content_receiver(data, data_length);
  8089. };
  8090. req.download_progress = std::move(progress);
  8091. if (max_timeout_msec_ > 0) {
  8092. req.start_time_ = std::chrono::steady_clock::now();
  8093. }
  8094. return send_(std::move(req));
  8095. }
  8096. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  8097. const Headers &headers,
  8098. ContentReceiver content_receiver,
  8099. DownloadProgress progress) {
  8100. return Get(path, params, headers, nullptr, std::move(content_receiver),
  8101. std::move(progress));
  8102. }
  8103. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  8104. const Headers &headers,
  8105. ResponseHandler response_handler,
  8106. ContentReceiver content_receiver,
  8107. DownloadProgress progress) {
  8108. if (params.empty()) {
  8109. return Get(path, headers, std::move(response_handler),
  8110. std::move(content_receiver), std::move(progress));
  8111. }
  8112. std::string path_with_query = append_query_params(path, params);
  8113. return Get(path_with_query, headers, std::move(response_handler),
  8114. std::move(content_receiver), std::move(progress));
  8115. }
  8116. inline Result ClientImpl::Head(const std::string &path) {
  8117. return Head(path, Headers());
  8118. }
  8119. inline Result ClientImpl::Head(const std::string &path,
  8120. const Headers &headers) {
  8121. Request req;
  8122. req.method = "HEAD";
  8123. req.headers = headers;
  8124. req.path = path;
  8125. if (max_timeout_msec_ > 0) {
  8126. req.start_time_ = std::chrono::steady_clock::now();
  8127. }
  8128. return send_(std::move(req));
  8129. }
  8130. inline Result ClientImpl::Post(const std::string &path) {
  8131. return Post(path, std::string(), std::string());
  8132. }
  8133. inline Result ClientImpl::Post(const std::string &path,
  8134. const Headers &headers) {
  8135. return Post(path, headers, nullptr, 0, std::string());
  8136. }
  8137. inline Result ClientImpl::Post(const std::string &path, const char *body,
  8138. size_t content_length,
  8139. const std::string &content_type,
  8140. UploadProgress progress) {
  8141. return Post(path, Headers(), body, content_length, content_type, progress);
  8142. }
  8143. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  8144. const std::string &content_type,
  8145. UploadProgress progress) {
  8146. return Post(path, Headers(), body, content_type, progress);
  8147. }
  8148. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  8149. return Post(path, Headers(), params);
  8150. }
  8151. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  8152. ContentProvider content_provider,
  8153. const std::string &content_type,
  8154. UploadProgress progress) {
  8155. return Post(path, Headers(), content_length, std::move(content_provider),
  8156. content_type, progress);
  8157. }
  8158. inline Result ClientImpl::Post(const std::string &path,
  8159. ContentProviderWithoutLength content_provider,
  8160. const std::string &content_type,
  8161. UploadProgress progress) {
  8162. return Post(path, Headers(), std::move(content_provider), content_type,
  8163. progress);
  8164. }
  8165. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8166. const Params &params) {
  8167. auto query = detail::params_to_query_str(params);
  8168. return Post(path, headers, query, "application/x-www-form-urlencoded");
  8169. }
  8170. inline Result ClientImpl::Post(const std::string &path,
  8171. const UploadFormDataItems &items,
  8172. UploadProgress progress) {
  8173. return Post(path, Headers(), items, progress);
  8174. }
  8175. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8176. const UploadFormDataItems &items,
  8177. UploadProgress progress) {
  8178. const auto &boundary = detail::make_multipart_data_boundary();
  8179. const auto &content_type =
  8180. detail::serialize_multipart_formdata_get_content_type(boundary);
  8181. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8182. return Post(path, headers, body, content_type, progress);
  8183. }
  8184. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8185. const UploadFormDataItems &items,
  8186. const std::string &boundary,
  8187. UploadProgress progress) {
  8188. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  8189. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  8190. }
  8191. const auto &content_type =
  8192. detail::serialize_multipart_formdata_get_content_type(boundary);
  8193. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8194. return Post(path, headers, body, content_type, progress);
  8195. }
  8196. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8197. const char *body, size_t content_length,
  8198. const std::string &content_type,
  8199. UploadProgress progress) {
  8200. return send_with_content_provider("POST", path, headers, body, content_length,
  8201. nullptr, nullptr, content_type, progress);
  8202. }
  8203. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8204. const std::string &body,
  8205. const std::string &content_type,
  8206. UploadProgress progress) {
  8207. return send_with_content_provider("POST", path, headers, body.data(),
  8208. body.size(), nullptr, nullptr, content_type,
  8209. progress);
  8210. }
  8211. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8212. size_t content_length,
  8213. ContentProvider content_provider,
  8214. const std::string &content_type,
  8215. UploadProgress progress) {
  8216. return send_with_content_provider("POST", path, headers, nullptr,
  8217. content_length, std::move(content_provider),
  8218. nullptr, content_type, progress);
  8219. }
  8220. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8221. ContentProviderWithoutLength content_provider,
  8222. const std::string &content_type,
  8223. UploadProgress progress) {
  8224. return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr,
  8225. std::move(content_provider), content_type,
  8226. progress);
  8227. }
  8228. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8229. const UploadFormDataItems &items,
  8230. const FormDataProviderItems &provider_items,
  8231. UploadProgress progress) {
  8232. const auto &boundary = detail::make_multipart_data_boundary();
  8233. const auto &content_type =
  8234. detail::serialize_multipart_formdata_get_content_type(boundary);
  8235. return send_with_content_provider(
  8236. "POST", path, headers, nullptr, 0, nullptr,
  8237. get_multipart_content_provider(boundary, items, provider_items),
  8238. content_type, progress);
  8239. }
  8240. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  8241. const std::string &body,
  8242. const std::string &content_type,
  8243. ContentReceiver content_receiver,
  8244. DownloadProgress progress) {
  8245. Request req;
  8246. req.method = "POST";
  8247. req.path = path;
  8248. req.headers = headers;
  8249. req.body = body;
  8250. req.content_receiver =
  8251. [content_receiver](const char *data, size_t data_length,
  8252. size_t /*offset*/, size_t /*total_length*/) {
  8253. return content_receiver(data, data_length);
  8254. };
  8255. req.download_progress = std::move(progress);
  8256. if (max_timeout_msec_ > 0) {
  8257. req.start_time_ = std::chrono::steady_clock::now();
  8258. }
  8259. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8260. return send_(std::move(req));
  8261. }
  8262. inline Result ClientImpl::Put(const std::string &path) {
  8263. return Put(path, std::string(), std::string());
  8264. }
  8265. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  8266. return Put(path, headers, nullptr, 0, std::string());
  8267. }
  8268. inline Result ClientImpl::Put(const std::string &path, const char *body,
  8269. size_t content_length,
  8270. const std::string &content_type,
  8271. UploadProgress progress) {
  8272. return Put(path, Headers(), body, content_length, content_type, progress);
  8273. }
  8274. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  8275. const std::string &content_type,
  8276. UploadProgress progress) {
  8277. return Put(path, Headers(), body, content_type, progress);
  8278. }
  8279. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  8280. return Put(path, Headers(), params);
  8281. }
  8282. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  8283. ContentProvider content_provider,
  8284. const std::string &content_type,
  8285. UploadProgress progress) {
  8286. return Put(path, Headers(), content_length, std::move(content_provider),
  8287. content_type, progress);
  8288. }
  8289. inline Result ClientImpl::Put(const std::string &path,
  8290. ContentProviderWithoutLength content_provider,
  8291. const std::string &content_type,
  8292. UploadProgress progress) {
  8293. return Put(path, Headers(), std::move(content_provider), content_type,
  8294. progress);
  8295. }
  8296. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8297. const Params &params) {
  8298. auto query = detail::params_to_query_str(params);
  8299. return Put(path, headers, query, "application/x-www-form-urlencoded");
  8300. }
  8301. inline Result ClientImpl::Put(const std::string &path,
  8302. const UploadFormDataItems &items,
  8303. UploadProgress progress) {
  8304. return Put(path, Headers(), items, progress);
  8305. }
  8306. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8307. const UploadFormDataItems &items,
  8308. UploadProgress progress) {
  8309. const auto &boundary = detail::make_multipart_data_boundary();
  8310. const auto &content_type =
  8311. detail::serialize_multipart_formdata_get_content_type(boundary);
  8312. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8313. return Put(path, headers, body, content_type, progress);
  8314. }
  8315. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8316. const UploadFormDataItems &items,
  8317. const std::string &boundary,
  8318. UploadProgress progress) {
  8319. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  8320. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  8321. }
  8322. const auto &content_type =
  8323. detail::serialize_multipart_formdata_get_content_type(boundary);
  8324. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8325. return Put(path, headers, body, content_type, progress);
  8326. }
  8327. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8328. const char *body, size_t content_length,
  8329. const std::string &content_type,
  8330. UploadProgress progress) {
  8331. return send_with_content_provider("PUT", path, headers, body, content_length,
  8332. nullptr, nullptr, content_type, progress);
  8333. }
  8334. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8335. const std::string &body,
  8336. const std::string &content_type,
  8337. UploadProgress progress) {
  8338. return send_with_content_provider("PUT", path, headers, body.data(),
  8339. body.size(), nullptr, nullptr, content_type,
  8340. progress);
  8341. }
  8342. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8343. size_t content_length,
  8344. ContentProvider content_provider,
  8345. const std::string &content_type,
  8346. UploadProgress progress) {
  8347. return send_with_content_provider("PUT", path, headers, nullptr,
  8348. content_length, std::move(content_provider),
  8349. nullptr, content_type, progress);
  8350. }
  8351. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8352. ContentProviderWithoutLength content_provider,
  8353. const std::string &content_type,
  8354. UploadProgress progress) {
  8355. return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr,
  8356. std::move(content_provider), content_type,
  8357. progress);
  8358. }
  8359. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8360. const UploadFormDataItems &items,
  8361. const FormDataProviderItems &provider_items,
  8362. UploadProgress progress) {
  8363. const auto &boundary = detail::make_multipart_data_boundary();
  8364. const auto &content_type =
  8365. detail::serialize_multipart_formdata_get_content_type(boundary);
  8366. return send_with_content_provider(
  8367. "PUT", path, headers, nullptr, 0, nullptr,
  8368. get_multipart_content_provider(boundary, items, provider_items),
  8369. content_type, progress);
  8370. }
  8371. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  8372. const std::string &body,
  8373. const std::string &content_type,
  8374. ContentReceiver content_receiver,
  8375. DownloadProgress progress) {
  8376. Request req;
  8377. req.method = "PUT";
  8378. req.path = path;
  8379. req.headers = headers;
  8380. req.body = body;
  8381. req.content_receiver =
  8382. [content_receiver](const char *data, size_t data_length,
  8383. size_t /*offset*/, size_t /*total_length*/) {
  8384. return content_receiver(data, data_length);
  8385. };
  8386. req.download_progress = std::move(progress);
  8387. if (max_timeout_msec_ > 0) {
  8388. req.start_time_ = std::chrono::steady_clock::now();
  8389. }
  8390. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8391. return send_(std::move(req));
  8392. }
  8393. inline Result ClientImpl::Patch(const std::string &path) {
  8394. return Patch(path, std::string(), std::string());
  8395. }
  8396. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8397. UploadProgress progress) {
  8398. return Patch(path, headers, nullptr, 0, std::string(), progress);
  8399. }
  8400. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  8401. size_t content_length,
  8402. const std::string &content_type,
  8403. UploadProgress progress) {
  8404. return Patch(path, Headers(), body, content_length, content_type, progress);
  8405. }
  8406. inline Result ClientImpl::Patch(const std::string &path,
  8407. const std::string &body,
  8408. const std::string &content_type,
  8409. UploadProgress progress) {
  8410. return Patch(path, Headers(), body, content_type, progress);
  8411. }
  8412. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  8413. return Patch(path, Headers(), params);
  8414. }
  8415. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  8416. ContentProvider content_provider,
  8417. const std::string &content_type,
  8418. UploadProgress progress) {
  8419. return Patch(path, Headers(), content_length, std::move(content_provider),
  8420. content_type, progress);
  8421. }
  8422. inline Result ClientImpl::Patch(const std::string &path,
  8423. ContentProviderWithoutLength content_provider,
  8424. const std::string &content_type,
  8425. UploadProgress progress) {
  8426. return Patch(path, Headers(), std::move(content_provider), content_type,
  8427. progress);
  8428. }
  8429. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8430. const Params &params) {
  8431. auto query = detail::params_to_query_str(params);
  8432. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  8433. }
  8434. inline Result ClientImpl::Patch(const std::string &path,
  8435. const UploadFormDataItems &items,
  8436. UploadProgress progress) {
  8437. return Patch(path, Headers(), items, progress);
  8438. }
  8439. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8440. const UploadFormDataItems &items,
  8441. UploadProgress progress) {
  8442. const auto &boundary = detail::make_multipart_data_boundary();
  8443. const auto &content_type =
  8444. detail::serialize_multipart_formdata_get_content_type(boundary);
  8445. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8446. return Patch(path, headers, body, content_type, progress);
  8447. }
  8448. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8449. const UploadFormDataItems &items,
  8450. const std::string &boundary,
  8451. UploadProgress progress) {
  8452. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  8453. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  8454. }
  8455. const auto &content_type =
  8456. detail::serialize_multipart_formdata_get_content_type(boundary);
  8457. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  8458. return Patch(path, headers, body, content_type, progress);
  8459. }
  8460. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8461. const char *body, size_t content_length,
  8462. const std::string &content_type,
  8463. UploadProgress progress) {
  8464. return send_with_content_provider("PATCH", path, headers, body,
  8465. content_length, nullptr, nullptr,
  8466. content_type, progress);
  8467. }
  8468. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8469. const std::string &body,
  8470. const std::string &content_type,
  8471. UploadProgress progress) {
  8472. return send_with_content_provider("PATCH", path, headers, body.data(),
  8473. body.size(), nullptr, nullptr, content_type,
  8474. progress);
  8475. }
  8476. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8477. size_t content_length,
  8478. ContentProvider content_provider,
  8479. const std::string &content_type,
  8480. UploadProgress progress) {
  8481. return send_with_content_provider("PATCH", path, headers, nullptr,
  8482. content_length, std::move(content_provider),
  8483. nullptr, content_type, progress);
  8484. }
  8485. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8486. ContentProviderWithoutLength content_provider,
  8487. const std::string &content_type,
  8488. UploadProgress progress) {
  8489. return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr,
  8490. std::move(content_provider), content_type,
  8491. progress);
  8492. }
  8493. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8494. const UploadFormDataItems &items,
  8495. const FormDataProviderItems &provider_items,
  8496. UploadProgress progress) {
  8497. const auto &boundary = detail::make_multipart_data_boundary();
  8498. const auto &content_type =
  8499. detail::serialize_multipart_formdata_get_content_type(boundary);
  8500. return send_with_content_provider(
  8501. "PATCH", path, headers, nullptr, 0, nullptr,
  8502. get_multipart_content_provider(boundary, items, provider_items),
  8503. content_type, progress);
  8504. }
  8505. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  8506. const std::string &body,
  8507. const std::string &content_type,
  8508. ContentReceiver content_receiver,
  8509. DownloadProgress progress) {
  8510. Request req;
  8511. req.method = "PATCH";
  8512. req.path = path;
  8513. req.headers = headers;
  8514. req.body = body;
  8515. req.content_receiver =
  8516. [content_receiver](const char *data, size_t data_length,
  8517. size_t /*offset*/, size_t /*total_length*/) {
  8518. return content_receiver(data, data_length);
  8519. };
  8520. req.download_progress = std::move(progress);
  8521. if (max_timeout_msec_ > 0) {
  8522. req.start_time_ = std::chrono::steady_clock::now();
  8523. }
  8524. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8525. return send_(std::move(req));
  8526. }
  8527. inline Result ClientImpl::Delete(const std::string &path,
  8528. DownloadProgress progress) {
  8529. return Delete(path, Headers(), std::string(), std::string(), progress);
  8530. }
  8531. inline Result ClientImpl::Delete(const std::string &path,
  8532. const Headers &headers,
  8533. DownloadProgress progress) {
  8534. return Delete(path, headers, std::string(), std::string(), progress);
  8535. }
  8536. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  8537. size_t content_length,
  8538. const std::string &content_type,
  8539. DownloadProgress progress) {
  8540. return Delete(path, Headers(), body, content_length, content_type, progress);
  8541. }
  8542. inline Result ClientImpl::Delete(const std::string &path,
  8543. const std::string &body,
  8544. const std::string &content_type,
  8545. DownloadProgress progress) {
  8546. return Delete(path, Headers(), body.data(), body.size(), content_type,
  8547. progress);
  8548. }
  8549. inline Result ClientImpl::Delete(const std::string &path,
  8550. const Headers &headers,
  8551. const std::string &body,
  8552. const std::string &content_type,
  8553. DownloadProgress progress) {
  8554. return Delete(path, headers, body.data(), body.size(), content_type,
  8555. progress);
  8556. }
  8557. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  8558. DownloadProgress progress) {
  8559. return Delete(path, Headers(), params, progress);
  8560. }
  8561. inline Result ClientImpl::Delete(const std::string &path,
  8562. const Headers &headers, const Params &params,
  8563. DownloadProgress progress) {
  8564. auto query = detail::params_to_query_str(params);
  8565. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  8566. progress);
  8567. }
  8568. inline Result ClientImpl::Delete(const std::string &path,
  8569. const Headers &headers, const char *body,
  8570. size_t content_length,
  8571. const std::string &content_type,
  8572. DownloadProgress progress) {
  8573. Request req;
  8574. req.method = "DELETE";
  8575. req.headers = headers;
  8576. req.path = path;
  8577. req.download_progress = std::move(progress);
  8578. if (max_timeout_msec_ > 0) {
  8579. req.start_time_ = std::chrono::steady_clock::now();
  8580. }
  8581. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  8582. req.body.assign(body, content_length);
  8583. return send_(std::move(req));
  8584. }
  8585. inline Result ClientImpl::Options(const std::string &path) {
  8586. return Options(path, Headers());
  8587. }
  8588. inline Result ClientImpl::Options(const std::string &path,
  8589. const Headers &headers) {
  8590. Request req;
  8591. req.method = "OPTIONS";
  8592. req.headers = headers;
  8593. req.path = path;
  8594. if (max_timeout_msec_ > 0) {
  8595. req.start_time_ = std::chrono::steady_clock::now();
  8596. }
  8597. return send_(std::move(req));
  8598. }
  8599. inline void ClientImpl::stop() {
  8600. std::lock_guard<std::mutex> guard(socket_mutex_);
  8601. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  8602. // do is to shutdown_socket, so that threads using this socket suddenly
  8603. // discover they can't read/write any more and error out. Everything else
  8604. // (closing the socket, shutting ssl down) is unsafe because these actions are
  8605. // not thread-safe.
  8606. if (socket_requests_in_flight_ > 0) {
  8607. shutdown_socket(socket_);
  8608. // Aside from that, we set a flag for the socket to be closed when we're
  8609. // done.
  8610. socket_should_be_closed_when_request_is_done_ = true;
  8611. return;
  8612. }
  8613. // Otherwise, still holding the mutex, we can shut everything down ourselves
  8614. shutdown_ssl(socket_, true);
  8615. shutdown_socket(socket_);
  8616. close_socket(socket_);
  8617. }
  8618. inline std::string ClientImpl::host() const { return host_; }
  8619. inline int ClientImpl::port() const { return port_; }
  8620. inline size_t ClientImpl::is_socket_open() const {
  8621. std::lock_guard<std::mutex> guard(socket_mutex_);
  8622. return socket_.is_open();
  8623. }
  8624. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  8625. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  8626. connection_timeout_sec_ = sec;
  8627. connection_timeout_usec_ = usec;
  8628. }
  8629. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  8630. read_timeout_sec_ = sec;
  8631. read_timeout_usec_ = usec;
  8632. }
  8633. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  8634. write_timeout_sec_ = sec;
  8635. write_timeout_usec_ = usec;
  8636. }
  8637. inline void ClientImpl::set_max_timeout(time_t msec) {
  8638. max_timeout_msec_ = msec;
  8639. }
  8640. inline void ClientImpl::set_basic_auth(const std::string &username,
  8641. const std::string &password) {
  8642. basic_auth_username_ = username;
  8643. basic_auth_password_ = password;
  8644. }
  8645. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  8646. bearer_token_auth_token_ = token;
  8647. }
  8648. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8649. inline void ClientImpl::set_digest_auth(const std::string &username,
  8650. const std::string &password) {
  8651. digest_auth_username_ = username;
  8652. digest_auth_password_ = password;
  8653. }
  8654. #endif
  8655. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  8656. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  8657. inline void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  8658. inline void
  8659. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  8660. addr_map_ = std::move(addr_map);
  8661. }
  8662. inline void ClientImpl::set_default_headers(Headers headers) {
  8663. default_headers_ = std::move(headers);
  8664. }
  8665. inline void ClientImpl::set_header_writer(
  8666. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  8667. header_writer_ = writer;
  8668. }
  8669. inline void ClientImpl::set_address_family(int family) {
  8670. address_family_ = family;
  8671. }
  8672. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  8673. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  8674. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  8675. socket_options_ = std::move(socket_options);
  8676. }
  8677. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  8678. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  8679. inline void ClientImpl::set_interface(const std::string &intf) {
  8680. interface_ = intf;
  8681. }
  8682. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  8683. proxy_host_ = host;
  8684. proxy_port_ = port;
  8685. }
  8686. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  8687. const std::string &password) {
  8688. proxy_basic_auth_username_ = username;
  8689. proxy_basic_auth_password_ = password;
  8690. }
  8691. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  8692. proxy_bearer_token_auth_token_ = token;
  8693. }
  8694. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8695. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  8696. const std::string &password) {
  8697. proxy_digest_auth_username_ = username;
  8698. proxy_digest_auth_password_ = password;
  8699. }
  8700. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  8701. const std::string &ca_cert_dir_path) {
  8702. ca_cert_file_path_ = ca_cert_file_path;
  8703. ca_cert_dir_path_ = ca_cert_dir_path;
  8704. }
  8705. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  8706. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  8707. ca_cert_store_ = ca_cert_store;
  8708. }
  8709. }
  8710. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  8711. std::size_t size) const {
  8712. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  8713. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  8714. if (!mem) { return nullptr; }
  8715. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  8716. if (!inf) { return nullptr; }
  8717. auto cts = X509_STORE_new();
  8718. if (cts) {
  8719. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  8720. auto itmp = sk_X509_INFO_value(inf, i);
  8721. if (!itmp) { continue; }
  8722. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  8723. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  8724. }
  8725. }
  8726. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  8727. return cts;
  8728. }
  8729. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  8730. server_certificate_verification_ = enabled;
  8731. }
  8732. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  8733. server_hostname_verification_ = enabled;
  8734. }
  8735. inline void ClientImpl::set_server_certificate_verifier(
  8736. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  8737. server_certificate_verifier_ = verifier;
  8738. }
  8739. #endif
  8740. inline void ClientImpl::set_logger(Logger logger) {
  8741. logger_ = std::move(logger);
  8742. }
  8743. inline void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  8744. error_logger_ = std::move(error_logger);
  8745. }
  8746. /*
  8747. * SSL Implementation
  8748. */
  8749. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8750. namespace detail {
  8751. inline bool is_ip_address(const std::string &host) {
  8752. struct in_addr addr4;
  8753. struct in6_addr addr6;
  8754. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  8755. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  8756. }
  8757. template <typename U, typename V>
  8758. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  8759. U SSL_connect_or_accept, V setup) {
  8760. SSL *ssl = nullptr;
  8761. {
  8762. std::lock_guard<std::mutex> guard(ctx_mutex);
  8763. ssl = SSL_new(ctx);
  8764. }
  8765. if (ssl) {
  8766. set_nonblocking(sock, true);
  8767. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  8768. BIO_set_nbio(bio, 1);
  8769. SSL_set_bio(ssl, bio, bio);
  8770. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  8771. SSL_shutdown(ssl);
  8772. {
  8773. std::lock_guard<std::mutex> guard(ctx_mutex);
  8774. SSL_free(ssl);
  8775. }
  8776. set_nonblocking(sock, false);
  8777. return nullptr;
  8778. }
  8779. BIO_set_nbio(bio, 0);
  8780. set_nonblocking(sock, false);
  8781. }
  8782. return ssl;
  8783. }
  8784. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock,
  8785. bool shutdown_gracefully) {
  8786. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  8787. // the remote has closed the network connection
  8788. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  8789. // best-efforts.
  8790. if (shutdown_gracefully) {
  8791. (void)(sock);
  8792. // SSL_shutdown() returns 0 on first call (indicating close_notify alert
  8793. // sent) and 1 on subsequent call (indicating close_notify alert received)
  8794. if (SSL_shutdown(ssl) == 0) {
  8795. // Expected to return 1, but even if it doesn't, we free ssl
  8796. SSL_shutdown(ssl);
  8797. }
  8798. }
  8799. std::lock_guard<std::mutex> guard(ctx_mutex);
  8800. SSL_free(ssl);
  8801. }
  8802. template <typename U>
  8803. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  8804. U ssl_connect_or_accept,
  8805. time_t timeout_sec, time_t timeout_usec,
  8806. int *ssl_error) {
  8807. auto res = 0;
  8808. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  8809. auto err = SSL_get_error(ssl, res);
  8810. switch (err) {
  8811. case SSL_ERROR_WANT_READ:
  8812. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  8813. break;
  8814. case SSL_ERROR_WANT_WRITE:
  8815. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  8816. break;
  8817. default: break;
  8818. }
  8819. if (ssl_error) { *ssl_error = err; }
  8820. return false;
  8821. }
  8822. return true;
  8823. }
  8824. template <typename T>
  8825. inline bool process_server_socket_ssl(
  8826. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  8827. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  8828. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  8829. time_t write_timeout_usec, T callback) {
  8830. return process_server_socket_core(
  8831. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  8832. [&](bool close_connection, bool &connection_closed) {
  8833. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  8834. write_timeout_sec, write_timeout_usec);
  8835. return callback(strm, close_connection, connection_closed);
  8836. });
  8837. }
  8838. template <typename T>
  8839. inline bool process_client_socket_ssl(
  8840. SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8841. time_t write_timeout_sec, time_t write_timeout_usec,
  8842. time_t max_timeout_msec,
  8843. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  8844. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  8845. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  8846. start_time);
  8847. return callback(strm);
  8848. }
  8849. // SSL socket stream implementation
  8850. inline SSLSocketStream::SSLSocketStream(
  8851. socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
  8852. time_t write_timeout_sec, time_t write_timeout_usec,
  8853. time_t max_timeout_msec,
  8854. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8855. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  8856. read_timeout_usec_(read_timeout_usec),
  8857. write_timeout_sec_(write_timeout_sec),
  8858. write_timeout_usec_(write_timeout_usec),
  8859. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  8860. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  8861. }
  8862. inline SSLSocketStream::~SSLSocketStream() = default;
  8863. inline bool SSLSocketStream::is_readable() const {
  8864. return SSL_pending(ssl_) > 0;
  8865. }
  8866. inline bool SSLSocketStream::wait_readable() const {
  8867. if (max_timeout_msec_ <= 0) {
  8868. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8869. }
  8870. time_t read_timeout_sec;
  8871. time_t read_timeout_usec;
  8872. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8873. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8874. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8875. }
  8876. inline bool SSLSocketStream::wait_writable() const {
  8877. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  8878. is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_);
  8879. }
  8880. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  8881. if (SSL_pending(ssl_) > 0) {
  8882. return SSL_read(ssl_, ptr, static_cast<int>(size));
  8883. } else if (wait_readable()) {
  8884. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  8885. if (ret < 0) {
  8886. auto err = SSL_get_error(ssl_, ret);
  8887. auto n = 1000;
  8888. #ifdef _WIN32
  8889. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  8890. (err == SSL_ERROR_SYSCALL &&
  8891. WSAGetLastError() == WSAETIMEDOUT))) {
  8892. #else
  8893. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  8894. #endif
  8895. if (SSL_pending(ssl_) > 0) {
  8896. return SSL_read(ssl_, ptr, static_cast<int>(size));
  8897. } else if (wait_readable()) {
  8898. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8899. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  8900. if (ret >= 0) { return ret; }
  8901. err = SSL_get_error(ssl_, ret);
  8902. } else {
  8903. break;
  8904. }
  8905. }
  8906. assert(ret < 0);
  8907. }
  8908. return ret;
  8909. } else {
  8910. return -1;
  8911. }
  8912. }
  8913. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  8914. if (wait_writable()) {
  8915. auto handle_size = static_cast<int>(
  8916. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  8917. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  8918. if (ret < 0) {
  8919. auto err = SSL_get_error(ssl_, ret);
  8920. auto n = 1000;
  8921. #ifdef _WIN32
  8922. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  8923. (err == SSL_ERROR_SYSCALL &&
  8924. WSAGetLastError() == WSAETIMEDOUT))) {
  8925. #else
  8926. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  8927. #endif
  8928. if (wait_writable()) {
  8929. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8930. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  8931. if (ret >= 0) { return ret; }
  8932. err = SSL_get_error(ssl_, ret);
  8933. } else {
  8934. break;
  8935. }
  8936. }
  8937. assert(ret < 0);
  8938. }
  8939. return ret;
  8940. }
  8941. return -1;
  8942. }
  8943. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  8944. int &port) const {
  8945. detail::get_remote_ip_and_port(sock_, ip, port);
  8946. }
  8947. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  8948. int &port) const {
  8949. detail::get_local_ip_and_port(sock_, ip, port);
  8950. }
  8951. inline socket_t SSLSocketStream::socket() const { return sock_; }
  8952. inline time_t SSLSocketStream::duration() const {
  8953. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8954. std::chrono::steady_clock::now() - start_time_)
  8955. .count();
  8956. }
  8957. } // namespace detail
  8958. // SSL HTTP server implementation
  8959. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  8960. const char *client_ca_cert_file_path,
  8961. const char *client_ca_cert_dir_path,
  8962. const char *private_key_password) {
  8963. ctx_ = SSL_CTX_new(TLS_server_method());
  8964. if (ctx_) {
  8965. SSL_CTX_set_options(ctx_,
  8966. SSL_OP_NO_COMPRESSION |
  8967. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  8968. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8969. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  8970. SSL_CTX_set_default_passwd_cb_userdata(
  8971. ctx_,
  8972. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  8973. }
  8974. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  8975. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  8976. 1 ||
  8977. SSL_CTX_check_private_key(ctx_) != 1) {
  8978. last_ssl_error_ = static_cast<int>(ERR_get_error());
  8979. SSL_CTX_free(ctx_);
  8980. ctx_ = nullptr;
  8981. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  8982. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  8983. client_ca_cert_dir_path);
  8984. SSL_CTX_set_verify(
  8985. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  8986. }
  8987. }
  8988. }
  8989. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  8990. X509_STORE *client_ca_cert_store) {
  8991. ctx_ = SSL_CTX_new(TLS_server_method());
  8992. if (ctx_) {
  8993. SSL_CTX_set_options(ctx_,
  8994. SSL_OP_NO_COMPRESSION |
  8995. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  8996. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8997. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  8998. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  8999. SSL_CTX_free(ctx_);
  9000. ctx_ = nullptr;
  9001. } else if (client_ca_cert_store) {
  9002. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  9003. SSL_CTX_set_verify(
  9004. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  9005. }
  9006. }
  9007. }
  9008. inline SSLServer::SSLServer(
  9009. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  9010. ctx_ = SSL_CTX_new(TLS_method());
  9011. if (ctx_) {
  9012. if (!setup_ssl_ctx_callback(*ctx_)) {
  9013. SSL_CTX_free(ctx_);
  9014. ctx_ = nullptr;
  9015. }
  9016. }
  9017. }
  9018. inline SSLServer::~SSLServer() {
  9019. if (ctx_) { SSL_CTX_free(ctx_); }
  9020. }
  9021. inline bool SSLServer::is_valid() const { return ctx_; }
  9022. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  9023. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  9024. X509_STORE *client_ca_cert_store) {
  9025. std::lock_guard<std::mutex> guard(ctx_mutex_);
  9026. SSL_CTX_use_certificate(ctx_, cert);
  9027. SSL_CTX_use_PrivateKey(ctx_, private_key);
  9028. if (client_ca_cert_store != nullptr) {
  9029. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  9030. }
  9031. }
  9032. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  9033. auto ssl = detail::ssl_new(
  9034. sock, ctx_, ctx_mutex_,
  9035. [&](SSL *ssl2) {
  9036. return detail::ssl_connect_or_accept_nonblocking(
  9037. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_,
  9038. &last_ssl_error_);
  9039. },
  9040. [](SSL * /*ssl2*/) { return true; });
  9041. auto ret = false;
  9042. if (ssl) {
  9043. std::string remote_addr;
  9044. int remote_port = 0;
  9045. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  9046. std::string local_addr;
  9047. int local_port = 0;
  9048. detail::get_local_ip_and_port(sock, local_addr, local_port);
  9049. ret = detail::process_server_socket_ssl(
  9050. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  9051. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  9052. write_timeout_usec_,
  9053. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  9054. return process_request(strm, remote_addr, remote_port, local_addr,
  9055. local_port, close_connection,
  9056. connection_closed,
  9057. [&](Request &req) { req.ssl = ssl; });
  9058. });
  9059. // Shutdown gracefully if the result seemed successful, non-gracefully if
  9060. // the connection appeared to be closed.
  9061. const bool shutdown_gracefully = ret;
  9062. detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
  9063. }
  9064. detail::shutdown_socket(sock);
  9065. detail::close_socket(sock);
  9066. return ret;
  9067. }
  9068. // SSL HTTP client implementation
  9069. inline SSLClient::SSLClient(const std::string &host)
  9070. : SSLClient(host, 443, std::string(), std::string()) {}
  9071. inline SSLClient::SSLClient(const std::string &host, int port)
  9072. : SSLClient(host, port, std::string(), std::string()) {}
  9073. inline SSLClient::SSLClient(const std::string &host, int port,
  9074. const std::string &client_cert_path,
  9075. const std::string &client_key_path,
  9076. const std::string &private_key_password)
  9077. : ClientImpl(host, port, client_cert_path, client_key_path) {
  9078. ctx_ = SSL_CTX_new(TLS_client_method());
  9079. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  9080. detail::split(&host_[0], &host_[host_.size()], '.',
  9081. [&](const char *b, const char *e) {
  9082. host_components_.emplace_back(b, e);
  9083. });
  9084. if (!client_cert_path.empty() && !client_key_path.empty()) {
  9085. if (!private_key_password.empty()) {
  9086. SSL_CTX_set_default_passwd_cb_userdata(
  9087. ctx_, reinterpret_cast<void *>(
  9088. const_cast<char *>(private_key_password.c_str())));
  9089. }
  9090. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  9091. SSL_FILETYPE_PEM) != 1 ||
  9092. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  9093. SSL_FILETYPE_PEM) != 1) {
  9094. last_openssl_error_ = ERR_get_error();
  9095. SSL_CTX_free(ctx_);
  9096. ctx_ = nullptr;
  9097. }
  9098. }
  9099. }
  9100. inline SSLClient::SSLClient(const std::string &host, int port,
  9101. X509 *client_cert, EVP_PKEY *client_key,
  9102. const std::string &private_key_password)
  9103. : ClientImpl(host, port) {
  9104. ctx_ = SSL_CTX_new(TLS_client_method());
  9105. detail::split(&host_[0], &host_[host_.size()], '.',
  9106. [&](const char *b, const char *e) {
  9107. host_components_.emplace_back(b, e);
  9108. });
  9109. if (client_cert != nullptr && client_key != nullptr) {
  9110. if (!private_key_password.empty()) {
  9111. SSL_CTX_set_default_passwd_cb_userdata(
  9112. ctx_, reinterpret_cast<void *>(
  9113. const_cast<char *>(private_key_password.c_str())));
  9114. }
  9115. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  9116. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  9117. last_openssl_error_ = ERR_get_error();
  9118. SSL_CTX_free(ctx_);
  9119. ctx_ = nullptr;
  9120. }
  9121. }
  9122. }
  9123. inline SSLClient::~SSLClient() {
  9124. if (ctx_) { SSL_CTX_free(ctx_); }
  9125. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  9126. // base function rather than the derived function once we get to the
  9127. // base class destructor, and won't free the SSL (causing a leak).
  9128. shutdown_ssl_impl(socket_, true);
  9129. }
  9130. inline bool SSLClient::is_valid() const { return ctx_; }
  9131. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  9132. if (ca_cert_store) {
  9133. if (ctx_) {
  9134. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  9135. // Free memory allocated for old cert and use new store `ca_cert_store`
  9136. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  9137. ca_cert_store_ = ca_cert_store;
  9138. }
  9139. } else {
  9140. X509_STORE_free(ca_cert_store);
  9141. }
  9142. }
  9143. }
  9144. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  9145. std::size_t size) {
  9146. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  9147. }
  9148. inline long SSLClient::get_openssl_verify_result() const {
  9149. return verify_result_;
  9150. }
  9151. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  9152. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  9153. return is_valid() && ClientImpl::create_and_connect_socket(socket, error);
  9154. }
  9155. // Assumes that socket_mutex_ is locked and that there are no requests in flight
  9156. inline bool SSLClient::connect_with_proxy(
  9157. Socket &socket,
  9158. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9159. Response &res, bool &success, Error &error) {
  9160. success = true;
  9161. Response proxy_res;
  9162. if (!detail::process_client_socket(
  9163. socket.sock, read_timeout_sec_, read_timeout_usec_,
  9164. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  9165. start_time, [&](Stream &strm) {
  9166. Request req2;
  9167. req2.method = "CONNECT";
  9168. req2.path = host_and_port_;
  9169. if (max_timeout_msec_ > 0) {
  9170. req2.start_time_ = std::chrono::steady_clock::now();
  9171. }
  9172. return process_request(strm, req2, proxy_res, false, error);
  9173. })) {
  9174. // Thread-safe to close everything because we are assuming there are no
  9175. // requests in flight
  9176. shutdown_ssl(socket, true);
  9177. shutdown_socket(socket);
  9178. close_socket(socket);
  9179. success = false;
  9180. return false;
  9181. }
  9182. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  9183. if (!proxy_digest_auth_username_.empty() &&
  9184. !proxy_digest_auth_password_.empty()) {
  9185. std::map<std::string, std::string> auth;
  9186. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  9187. // Close the current socket and create a new one for the authenticated
  9188. // request
  9189. shutdown_ssl(socket, true);
  9190. shutdown_socket(socket);
  9191. close_socket(socket);
  9192. // Create a new socket for the authenticated CONNECT request
  9193. if (!create_and_connect_socket(socket, error)) {
  9194. success = false;
  9195. output_error_log(error, nullptr);
  9196. return false;
  9197. }
  9198. proxy_res = Response();
  9199. if (!detail::process_client_socket(
  9200. socket.sock, read_timeout_sec_, read_timeout_usec_,
  9201. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  9202. start_time, [&](Stream &strm) {
  9203. Request req3;
  9204. req3.method = "CONNECT";
  9205. req3.path = host_and_port_;
  9206. req3.headers.insert(detail::make_digest_authentication_header(
  9207. req3, auth, 1, detail::random_string(10),
  9208. proxy_digest_auth_username_, proxy_digest_auth_password_,
  9209. true));
  9210. if (max_timeout_msec_ > 0) {
  9211. req3.start_time_ = std::chrono::steady_clock::now();
  9212. }
  9213. return process_request(strm, req3, proxy_res, false, error);
  9214. })) {
  9215. // Thread-safe to close everything because we are assuming there are
  9216. // no requests in flight
  9217. shutdown_ssl(socket, true);
  9218. shutdown_socket(socket);
  9219. close_socket(socket);
  9220. success = false;
  9221. return false;
  9222. }
  9223. }
  9224. }
  9225. }
  9226. // If status code is not 200, proxy request is failed.
  9227. // Set error to ProxyConnection and return proxy response
  9228. // as the response of the request
  9229. if (proxy_res.status != StatusCode::OK_200) {
  9230. error = Error::ProxyConnection;
  9231. output_error_log(error, nullptr);
  9232. res = std::move(proxy_res);
  9233. // Thread-safe to close everything because we are assuming there are
  9234. // no requests in flight
  9235. shutdown_ssl(socket, true);
  9236. shutdown_socket(socket);
  9237. close_socket(socket);
  9238. return false;
  9239. }
  9240. return true;
  9241. }
  9242. inline bool SSLClient::load_certs() {
  9243. auto ret = true;
  9244. std::call_once(initialize_cert_, [&]() {
  9245. std::lock_guard<std::mutex> guard(ctx_mutex_);
  9246. if (!ca_cert_file_path_.empty()) {
  9247. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  9248. nullptr)) {
  9249. last_openssl_error_ = ERR_get_error();
  9250. ret = false;
  9251. }
  9252. } else if (!ca_cert_dir_path_.empty()) {
  9253. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  9254. ca_cert_dir_path_.c_str())) {
  9255. last_openssl_error_ = ERR_get_error();
  9256. ret = false;
  9257. }
  9258. } else {
  9259. auto loaded = false;
  9260. #ifdef _WIN32
  9261. loaded =
  9262. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  9263. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  9264. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  9265. #endif // _WIN32
  9266. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  9267. }
  9268. });
  9269. return ret;
  9270. }
  9271. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  9272. auto ssl = detail::ssl_new(
  9273. socket.sock, ctx_, ctx_mutex_,
  9274. [&](SSL *ssl2) {
  9275. if (server_certificate_verification_) {
  9276. if (!load_certs()) {
  9277. error = Error::SSLLoadingCerts;
  9278. output_error_log(error, nullptr);
  9279. return false;
  9280. }
  9281. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  9282. }
  9283. if (!detail::ssl_connect_or_accept_nonblocking(
  9284. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  9285. connection_timeout_usec_, &last_ssl_error_)) {
  9286. error = Error::SSLConnection;
  9287. output_error_log(error, nullptr);
  9288. return false;
  9289. }
  9290. if (server_certificate_verification_) {
  9291. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  9292. if (server_certificate_verifier_) {
  9293. verification_status = server_certificate_verifier_(ssl2);
  9294. }
  9295. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  9296. last_openssl_error_ = ERR_get_error();
  9297. error = Error::SSLServerVerification;
  9298. output_error_log(error, nullptr);
  9299. return false;
  9300. }
  9301. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  9302. verify_result_ = SSL_get_verify_result(ssl2);
  9303. if (verify_result_ != X509_V_OK) {
  9304. last_openssl_error_ = static_cast<unsigned long>(verify_result_);
  9305. error = Error::SSLServerVerification;
  9306. output_error_log(error, nullptr);
  9307. return false;
  9308. }
  9309. auto server_cert = SSL_get1_peer_certificate(ssl2);
  9310. auto se = detail::scope_exit([&] { X509_free(server_cert); });
  9311. if (server_cert == nullptr) {
  9312. last_openssl_error_ = ERR_get_error();
  9313. error = Error::SSLServerVerification;
  9314. output_error_log(error, nullptr);
  9315. return false;
  9316. }
  9317. if (server_hostname_verification_) {
  9318. if (!verify_host(server_cert)) {
  9319. last_openssl_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  9320. error = Error::SSLServerHostnameVerification;
  9321. output_error_log(error, nullptr);
  9322. return false;
  9323. }
  9324. }
  9325. }
  9326. }
  9327. return true;
  9328. },
  9329. [&](SSL *ssl2) {
  9330. // Set SNI only if host is not IP address
  9331. if (!detail::is_ip_address(host_)) {
  9332. #if defined(OPENSSL_IS_BORINGSSL)
  9333. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  9334. #else
  9335. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  9336. // -Wold-style-cast warning
  9337. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME,
  9338. TLSEXT_NAMETYPE_host_name,
  9339. static_cast<void *>(const_cast<char *>(host_.c_str())));
  9340. #endif
  9341. }
  9342. return true;
  9343. });
  9344. if (ssl) {
  9345. socket.ssl = ssl;
  9346. return true;
  9347. }
  9348. shutdown_socket(socket);
  9349. close_socket(socket);
  9350. return false;
  9351. }
  9352. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  9353. shutdown_ssl_impl(socket, shutdown_gracefully);
  9354. }
  9355. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  9356. bool shutdown_gracefully) {
  9357. if (socket.sock == INVALID_SOCKET) {
  9358. assert(socket.ssl == nullptr);
  9359. return;
  9360. }
  9361. if (socket.ssl) {
  9362. detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock,
  9363. shutdown_gracefully);
  9364. socket.ssl = nullptr;
  9365. }
  9366. assert(socket.ssl == nullptr);
  9367. }
  9368. inline bool SSLClient::process_socket(
  9369. const Socket &socket,
  9370. std::chrono::time_point<std::chrono::steady_clock> start_time,
  9371. std::function<bool(Stream &strm)> callback) {
  9372. assert(socket.ssl);
  9373. return detail::process_client_socket_ssl(
  9374. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  9375. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  9376. std::move(callback));
  9377. }
  9378. inline bool SSLClient::is_ssl() const { return true; }
  9379. inline bool SSLClient::verify_host(X509 *server_cert) const {
  9380. /* Quote from RFC2818 section 3.1 "Server Identity"
  9381. If a subjectAltName extension of type dNSName is present, that MUST
  9382. be used as the identity. Otherwise, the (most specific) Common Name
  9383. field in the Subject field of the certificate MUST be used. Although
  9384. the use of the Common Name is existing practice, it is deprecated and
  9385. Certification Authorities are encouraged to use the dNSName instead.
  9386. Matching is performed using the matching rules specified by
  9387. [RFC2459]. If more than one identity of a given type is present in
  9388. the certificate (e.g., more than one dNSName name, a match in any one
  9389. of the set is considered acceptable.) Names may contain the wildcard
  9390. character * which is considered to match any single domain name
  9391. component or component fragment. E.g., *.a.com matches foo.a.com but
  9392. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  9393. In some cases, the URI is specified as an IP address rather than a
  9394. hostname. In this case, the iPAddress subjectAltName must be present
  9395. in the certificate and must exactly match the IP in the URI.
  9396. */
  9397. return verify_host_with_subject_alt_name(server_cert) ||
  9398. verify_host_with_common_name(server_cert);
  9399. }
  9400. inline bool
  9401. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  9402. auto ret = false;
  9403. auto type = GEN_DNS;
  9404. struct in6_addr addr6 = {};
  9405. struct in_addr addr = {};
  9406. size_t addr_len = 0;
  9407. #ifndef __MINGW32__
  9408. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  9409. type = GEN_IPADD;
  9410. addr_len = sizeof(struct in6_addr);
  9411. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  9412. type = GEN_IPADD;
  9413. addr_len = sizeof(struct in_addr);
  9414. }
  9415. #endif
  9416. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  9417. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  9418. if (alt_names) {
  9419. auto dsn_matched = false;
  9420. auto ip_matched = false;
  9421. auto count = sk_GENERAL_NAME_num(alt_names);
  9422. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  9423. auto val = sk_GENERAL_NAME_value(alt_names, i);
  9424. if (val->type == type) {
  9425. auto name =
  9426. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  9427. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  9428. switch (type) {
  9429. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  9430. case GEN_IPADD:
  9431. if (!memcmp(&addr6, name, addr_len) ||
  9432. !memcmp(&addr, name, addr_len)) {
  9433. ip_matched = true;
  9434. }
  9435. break;
  9436. }
  9437. }
  9438. }
  9439. if (dsn_matched || ip_matched) { ret = true; }
  9440. }
  9441. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  9442. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  9443. return ret;
  9444. }
  9445. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  9446. const auto subject_name = X509_get_subject_name(server_cert);
  9447. if (subject_name != nullptr) {
  9448. char name[BUFSIZ];
  9449. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  9450. name, sizeof(name));
  9451. if (name_len != -1) {
  9452. return check_host_name(name, static_cast<size_t>(name_len));
  9453. }
  9454. }
  9455. return false;
  9456. }
  9457. inline bool SSLClient::check_host_name(const char *pattern,
  9458. size_t pattern_len) const {
  9459. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  9460. // Wildcard match
  9461. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  9462. std::vector<std::string> pattern_components;
  9463. detail::split(&pattern[0], &pattern[pattern_len], '.',
  9464. [&](const char *b, const char *e) {
  9465. pattern_components.emplace_back(b, e);
  9466. });
  9467. if (host_components_.size() != pattern_components.size()) { return false; }
  9468. auto itr = pattern_components.begin();
  9469. for (const auto &h : host_components_) {
  9470. auto &p = *itr;
  9471. if (p != h && p != "*") {
  9472. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  9473. !p.compare(0, p.size() - 1, h));
  9474. if (!partial_match) { return false; }
  9475. }
  9476. ++itr;
  9477. }
  9478. return true;
  9479. }
  9480. #endif
  9481. // Universal client implementation
  9482. inline Client::Client(const std::string &scheme_host_port)
  9483. : Client(scheme_host_port, std::string(), std::string()) {}
  9484. inline Client::Client(const std::string &scheme_host_port,
  9485. const std::string &client_cert_path,
  9486. const std::string &client_key_path) {
  9487. const static std::regex re(
  9488. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  9489. std::smatch m;
  9490. if (std::regex_match(scheme_host_port, m, re)) {
  9491. auto scheme = m[1].str();
  9492. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9493. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  9494. #else
  9495. if (!scheme.empty() && scheme != "http") {
  9496. #endif
  9497. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9498. std::string msg = "'" + scheme + "' scheme is not supported.";
  9499. throw std::invalid_argument(msg);
  9500. #endif
  9501. return;
  9502. }
  9503. auto is_ssl = scheme == "https";
  9504. auto host = m[2].str();
  9505. if (host.empty()) { host = m[3].str(); }
  9506. auto port_str = m[4].str();
  9507. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  9508. if (is_ssl) {
  9509. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9510. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  9511. client_key_path);
  9512. is_ssl_ = is_ssl;
  9513. #endif
  9514. } else {
  9515. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  9516. client_key_path);
  9517. }
  9518. } else {
  9519. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  9520. // if port param below changes.
  9521. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  9522. client_cert_path, client_key_path);
  9523. }
  9524. } // namespace detail
  9525. inline Client::Client(const std::string &host, int port)
  9526. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  9527. inline Client::Client(const std::string &host, int port,
  9528. const std::string &client_cert_path,
  9529. const std::string &client_key_path)
  9530. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  9531. client_key_path)) {}
  9532. inline Client::~Client() = default;
  9533. inline bool Client::is_valid() const {
  9534. return cli_ != nullptr && cli_->is_valid();
  9535. }
  9536. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  9537. return cli_->Get(path, std::move(progress));
  9538. }
  9539. inline Result Client::Get(const std::string &path, const Headers &headers,
  9540. DownloadProgress progress) {
  9541. return cli_->Get(path, headers, std::move(progress));
  9542. }
  9543. inline Result Client::Get(const std::string &path,
  9544. ContentReceiver content_receiver,
  9545. DownloadProgress progress) {
  9546. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  9547. }
  9548. inline Result Client::Get(const std::string &path, const Headers &headers,
  9549. ContentReceiver content_receiver,
  9550. DownloadProgress progress) {
  9551. return cli_->Get(path, headers, std::move(content_receiver),
  9552. std::move(progress));
  9553. }
  9554. inline Result Client::Get(const std::string &path,
  9555. ResponseHandler response_handler,
  9556. ContentReceiver content_receiver,
  9557. DownloadProgress progress) {
  9558. return cli_->Get(path, std::move(response_handler),
  9559. std::move(content_receiver), std::move(progress));
  9560. }
  9561. inline Result Client::Get(const std::string &path, const Headers &headers,
  9562. ResponseHandler response_handler,
  9563. ContentReceiver content_receiver,
  9564. DownloadProgress progress) {
  9565. return cli_->Get(path, headers, std::move(response_handler),
  9566. std::move(content_receiver), std::move(progress));
  9567. }
  9568. inline Result Client::Get(const std::string &path, const Params &params,
  9569. const Headers &headers, DownloadProgress progress) {
  9570. return cli_->Get(path, params, headers, std::move(progress));
  9571. }
  9572. inline Result Client::Get(const std::string &path, const Params &params,
  9573. const Headers &headers,
  9574. ContentReceiver content_receiver,
  9575. DownloadProgress progress) {
  9576. return cli_->Get(path, params, headers, std::move(content_receiver),
  9577. std::move(progress));
  9578. }
  9579. inline Result Client::Get(const std::string &path, const Params &params,
  9580. const Headers &headers,
  9581. ResponseHandler response_handler,
  9582. ContentReceiver content_receiver,
  9583. DownloadProgress progress) {
  9584. return cli_->Get(path, params, headers, std::move(response_handler),
  9585. std::move(content_receiver), std::move(progress));
  9586. }
  9587. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  9588. inline Result Client::Head(const std::string &path, const Headers &headers) {
  9589. return cli_->Head(path, headers);
  9590. }
  9591. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  9592. inline Result Client::Post(const std::string &path, const Headers &headers) {
  9593. return cli_->Post(path, headers);
  9594. }
  9595. inline Result Client::Post(const std::string &path, const char *body,
  9596. size_t content_length,
  9597. const std::string &content_type,
  9598. UploadProgress progress) {
  9599. return cli_->Post(path, body, content_length, content_type, progress);
  9600. }
  9601. inline Result Client::Post(const std::string &path, const Headers &headers,
  9602. const char *body, size_t content_length,
  9603. const std::string &content_type,
  9604. UploadProgress progress) {
  9605. return cli_->Post(path, headers, body, content_length, content_type,
  9606. progress);
  9607. }
  9608. inline Result Client::Post(const std::string &path, const std::string &body,
  9609. const std::string &content_type,
  9610. UploadProgress progress) {
  9611. return cli_->Post(path, body, content_type, progress);
  9612. }
  9613. inline Result Client::Post(const std::string &path, const Headers &headers,
  9614. const std::string &body,
  9615. const std::string &content_type,
  9616. UploadProgress progress) {
  9617. return cli_->Post(path, headers, body, content_type, progress);
  9618. }
  9619. inline Result Client::Post(const std::string &path, size_t content_length,
  9620. ContentProvider content_provider,
  9621. const std::string &content_type,
  9622. UploadProgress progress) {
  9623. return cli_->Post(path, content_length, std::move(content_provider),
  9624. content_type, progress);
  9625. }
  9626. inline Result Client::Post(const std::string &path,
  9627. ContentProviderWithoutLength content_provider,
  9628. const std::string &content_type,
  9629. UploadProgress progress) {
  9630. return cli_->Post(path, std::move(content_provider), content_type, progress);
  9631. }
  9632. inline Result Client::Post(const std::string &path, const Headers &headers,
  9633. size_t content_length,
  9634. ContentProvider content_provider,
  9635. const std::string &content_type,
  9636. UploadProgress progress) {
  9637. return cli_->Post(path, headers, content_length, std::move(content_provider),
  9638. content_type, progress);
  9639. }
  9640. inline Result Client::Post(const std::string &path, const Headers &headers,
  9641. ContentProviderWithoutLength content_provider,
  9642. const std::string &content_type,
  9643. UploadProgress progress) {
  9644. return cli_->Post(path, headers, std::move(content_provider), content_type,
  9645. progress);
  9646. }
  9647. inline Result Client::Post(const std::string &path, const Params &params) {
  9648. return cli_->Post(path, params);
  9649. }
  9650. inline Result Client::Post(const std::string &path, const Headers &headers,
  9651. const Params &params) {
  9652. return cli_->Post(path, headers, params);
  9653. }
  9654. inline Result Client::Post(const std::string &path,
  9655. const UploadFormDataItems &items,
  9656. UploadProgress progress) {
  9657. return cli_->Post(path, items, progress);
  9658. }
  9659. inline Result Client::Post(const std::string &path, const Headers &headers,
  9660. const UploadFormDataItems &items,
  9661. UploadProgress progress) {
  9662. return cli_->Post(path, headers, items, progress);
  9663. }
  9664. inline Result Client::Post(const std::string &path, const Headers &headers,
  9665. const UploadFormDataItems &items,
  9666. const std::string &boundary,
  9667. UploadProgress progress) {
  9668. return cli_->Post(path, headers, items, boundary, progress);
  9669. }
  9670. inline Result Client::Post(const std::string &path, const Headers &headers,
  9671. const UploadFormDataItems &items,
  9672. const FormDataProviderItems &provider_items,
  9673. UploadProgress progress) {
  9674. return cli_->Post(path, headers, items, provider_items, progress);
  9675. }
  9676. inline Result Client::Post(const std::string &path, const Headers &headers,
  9677. const std::string &body,
  9678. const std::string &content_type,
  9679. ContentReceiver content_receiver,
  9680. DownloadProgress progress) {
  9681. return cli_->Post(path, headers, body, content_type, content_receiver,
  9682. progress);
  9683. }
  9684. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  9685. inline Result Client::Put(const std::string &path, const Headers &headers) {
  9686. return cli_->Put(path, headers);
  9687. }
  9688. inline Result Client::Put(const std::string &path, const char *body,
  9689. size_t content_length,
  9690. const std::string &content_type,
  9691. UploadProgress progress) {
  9692. return cli_->Put(path, body, content_length, content_type, progress);
  9693. }
  9694. inline Result Client::Put(const std::string &path, const Headers &headers,
  9695. const char *body, size_t content_length,
  9696. const std::string &content_type,
  9697. UploadProgress progress) {
  9698. return cli_->Put(path, headers, body, content_length, content_type, progress);
  9699. }
  9700. inline Result Client::Put(const std::string &path, const std::string &body,
  9701. const std::string &content_type,
  9702. UploadProgress progress) {
  9703. return cli_->Put(path, body, content_type, progress);
  9704. }
  9705. inline Result Client::Put(const std::string &path, const Headers &headers,
  9706. const std::string &body,
  9707. const std::string &content_type,
  9708. UploadProgress progress) {
  9709. return cli_->Put(path, headers, body, content_type, progress);
  9710. }
  9711. inline Result Client::Put(const std::string &path, size_t content_length,
  9712. ContentProvider content_provider,
  9713. const std::string &content_type,
  9714. UploadProgress progress) {
  9715. return cli_->Put(path, content_length, std::move(content_provider),
  9716. content_type, progress);
  9717. }
  9718. inline Result Client::Put(const std::string &path,
  9719. ContentProviderWithoutLength content_provider,
  9720. const std::string &content_type,
  9721. UploadProgress progress) {
  9722. return cli_->Put(path, std::move(content_provider), content_type, progress);
  9723. }
  9724. inline Result Client::Put(const std::string &path, const Headers &headers,
  9725. size_t content_length,
  9726. ContentProvider content_provider,
  9727. const std::string &content_type,
  9728. UploadProgress progress) {
  9729. return cli_->Put(path, headers, content_length, std::move(content_provider),
  9730. content_type, progress);
  9731. }
  9732. inline Result Client::Put(const std::string &path, const Headers &headers,
  9733. ContentProviderWithoutLength content_provider,
  9734. const std::string &content_type,
  9735. UploadProgress progress) {
  9736. return cli_->Put(path, headers, std::move(content_provider), content_type,
  9737. progress);
  9738. }
  9739. inline Result Client::Put(const std::string &path, const Params &params) {
  9740. return cli_->Put(path, params);
  9741. }
  9742. inline Result Client::Put(const std::string &path, const Headers &headers,
  9743. const Params &params) {
  9744. return cli_->Put(path, headers, params);
  9745. }
  9746. inline Result Client::Put(const std::string &path,
  9747. const UploadFormDataItems &items,
  9748. UploadProgress progress) {
  9749. return cli_->Put(path, items, progress);
  9750. }
  9751. inline Result Client::Put(const std::string &path, const Headers &headers,
  9752. const UploadFormDataItems &items,
  9753. UploadProgress progress) {
  9754. return cli_->Put(path, headers, items, progress);
  9755. }
  9756. inline Result Client::Put(const std::string &path, const Headers &headers,
  9757. const UploadFormDataItems &items,
  9758. const std::string &boundary,
  9759. UploadProgress progress) {
  9760. return cli_->Put(path, headers, items, boundary, progress);
  9761. }
  9762. inline Result Client::Put(const std::string &path, const Headers &headers,
  9763. const UploadFormDataItems &items,
  9764. const FormDataProviderItems &provider_items,
  9765. UploadProgress progress) {
  9766. return cli_->Put(path, headers, items, provider_items, progress);
  9767. }
  9768. inline Result Client::Put(const std::string &path, const Headers &headers,
  9769. const std::string &body,
  9770. const std::string &content_type,
  9771. ContentReceiver content_receiver,
  9772. DownloadProgress progress) {
  9773. return cli_->Put(path, headers, body, content_type, content_receiver,
  9774. progress);
  9775. }
  9776. inline Result Client::Patch(const std::string &path) {
  9777. return cli_->Patch(path);
  9778. }
  9779. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  9780. return cli_->Patch(path, headers);
  9781. }
  9782. inline Result Client::Patch(const std::string &path, const char *body,
  9783. size_t content_length,
  9784. const std::string &content_type,
  9785. UploadProgress progress) {
  9786. return cli_->Patch(path, body, content_length, content_type, progress);
  9787. }
  9788. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9789. const char *body, size_t content_length,
  9790. const std::string &content_type,
  9791. UploadProgress progress) {
  9792. return cli_->Patch(path, headers, body, content_length, content_type,
  9793. progress);
  9794. }
  9795. inline Result Client::Patch(const std::string &path, const std::string &body,
  9796. const std::string &content_type,
  9797. UploadProgress progress) {
  9798. return cli_->Patch(path, body, content_type, progress);
  9799. }
  9800. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9801. const std::string &body,
  9802. const std::string &content_type,
  9803. UploadProgress progress) {
  9804. return cli_->Patch(path, headers, body, content_type, progress);
  9805. }
  9806. inline Result Client::Patch(const std::string &path, size_t content_length,
  9807. ContentProvider content_provider,
  9808. const std::string &content_type,
  9809. UploadProgress progress) {
  9810. return cli_->Patch(path, content_length, std::move(content_provider),
  9811. content_type, progress);
  9812. }
  9813. inline Result Client::Patch(const std::string &path,
  9814. ContentProviderWithoutLength content_provider,
  9815. const std::string &content_type,
  9816. UploadProgress progress) {
  9817. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  9818. }
  9819. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9820. size_t content_length,
  9821. ContentProvider content_provider,
  9822. const std::string &content_type,
  9823. UploadProgress progress) {
  9824. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  9825. content_type, progress);
  9826. }
  9827. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9828. ContentProviderWithoutLength content_provider,
  9829. const std::string &content_type,
  9830. UploadProgress progress) {
  9831. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  9832. progress);
  9833. }
  9834. inline Result Client::Patch(const std::string &path, const Params &params) {
  9835. return cli_->Patch(path, params);
  9836. }
  9837. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9838. const Params &params) {
  9839. return cli_->Patch(path, headers, params);
  9840. }
  9841. inline Result Client::Patch(const std::string &path,
  9842. const UploadFormDataItems &items,
  9843. UploadProgress progress) {
  9844. return cli_->Patch(path, items, progress);
  9845. }
  9846. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9847. const UploadFormDataItems &items,
  9848. UploadProgress progress) {
  9849. return cli_->Patch(path, headers, items, progress);
  9850. }
  9851. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9852. const UploadFormDataItems &items,
  9853. const std::string &boundary,
  9854. UploadProgress progress) {
  9855. return cli_->Patch(path, headers, items, boundary, progress);
  9856. }
  9857. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9858. const UploadFormDataItems &items,
  9859. const FormDataProviderItems &provider_items,
  9860. UploadProgress progress) {
  9861. return cli_->Patch(path, headers, items, provider_items, progress);
  9862. }
  9863. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9864. const std::string &body,
  9865. const std::string &content_type,
  9866. ContentReceiver content_receiver,
  9867. DownloadProgress progress) {
  9868. return cli_->Patch(path, headers, body, content_type, content_receiver,
  9869. progress);
  9870. }
  9871. inline Result Client::Delete(const std::string &path,
  9872. DownloadProgress progress) {
  9873. return cli_->Delete(path, progress);
  9874. }
  9875. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9876. DownloadProgress progress) {
  9877. return cli_->Delete(path, headers, progress);
  9878. }
  9879. inline Result Client::Delete(const std::string &path, const char *body,
  9880. size_t content_length,
  9881. const std::string &content_type,
  9882. DownloadProgress progress) {
  9883. return cli_->Delete(path, body, content_length, content_type, progress);
  9884. }
  9885. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9886. const char *body, size_t content_length,
  9887. const std::string &content_type,
  9888. DownloadProgress progress) {
  9889. return cli_->Delete(path, headers, body, content_length, content_type,
  9890. progress);
  9891. }
  9892. inline Result Client::Delete(const std::string &path, const std::string &body,
  9893. const std::string &content_type,
  9894. DownloadProgress progress) {
  9895. return cli_->Delete(path, body, content_type, progress);
  9896. }
  9897. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9898. const std::string &body,
  9899. const std::string &content_type,
  9900. DownloadProgress progress) {
  9901. return cli_->Delete(path, headers, body, content_type, progress);
  9902. }
  9903. inline Result Client::Delete(const std::string &path, const Params &params,
  9904. DownloadProgress progress) {
  9905. return cli_->Delete(path, params, progress);
  9906. }
  9907. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9908. const Params &params, DownloadProgress progress) {
  9909. return cli_->Delete(path, headers, params, progress);
  9910. }
  9911. inline Result Client::Options(const std::string &path) {
  9912. return cli_->Options(path);
  9913. }
  9914. inline Result Client::Options(const std::string &path, const Headers &headers) {
  9915. return cli_->Options(path, headers);
  9916. }
  9917. inline bool Client::send(Request &req, Response &res, Error &error) {
  9918. return cli_->send(req, res, error);
  9919. }
  9920. inline Result Client::send(const Request &req) { return cli_->send(req); }
  9921. inline void Client::stop() { cli_->stop(); }
  9922. inline std::string Client::host() const { return cli_->host(); }
  9923. inline int Client::port() const { return cli_->port(); }
  9924. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  9925. inline socket_t Client::socket() const { return cli_->socket(); }
  9926. inline void
  9927. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  9928. cli_->set_hostname_addr_map(std::move(addr_map));
  9929. }
  9930. inline void Client::set_default_headers(Headers headers) {
  9931. cli_->set_default_headers(std::move(headers));
  9932. }
  9933. inline void Client::set_header_writer(
  9934. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9935. cli_->set_header_writer(writer);
  9936. }
  9937. inline void Client::set_address_family(int family) {
  9938. cli_->set_address_family(family);
  9939. }
  9940. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  9941. inline void Client::set_socket_options(SocketOptions socket_options) {
  9942. cli_->set_socket_options(std::move(socket_options));
  9943. }
  9944. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  9945. cli_->set_connection_timeout(sec, usec);
  9946. }
  9947. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  9948. cli_->set_read_timeout(sec, usec);
  9949. }
  9950. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  9951. cli_->set_write_timeout(sec, usec);
  9952. }
  9953. inline void Client::set_basic_auth(const std::string &username,
  9954. const std::string &password) {
  9955. cli_->set_basic_auth(username, password);
  9956. }
  9957. inline void Client::set_bearer_token_auth(const std::string &token) {
  9958. cli_->set_bearer_token_auth(token);
  9959. }
  9960. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9961. inline void Client::set_digest_auth(const std::string &username,
  9962. const std::string &password) {
  9963. cli_->set_digest_auth(username, password);
  9964. }
  9965. #endif
  9966. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  9967. inline void Client::set_follow_location(bool on) {
  9968. cli_->set_follow_location(on);
  9969. }
  9970. inline void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  9971. [[deprecated("Use set_path_encode instead")]]
  9972. inline void Client::set_url_encode(bool on) {
  9973. cli_->set_path_encode(on);
  9974. }
  9975. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  9976. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  9977. inline void Client::set_interface(const std::string &intf) {
  9978. cli_->set_interface(intf);
  9979. }
  9980. inline void Client::set_proxy(const std::string &host, int port) {
  9981. cli_->set_proxy(host, port);
  9982. }
  9983. inline void Client::set_proxy_basic_auth(const std::string &username,
  9984. const std::string &password) {
  9985. cli_->set_proxy_basic_auth(username, password);
  9986. }
  9987. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  9988. cli_->set_proxy_bearer_token_auth(token);
  9989. }
  9990. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9991. inline void Client::set_proxy_digest_auth(const std::string &username,
  9992. const std::string &password) {
  9993. cli_->set_proxy_digest_auth(username, password);
  9994. }
  9995. #endif
  9996. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9997. inline void Client::enable_server_certificate_verification(bool enabled) {
  9998. cli_->enable_server_certificate_verification(enabled);
  9999. }
  10000. inline void Client::enable_server_hostname_verification(bool enabled) {
  10001. cli_->enable_server_hostname_verification(enabled);
  10002. }
  10003. inline void Client::set_server_certificate_verifier(
  10004. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  10005. cli_->set_server_certificate_verifier(verifier);
  10006. }
  10007. #endif
  10008. inline void Client::set_logger(Logger logger) {
  10009. cli_->set_logger(std::move(logger));
  10010. }
  10011. inline void Client::set_error_logger(ErrorLogger error_logger) {
  10012. cli_->set_error_logger(std::move(error_logger));
  10013. }
  10014. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10015. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  10016. const std::string &ca_cert_dir_path) {
  10017. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  10018. }
  10019. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  10020. if (is_ssl_) {
  10021. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  10022. } else {
  10023. cli_->set_ca_cert_store(ca_cert_store);
  10024. }
  10025. }
  10026. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  10027. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  10028. }
  10029. inline long Client::get_openssl_verify_result() const {
  10030. if (is_ssl_) {
  10031. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  10032. }
  10033. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  10034. }
  10035. inline SSL_CTX *Client::ssl_context() const {
  10036. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  10037. return nullptr;
  10038. }
  10039. #endif
  10040. // ----------------------------------------------------------------------------
  10041. } // namespace httplib
  10042. #endif // CPPHTTPLIB_HTTPLIB_H