httplib.cpp 310 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584
  1. #include "httplib.h"
  2. namespace httplib {
  3. /*
  4. * Implementation that will be part of the .cc file if split into .h + .cc.
  5. */
  6. namespace detail {
  7. bool is_hex(char c, int &v) {
  8. if (0x20 <= c && isdigit(c)) {
  9. v = c - '0';
  10. return true;
  11. } else if ('A' <= c && c <= 'F') {
  12. v = c - 'A' + 10;
  13. return true;
  14. } else if ('a' <= c && c <= 'f') {
  15. v = c - 'a' + 10;
  16. return true;
  17. }
  18. return false;
  19. }
  20. bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  21. int &val) {
  22. if (i >= s.size()) { return false; }
  23. val = 0;
  24. for (; cnt; i++, cnt--) {
  25. if (!s[i]) { return false; }
  26. auto v = 0;
  27. if (is_hex(s[i], v)) {
  28. val = val * 16 + v;
  29. } else {
  30. return false;
  31. }
  32. }
  33. return true;
  34. }
  35. std::string from_i_to_hex(size_t n) {
  36. static const auto charset = "0123456789abcdef";
  37. std::string ret;
  38. do {
  39. ret = charset[n & 15] + ret;
  40. n >>= 4;
  41. } while (n > 0);
  42. return ret;
  43. }
  44. size_t to_utf8(int code, char *buff) {
  45. if (code < 0x0080) {
  46. buff[0] = static_cast<char>(code & 0x7F);
  47. return 1;
  48. } else if (code < 0x0800) {
  49. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  50. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  51. return 2;
  52. } else if (code < 0xD800) {
  53. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  54. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  55. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  56. return 3;
  57. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  58. return 0;
  59. } else if (code < 0x10000) {
  60. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  61. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  62. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  63. return 3;
  64. } else if (code < 0x110000) {
  65. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  66. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  67. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  68. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  69. return 4;
  70. }
  71. // NOTREACHED
  72. return 0;
  73. }
  74. // NOTE: This code came up with the following stackoverflow post:
  75. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  76. std::string base64_encode(const std::string &in) {
  77. static const auto lookup =
  78. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  79. std::string out;
  80. out.reserve(in.size());
  81. auto val = 0;
  82. auto valb = -6;
  83. for (auto c : in) {
  84. val = (val << 8) + static_cast<uint8_t>(c);
  85. valb += 8;
  86. while (valb >= 0) {
  87. out.push_back(lookup[(val >> valb) & 0x3F]);
  88. valb -= 6;
  89. }
  90. }
  91. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  92. while (out.size() % 4) {
  93. out.push_back('=');
  94. }
  95. return out;
  96. }
  97. bool is_valid_path(const std::string &path) {
  98. size_t level = 0;
  99. size_t i = 0;
  100. // Skip slash
  101. while (i < path.size() && path[i] == '/') {
  102. i++;
  103. }
  104. while (i < path.size()) {
  105. // Read component
  106. auto beg = i;
  107. while (i < path.size() && path[i] != '/') {
  108. if (path[i] == '\0') {
  109. return false;
  110. } else if (path[i] == '\\') {
  111. return false;
  112. }
  113. i++;
  114. }
  115. auto len = i - beg;
  116. assert(len > 0);
  117. if (!path.compare(beg, len, ".")) {
  118. ;
  119. } else if (!path.compare(beg, len, "..")) {
  120. if (level == 0) { return false; }
  121. level--;
  122. } else {
  123. level++;
  124. }
  125. // Skip slash
  126. while (i < path.size() && path[i] == '/') {
  127. i++;
  128. }
  129. }
  130. return true;
  131. }
  132. FileStat::FileStat(const std::string &path) {
  133. #if defined(_WIN32)
  134. auto wpath = u8string_to_wstring(path.c_str());
  135. ret_ = _wstat(wpath.c_str(), &st_);
  136. #else
  137. ret_ = stat(path.c_str(), &st_);
  138. #endif
  139. }
  140. bool FileStat::is_file() const {
  141. return ret_ >= 0 && S_ISREG(st_.st_mode);
  142. }
  143. bool FileStat::is_dir() const {
  144. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  145. }
  146. std::string encode_path(const std::string &s) {
  147. std::string result;
  148. result.reserve(s.size());
  149. for (size_t i = 0; s[i]; i++) {
  150. switch (s[i]) {
  151. case ' ': result += "%20"; break;
  152. case '+': result += "%2B"; break;
  153. case '\r': result += "%0D"; break;
  154. case '\n': result += "%0A"; break;
  155. case '\'': result += "%27"; break;
  156. case ',': result += "%2C"; break;
  157. // case ':': result += "%3A"; break; // ok? probably...
  158. case ';': result += "%3B"; break;
  159. default:
  160. auto c = static_cast<uint8_t>(s[i]);
  161. if (c >= 0x80) {
  162. result += '%';
  163. char hex[4];
  164. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  165. assert(len == 2);
  166. result.append(hex, static_cast<size_t>(len));
  167. } else {
  168. result += s[i];
  169. }
  170. break;
  171. }
  172. }
  173. return result;
  174. }
  175. std::string file_extension(const std::string &path) {
  176. std::smatch m;
  177. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  178. if (std::regex_search(path, m, re)) { return m[1].str(); }
  179. return std::string();
  180. }
  181. bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  182. std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  183. size_t right) {
  184. while (b + left < e && is_space_or_tab(b[left])) {
  185. left++;
  186. }
  187. while (right > 0 && is_space_or_tab(b[right - 1])) {
  188. right--;
  189. }
  190. return std::make_pair(left, right);
  191. }
  192. std::string trim_copy(const std::string &s) {
  193. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  194. return s.substr(r.first, r.second - r.first);
  195. }
  196. std::string trim_double_quotes_copy(const std::string &s) {
  197. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  198. return s.substr(1, s.size() - 2);
  199. }
  200. return s;
  201. }
  202. void
  203. divide(const char *data, std::size_t size, char d,
  204. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  205. fn) {
  206. const auto it = std::find(data, data + size, d);
  207. const auto found = static_cast<std::size_t>(it != data + size);
  208. const auto lhs_data = data;
  209. const auto lhs_size = static_cast<std::size_t>(it - data);
  210. const auto rhs_data = it + found;
  211. const auto rhs_size = size - lhs_size - found;
  212. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  213. }
  214. void
  215. divide(const std::string &str, char d,
  216. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  217. fn) {
  218. divide(str.data(), str.size(), d, std::move(fn));
  219. }
  220. void split(const char *b, const char *e, char d,
  221. std::function<void(const char *, const char *)> fn) {
  222. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  223. }
  224. void split(const char *b, const char *e, char d, size_t m,
  225. std::function<void(const char *, const char *)> fn) {
  226. size_t i = 0;
  227. size_t beg = 0;
  228. size_t count = 1;
  229. while (e ? (b + i < e) : (b[i] != '\0')) {
  230. if (b[i] == d && count < m) {
  231. auto r = trim(b, e, beg, i);
  232. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  233. beg = i + 1;
  234. count++;
  235. }
  236. i++;
  237. }
  238. if (i) {
  239. auto r = trim(b, e, beg, i);
  240. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  241. }
  242. }
  243. stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  244. size_t fixed_buffer_size)
  245. : strm_(strm), fixed_buffer_(fixed_buffer),
  246. fixed_buffer_size_(fixed_buffer_size) {}
  247. const char *stream_line_reader::ptr() const {
  248. if (growable_buffer_.empty()) {
  249. return fixed_buffer_;
  250. } else {
  251. return growable_buffer_.data();
  252. }
  253. }
  254. size_t stream_line_reader::size() const {
  255. if (growable_buffer_.empty()) {
  256. return fixed_buffer_used_size_;
  257. } else {
  258. return growable_buffer_.size();
  259. }
  260. }
  261. bool stream_line_reader::end_with_crlf() const {
  262. auto end = ptr() + size();
  263. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  264. }
  265. bool stream_line_reader::getline() {
  266. fixed_buffer_used_size_ = 0;
  267. growable_buffer_.clear();
  268. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  269. char prev_byte = 0;
  270. #endif
  271. for (size_t i = 0;; i++) {
  272. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  273. // Treat exceptionally long lines as an error to
  274. // prevent infinite loops/memory exhaustion
  275. return false;
  276. }
  277. char byte;
  278. auto n = strm_.read(&byte, 1);
  279. if (n < 0) {
  280. return false;
  281. } else if (n == 0) {
  282. if (i == 0) {
  283. return false;
  284. } else {
  285. break;
  286. }
  287. }
  288. append(byte);
  289. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  290. if (byte == '\n') { break; }
  291. #else
  292. if (prev_byte == '\r' && byte == '\n') { break; }
  293. prev_byte = byte;
  294. #endif
  295. }
  296. return true;
  297. }
  298. void stream_line_reader::append(char c) {
  299. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  300. fixed_buffer_[fixed_buffer_used_size_++] = c;
  301. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  302. } else {
  303. if (growable_buffer_.empty()) {
  304. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  305. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  306. }
  307. growable_buffer_ += c;
  308. }
  309. }
  310. mmap::mmap(const char *path) { open(path); }
  311. mmap::~mmap() { close(); }
  312. bool mmap::open(const char *path) {
  313. close();
  314. #if defined(_WIN32)
  315. auto wpath = u8string_to_wstring(path);
  316. if (wpath.empty()) { return false; }
  317. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  318. OPEN_EXISTING, NULL);
  319. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  320. LARGE_INTEGER size{};
  321. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  322. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  323. // See:
  324. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  325. if (static_cast<ULONGLONG>(size.QuadPart) >
  326. (std::numeric_limits<decltype(size_)>::max)()) {
  327. // `size_t` might be 32-bits, on 32-bits Windows.
  328. return false;
  329. }
  330. size_ = static_cast<size_t>(size.QuadPart);
  331. hMapping_ =
  332. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  333. // Special treatment for an empty file...
  334. if (hMapping_ == NULL && size_ == 0) {
  335. close();
  336. is_open_empty_file = true;
  337. return true;
  338. }
  339. if (hMapping_ == NULL) {
  340. close();
  341. return false;
  342. }
  343. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  344. if (addr_ == nullptr) {
  345. close();
  346. return false;
  347. }
  348. #else
  349. fd_ = ::open(path, O_RDONLY);
  350. if (fd_ == -1) { return false; }
  351. struct stat sb;
  352. if (fstat(fd_, &sb) == -1) {
  353. close();
  354. return false;
  355. }
  356. size_ = static_cast<size_t>(sb.st_size);
  357. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  358. // Special treatment for an empty file...
  359. if (addr_ == MAP_FAILED && size_ == 0) {
  360. close();
  361. is_open_empty_file = true;
  362. return false;
  363. }
  364. #endif
  365. return true;
  366. }
  367. bool mmap::is_open() const {
  368. return is_open_empty_file ? true : addr_ != nullptr;
  369. }
  370. size_t mmap::size() const { return size_; }
  371. const char *mmap::data() const {
  372. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  373. }
  374. void mmap::close() {
  375. #if defined(_WIN32)
  376. if (addr_) {
  377. ::UnmapViewOfFile(addr_);
  378. addr_ = nullptr;
  379. }
  380. if (hMapping_) {
  381. ::CloseHandle(hMapping_);
  382. hMapping_ = NULL;
  383. }
  384. if (hFile_ != INVALID_HANDLE_VALUE) {
  385. ::CloseHandle(hFile_);
  386. hFile_ = INVALID_HANDLE_VALUE;
  387. }
  388. is_open_empty_file = false;
  389. #else
  390. if (addr_ != nullptr) {
  391. munmap(addr_, size_);
  392. addr_ = nullptr;
  393. }
  394. if (fd_ != -1) {
  395. ::close(fd_);
  396. fd_ = -1;
  397. }
  398. #endif
  399. size_ = 0;
  400. }
  401. int close_socket(socket_t sock) {
  402. #ifdef _WIN32
  403. return closesocket(sock);
  404. #else
  405. return close(sock);
  406. #endif
  407. }
  408. template <typename T> inline ssize_t handle_EINTR(T fn) {
  409. ssize_t res = 0;
  410. while (true) {
  411. res = fn();
  412. if (res < 0 && errno == EINTR) {
  413. std::this_thread::sleep_for(std::chrono::microseconds{1});
  414. continue;
  415. }
  416. break;
  417. }
  418. return res;
  419. }
  420. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  421. return handle_EINTR([&]() {
  422. return recv(sock,
  423. #ifdef _WIN32
  424. static_cast<char *>(ptr), static_cast<int>(size),
  425. #else
  426. ptr, size,
  427. #endif
  428. flags);
  429. });
  430. }
  431. ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  432. int flags) {
  433. return handle_EINTR([&]() {
  434. return send(sock,
  435. #ifdef _WIN32
  436. static_cast<const char *>(ptr), static_cast<int>(size),
  437. #else
  438. ptr, size,
  439. #endif
  440. flags);
  441. });
  442. }
  443. int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  444. #ifdef _WIN32
  445. return ::WSAPoll(fds, nfds, timeout);
  446. #else
  447. return ::poll(fds, nfds, timeout);
  448. #endif
  449. }
  450. template <bool Read>
  451. ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  452. #ifdef __APPLE__
  453. if (sock >= FD_SETSIZE) { return -1; }
  454. fd_set fds, *rfds, *wfds;
  455. FD_ZERO(&fds);
  456. FD_SET(sock, &fds);
  457. rfds = (Read ? &fds : nullptr);
  458. wfds = (Read ? nullptr : &fds);
  459. timeval tv;
  460. tv.tv_sec = static_cast<long>(sec);
  461. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  462. return handle_EINTR([&]() {
  463. return select(static_cast<int>(sock + 1), rfds, wfds, nullptr, &tv);
  464. });
  465. #else
  466. struct pollfd pfd;
  467. pfd.fd = sock;
  468. pfd.events = (Read ? POLLIN : POLLOUT);
  469. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  470. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  471. #endif
  472. }
  473. ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  474. return select_impl<true>(sock, sec, usec);
  475. }
  476. ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  477. return select_impl<false>(sock, sec, usec);
  478. }
  479. Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  480. time_t usec) {
  481. #ifdef __APPLE__
  482. if (sock >= FD_SETSIZE) { return Error::Connection; }
  483. fd_set fdsr, fdsw;
  484. FD_ZERO(&fdsr);
  485. FD_ZERO(&fdsw);
  486. FD_SET(sock, &fdsr);
  487. FD_SET(sock, &fdsw);
  488. timeval tv;
  489. tv.tv_sec = static_cast<long>(sec);
  490. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  491. auto ret = handle_EINTR([&]() {
  492. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, nullptr, &tv);
  493. });
  494. if (ret == 0) { return Error::ConnectionTimeout; }
  495. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  496. auto error = 0;
  497. socklen_t len = sizeof(error);
  498. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  499. reinterpret_cast<char *>(&error), &len);
  500. auto successful = res >= 0 && !error;
  501. return successful ? Error::Success : Error::Connection;
  502. }
  503. return Error::Connection;
  504. #else
  505. struct pollfd pfd_read;
  506. pfd_read.fd = sock;
  507. pfd_read.events = POLLIN | POLLOUT;
  508. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  509. auto poll_res =
  510. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  511. if (poll_res == 0) { return Error::ConnectionTimeout; }
  512. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  513. auto error = 0;
  514. socklen_t len = sizeof(error);
  515. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  516. reinterpret_cast<char *>(&error), &len);
  517. auto successful = res >= 0 && !error;
  518. return successful ? Error::Success : Error::Connection;
  519. }
  520. return Error::Connection;
  521. #endif
  522. }
  523. bool is_socket_alive(socket_t sock) {
  524. const auto val = detail::select_read(sock, 0, 0);
  525. if (val == 0) {
  526. return true;
  527. } else if (val < 0 && errno == EBADF) {
  528. return false;
  529. }
  530. char buf[1];
  531. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  532. }
  533. class SocketStream final : public Stream {
  534. public:
  535. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  536. time_t write_timeout_sec, time_t write_timeout_usec,
  537. time_t max_timeout_msec = 0,
  538. std::chrono::time_point<std::chrono::steady_clock> start_time =
  539. (std::chrono::steady_clock::time_point::min)());
  540. ~SocketStream() override;
  541. bool is_readable() const override;
  542. bool wait_readable() const override;
  543. bool wait_writable() const override;
  544. ssize_t read(char *ptr, size_t size) override;
  545. ssize_t write(const char *ptr, size_t size) override;
  546. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  547. void get_local_ip_and_port(std::string &ip, int &port) const override;
  548. socket_t socket() const override;
  549. time_t duration() const override;
  550. private:
  551. socket_t sock_;
  552. time_t read_timeout_sec_;
  553. time_t read_timeout_usec_;
  554. time_t write_timeout_sec_;
  555. time_t write_timeout_usec_;
  556. time_t max_timeout_msec_;
  557. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  558. std::vector<char> read_buff_;
  559. size_t read_buff_off_ = 0;
  560. size_t read_buff_content_size_ = 0;
  561. static const size_t read_buff_size_ = 1024l * 4;
  562. };
  563. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  564. class SSLSocketStream final : public Stream {
  565. public:
  566. SSLSocketStream(
  567. socket_t sock, SSL *ssl, time_t read_timeout_sec,
  568. time_t read_timeout_usec, time_t write_timeout_sec,
  569. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  570. std::chrono::time_point<std::chrono::steady_clock> start_time =
  571. (std::chrono::steady_clock::time_point::min)());
  572. ~SSLSocketStream() override;
  573. bool is_readable() const override;
  574. bool wait_readable() const override;
  575. bool wait_writable() const override;
  576. ssize_t read(char *ptr, size_t size) override;
  577. ssize_t write(const char *ptr, size_t size) override;
  578. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  579. void get_local_ip_and_port(std::string &ip, int &port) const override;
  580. socket_t socket() const override;
  581. time_t duration() const override;
  582. private:
  583. socket_t sock_;
  584. SSL *ssl_;
  585. time_t read_timeout_sec_;
  586. time_t read_timeout_usec_;
  587. time_t write_timeout_sec_;
  588. time_t write_timeout_usec_;
  589. time_t max_timeout_msec_;
  590. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  591. };
  592. #endif
  593. bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  594. time_t keep_alive_timeout_sec) {
  595. using namespace std::chrono;
  596. const auto interval_usec =
  597. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  598. // Avoid expensive `steady_clock::now()` call for the first time
  599. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  600. const auto start = steady_clock::now() - microseconds{interval_usec};
  601. const auto timeout = seconds{keep_alive_timeout_sec};
  602. while (true) {
  603. if (svr_sock == INVALID_SOCKET) {
  604. break; // Server socket is closed
  605. }
  606. auto val = select_read(sock, 0, interval_usec);
  607. if (val < 0) {
  608. break; // Ssocket error
  609. } else if (val == 0) {
  610. if (steady_clock::now() - start > timeout) {
  611. break; // Timeout
  612. }
  613. } else {
  614. return true; // Ready for read
  615. }
  616. }
  617. return false;
  618. }
  619. template <typename T>
  620. bool
  621. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  622. size_t keep_alive_max_count,
  623. time_t keep_alive_timeout_sec, T callback) {
  624. assert(keep_alive_max_count > 0);
  625. auto ret = false;
  626. auto count = keep_alive_max_count;
  627. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  628. auto close_connection = count == 1;
  629. auto connection_closed = false;
  630. ret = callback(close_connection, connection_closed);
  631. if (!ret || connection_closed) { break; }
  632. count--;
  633. }
  634. return ret;
  635. }
  636. template <typename T>
  637. bool
  638. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  639. size_t keep_alive_max_count,
  640. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  641. time_t read_timeout_usec, time_t write_timeout_sec,
  642. time_t write_timeout_usec, T callback) {
  643. return process_server_socket_core(
  644. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  645. [&](bool close_connection, bool &connection_closed) {
  646. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  647. write_timeout_sec, write_timeout_usec);
  648. return callback(strm, close_connection, connection_closed);
  649. });
  650. }
  651. bool process_client_socket(
  652. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  653. time_t write_timeout_sec, time_t write_timeout_usec,
  654. time_t max_timeout_msec,
  655. std::chrono::time_point<std::chrono::steady_clock> start_time,
  656. std::function<bool(Stream &)> callback) {
  657. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  658. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  659. start_time);
  660. return callback(strm);
  661. }
  662. int shutdown_socket(socket_t sock) {
  663. #ifdef _WIN32
  664. return shutdown(sock, SD_BOTH);
  665. #else
  666. return shutdown(sock, SHUT_RDWR);
  667. #endif
  668. }
  669. std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  670. if (s.size() > 1 && s[0] == '\0') {
  671. auto ret = s;
  672. ret[0] = '@';
  673. return ret;
  674. }
  675. return s;
  676. }
  677. std::string
  678. unescape_abstract_namespace_unix_domain(const std::string &s) {
  679. if (s.size() > 1 && s[0] == '@') {
  680. auto ret = s;
  681. ret[0] = '\0';
  682. return ret;
  683. }
  684. return s;
  685. }
  686. int getaddrinfo_with_timeout(const char *node, const char *service,
  687. const struct addrinfo *hints,
  688. struct addrinfo **res, time_t timeout_sec) {
  689. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  690. if (timeout_sec <= 0) {
  691. // No timeout specified, use standard getaddrinfo
  692. return getaddrinfo(node, service, hints, res);
  693. }
  694. #ifdef _WIN32
  695. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  696. OVERLAPPED overlapped = {0};
  697. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  698. if (!event) { return EAI_FAIL; }
  699. overlapped.hEvent = event;
  700. PADDRINFOEXW result_addrinfo = nullptr;
  701. HANDLE cancel_handle = nullptr;
  702. ADDRINFOEXW hints_ex = {0};
  703. if (hints) {
  704. hints_ex.ai_flags = hints->ai_flags;
  705. hints_ex.ai_family = hints->ai_family;
  706. hints_ex.ai_socktype = hints->ai_socktype;
  707. hints_ex.ai_protocol = hints->ai_protocol;
  708. }
  709. auto wnode = u8string_to_wstring(node);
  710. auto wservice = u8string_to_wstring(service);
  711. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  712. hints ? &hints_ex : nullptr, &result_addrinfo,
  713. nullptr, &overlapped, nullptr, &cancel_handle);
  714. if (ret == WSA_IO_PENDING) {
  715. auto wait_result =
  716. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  717. if (wait_result == WAIT_TIMEOUT) {
  718. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  719. ::CloseHandle(event);
  720. return EAI_AGAIN;
  721. }
  722. DWORD bytes_returned;
  723. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  724. &bytes_returned, FALSE)) {
  725. ::CloseHandle(event);
  726. return ::WSAGetLastError();
  727. }
  728. }
  729. ::CloseHandle(event);
  730. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  731. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  732. return 0;
  733. }
  734. return ret;
  735. #elif TARGET_OS_MAC
  736. // macOS implementation using CFHost API for asynchronous DNS resolution
  737. CFStringRef hostname_ref = CFStringCreateWithCString(
  738. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  739. if (!hostname_ref) { return EAI_MEMORY; }
  740. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  741. CFRelease(hostname_ref);
  742. if (!host_ref) { return EAI_MEMORY; }
  743. // Set up context for callback
  744. struct CFHostContext {
  745. bool completed = false;
  746. bool success = false;
  747. CFArrayRef addresses = nullptr;
  748. std::mutex mutex;
  749. std::condition_variable cv;
  750. } context;
  751. CFHostClientContext client_context;
  752. memset(&client_context, 0, sizeof(client_context));
  753. client_context.info = &context;
  754. // Set callback
  755. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  756. const CFStreamError *error, void *info) {
  757. auto ctx = static_cast<CFHostContext *>(info);
  758. std::lock_guard<std::mutex> lock(ctx->mutex);
  759. if (error && error->error != 0) {
  760. ctx->success = false;
  761. } else {
  762. Boolean hasBeenResolved;
  763. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  764. if (ctx->addresses && hasBeenResolved) {
  765. CFRetain(ctx->addresses);
  766. ctx->success = true;
  767. } else {
  768. ctx->success = false;
  769. }
  770. }
  771. ctx->completed = true;
  772. ctx->cv.notify_one();
  773. };
  774. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  775. CFRelease(host_ref);
  776. return EAI_SYSTEM;
  777. }
  778. // Schedule on run loop
  779. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  780. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  781. // Start resolution
  782. CFStreamError stream_error;
  783. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  784. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  785. CFRelease(host_ref);
  786. return EAI_FAIL;
  787. }
  788. // Wait for completion with timeout
  789. auto timeout_time =
  790. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  791. bool timed_out = false;
  792. {
  793. std::unique_lock<std::mutex> lock(context.mutex);
  794. while (!context.completed) {
  795. auto now = std::chrono::steady_clock::now();
  796. if (now >= timeout_time) {
  797. timed_out = true;
  798. break;
  799. }
  800. // Run the runloop for a short time
  801. lock.unlock();
  802. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  803. lock.lock();
  804. }
  805. }
  806. // Clean up
  807. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  808. CFHostSetClient(host_ref, nullptr, nullptr);
  809. if (timed_out || !context.completed) {
  810. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  811. CFRelease(host_ref);
  812. return EAI_AGAIN;
  813. }
  814. if (!context.success || !context.addresses) {
  815. CFRelease(host_ref);
  816. return EAI_NODATA;
  817. }
  818. // Convert CFArray to addrinfo
  819. CFIndex count = CFArrayGetCount(context.addresses);
  820. if (count == 0) {
  821. CFRelease(context.addresses);
  822. CFRelease(host_ref);
  823. return EAI_NODATA;
  824. }
  825. struct addrinfo *result_addrinfo = nullptr;
  826. struct addrinfo **current = &result_addrinfo;
  827. for (CFIndex i = 0; i < count; i++) {
  828. CFDataRef addr_data =
  829. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  830. if (!addr_data) continue;
  831. const struct sockaddr *sockaddr_ptr =
  832. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  833. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  834. // Allocate addrinfo structure
  835. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  836. if (!*current) {
  837. freeaddrinfo(result_addrinfo);
  838. CFRelease(context.addresses);
  839. CFRelease(host_ref);
  840. return EAI_MEMORY;
  841. }
  842. memset(*current, 0, sizeof(struct addrinfo));
  843. // Set up addrinfo fields
  844. (*current)->ai_family = sockaddr_ptr->sa_family;
  845. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  846. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  847. (*current)->ai_addrlen = sockaddr_len;
  848. // Copy sockaddr
  849. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  850. if (!(*current)->ai_addr) {
  851. freeaddrinfo(result_addrinfo);
  852. CFRelease(context.addresses);
  853. CFRelease(host_ref);
  854. return EAI_MEMORY;
  855. }
  856. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  857. // Set port if service is specified
  858. if (service && strlen(service) > 0) {
  859. int port = atoi(service);
  860. if (port > 0) {
  861. if (sockaddr_ptr->sa_family == AF_INET) {
  862. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  863. ->sin_port = htons(static_cast<uint16_t>(port));
  864. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  865. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  866. ->sin6_port = htons(static_cast<uint16_t>(port));
  867. }
  868. }
  869. }
  870. current = &((*current)->ai_next);
  871. }
  872. CFRelease(context.addresses);
  873. CFRelease(host_ref);
  874. *res = result_addrinfo;
  875. return 0;
  876. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  877. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  878. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  879. struct gaicb request;
  880. struct gaicb *requests[1] = {&request};
  881. struct sigevent sevp;
  882. struct timespec timeout;
  883. // Initialize the request structure
  884. memset(&request, 0, sizeof(request));
  885. request.ar_name = node;
  886. request.ar_service = service;
  887. request.ar_request = hints;
  888. // Set up timeout
  889. timeout.tv_sec = timeout_sec;
  890. timeout.tv_nsec = 0;
  891. // Initialize sigevent structure (not used, but required)
  892. memset(&sevp, 0, sizeof(sevp));
  893. sevp.sigev_notify = SIGEV_NONE;
  894. // Start asynchronous resolution
  895. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  896. if (start_result != 0) { return start_result; }
  897. // Wait for completion with timeout
  898. int wait_result =
  899. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  900. if (wait_result == 0 || wait_result == EAI_ALLDONE) {
  901. // Completed successfully, get the result
  902. int gai_result = gai_error(&request);
  903. if (gai_result == 0) {
  904. *res = request.ar_result;
  905. return 0;
  906. } else {
  907. // Clean up on error
  908. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  909. return gai_result;
  910. }
  911. } else if (wait_result == EAI_AGAIN) {
  912. // Timeout occurred, cancel the request
  913. gai_cancel(&request);
  914. return EAI_AGAIN;
  915. } else {
  916. // Other error occurred
  917. gai_cancel(&request);
  918. return wait_result;
  919. }
  920. #else
  921. // Fallback implementation using thread-based timeout for other Unix systems
  922. struct GetAddrInfoState {
  923. ~GetAddrInfoState() {
  924. if (info) { freeaddrinfo(info); }
  925. }
  926. std::mutex mutex;
  927. std::condition_variable result_cv;
  928. bool completed = false;
  929. int result = EAI_SYSTEM;
  930. std::string node;
  931. std::string service;
  932. struct addrinfo hints;
  933. struct addrinfo *info = nullptr;
  934. };
  935. // Allocate on the heap, so the resolver thread can keep using the data.
  936. auto state = std::make_shared<GetAddrInfoState>();
  937. state->node = node;
  938. state->service = service;
  939. state->hints = *hints;
  940. std::thread resolve_thread([state]() {
  941. auto thread_result =
  942. getaddrinfo(state->node.c_str(), state->service.c_str(), &state->hints,
  943. &state->info);
  944. std::lock_guard<std::mutex> lock(state->mutex);
  945. state->result = thread_result;
  946. state->completed = true;
  947. state->result_cv.notify_one();
  948. });
  949. // Wait for completion or timeout
  950. std::unique_lock<std::mutex> lock(state->mutex);
  951. auto finished =
  952. state->result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  953. [&] { return state->completed; });
  954. if (finished) {
  955. // Operation completed within timeout
  956. resolve_thread.join();
  957. *res = state->info;
  958. state->info = nullptr; // Pass ownership to caller
  959. return state->result;
  960. } else {
  961. // Timeout occurred
  962. resolve_thread.detach(); // Let the thread finish in background
  963. return EAI_AGAIN; // Return timeout error
  964. }
  965. #endif
  966. #else
  967. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  968. return getaddrinfo(node, service, hints, res);
  969. #endif
  970. }
  971. template <typename BindOrConnect>
  972. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  973. int address_family, int socket_flags, bool tcp_nodelay,
  974. bool ipv6_v6only, SocketOptions socket_options,
  975. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  976. // Get address info
  977. const char *node = nullptr;
  978. struct addrinfo hints;
  979. struct addrinfo *result;
  980. memset(&hints, 0, sizeof(struct addrinfo));
  981. hints.ai_socktype = SOCK_STREAM;
  982. hints.ai_protocol = IPPROTO_IP;
  983. if (!ip.empty()) {
  984. node = ip.c_str();
  985. // Ask getaddrinfo to convert IP in c-string to address
  986. hints.ai_family = AF_UNSPEC;
  987. hints.ai_flags = AI_NUMERICHOST;
  988. } else {
  989. if (!host.empty()) { node = host.c_str(); }
  990. hints.ai_family = address_family;
  991. hints.ai_flags = socket_flags;
  992. }
  993. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  994. if (hints.ai_family == AF_UNIX) {
  995. const auto addrlen = host.length();
  996. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  997. #ifdef SOCK_CLOEXEC
  998. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  999. hints.ai_protocol);
  1000. #else
  1001. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  1002. #endif
  1003. if (sock != INVALID_SOCKET) {
  1004. sockaddr_un addr{};
  1005. addr.sun_family = AF_UNIX;
  1006. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  1007. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  1008. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  1009. hints.ai_addrlen = static_cast<socklen_t>(
  1010. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  1011. #ifndef SOCK_CLOEXEC
  1012. #ifndef _WIN32
  1013. fcntl(sock, F_SETFD, FD_CLOEXEC);
  1014. #endif
  1015. #endif
  1016. if (socket_options) { socket_options(sock); }
  1017. #ifdef _WIN32
  1018. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  1019. // remove the option.
  1020. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  1021. #endif
  1022. bool dummy;
  1023. if (!bind_or_connect(sock, hints, dummy)) {
  1024. close_socket(sock);
  1025. sock = INVALID_SOCKET;
  1026. }
  1027. }
  1028. return sock;
  1029. }
  1030. #endif
  1031. auto service = std::to_string(port);
  1032. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  1033. timeout_sec)) {
  1034. #if defined __linux__ && !defined __ANDROID__
  1035. res_init();
  1036. #endif
  1037. return INVALID_SOCKET;
  1038. }
  1039. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  1040. for (auto rp = result; rp; rp = rp->ai_next) {
  1041. // Create a socket
  1042. #ifdef _WIN32
  1043. auto sock =
  1044. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  1045. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  1046. /**
  1047. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  1048. * and above the socket creation fails on older Windows Systems.
  1049. *
  1050. * Let's try to create a socket the old way in this case.
  1051. *
  1052. * Reference:
  1053. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  1054. *
  1055. * WSA_FLAG_NO_HANDLE_INHERIT:
  1056. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  1057. * SP1, and later
  1058. *
  1059. */
  1060. if (sock == INVALID_SOCKET) {
  1061. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1062. }
  1063. #else
  1064. #ifdef SOCK_CLOEXEC
  1065. auto sock =
  1066. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  1067. #else
  1068. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1069. #endif
  1070. #endif
  1071. if (sock == INVALID_SOCKET) { continue; }
  1072. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  1073. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  1074. close_socket(sock);
  1075. continue;
  1076. }
  1077. #endif
  1078. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  1079. if (rp->ai_family == AF_INET6) {
  1080. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  1081. }
  1082. if (socket_options) { socket_options(sock); }
  1083. // bind or connect
  1084. auto quit = false;
  1085. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  1086. close_socket(sock);
  1087. if (quit) { break; }
  1088. }
  1089. return INVALID_SOCKET;
  1090. }
  1091. void set_nonblocking(socket_t sock, bool nonblocking) {
  1092. #ifdef _WIN32
  1093. auto flags = nonblocking ? 1UL : 0UL;
  1094. ioctlsocket(sock, FIONBIO, &flags);
  1095. #else
  1096. auto flags = fcntl(sock, F_GETFL, 0);
  1097. fcntl(sock, F_SETFL,
  1098. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  1099. #endif
  1100. }
  1101. bool is_connection_error() {
  1102. #ifdef _WIN32
  1103. return WSAGetLastError() != WSAEWOULDBLOCK;
  1104. #else
  1105. return errno != EINPROGRESS;
  1106. #endif
  1107. }
  1108. bool bind_ip_address(socket_t sock, const std::string &host) {
  1109. struct addrinfo hints;
  1110. struct addrinfo *result;
  1111. memset(&hints, 0, sizeof(struct addrinfo));
  1112. hints.ai_family = AF_UNSPEC;
  1113. hints.ai_socktype = SOCK_STREAM;
  1114. hints.ai_protocol = 0;
  1115. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  1116. return false;
  1117. }
  1118. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  1119. auto ret = false;
  1120. for (auto rp = result; rp; rp = rp->ai_next) {
  1121. const auto &ai = *rp;
  1122. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  1123. ret = true;
  1124. break;
  1125. }
  1126. }
  1127. return ret;
  1128. }
  1129. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  1130. #define USE_IF2IP
  1131. #endif
  1132. #ifdef USE_IF2IP
  1133. std::string if2ip(int address_family, const std::string &ifn) {
  1134. struct ifaddrs *ifap;
  1135. getifaddrs(&ifap);
  1136. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  1137. std::string addr_candidate;
  1138. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  1139. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  1140. (AF_UNSPEC == address_family ||
  1141. ifa->ifa_addr->sa_family == address_family)) {
  1142. if (ifa->ifa_addr->sa_family == AF_INET) {
  1143. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  1144. char buf[INET_ADDRSTRLEN];
  1145. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  1146. return std::string(buf, INET_ADDRSTRLEN);
  1147. }
  1148. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  1149. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  1150. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  1151. char buf[INET6_ADDRSTRLEN] = {};
  1152. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  1153. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  1154. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  1155. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  1156. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  1157. } else {
  1158. return std::string(buf, INET6_ADDRSTRLEN);
  1159. }
  1160. }
  1161. }
  1162. }
  1163. }
  1164. }
  1165. return addr_candidate;
  1166. }
  1167. #endif
  1168. socket_t create_client_socket(
  1169. const std::string &host, const std::string &ip, int port,
  1170. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  1171. SocketOptions socket_options, time_t connection_timeout_sec,
  1172. time_t connection_timeout_usec, time_t read_timeout_sec,
  1173. time_t read_timeout_usec, time_t write_timeout_sec,
  1174. time_t write_timeout_usec, const std::string &intf, Error &error) {
  1175. auto sock = create_socket(
  1176. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  1177. std::move(socket_options),
  1178. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  1179. if (!intf.empty()) {
  1180. #ifdef USE_IF2IP
  1181. auto ip_from_if = if2ip(address_family, intf);
  1182. if (ip_from_if.empty()) { ip_from_if = intf; }
  1183. if (!bind_ip_address(sock2, ip_from_if)) {
  1184. error = Error::BindIPAddress;
  1185. return false;
  1186. }
  1187. #endif
  1188. }
  1189. set_nonblocking(sock2, true);
  1190. auto ret =
  1191. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  1192. if (ret < 0) {
  1193. if (is_connection_error()) {
  1194. error = Error::Connection;
  1195. return false;
  1196. }
  1197. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  1198. connection_timeout_usec);
  1199. if (error != Error::Success) {
  1200. if (error == Error::ConnectionTimeout) { quit = true; }
  1201. return false;
  1202. }
  1203. }
  1204. set_nonblocking(sock2, false);
  1205. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  1206. read_timeout_usec);
  1207. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  1208. write_timeout_usec);
  1209. error = Error::Success;
  1210. return true;
  1211. },
  1212. connection_timeout_sec); // Pass DNS timeout
  1213. if (sock != INVALID_SOCKET) {
  1214. error = Error::Success;
  1215. } else {
  1216. if (error == Error::Success) { error = Error::Connection; }
  1217. }
  1218. return sock;
  1219. }
  1220. bool get_ip_and_port(const struct sockaddr_storage &addr,
  1221. socklen_t addr_len, std::string &ip, int &port) {
  1222. if (addr.ss_family == AF_INET) {
  1223. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  1224. } else if (addr.ss_family == AF_INET6) {
  1225. port =
  1226. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  1227. } else {
  1228. return false;
  1229. }
  1230. std::array<char, NI_MAXHOST> ipstr{};
  1231. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  1232. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  1233. 0, NI_NUMERICHOST)) {
  1234. return false;
  1235. }
  1236. ip = ipstr.data();
  1237. return true;
  1238. }
  1239. void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  1240. struct sockaddr_storage addr;
  1241. socklen_t addr_len = sizeof(addr);
  1242. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  1243. &addr_len)) {
  1244. get_ip_and_port(addr, addr_len, ip, port);
  1245. }
  1246. }
  1247. void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  1248. struct sockaddr_storage addr;
  1249. socklen_t addr_len = sizeof(addr);
  1250. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  1251. &addr_len)) {
  1252. #ifndef _WIN32
  1253. if (addr.ss_family == AF_UNIX) {
  1254. #if defined(__linux__)
  1255. struct ucred ucred;
  1256. socklen_t len = sizeof(ucred);
  1257. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  1258. port = ucred.pid;
  1259. }
  1260. #elif defined(SOL_LOCAL) && defined(SO_PEERPID)
  1261. pid_t pid;
  1262. socklen_t len = sizeof(pid);
  1263. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  1264. port = pid;
  1265. }
  1266. #endif
  1267. return;
  1268. }
  1269. #endif
  1270. get_ip_and_port(addr, addr_len, ip, port);
  1271. }
  1272. }
  1273. constexpr unsigned int str2tag_core(const char *s, size_t l,
  1274. unsigned int h) {
  1275. return (l == 0)
  1276. ? h
  1277. : str2tag_core(
  1278. s + 1, l - 1,
  1279. // Unsets the 6 high bits of h, therefore no overflow happens
  1280. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  1281. h * 33) ^
  1282. static_cast<unsigned char>(*s));
  1283. }
  1284. unsigned int str2tag(const std::string &s) {
  1285. return str2tag_core(s.data(), s.size(), 0);
  1286. }
  1287. namespace udl {
  1288. constexpr unsigned int operator""_t(const char *s, size_t l) {
  1289. return str2tag_core(s, l, 0);
  1290. }
  1291. } // namespace udl
  1292. std::string
  1293. find_content_type(const std::string &path,
  1294. const std::map<std::string, std::string> &user_data,
  1295. const std::string &default_content_type) {
  1296. auto ext = file_extension(path);
  1297. auto it = user_data.find(ext);
  1298. if (it != user_data.end()) { return it->second; }
  1299. using udl::operator""_t;
  1300. switch (str2tag(ext)) {
  1301. default: return default_content_type;
  1302. case "css"_t: return "text/css";
  1303. case "csv"_t: return "text/csv";
  1304. case "htm"_t:
  1305. case "html"_t: return "text/html";
  1306. case "js"_t:
  1307. case "mjs"_t: return "text/javascript";
  1308. case "txt"_t: return "text/plain";
  1309. case "vtt"_t: return "text/vtt";
  1310. case "apng"_t: return "image/apng";
  1311. case "avif"_t: return "image/avif";
  1312. case "bmp"_t: return "image/bmp";
  1313. case "gif"_t: return "image/gif";
  1314. case "png"_t: return "image/png";
  1315. case "svg"_t: return "image/svg+xml";
  1316. case "webp"_t: return "image/webp";
  1317. case "ico"_t: return "image/x-icon";
  1318. case "tif"_t: return "image/tiff";
  1319. case "tiff"_t: return "image/tiff";
  1320. case "jpg"_t:
  1321. case "jpeg"_t: return "image/jpeg";
  1322. case "mp4"_t: return "video/mp4";
  1323. case "mpeg"_t: return "video/mpeg";
  1324. case "webm"_t: return "video/webm";
  1325. case "mp3"_t: return "audio/mp3";
  1326. case "mpga"_t: return "audio/mpeg";
  1327. case "weba"_t: return "audio/webm";
  1328. case "wav"_t: return "audio/wave";
  1329. case "otf"_t: return "font/otf";
  1330. case "ttf"_t: return "font/ttf";
  1331. case "woff"_t: return "font/woff";
  1332. case "woff2"_t: return "font/woff2";
  1333. case "7z"_t: return "application/x-7z-compressed";
  1334. case "atom"_t: return "application/atom+xml";
  1335. case "pdf"_t: return "application/pdf";
  1336. case "json"_t: return "application/json";
  1337. case "rss"_t: return "application/rss+xml";
  1338. case "tar"_t: return "application/x-tar";
  1339. case "xht"_t:
  1340. case "xhtml"_t: return "application/xhtml+xml";
  1341. case "xslt"_t: return "application/xslt+xml";
  1342. case "xml"_t: return "application/xml";
  1343. case "gz"_t: return "application/gzip";
  1344. case "zip"_t: return "application/zip";
  1345. case "wasm"_t: return "application/wasm";
  1346. }
  1347. }
  1348. bool can_compress_content_type(const std::string &content_type) {
  1349. using udl::operator""_t;
  1350. auto tag = str2tag(content_type);
  1351. switch (tag) {
  1352. case "image/svg+xml"_t:
  1353. case "application/javascript"_t:
  1354. case "application/json"_t:
  1355. case "application/xml"_t:
  1356. case "application/protobuf"_t:
  1357. case "application/xhtml+xml"_t: return true;
  1358. case "text/event-stream"_t: return false;
  1359. default: return !content_type.rfind("text/", 0);
  1360. }
  1361. }
  1362. EncodingType encoding_type(const Request &req, const Response &res) {
  1363. auto ret =
  1364. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  1365. if (!ret) { return EncodingType::None; }
  1366. const auto &s = req.get_header_value("Accept-Encoding");
  1367. (void)(s);
  1368. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1369. // TODO: 'Accept-Encoding' has br, not br;q=0
  1370. ret = s.find("br") != std::string::npos;
  1371. if (ret) { return EncodingType::Brotli; }
  1372. #endif
  1373. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1374. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  1375. ret = s.find("gzip") != std::string::npos;
  1376. if (ret) { return EncodingType::Gzip; }
  1377. #endif
  1378. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  1379. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  1380. ret = s.find("zstd") != std::string::npos;
  1381. if (ret) { return EncodingType::Zstd; }
  1382. #endif
  1383. return EncodingType::None;
  1384. }
  1385. bool nocompressor::compress(const char *data, size_t data_length,
  1386. bool /*last*/, Callback callback) {
  1387. if (!data_length) { return true; }
  1388. return callback(data, data_length);
  1389. }
  1390. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1391. gzip_compressor::gzip_compressor() {
  1392. std::memset(&strm_, 0, sizeof(strm_));
  1393. strm_.zalloc = Z_NULL;
  1394. strm_.zfree = Z_NULL;
  1395. strm_.opaque = Z_NULL;
  1396. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  1397. Z_DEFAULT_STRATEGY) == Z_OK;
  1398. }
  1399. gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  1400. bool gzip_compressor::compress(const char *data, size_t data_length,
  1401. bool last, Callback callback) {
  1402. assert(is_valid_);
  1403. do {
  1404. constexpr size_t max_avail_in =
  1405. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  1406. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  1407. (std::min)(data_length, max_avail_in));
  1408. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  1409. data_length -= strm_.avail_in;
  1410. data += strm_.avail_in;
  1411. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  1412. auto ret = Z_OK;
  1413. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1414. do {
  1415. strm_.avail_out = static_cast<uInt>(buff.size());
  1416. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  1417. ret = deflate(&strm_, flush);
  1418. if (ret == Z_STREAM_ERROR) { return false; }
  1419. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  1420. return false;
  1421. }
  1422. } while (strm_.avail_out == 0);
  1423. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  1424. (flush == Z_NO_FLUSH && ret == Z_OK));
  1425. assert(strm_.avail_in == 0);
  1426. } while (data_length > 0);
  1427. return true;
  1428. }
  1429. gzip_decompressor::gzip_decompressor() {
  1430. std::memset(&strm_, 0, sizeof(strm_));
  1431. strm_.zalloc = Z_NULL;
  1432. strm_.zfree = Z_NULL;
  1433. strm_.opaque = Z_NULL;
  1434. // 15 is the value of wbits, which should be at the maximum possible value
  1435. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  1436. // that the stream type should be automatically detected either gzip or
  1437. // deflate.
  1438. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  1439. }
  1440. gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  1441. bool gzip_decompressor::is_valid() const { return is_valid_; }
  1442. bool gzip_decompressor::decompress(const char *data, size_t data_length,
  1443. Callback callback) {
  1444. assert(is_valid_);
  1445. auto ret = Z_OK;
  1446. do {
  1447. constexpr size_t max_avail_in =
  1448. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  1449. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  1450. (std::min)(data_length, max_avail_in));
  1451. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  1452. data_length -= strm_.avail_in;
  1453. data += strm_.avail_in;
  1454. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1455. while (strm_.avail_in > 0 && ret == Z_OK) {
  1456. strm_.avail_out = static_cast<uInt>(buff.size());
  1457. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  1458. ret = inflate(&strm_, Z_NO_FLUSH);
  1459. assert(ret != Z_STREAM_ERROR);
  1460. switch (ret) {
  1461. case Z_NEED_DICT:
  1462. case Z_DATA_ERROR:
  1463. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  1464. }
  1465. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  1466. return false;
  1467. }
  1468. }
  1469. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  1470. } while (data_length > 0);
  1471. return true;
  1472. }
  1473. #endif
  1474. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1475. brotli_compressor::brotli_compressor() {
  1476. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  1477. }
  1478. brotli_compressor::~brotli_compressor() {
  1479. BrotliEncoderDestroyInstance(state_);
  1480. }
  1481. bool brotli_compressor::compress(const char *data, size_t data_length,
  1482. bool last, Callback callback) {
  1483. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1484. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  1485. auto available_in = data_length;
  1486. auto next_in = reinterpret_cast<const uint8_t *>(data);
  1487. for (;;) {
  1488. if (last) {
  1489. if (BrotliEncoderIsFinished(state_)) { break; }
  1490. } else {
  1491. if (!available_in) { break; }
  1492. }
  1493. auto available_out = buff.size();
  1494. auto next_out = buff.data();
  1495. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  1496. &available_out, &next_out, nullptr)) {
  1497. return false;
  1498. }
  1499. auto output_bytes = buff.size() - available_out;
  1500. if (output_bytes) {
  1501. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  1502. }
  1503. }
  1504. return true;
  1505. }
  1506. brotli_decompressor::brotli_decompressor() {
  1507. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  1508. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  1509. : BROTLI_DECODER_RESULT_ERROR;
  1510. }
  1511. brotli_decompressor::~brotli_decompressor() {
  1512. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  1513. }
  1514. bool brotli_decompressor::is_valid() const { return decoder_s; }
  1515. bool brotli_decompressor::decompress(const char *data,
  1516. size_t data_length,
  1517. Callback callback) {
  1518. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  1519. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  1520. return 0;
  1521. }
  1522. auto next_in = reinterpret_cast<const uint8_t *>(data);
  1523. size_t avail_in = data_length;
  1524. size_t total_out;
  1525. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  1526. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1527. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  1528. char *next_out = buff.data();
  1529. size_t avail_out = buff.size();
  1530. decoder_r = BrotliDecoderDecompressStream(
  1531. decoder_s, &avail_in, &next_in, &avail_out,
  1532. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  1533. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  1534. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  1535. }
  1536. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  1537. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  1538. }
  1539. #endif
  1540. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  1541. zstd_compressor::zstd_compressor() {
  1542. ctx_ = ZSTD_createCCtx();
  1543. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  1544. }
  1545. zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  1546. bool zstd_compressor::compress(const char *data, size_t data_length,
  1547. bool last, Callback callback) {
  1548. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1549. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  1550. ZSTD_inBuffer input = {data, data_length, 0};
  1551. bool finished;
  1552. do {
  1553. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  1554. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  1555. if (ZSTD_isError(remaining)) { return false; }
  1556. if (!callback(buff.data(), output.pos)) { return false; }
  1557. finished = last ? (remaining == 0) : (input.pos == input.size);
  1558. } while (!finished);
  1559. return true;
  1560. }
  1561. zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  1562. zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  1563. bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  1564. bool zstd_decompressor::decompress(const char *data, size_t data_length,
  1565. Callback callback) {
  1566. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1567. ZSTD_inBuffer input = {data, data_length, 0};
  1568. while (input.pos < input.size) {
  1569. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  1570. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  1571. if (ZSTD_isError(remaining)) { return false; }
  1572. if (!callback(buff.data(), output.pos)) { return false; }
  1573. }
  1574. return true;
  1575. }
  1576. #endif
  1577. bool is_prohibited_header_name(const std::string &name) {
  1578. using udl::operator""_t;
  1579. switch (str2tag(name)) {
  1580. case "REMOTE_ADDR"_t:
  1581. case "REMOTE_PORT"_t:
  1582. case "LOCAL_ADDR"_t:
  1583. case "LOCAL_PORT"_t: return true;
  1584. default: return false;
  1585. }
  1586. }
  1587. bool has_header(const Headers &headers, const std::string &key) {
  1588. if (is_prohibited_header_name(key)) { return false; }
  1589. return headers.find(key) != headers.end();
  1590. }
  1591. const char *get_header_value(const Headers &headers,
  1592. const std::string &key, const char *def,
  1593. size_t id) {
  1594. if (is_prohibited_header_name(key)) {
  1595. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1596. std::string msg = "Prohibited header name '" + key + "' is specified.";
  1597. throw std::invalid_argument(msg);
  1598. #else
  1599. return "";
  1600. #endif
  1601. }
  1602. auto rng = headers.equal_range(key);
  1603. auto it = rng.first;
  1604. std::advance(it, static_cast<ssize_t>(id));
  1605. if (it != rng.second) { return it->second.c_str(); }
  1606. return def;
  1607. }
  1608. template <typename T>
  1609. bool parse_header(const char *beg, const char *end, T fn) {
  1610. // Skip trailing spaces and tabs.
  1611. while (beg < end && is_space_or_tab(end[-1])) {
  1612. end--;
  1613. }
  1614. auto p = beg;
  1615. while (p < end && *p != ':') {
  1616. p++;
  1617. }
  1618. auto name = std::string(beg, p);
  1619. if (!detail::fields::is_field_name(name)) { return false; }
  1620. if (p == end) { return false; }
  1621. auto key_end = p;
  1622. if (*p++ != ':') { return false; }
  1623. while (p < end && is_space_or_tab(*p)) {
  1624. p++;
  1625. }
  1626. if (p <= end) {
  1627. auto key_len = key_end - beg;
  1628. if (!key_len) { return false; }
  1629. auto key = std::string(beg, key_end);
  1630. auto val = std::string(p, end);
  1631. if (!detail::fields::is_field_value(val)) { return false; }
  1632. if (case_ignore::equal(key, "Location") ||
  1633. case_ignore::equal(key, "Referer")) {
  1634. fn(key, val);
  1635. } else {
  1636. fn(key, decode_path_component(val));
  1637. }
  1638. return true;
  1639. }
  1640. return false;
  1641. }
  1642. bool read_headers(Stream &strm, Headers &headers) {
  1643. const auto bufsiz = 2048;
  1644. char buf[bufsiz];
  1645. stream_line_reader line_reader(strm, buf, bufsiz);
  1646. size_t header_count = 0;
  1647. for (;;) {
  1648. if (!line_reader.getline()) { return false; }
  1649. // Check if the line ends with CRLF.
  1650. auto line_terminator_len = 2;
  1651. if (line_reader.end_with_crlf()) {
  1652. // Blank line indicates end of headers.
  1653. if (line_reader.size() == 2) { break; }
  1654. } else {
  1655. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  1656. // Blank line indicates end of headers.
  1657. if (line_reader.size() == 1) { break; }
  1658. line_terminator_len = 1;
  1659. #else
  1660. continue; // Skip invalid line.
  1661. #endif
  1662. }
  1663. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  1664. // Check header count limit
  1665. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  1666. // Exclude line terminator
  1667. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  1668. if (!parse_header(line_reader.ptr(), end,
  1669. [&](const std::string &key, const std::string &val) {
  1670. headers.emplace(key, val);
  1671. })) {
  1672. return false;
  1673. }
  1674. header_count++;
  1675. }
  1676. return true;
  1677. }
  1678. bool read_content_with_length(Stream &strm, size_t len,
  1679. DownloadProgress progress,
  1680. ContentReceiverWithProgress out) {
  1681. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1682. size_t r = 0;
  1683. while (r < len) {
  1684. auto read_len = static_cast<size_t>(len - r);
  1685. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1686. if (n <= 0) { return false; }
  1687. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  1688. r += static_cast<size_t>(n);
  1689. if (progress) {
  1690. if (!progress(r, len)) { return false; }
  1691. }
  1692. }
  1693. return true;
  1694. }
  1695. void skip_content_with_length(Stream &strm, size_t len) {
  1696. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1697. size_t r = 0;
  1698. while (r < len) {
  1699. auto read_len = static_cast<size_t>(len - r);
  1700. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1701. if (n <= 0) { return; }
  1702. r += static_cast<size_t>(n);
  1703. }
  1704. }
  1705. enum class ReadContentResult {
  1706. Success, // Successfully read the content
  1707. PayloadTooLarge, // The content exceeds the specified payload limit
  1708. Error // An error occurred while reading the content
  1709. };
  1710. ReadContentResult
  1711. read_content_without_length(Stream &strm, size_t payload_max_length,
  1712. ContentReceiverWithProgress out) {
  1713. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1714. size_t r = 0;
  1715. for (;;) {
  1716. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  1717. if (n == 0) { return ReadContentResult::Success; }
  1718. if (n < 0) { return ReadContentResult::Error; }
  1719. // Check if adding this data would exceed the payload limit
  1720. if (r > payload_max_length ||
  1721. payload_max_length - r < static_cast<size_t>(n)) {
  1722. return ReadContentResult::PayloadTooLarge;
  1723. }
  1724. if (!out(buf, static_cast<size_t>(n), r, 0)) {
  1725. return ReadContentResult::Error;
  1726. }
  1727. r += static_cast<size_t>(n);
  1728. }
  1729. return ReadContentResult::Success;
  1730. }
  1731. template <typename T>
  1732. ReadContentResult read_content_chunked(Stream &strm, T &x,
  1733. size_t payload_max_length,
  1734. ContentReceiverWithProgress out) {
  1735. const auto bufsiz = 16;
  1736. char buf[bufsiz];
  1737. stream_line_reader line_reader(strm, buf, bufsiz);
  1738. if (!line_reader.getline()) { return ReadContentResult::Error; }
  1739. unsigned long chunk_len;
  1740. size_t total_len = 0;
  1741. while (true) {
  1742. char *end_ptr;
  1743. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  1744. if (end_ptr == line_reader.ptr()) { return ReadContentResult::Error; }
  1745. if (chunk_len == ULONG_MAX) { return ReadContentResult::Error; }
  1746. if (chunk_len == 0) { break; }
  1747. // Check if adding this chunk would exceed the payload limit
  1748. if (total_len > payload_max_length ||
  1749. payload_max_length - total_len < chunk_len) {
  1750. return ReadContentResult::PayloadTooLarge;
  1751. }
  1752. total_len += chunk_len;
  1753. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  1754. return ReadContentResult::Error;
  1755. }
  1756. if (!line_reader.getline()) { return ReadContentResult::Error; }
  1757. if (strcmp(line_reader.ptr(), "\r\n") != 0) {
  1758. return ReadContentResult::Error;
  1759. }
  1760. if (!line_reader.getline()) { return ReadContentResult::Error; }
  1761. }
  1762. assert(chunk_len == 0);
  1763. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  1764. // transfer coding is complete when a chunk with a chunk-size of zero is
  1765. // received, possibly followed by a trailer section, and finally terminated by
  1766. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  1767. //
  1768. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  1769. // does't care for the existence of the final CRLF. In other words, it seems
  1770. // to be ok whether the final CRLF exists or not in the chunked data.
  1771. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  1772. //
  1773. // According to the reference code in RFC 9112, cpp-httplib now allows
  1774. // chunked transfer coding data without the final CRLF.
  1775. if (!line_reader.getline()) { return ReadContentResult::Success; }
  1776. // RFC 7230 Section 4.1.2 - Headers prohibited in trailers
  1777. thread_local case_ignore::unordered_set<std::string> prohibited_trailers = {
  1778. // Message framing
  1779. "transfer-encoding", "content-length",
  1780. // Routing
  1781. "host",
  1782. // Authentication
  1783. "authorization", "www-authenticate", "proxy-authenticate",
  1784. "proxy-authorization", "cookie", "set-cookie",
  1785. // Request modifiers
  1786. "cache-control", "expect", "max-forwards", "pragma", "range", "te",
  1787. // Response control
  1788. "age", "expires", "date", "location", "retry-after", "vary", "warning",
  1789. // Payload processing
  1790. "content-encoding", "content-type", "content-range", "trailer"};
  1791. // Parse declared trailer headers once for performance
  1792. case_ignore::unordered_set<std::string> declared_trailers;
  1793. if (has_header(x.headers, "Trailer")) {
  1794. auto trailer_header = get_header_value(x.headers, "Trailer", "", 0);
  1795. auto len = std::strlen(trailer_header);
  1796. split(trailer_header, trailer_header + len, ',',
  1797. [&](const char *b, const char *e) {
  1798. std::string key(b, e);
  1799. if (prohibited_trailers.find(key) == prohibited_trailers.end()) {
  1800. declared_trailers.insert(key);
  1801. }
  1802. });
  1803. }
  1804. size_t trailer_header_count = 0;
  1805. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  1806. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) {
  1807. return ReadContentResult::Error;
  1808. }
  1809. // Check trailer header count limit
  1810. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) {
  1811. return ReadContentResult::Error;
  1812. }
  1813. // Exclude line terminator
  1814. constexpr auto line_terminator_len = 2;
  1815. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  1816. parse_header(line_reader.ptr(), end,
  1817. [&](const std::string &key, const std::string &val) {
  1818. if (declared_trailers.find(key) != declared_trailers.end()) {
  1819. x.trailers.emplace(key, val);
  1820. trailer_header_count++;
  1821. }
  1822. });
  1823. if (!line_reader.getline()) { return ReadContentResult::Error; }
  1824. }
  1825. return ReadContentResult::Success;
  1826. }
  1827. bool is_chunked_transfer_encoding(const Headers &headers) {
  1828. return case_ignore::equal(
  1829. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  1830. }
  1831. template <typename T, typename U>
  1832. bool prepare_content_receiver(T &x, int &status,
  1833. ContentReceiverWithProgress receiver,
  1834. bool decompress, U callback) {
  1835. if (decompress) {
  1836. std::string encoding = x.get_header_value("Content-Encoding");
  1837. std::unique_ptr<decompressor> decompressor;
  1838. if (encoding == "gzip" || encoding == "deflate") {
  1839. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1840. decompressor = detail::make_unique<gzip_decompressor>();
  1841. #else
  1842. status = StatusCode::UnsupportedMediaType_415;
  1843. return false;
  1844. #endif
  1845. } else if (encoding.find("br") != std::string::npos) {
  1846. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1847. decompressor = detail::make_unique<brotli_decompressor>();
  1848. #else
  1849. status = StatusCode::UnsupportedMediaType_415;
  1850. return false;
  1851. #endif
  1852. } else if (encoding == "zstd") {
  1853. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  1854. decompressor = detail::make_unique<zstd_decompressor>();
  1855. #else
  1856. status = StatusCode::UnsupportedMediaType_415;
  1857. return false;
  1858. #endif
  1859. }
  1860. if (decompressor) {
  1861. if (decompressor->is_valid()) {
  1862. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  1863. size_t off, size_t len) {
  1864. return decompressor->decompress(buf, n,
  1865. [&](const char *buf2, size_t n2) {
  1866. return receiver(buf2, n2, off, len);
  1867. });
  1868. };
  1869. return callback(std::move(out));
  1870. } else {
  1871. status = StatusCode::InternalServerError_500;
  1872. return false;
  1873. }
  1874. }
  1875. }
  1876. ContentReceiverWithProgress out = [&](const char *buf, size_t n, size_t off,
  1877. size_t len) {
  1878. return receiver(buf, n, off, len);
  1879. };
  1880. return callback(std::move(out));
  1881. }
  1882. template <typename T>
  1883. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  1884. DownloadProgress progress,
  1885. ContentReceiverWithProgress receiver, bool decompress) {
  1886. return prepare_content_receiver(
  1887. x, status, std::move(receiver), decompress,
  1888. [&](const ContentReceiverWithProgress &out) {
  1889. auto ret = true;
  1890. auto exceed_payload_max_length = false;
  1891. if (is_chunked_transfer_encoding(x.headers)) {
  1892. auto result = read_content_chunked(strm, x, payload_max_length, out);
  1893. if (result == ReadContentResult::Success) {
  1894. ret = true;
  1895. } else if (result == ReadContentResult::PayloadTooLarge) {
  1896. exceed_payload_max_length = true;
  1897. ret = false;
  1898. } else {
  1899. ret = false;
  1900. }
  1901. } else if (!has_header(x.headers, "Content-Length")) {
  1902. auto result =
  1903. read_content_without_length(strm, payload_max_length, out);
  1904. if (result == ReadContentResult::Success) {
  1905. ret = true;
  1906. } else if (result == ReadContentResult::PayloadTooLarge) {
  1907. exceed_payload_max_length = true;
  1908. ret = false;
  1909. } else {
  1910. ret = false;
  1911. }
  1912. } else {
  1913. auto is_invalid_value = false;
  1914. auto len = get_header_value_u64(x.headers, "Content-Length",
  1915. (std::numeric_limits<size_t>::max)(),
  1916. 0, is_invalid_value);
  1917. if (is_invalid_value) {
  1918. ret = false;
  1919. } else if (len > payload_max_length) {
  1920. exceed_payload_max_length = true;
  1921. skip_content_with_length(strm, len);
  1922. ret = false;
  1923. } else if (len > 0) {
  1924. ret = read_content_with_length(strm, len, std::move(progress), out);
  1925. }
  1926. }
  1927. if (!ret) {
  1928. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  1929. : StatusCode::BadRequest_400;
  1930. }
  1931. return ret;
  1932. });
  1933. }
  1934. ssize_t write_request_line(Stream &strm, const std::string &method,
  1935. const std::string &path) {
  1936. std::string s = method;
  1937. s += " ";
  1938. s += path;
  1939. s += " HTTP/1.1\r\n";
  1940. return strm.write(s.data(), s.size());
  1941. }
  1942. ssize_t write_response_line(Stream &strm, int status) {
  1943. std::string s = "HTTP/1.1 ";
  1944. s += std::to_string(status);
  1945. s += " ";
  1946. s += httplib::status_message(status);
  1947. s += "\r\n";
  1948. return strm.write(s.data(), s.size());
  1949. }
  1950. ssize_t write_headers(Stream &strm, const Headers &headers) {
  1951. ssize_t write_len = 0;
  1952. for (const auto &x : headers) {
  1953. std::string s;
  1954. s = x.first;
  1955. s += ": ";
  1956. s += x.second;
  1957. s += "\r\n";
  1958. auto len = strm.write(s.data(), s.size());
  1959. if (len < 0) { return len; }
  1960. write_len += len;
  1961. }
  1962. auto len = strm.write("\r\n");
  1963. if (len < 0) { return len; }
  1964. write_len += len;
  1965. return write_len;
  1966. }
  1967. bool write_data(Stream &strm, const char *d, size_t l) {
  1968. size_t offset = 0;
  1969. while (offset < l) {
  1970. auto length = strm.write(d + offset, l - offset);
  1971. if (length < 0) { return false; }
  1972. offset += static_cast<size_t>(length);
  1973. }
  1974. return true;
  1975. }
  1976. template <typename T>
  1977. bool write_content_with_progress(Stream &strm,
  1978. const ContentProvider &content_provider,
  1979. size_t offset, size_t length,
  1980. T is_shutting_down,
  1981. const UploadProgress &upload_progress,
  1982. Error &error) {
  1983. size_t end_offset = offset + length;
  1984. size_t start_offset = offset;
  1985. auto ok = true;
  1986. DataSink data_sink;
  1987. data_sink.write = [&](const char *d, size_t l) -> bool {
  1988. if (ok) {
  1989. if (write_data(strm, d, l)) {
  1990. offset += l;
  1991. if (upload_progress && length > 0) {
  1992. size_t current_written = offset - start_offset;
  1993. if (!upload_progress(current_written, length)) {
  1994. ok = false;
  1995. return false;
  1996. }
  1997. }
  1998. } else {
  1999. ok = false;
  2000. }
  2001. }
  2002. return ok;
  2003. };
  2004. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  2005. while (offset < end_offset && !is_shutting_down()) {
  2006. if (!strm.wait_writable()) {
  2007. error = Error::Write;
  2008. return false;
  2009. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  2010. error = Error::Canceled;
  2011. return false;
  2012. } else if (!ok) {
  2013. error = Error::Write;
  2014. return false;
  2015. }
  2016. }
  2017. error = Error::Success;
  2018. return true;
  2019. }
  2020. template <typename T>
  2021. bool write_content(Stream &strm, const ContentProvider &content_provider,
  2022. size_t offset, size_t length, T is_shutting_down,
  2023. Error &error) {
  2024. return write_content_with_progress<T>(strm, content_provider, offset, length,
  2025. is_shutting_down, nullptr, error);
  2026. }
  2027. template <typename T>
  2028. bool write_content(Stream &strm, const ContentProvider &content_provider,
  2029. size_t offset, size_t length,
  2030. const T &is_shutting_down) {
  2031. auto error = Error::Success;
  2032. return write_content(strm, content_provider, offset, length, is_shutting_down,
  2033. error);
  2034. }
  2035. template <typename T>
  2036. bool
  2037. write_content_without_length(Stream &strm,
  2038. const ContentProvider &content_provider,
  2039. const T &is_shutting_down) {
  2040. size_t offset = 0;
  2041. auto data_available = true;
  2042. auto ok = true;
  2043. DataSink data_sink;
  2044. data_sink.write = [&](const char *d, size_t l) -> bool {
  2045. if (ok) {
  2046. offset += l;
  2047. if (!write_data(strm, d, l)) { ok = false; }
  2048. }
  2049. return ok;
  2050. };
  2051. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  2052. data_sink.done = [&](void) { data_available = false; };
  2053. while (data_available && !is_shutting_down()) {
  2054. if (!strm.wait_writable()) {
  2055. return false;
  2056. } else if (!content_provider(offset, 0, data_sink)) {
  2057. return false;
  2058. } else if (!ok) {
  2059. return false;
  2060. }
  2061. }
  2062. return true;
  2063. }
  2064. template <typename T, typename U>
  2065. bool
  2066. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  2067. const T &is_shutting_down, U &compressor, Error &error) {
  2068. size_t offset = 0;
  2069. auto data_available = true;
  2070. auto ok = true;
  2071. DataSink data_sink;
  2072. data_sink.write = [&](const char *d, size_t l) -> bool {
  2073. if (ok) {
  2074. data_available = l > 0;
  2075. offset += l;
  2076. std::string payload;
  2077. if (compressor.compress(d, l, false,
  2078. [&](const char *data, size_t data_len) {
  2079. payload.append(data, data_len);
  2080. return true;
  2081. })) {
  2082. if (!payload.empty()) {
  2083. // Emit chunked response header and footer for each chunk
  2084. auto chunk =
  2085. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  2086. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  2087. }
  2088. } else {
  2089. ok = false;
  2090. }
  2091. }
  2092. return ok;
  2093. };
  2094. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  2095. auto done_with_trailer = [&](const Headers *trailer) {
  2096. if (!ok) { return; }
  2097. data_available = false;
  2098. std::string payload;
  2099. if (!compressor.compress(nullptr, 0, true,
  2100. [&](const char *data, size_t data_len) {
  2101. payload.append(data, data_len);
  2102. return true;
  2103. })) {
  2104. ok = false;
  2105. return;
  2106. }
  2107. if (!payload.empty()) {
  2108. // Emit chunked response header and footer for each chunk
  2109. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  2110. if (!write_data(strm, chunk.data(), chunk.size())) {
  2111. ok = false;
  2112. return;
  2113. }
  2114. }
  2115. constexpr const char done_marker[] = "0\r\n";
  2116. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  2117. // Trailer
  2118. if (trailer) {
  2119. for (const auto &kv : *trailer) {
  2120. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  2121. if (!write_data(strm, field_line.data(), field_line.size())) {
  2122. ok = false;
  2123. }
  2124. }
  2125. }
  2126. constexpr const char crlf[] = "\r\n";
  2127. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  2128. };
  2129. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  2130. data_sink.done_with_trailer = [&](const Headers &trailer) {
  2131. done_with_trailer(&trailer);
  2132. };
  2133. while (data_available && !is_shutting_down()) {
  2134. if (!strm.wait_writable()) {
  2135. error = Error::Write;
  2136. return false;
  2137. } else if (!content_provider(offset, 0, data_sink)) {
  2138. error = Error::Canceled;
  2139. return false;
  2140. } else if (!ok) {
  2141. error = Error::Write;
  2142. return false;
  2143. }
  2144. }
  2145. error = Error::Success;
  2146. return true;
  2147. }
  2148. template <typename T, typename U>
  2149. bool write_content_chunked(Stream &strm,
  2150. const ContentProvider &content_provider,
  2151. const T &is_shutting_down, U &compressor) {
  2152. auto error = Error::Success;
  2153. return write_content_chunked(strm, content_provider, is_shutting_down,
  2154. compressor, error);
  2155. }
  2156. template <typename T>
  2157. bool redirect(T &cli, Request &req, Response &res,
  2158. const std::string &path, const std::string &location,
  2159. Error &error) {
  2160. Request new_req = req;
  2161. new_req.path = path;
  2162. new_req.redirect_count_ -= 1;
  2163. if (res.status == StatusCode::SeeOther_303 &&
  2164. (req.method != "GET" && req.method != "HEAD")) {
  2165. new_req.method = "GET";
  2166. new_req.body.clear();
  2167. new_req.headers.clear();
  2168. }
  2169. Response new_res;
  2170. auto ret = cli.send(new_req, new_res, error);
  2171. if (ret) {
  2172. req = new_req;
  2173. res = new_res;
  2174. if (res.location.empty()) { res.location = location; }
  2175. }
  2176. return ret;
  2177. }
  2178. std::string params_to_query_str(const Params &params) {
  2179. std::string query;
  2180. for (auto it = params.begin(); it != params.end(); ++it) {
  2181. if (it != params.begin()) { query += "&"; }
  2182. query += encode_query_component(it->first);
  2183. query += "=";
  2184. query += encode_query_component(it->second);
  2185. }
  2186. return query;
  2187. }
  2188. void parse_query_text(const char *data, std::size_t size,
  2189. Params &params) {
  2190. std::set<std::string> cache;
  2191. split(data, data + size, '&', [&](const char *b, const char *e) {
  2192. std::string kv(b, e);
  2193. if (cache.find(kv) != cache.end()) { return; }
  2194. cache.insert(std::move(kv));
  2195. std::string key;
  2196. std::string val;
  2197. divide(b, static_cast<std::size_t>(e - b), '=',
  2198. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  2199. std::size_t rhs_size) {
  2200. key.assign(lhs_data, lhs_size);
  2201. val.assign(rhs_data, rhs_size);
  2202. });
  2203. if (!key.empty()) {
  2204. params.emplace(decode_query_component(key), decode_query_component(val));
  2205. }
  2206. });
  2207. }
  2208. void parse_query_text(const std::string &s, Params &params) {
  2209. parse_query_text(s.data(), s.size(), params);
  2210. }
  2211. bool parse_multipart_boundary(const std::string &content_type,
  2212. std::string &boundary) {
  2213. auto boundary_keyword = "boundary=";
  2214. auto pos = content_type.find(boundary_keyword);
  2215. if (pos == std::string::npos) { return false; }
  2216. auto end = content_type.find(';', pos);
  2217. auto beg = pos + strlen(boundary_keyword);
  2218. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  2219. return !boundary.empty();
  2220. }
  2221. void parse_disposition_params(const std::string &s, Params &params) {
  2222. std::set<std::string> cache;
  2223. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  2224. std::string kv(b, e);
  2225. if (cache.find(kv) != cache.end()) { return; }
  2226. cache.insert(kv);
  2227. std::string key;
  2228. std::string val;
  2229. split(b, e, '=', [&](const char *b2, const char *e2) {
  2230. if (key.empty()) {
  2231. key.assign(b2, e2);
  2232. } else {
  2233. val.assign(b2, e2);
  2234. }
  2235. });
  2236. if (!key.empty()) {
  2237. params.emplace(trim_double_quotes_copy((key)),
  2238. trim_double_quotes_copy((val)));
  2239. }
  2240. });
  2241. }
  2242. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  2243. bool parse_range_header(const std::string &s, Ranges &ranges) {
  2244. #else
  2245. bool parse_range_header(const std::string &s, Ranges &ranges) try {
  2246. #endif
  2247. auto is_valid = [](const std::string &str) {
  2248. return std::all_of(str.cbegin(), str.cend(),
  2249. [](unsigned char c) { return std::isdigit(c); });
  2250. };
  2251. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  2252. const auto pos = static_cast<size_t>(6);
  2253. const auto len = static_cast<size_t>(s.size() - 6);
  2254. auto all_valid_ranges = true;
  2255. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  2256. if (!all_valid_ranges) { return; }
  2257. const auto it = std::find(b, e, '-');
  2258. if (it == e) {
  2259. all_valid_ranges = false;
  2260. return;
  2261. }
  2262. const auto lhs = std::string(b, it);
  2263. const auto rhs = std::string(it + 1, e);
  2264. if (!is_valid(lhs) || !is_valid(rhs)) {
  2265. all_valid_ranges = false;
  2266. return;
  2267. }
  2268. const auto first =
  2269. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  2270. const auto last =
  2271. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  2272. if ((first == -1 && last == -1) ||
  2273. (first != -1 && last != -1 && first > last)) {
  2274. all_valid_ranges = false;
  2275. return;
  2276. }
  2277. ranges.emplace_back(first, last);
  2278. });
  2279. return all_valid_ranges && !ranges.empty();
  2280. }
  2281. return false;
  2282. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  2283. }
  2284. #else
  2285. } catch (...) { return false; }
  2286. #endif
  2287. bool parse_accept_header(const std::string &s,
  2288. std::vector<std::string> &content_types) {
  2289. content_types.clear();
  2290. // Empty string is considered valid (no preference)
  2291. if (s.empty()) { return true; }
  2292. // Check for invalid patterns: leading/trailing commas or consecutive commas
  2293. if (s.front() == ',' || s.back() == ',' ||
  2294. s.find(",,") != std::string::npos) {
  2295. return false;
  2296. }
  2297. struct AcceptEntry {
  2298. std::string media_type;
  2299. double quality;
  2300. int order; // Original order in header
  2301. };
  2302. std::vector<AcceptEntry> entries;
  2303. int order = 0;
  2304. bool has_invalid_entry = false;
  2305. // Split by comma and parse each entry
  2306. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  2307. std::string entry(b, e);
  2308. entry = trim_copy(entry);
  2309. if (entry.empty()) {
  2310. has_invalid_entry = true;
  2311. return;
  2312. }
  2313. AcceptEntry accept_entry;
  2314. accept_entry.quality = 1.0; // Default quality
  2315. accept_entry.order = order++;
  2316. // Find q= parameter
  2317. auto q_pos = entry.find(";q=");
  2318. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  2319. if (q_pos != std::string::npos) {
  2320. // Extract media type (before q parameter)
  2321. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  2322. // Extract quality value
  2323. auto q_start = entry.find('=', q_pos) + 1;
  2324. auto q_end = entry.find(';', q_start);
  2325. if (q_end == std::string::npos) { q_end = entry.length(); }
  2326. std::string quality_str =
  2327. trim_copy(entry.substr(q_start, q_end - q_start));
  2328. if (quality_str.empty()) {
  2329. has_invalid_entry = true;
  2330. return;
  2331. }
  2332. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  2333. {
  2334. std::istringstream iss(quality_str);
  2335. iss >> accept_entry.quality;
  2336. // Check if conversion was successful and entire string was consumed
  2337. if (iss.fail() || !iss.eof()) {
  2338. has_invalid_entry = true;
  2339. return;
  2340. }
  2341. }
  2342. #else
  2343. try {
  2344. accept_entry.quality = std::stod(quality_str);
  2345. } catch (...) {
  2346. has_invalid_entry = true;
  2347. return;
  2348. }
  2349. #endif
  2350. // Check if quality is in valid range [0.0, 1.0]
  2351. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  2352. has_invalid_entry = true;
  2353. return;
  2354. }
  2355. } else {
  2356. // No quality parameter, use entire entry as media type
  2357. accept_entry.media_type = entry;
  2358. }
  2359. // Remove additional parameters from media type
  2360. auto param_pos = accept_entry.media_type.find(';');
  2361. if (param_pos != std::string::npos) {
  2362. accept_entry.media_type =
  2363. trim_copy(accept_entry.media_type.substr(0, param_pos));
  2364. }
  2365. // Basic validation of media type format
  2366. if (accept_entry.media_type.empty()) {
  2367. has_invalid_entry = true;
  2368. return;
  2369. }
  2370. // Check for basic media type format (should contain '/' or be '*')
  2371. if (accept_entry.media_type != "*" &&
  2372. accept_entry.media_type.find('/') == std::string::npos) {
  2373. has_invalid_entry = true;
  2374. return;
  2375. }
  2376. entries.push_back(accept_entry);
  2377. });
  2378. // Return false if any invalid entry was found
  2379. if (has_invalid_entry) { return false; }
  2380. // Sort by quality (descending), then by original order (ascending)
  2381. std::sort(entries.begin(), entries.end(),
  2382. [](const AcceptEntry &a, const AcceptEntry &b) {
  2383. if (a.quality != b.quality) {
  2384. return a.quality > b.quality; // Higher quality first
  2385. }
  2386. return a.order < b.order; // Earlier order first for same quality
  2387. });
  2388. // Extract sorted media types
  2389. content_types.reserve(entries.size());
  2390. for (const auto &entry : entries) {
  2391. content_types.push_back(entry.media_type);
  2392. }
  2393. return true;
  2394. }
  2395. class FormDataParser {
  2396. public:
  2397. FormDataParser() = default;
  2398. void set_boundary(std::string &&boundary) {
  2399. boundary_ = boundary;
  2400. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  2401. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  2402. }
  2403. bool is_valid() const { return is_valid_; }
  2404. bool parse(const char *buf, size_t n, const FormDataHeader &header_callback,
  2405. const ContentReceiver &content_callback) {
  2406. buf_append(buf, n);
  2407. while (buf_size() > 0) {
  2408. switch (state_) {
  2409. case 0: { // Initial boundary
  2410. auto pos = buf_find(dash_boundary_crlf_);
  2411. if (pos == buf_size()) { return true; }
  2412. buf_erase(pos + dash_boundary_crlf_.size());
  2413. state_ = 1;
  2414. break;
  2415. }
  2416. case 1: { // New entry
  2417. clear_file_info();
  2418. state_ = 2;
  2419. break;
  2420. }
  2421. case 2: { // Headers
  2422. auto pos = buf_find(crlf_);
  2423. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  2424. while (pos < buf_size()) {
  2425. // Empty line
  2426. if (pos == 0) {
  2427. if (!header_callback(file_)) {
  2428. is_valid_ = false;
  2429. return false;
  2430. }
  2431. buf_erase(crlf_.size());
  2432. state_ = 3;
  2433. break;
  2434. }
  2435. const auto header = buf_head(pos);
  2436. if (!parse_header(header.data(), header.data() + header.size(),
  2437. [&](const std::string &, const std::string &) {})) {
  2438. is_valid_ = false;
  2439. return false;
  2440. }
  2441. // Parse and emplace space trimmed headers into a map
  2442. if (!parse_header(
  2443. header.data(), header.data() + header.size(),
  2444. [&](const std::string &key, const std::string &val) {
  2445. file_.headers.emplace(key, val);
  2446. })) {
  2447. is_valid_ = false;
  2448. return false;
  2449. }
  2450. constexpr const char header_content_type[] = "Content-Type:";
  2451. if (start_with_case_ignore(header, header_content_type)) {
  2452. file_.content_type =
  2453. trim_copy(header.substr(str_len(header_content_type)));
  2454. } else {
  2455. thread_local const std::regex re_content_disposition(
  2456. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  2457. std::regex_constants::icase);
  2458. std::smatch m;
  2459. if (std::regex_match(header, m, re_content_disposition)) {
  2460. Params params;
  2461. parse_disposition_params(m[1], params);
  2462. auto it = params.find("name");
  2463. if (it != params.end()) {
  2464. file_.name = it->second;
  2465. } else {
  2466. is_valid_ = false;
  2467. return false;
  2468. }
  2469. it = params.find("filename");
  2470. if (it != params.end()) { file_.filename = it->second; }
  2471. it = params.find("filename*");
  2472. if (it != params.end()) {
  2473. // Only allow UTF-8 encoding...
  2474. thread_local const std::regex re_rfc5987_encoding(
  2475. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  2476. std::smatch m2;
  2477. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  2478. file_.filename = decode_path_component(m2[1]); // override...
  2479. } else {
  2480. is_valid_ = false;
  2481. return false;
  2482. }
  2483. }
  2484. }
  2485. }
  2486. buf_erase(pos + crlf_.size());
  2487. pos = buf_find(crlf_);
  2488. }
  2489. if (state_ != 3) { return true; }
  2490. break;
  2491. }
  2492. case 3: { // Body
  2493. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  2494. auto pos = buf_find(crlf_dash_boundary_);
  2495. if (pos < buf_size()) {
  2496. if (!content_callback(buf_data(), pos)) {
  2497. is_valid_ = false;
  2498. return false;
  2499. }
  2500. buf_erase(pos + crlf_dash_boundary_.size());
  2501. state_ = 4;
  2502. } else {
  2503. auto len = buf_size() - crlf_dash_boundary_.size();
  2504. if (len > 0) {
  2505. if (!content_callback(buf_data(), len)) {
  2506. is_valid_ = false;
  2507. return false;
  2508. }
  2509. buf_erase(len);
  2510. }
  2511. return true;
  2512. }
  2513. break;
  2514. }
  2515. case 4: { // Boundary
  2516. if (crlf_.size() > buf_size()) { return true; }
  2517. if (buf_start_with(crlf_)) {
  2518. buf_erase(crlf_.size());
  2519. state_ = 1;
  2520. } else {
  2521. if (dash_.size() > buf_size()) { return true; }
  2522. if (buf_start_with(dash_)) {
  2523. buf_erase(dash_.size());
  2524. is_valid_ = true;
  2525. buf_erase(buf_size()); // Remove epilogue
  2526. } else {
  2527. return true;
  2528. }
  2529. }
  2530. break;
  2531. }
  2532. }
  2533. }
  2534. return true;
  2535. }
  2536. private:
  2537. void clear_file_info() {
  2538. file_.name.clear();
  2539. file_.filename.clear();
  2540. file_.content_type.clear();
  2541. file_.headers.clear();
  2542. }
  2543. bool start_with_case_ignore(const std::string &a, const char *b) const {
  2544. const auto b_len = strlen(b);
  2545. if (a.size() < b_len) { return false; }
  2546. for (size_t i = 0; i < b_len; i++) {
  2547. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  2548. return false;
  2549. }
  2550. }
  2551. return true;
  2552. }
  2553. const std::string dash_ = "--";
  2554. const std::string crlf_ = "\r\n";
  2555. std::string boundary_;
  2556. std::string dash_boundary_crlf_;
  2557. std::string crlf_dash_boundary_;
  2558. size_t state_ = 0;
  2559. bool is_valid_ = false;
  2560. FormData file_;
  2561. // Buffer
  2562. bool start_with(const std::string &a, size_t spos, size_t epos,
  2563. const std::string &b) const {
  2564. if (epos - spos < b.size()) { return false; }
  2565. for (size_t i = 0; i < b.size(); i++) {
  2566. if (a[i + spos] != b[i]) { return false; }
  2567. }
  2568. return true;
  2569. }
  2570. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  2571. const char *buf_data() const { return &buf_[buf_spos_]; }
  2572. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  2573. bool buf_start_with(const std::string &s) const {
  2574. return start_with(buf_, buf_spos_, buf_epos_, s);
  2575. }
  2576. size_t buf_find(const std::string &s) const {
  2577. auto c = s.front();
  2578. size_t off = buf_spos_;
  2579. while (off < buf_epos_) {
  2580. auto pos = off;
  2581. while (true) {
  2582. if (pos == buf_epos_) { return buf_size(); }
  2583. if (buf_[pos] == c) { break; }
  2584. pos++;
  2585. }
  2586. auto remaining_size = buf_epos_ - pos;
  2587. if (s.size() > remaining_size) { return buf_size(); }
  2588. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  2589. off = pos + 1;
  2590. }
  2591. return buf_size();
  2592. }
  2593. void buf_append(const char *data, size_t n) {
  2594. auto remaining_size = buf_size();
  2595. if (remaining_size > 0 && buf_spos_ > 0) {
  2596. for (size_t i = 0; i < remaining_size; i++) {
  2597. buf_[i] = buf_[buf_spos_ + i];
  2598. }
  2599. }
  2600. buf_spos_ = 0;
  2601. buf_epos_ = remaining_size;
  2602. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  2603. for (size_t i = 0; i < n; i++) {
  2604. buf_[buf_epos_ + i] = data[i];
  2605. }
  2606. buf_epos_ += n;
  2607. }
  2608. void buf_erase(size_t size) { buf_spos_ += size; }
  2609. std::string buf_;
  2610. size_t buf_spos_ = 0;
  2611. size_t buf_epos_ = 0;
  2612. };
  2613. std::string random_string(size_t length) {
  2614. constexpr const char data[] =
  2615. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2616. thread_local auto engine([]() {
  2617. // std::random_device might actually be deterministic on some
  2618. // platforms, but due to lack of support in the c++ standard library,
  2619. // doing better requires either some ugly hacks or breaking portability.
  2620. std::random_device seed_gen;
  2621. // Request 128 bits of entropy for initialization
  2622. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  2623. return std::mt19937(seed_sequence);
  2624. }());
  2625. std::string result;
  2626. for (size_t i = 0; i < length; i++) {
  2627. result += data[engine() % (sizeof(data) - 1)];
  2628. }
  2629. return result;
  2630. }
  2631. std::string make_multipart_data_boundary() {
  2632. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  2633. }
  2634. bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  2635. auto valid = true;
  2636. for (size_t i = 0; i < boundary.size(); i++) {
  2637. auto c = boundary[i];
  2638. if (!std::isalnum(c) && c != '-' && c != '_') {
  2639. valid = false;
  2640. break;
  2641. }
  2642. }
  2643. return valid;
  2644. }
  2645. template <typename T>
  2646. std::string
  2647. serialize_multipart_formdata_item_begin(const T &item,
  2648. const std::string &boundary) {
  2649. std::string body = "--" + boundary + "\r\n";
  2650. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2651. if (!item.filename.empty()) {
  2652. body += "; filename=\"" + item.filename + "\"";
  2653. }
  2654. body += "\r\n";
  2655. if (!item.content_type.empty()) {
  2656. body += "Content-Type: " + item.content_type + "\r\n";
  2657. }
  2658. body += "\r\n";
  2659. return body;
  2660. }
  2661. std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  2662. std::string
  2663. serialize_multipart_formdata_finish(const std::string &boundary) {
  2664. return "--" + boundary + "--\r\n";
  2665. }
  2666. std::string
  2667. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  2668. return "multipart/form-data; boundary=" + boundary;
  2669. }
  2670. std::string
  2671. serialize_multipart_formdata(const UploadFormDataItems &items,
  2672. const std::string &boundary, bool finish = true) {
  2673. std::string body;
  2674. for (const auto &item : items) {
  2675. body += serialize_multipart_formdata_item_begin(item, boundary);
  2676. body += item.content + serialize_multipart_formdata_item_end();
  2677. }
  2678. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  2679. return body;
  2680. }
  2681. void coalesce_ranges(Ranges &ranges, size_t content_length) {
  2682. if (ranges.size() <= 1) return;
  2683. // Sort ranges by start position
  2684. std::sort(ranges.begin(), ranges.end(),
  2685. [](const Range &a, const Range &b) { return a.first < b.first; });
  2686. Ranges coalesced;
  2687. coalesced.reserve(ranges.size());
  2688. for (auto &r : ranges) {
  2689. auto first_pos = r.first;
  2690. auto last_pos = r.second;
  2691. // Handle special cases like in range_error
  2692. if (first_pos == -1 && last_pos == -1) {
  2693. first_pos = 0;
  2694. last_pos = static_cast<ssize_t>(content_length);
  2695. }
  2696. if (first_pos == -1) {
  2697. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  2698. last_pos = static_cast<ssize_t>(content_length) - 1;
  2699. }
  2700. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  2701. last_pos = static_cast<ssize_t>(content_length) - 1;
  2702. }
  2703. // Skip invalid ranges
  2704. if (!(0 <= first_pos && first_pos <= last_pos &&
  2705. last_pos < static_cast<ssize_t>(content_length))) {
  2706. continue;
  2707. }
  2708. // Coalesce with previous range if overlapping or adjacent (but not
  2709. // identical)
  2710. if (!coalesced.empty()) {
  2711. auto &prev = coalesced.back();
  2712. // Check if current range overlaps or is adjacent to previous range
  2713. // but don't coalesce identical ranges (allow duplicates)
  2714. if (first_pos <= prev.second + 1 &&
  2715. !(first_pos == prev.first && last_pos == prev.second)) {
  2716. // Extend the previous range
  2717. prev.second = (std::max)(prev.second, last_pos);
  2718. continue;
  2719. }
  2720. }
  2721. // Add new range
  2722. coalesced.emplace_back(first_pos, last_pos);
  2723. }
  2724. ranges = std::move(coalesced);
  2725. }
  2726. bool range_error(Request &req, Response &res) {
  2727. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  2728. ssize_t content_len = static_cast<ssize_t>(
  2729. res.content_length_ ? res.content_length_ : res.body.size());
  2730. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  2731. size_t overwrapping_count = 0;
  2732. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  2733. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  2734. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  2735. // Too many ranges
  2736. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  2737. for (auto &r : req.ranges) {
  2738. auto &first_pos = r.first;
  2739. auto &last_pos = r.second;
  2740. if (first_pos == -1 && last_pos == -1) {
  2741. first_pos = 0;
  2742. last_pos = content_len;
  2743. }
  2744. if (first_pos == -1) {
  2745. first_pos = content_len - last_pos;
  2746. last_pos = content_len - 1;
  2747. }
  2748. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  2749. // A client can limit the number of bytes requested without knowing the
  2750. // size of the selected representation. If the last-pos value is absent,
  2751. // or if the value is greater than or equal to the current length of the
  2752. // representation data, the byte range is interpreted as the remainder of
  2753. // the representation (i.e., the server replaces the value of last-pos
  2754. // with a value that is one less than the current length of the selected
  2755. // representation).
  2756. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  2757. if (last_pos == -1 || last_pos >= content_len) {
  2758. last_pos = content_len - 1;
  2759. }
  2760. // Range must be within content length
  2761. if (!(0 <= first_pos && first_pos <= last_pos &&
  2762. last_pos <= content_len - 1)) {
  2763. return true;
  2764. }
  2765. // Request must not have more than two overlapping ranges
  2766. for (const auto &processed_range : processed_ranges) {
  2767. if (!(last_pos < processed_range.first ||
  2768. first_pos > processed_range.second)) {
  2769. overwrapping_count++;
  2770. if (overwrapping_count > 2) { return true; }
  2771. break; // Only count once per range
  2772. }
  2773. }
  2774. processed_ranges.emplace_back(first_pos, last_pos);
  2775. }
  2776. // After validation, coalesce overlapping ranges as per RFC 9110
  2777. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  2778. }
  2779. return false;
  2780. }
  2781. std::pair<size_t, size_t>
  2782. get_range_offset_and_length(Range r, size_t content_length) {
  2783. assert(r.first != -1 && r.second != -1);
  2784. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  2785. assert(r.first <= r.second &&
  2786. r.second < static_cast<ssize_t>(content_length));
  2787. (void)(content_length);
  2788. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  2789. }
  2790. std::string make_content_range_header_field(
  2791. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  2792. auto st = offset_and_length.first;
  2793. auto ed = st + offset_and_length.second - 1;
  2794. std::string field = "bytes ";
  2795. field += std::to_string(st);
  2796. field += "-";
  2797. field += std::to_string(ed);
  2798. field += "/";
  2799. field += std::to_string(content_length);
  2800. return field;
  2801. }
  2802. template <typename SToken, typename CToken, typename Content>
  2803. bool process_multipart_ranges_data(const Request &req,
  2804. const std::string &boundary,
  2805. const std::string &content_type,
  2806. size_t content_length, SToken stoken,
  2807. CToken ctoken, Content content) {
  2808. for (size_t i = 0; i < req.ranges.size(); i++) {
  2809. ctoken("--");
  2810. stoken(boundary);
  2811. ctoken("\r\n");
  2812. if (!content_type.empty()) {
  2813. ctoken("Content-Type: ");
  2814. stoken(content_type);
  2815. ctoken("\r\n");
  2816. }
  2817. auto offset_and_length =
  2818. get_range_offset_and_length(req.ranges[i], content_length);
  2819. ctoken("Content-Range: ");
  2820. stoken(make_content_range_header_field(offset_and_length, content_length));
  2821. ctoken("\r\n");
  2822. ctoken("\r\n");
  2823. if (!content(offset_and_length.first, offset_and_length.second)) {
  2824. return false;
  2825. }
  2826. ctoken("\r\n");
  2827. }
  2828. ctoken("--");
  2829. stoken(boundary);
  2830. ctoken("--");
  2831. return true;
  2832. }
  2833. void make_multipart_ranges_data(const Request &req, Response &res,
  2834. const std::string &boundary,
  2835. const std::string &content_type,
  2836. size_t content_length,
  2837. std::string &data) {
  2838. process_multipart_ranges_data(
  2839. req, boundary, content_type, content_length,
  2840. [&](const std::string &token) { data += token; },
  2841. [&](const std::string &token) { data += token; },
  2842. [&](size_t offset, size_t length) {
  2843. assert(offset + length <= content_length);
  2844. data += res.body.substr(offset, length);
  2845. return true;
  2846. });
  2847. }
  2848. size_t get_multipart_ranges_data_length(const Request &req,
  2849. const std::string &boundary,
  2850. const std::string &content_type,
  2851. size_t content_length) {
  2852. size_t data_length = 0;
  2853. process_multipart_ranges_data(
  2854. req, boundary, content_type, content_length,
  2855. [&](const std::string &token) { data_length += token.size(); },
  2856. [&](const std::string &token) { data_length += token.size(); },
  2857. [&](size_t /*offset*/, size_t length) {
  2858. data_length += length;
  2859. return true;
  2860. });
  2861. return data_length;
  2862. }
  2863. template <typename T>
  2864. bool
  2865. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  2866. const std::string &boundary,
  2867. const std::string &content_type,
  2868. size_t content_length, const T &is_shutting_down) {
  2869. return process_multipart_ranges_data(
  2870. req, boundary, content_type, content_length,
  2871. [&](const std::string &token) { strm.write(token); },
  2872. [&](const std::string &token) { strm.write(token); },
  2873. [&](size_t offset, size_t length) {
  2874. return write_content(strm, res.content_provider_, offset, length,
  2875. is_shutting_down);
  2876. });
  2877. }
  2878. bool expect_content(const Request &req) {
  2879. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  2880. req.method == "DELETE") {
  2881. return true;
  2882. }
  2883. if (req.has_header("Content-Length") &&
  2884. req.get_header_value_u64("Content-Length") > 0) {
  2885. return true;
  2886. }
  2887. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  2888. return false;
  2889. }
  2890. bool has_crlf(const std::string &s) {
  2891. auto p = s.c_str();
  2892. while (*p) {
  2893. if (*p == '\r' || *p == '\n') { return true; }
  2894. p++;
  2895. }
  2896. return false;
  2897. }
  2898. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2899. std::string message_digest(const std::string &s, const EVP_MD *algo) {
  2900. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  2901. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  2902. unsigned int hash_length = 0;
  2903. unsigned char hash[EVP_MAX_MD_SIZE];
  2904. EVP_DigestInit_ex(context.get(), algo, nullptr);
  2905. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  2906. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  2907. std::stringstream ss;
  2908. for (auto i = 0u; i < hash_length; ++i) {
  2909. ss << std::hex << std::setw(2) << std::setfill('0')
  2910. << static_cast<unsigned int>(hash[i]);
  2911. }
  2912. return ss.str();
  2913. }
  2914. std::string MD5(const std::string &s) {
  2915. return message_digest(s, EVP_md5());
  2916. }
  2917. std::string SHA_256(const std::string &s) {
  2918. return message_digest(s, EVP_sha256());
  2919. }
  2920. std::string SHA_512(const std::string &s) {
  2921. return message_digest(s, EVP_sha512());
  2922. }
  2923. std::pair<std::string, std::string> make_digest_authentication_header(
  2924. const Request &req, const std::map<std::string, std::string> &auth,
  2925. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  2926. const std::string &password, bool is_proxy = false) {
  2927. std::string nc;
  2928. {
  2929. std::stringstream ss;
  2930. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  2931. nc = ss.str();
  2932. }
  2933. std::string qop;
  2934. if (auth.find("qop") != auth.end()) {
  2935. qop = auth.at("qop");
  2936. if (qop.find("auth-int") != std::string::npos) {
  2937. qop = "auth-int";
  2938. } else if (qop.find("auth") != std::string::npos) {
  2939. qop = "auth";
  2940. } else {
  2941. qop.clear();
  2942. }
  2943. }
  2944. std::string algo = "MD5";
  2945. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  2946. std::string response;
  2947. {
  2948. auto H = algo == "SHA-256" ? detail::SHA_256
  2949. : algo == "SHA-512" ? detail::SHA_512
  2950. : detail::MD5;
  2951. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  2952. auto A2 = req.method + ":" + req.path;
  2953. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  2954. if (qop.empty()) {
  2955. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  2956. } else {
  2957. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  2958. ":" + qop + ":" + H(A2));
  2959. }
  2960. }
  2961. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  2962. auto field = "Digest username=\"" + username + "\", realm=\"" +
  2963. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  2964. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  2965. (qop.empty() ? ", response=\""
  2966. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  2967. cnonce + "\", response=\"") +
  2968. response + "\"" +
  2969. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  2970. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2971. return std::make_pair(key, field);
  2972. }
  2973. bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) {
  2974. detail::set_nonblocking(sock, true);
  2975. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  2976. char buf[1];
  2977. return !SSL_peek(ssl, buf, 1) &&
  2978. SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
  2979. }
  2980. #ifdef _WIN32
  2981. // NOTE: This code came up with the following stackoverflow post:
  2982. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  2983. bool load_system_certs_on_windows(X509_STORE *store) {
  2984. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  2985. if (!hStore) { return false; }
  2986. auto result = false;
  2987. PCCERT_CONTEXT pContext = NULL;
  2988. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  2989. nullptr) {
  2990. auto encoded_cert =
  2991. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  2992. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  2993. if (x509) {
  2994. X509_STORE_add_cert(store, x509);
  2995. X509_free(x509);
  2996. result = true;
  2997. }
  2998. }
  2999. CertFreeCertificateContext(pContext);
  3000. CertCloseStore(hStore, 0);
  3001. return result;
  3002. }
  3003. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  3004. template <typename T>
  3005. using CFObjectPtr =
  3006. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  3007. void cf_object_ptr_deleter(CFTypeRef obj) {
  3008. if (obj) { CFRelease(obj); }
  3009. }
  3010. bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  3011. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  3012. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  3013. kCFBooleanTrue};
  3014. CFObjectPtr<CFDictionaryRef> query(
  3015. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  3016. sizeof(keys) / sizeof(keys[0]),
  3017. &kCFTypeDictionaryKeyCallBacks,
  3018. &kCFTypeDictionaryValueCallBacks),
  3019. cf_object_ptr_deleter);
  3020. if (!query) { return false; }
  3021. CFTypeRef security_items = nullptr;
  3022. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  3023. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  3024. return false;
  3025. }
  3026. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  3027. return true;
  3028. }
  3029. bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  3030. CFArrayRef root_security_items = nullptr;
  3031. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  3032. return false;
  3033. }
  3034. certs.reset(root_security_items);
  3035. return true;
  3036. }
  3037. bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  3038. auto result = false;
  3039. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  3040. const auto cert = reinterpret_cast<const __SecCertificate *>(
  3041. CFArrayGetValueAtIndex(certs, i));
  3042. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  3043. CFDataRef cert_data = nullptr;
  3044. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  3045. errSecSuccess) {
  3046. continue;
  3047. }
  3048. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  3049. auto encoded_cert = static_cast<const unsigned char *>(
  3050. CFDataGetBytePtr(cert_data_ptr.get()));
  3051. auto x509 =
  3052. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  3053. if (x509) {
  3054. X509_STORE_add_cert(store, x509);
  3055. X509_free(x509);
  3056. result = true;
  3057. }
  3058. }
  3059. return result;
  3060. }
  3061. bool load_system_certs_on_macos(X509_STORE *store) {
  3062. auto result = false;
  3063. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  3064. if (retrieve_certs_from_keychain(certs) && certs) {
  3065. result = add_certs_to_x509_store(certs.get(), store);
  3066. }
  3067. if (retrieve_root_certs_from_keychain(certs) && certs) {
  3068. result = add_certs_to_x509_store(certs.get(), store) || result;
  3069. }
  3070. return result;
  3071. }
  3072. #endif // _WIN32
  3073. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  3074. #ifdef _WIN32
  3075. class WSInit {
  3076. public:
  3077. WSInit() {
  3078. WSADATA wsaData;
  3079. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  3080. }
  3081. ~WSInit() {
  3082. if (is_valid_) WSACleanup();
  3083. }
  3084. bool is_valid_ = false;
  3085. };
  3086. static WSInit wsinit_;
  3087. #endif
  3088. bool parse_www_authenticate(const Response &res,
  3089. std::map<std::string, std::string> &auth,
  3090. bool is_proxy) {
  3091. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  3092. if (res.has_header(auth_key)) {
  3093. thread_local auto re =
  3094. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  3095. auto s = res.get_header_value(auth_key);
  3096. auto pos = s.find(' ');
  3097. if (pos != std::string::npos) {
  3098. auto type = s.substr(0, pos);
  3099. if (type == "Basic") {
  3100. return false;
  3101. } else if (type == "Digest") {
  3102. s = s.substr(pos + 1);
  3103. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  3104. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  3105. const auto &m = *i;
  3106. auto key = s.substr(static_cast<size_t>(m.position(1)),
  3107. static_cast<size_t>(m.length(1)));
  3108. auto val = m.length(2) > 0
  3109. ? s.substr(static_cast<size_t>(m.position(2)),
  3110. static_cast<size_t>(m.length(2)))
  3111. : s.substr(static_cast<size_t>(m.position(3)),
  3112. static_cast<size_t>(m.length(3)));
  3113. auth[key] = val;
  3114. }
  3115. return true;
  3116. }
  3117. }
  3118. }
  3119. return false;
  3120. }
  3121. class ContentProviderAdapter {
  3122. public:
  3123. explicit ContentProviderAdapter(
  3124. ContentProviderWithoutLength &&content_provider)
  3125. : content_provider_(content_provider) {}
  3126. bool operator()(size_t offset, size_t, DataSink &sink) {
  3127. return content_provider_(offset, sink);
  3128. }
  3129. private:
  3130. ContentProviderWithoutLength content_provider_;
  3131. };
  3132. } // namespace detail
  3133. std::string hosted_at(const std::string &hostname) {
  3134. std::vector<std::string> addrs;
  3135. hosted_at(hostname, addrs);
  3136. if (addrs.empty()) { return std::string(); }
  3137. return addrs[0];
  3138. }
  3139. void hosted_at(const std::string &hostname,
  3140. std::vector<std::string> &addrs) {
  3141. struct addrinfo hints;
  3142. struct addrinfo *result;
  3143. memset(&hints, 0, sizeof(struct addrinfo));
  3144. hints.ai_family = AF_UNSPEC;
  3145. hints.ai_socktype = SOCK_STREAM;
  3146. hints.ai_protocol = 0;
  3147. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  3148. &result, 0)) {
  3149. #if defined __linux__ && !defined __ANDROID__
  3150. res_init();
  3151. #endif
  3152. return;
  3153. }
  3154. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  3155. for (auto rp = result; rp; rp = rp->ai_next) {
  3156. const auto &addr =
  3157. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  3158. std::string ip;
  3159. auto dummy = -1;
  3160. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  3161. dummy)) {
  3162. addrs.push_back(ip);
  3163. }
  3164. }
  3165. }
  3166. std::string encode_uri_component(const std::string &value) {
  3167. std::ostringstream escaped;
  3168. escaped.fill('0');
  3169. escaped << std::hex;
  3170. for (auto c : value) {
  3171. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  3172. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  3173. c == ')') {
  3174. escaped << c;
  3175. } else {
  3176. escaped << std::uppercase;
  3177. escaped << '%' << std::setw(2)
  3178. << static_cast<int>(static_cast<unsigned char>(c));
  3179. escaped << std::nouppercase;
  3180. }
  3181. }
  3182. return escaped.str();
  3183. }
  3184. std::string encode_uri(const std::string &value) {
  3185. std::ostringstream escaped;
  3186. escaped.fill('0');
  3187. escaped << std::hex;
  3188. for (auto c : value) {
  3189. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  3190. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  3191. c == ')' || c == ';' || c == '/' || c == '?' || c == ':' || c == '@' ||
  3192. c == '&' || c == '=' || c == '+' || c == '$' || c == ',' || c == '#') {
  3193. escaped << c;
  3194. } else {
  3195. escaped << std::uppercase;
  3196. escaped << '%' << std::setw(2)
  3197. << static_cast<int>(static_cast<unsigned char>(c));
  3198. escaped << std::nouppercase;
  3199. }
  3200. }
  3201. return escaped.str();
  3202. }
  3203. std::string decode_uri_component(const std::string &value) {
  3204. std::string result;
  3205. for (size_t i = 0; i < value.size(); i++) {
  3206. if (value[i] == '%' && i + 2 < value.size()) {
  3207. auto val = 0;
  3208. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  3209. result += static_cast<char>(val);
  3210. i += 2;
  3211. } else {
  3212. result += value[i];
  3213. }
  3214. } else {
  3215. result += value[i];
  3216. }
  3217. }
  3218. return result;
  3219. }
  3220. std::string decode_uri(const std::string &value) {
  3221. std::string result;
  3222. for (size_t i = 0; i < value.size(); i++) {
  3223. if (value[i] == '%' && i + 2 < value.size()) {
  3224. auto val = 0;
  3225. if (detail::from_hex_to_i(value, i + 1, 2, val)) {
  3226. result += static_cast<char>(val);
  3227. i += 2;
  3228. } else {
  3229. result += value[i];
  3230. }
  3231. } else {
  3232. result += value[i];
  3233. }
  3234. }
  3235. return result;
  3236. }
  3237. std::string encode_path_component(const std::string &component) {
  3238. std::string result;
  3239. result.reserve(component.size() * 3);
  3240. for (size_t i = 0; i < component.size(); i++) {
  3241. auto c = static_cast<unsigned char>(component[i]);
  3242. // Unreserved characters per RFC 3986: ALPHA / DIGIT / "-" / "." / "_" / "~"
  3243. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  3244. result += static_cast<char>(c);
  3245. }
  3246. // Path-safe sub-delimiters: "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" /
  3247. // "," / ";" / "="
  3248. else if (c == '!' || c == '$' || c == '&' || c == '\'' || c == '(' ||
  3249. c == ')' || c == '*' || c == '+' || c == ',' || c == ';' ||
  3250. c == '=') {
  3251. result += static_cast<char>(c);
  3252. }
  3253. // Colon is allowed in path segments except first segment
  3254. else if (c == ':') {
  3255. result += static_cast<char>(c);
  3256. }
  3257. // @ is allowed in path
  3258. else if (c == '@') {
  3259. result += static_cast<char>(c);
  3260. } else {
  3261. result += '%';
  3262. char hex[3];
  3263. snprintf(hex, sizeof(hex), "%02X", c);
  3264. result.append(hex, 2);
  3265. }
  3266. }
  3267. return result;
  3268. }
  3269. std::string decode_path_component(const std::string &component) {
  3270. std::string result;
  3271. result.reserve(component.size());
  3272. for (size_t i = 0; i < component.size(); i++) {
  3273. if (component[i] == '%' && i + 1 < component.size()) {
  3274. if (component[i + 1] == 'u') {
  3275. // Unicode %uXXXX encoding
  3276. auto val = 0;
  3277. if (detail::from_hex_to_i(component, i + 2, 4, val)) {
  3278. // 4 digits Unicode codes
  3279. char buff[4];
  3280. size_t len = detail::to_utf8(val, buff);
  3281. if (len > 0) { result.append(buff, len); }
  3282. i += 5; // 'u0000'
  3283. } else {
  3284. result += component[i];
  3285. }
  3286. } else {
  3287. // Standard %XX encoding
  3288. auto val = 0;
  3289. if (detail::from_hex_to_i(component, i + 1, 2, val)) {
  3290. // 2 digits hex codes
  3291. result += static_cast<char>(val);
  3292. i += 2; // 'XX'
  3293. } else {
  3294. result += component[i];
  3295. }
  3296. }
  3297. } else {
  3298. result += component[i];
  3299. }
  3300. }
  3301. return result;
  3302. }
  3303. std::string encode_query_component(const std::string &component,
  3304. bool space_as_plus) {
  3305. std::string result;
  3306. result.reserve(component.size() * 3);
  3307. for (size_t i = 0; i < component.size(); i++) {
  3308. auto c = static_cast<unsigned char>(component[i]);
  3309. // Unreserved characters per RFC 3986
  3310. if (std::isalnum(c) || c == '-' || c == '.' || c == '_' || c == '~') {
  3311. result += static_cast<char>(c);
  3312. }
  3313. // Space handling
  3314. else if (c == ' ') {
  3315. if (space_as_plus) {
  3316. result += '+';
  3317. } else {
  3318. result += "%20";
  3319. }
  3320. }
  3321. // Plus sign handling
  3322. else if (c == '+') {
  3323. if (space_as_plus) {
  3324. result += "%2B";
  3325. } else {
  3326. result += static_cast<char>(c);
  3327. }
  3328. }
  3329. // Query-safe sub-delimiters (excluding & and = which are query delimiters)
  3330. else if (c == '!' || c == '$' || c == '\'' || c == '(' || c == ')' ||
  3331. c == '*' || c == ',' || c == ';') {
  3332. result += static_cast<char>(c);
  3333. }
  3334. // Colon and @ are allowed in query
  3335. else if (c == ':' || c == '@') {
  3336. result += static_cast<char>(c);
  3337. }
  3338. // Forward slash is allowed in query values
  3339. else if (c == '/') {
  3340. result += static_cast<char>(c);
  3341. }
  3342. // Question mark is allowed in query values (after first ?)
  3343. else if (c == '?') {
  3344. result += static_cast<char>(c);
  3345. } else {
  3346. result += '%';
  3347. char hex[3];
  3348. snprintf(hex, sizeof(hex), "%02X", c);
  3349. result.append(hex, 2);
  3350. }
  3351. }
  3352. return result;
  3353. }
  3354. std::string decode_query_component(const std::string &component,
  3355. bool plus_as_space) {
  3356. std::string result;
  3357. result.reserve(component.size());
  3358. for (size_t i = 0; i < component.size(); i++) {
  3359. if (component[i] == '%' && i + 2 < component.size()) {
  3360. std::string hex = component.substr(i + 1, 2);
  3361. char *end;
  3362. unsigned long value = std::strtoul(hex.c_str(), &end, 16);
  3363. if (end == hex.c_str() + 2) {
  3364. result += static_cast<char>(value);
  3365. i += 2;
  3366. } else {
  3367. result += component[i];
  3368. }
  3369. } else if (component[i] == '+' && plus_as_space) {
  3370. result += ' '; // + becomes space in form-urlencoded
  3371. } else {
  3372. result += component[i];
  3373. }
  3374. }
  3375. return result;
  3376. }
  3377. std::string append_query_params(const std::string &path,
  3378. const Params &params) {
  3379. std::string path_with_query = path;
  3380. thread_local const std::regex re("[^?]+\\?.*");
  3381. auto delm = std::regex_match(path, re) ? '&' : '?';
  3382. path_with_query += delm + detail::params_to_query_str(params);
  3383. return path_with_query;
  3384. }
  3385. // Header utilities
  3386. std::pair<std::string, std::string>
  3387. make_range_header(const Ranges &ranges) {
  3388. std::string field = "bytes=";
  3389. auto i = 0;
  3390. for (const auto &r : ranges) {
  3391. if (i != 0) { field += ", "; }
  3392. if (r.first != -1) { field += std::to_string(r.first); }
  3393. field += '-';
  3394. if (r.second != -1) { field += std::to_string(r.second); }
  3395. i++;
  3396. }
  3397. return std::make_pair("Range", std::move(field));
  3398. }
  3399. std::pair<std::string, std::string>
  3400. make_basic_authentication_header(const std::string &username,
  3401. const std::string &password, bool is_proxy) {
  3402. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  3403. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  3404. return std::make_pair(key, std::move(field));
  3405. }
  3406. std::pair<std::string, std::string>
  3407. make_bearer_token_authentication_header(const std::string &token,
  3408. bool is_proxy = false) {
  3409. auto field = "Bearer " + token;
  3410. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  3411. return std::make_pair(key, std::move(field));
  3412. }
  3413. // Request implementation
  3414. bool Request::has_header(const std::string &key) const {
  3415. return detail::has_header(headers, key);
  3416. }
  3417. std::string Request::get_header_value(const std::string &key,
  3418. const char *def, size_t id) const {
  3419. return detail::get_header_value(headers, key, def, id);
  3420. }
  3421. size_t Request::get_header_value_count(const std::string &key) const {
  3422. auto r = headers.equal_range(key);
  3423. return static_cast<size_t>(std::distance(r.first, r.second));
  3424. }
  3425. void Request::set_header(const std::string &key,
  3426. const std::string &val) {
  3427. if (detail::fields::is_field_name(key) &&
  3428. detail::fields::is_field_value(val)) {
  3429. headers.emplace(key, val);
  3430. }
  3431. }
  3432. bool Request::has_trailer(const std::string &key) const {
  3433. return trailers.find(key) != trailers.end();
  3434. }
  3435. std::string Request::get_trailer_value(const std::string &key,
  3436. size_t id) const {
  3437. auto rng = trailers.equal_range(key);
  3438. auto it = rng.first;
  3439. std::advance(it, static_cast<ssize_t>(id));
  3440. if (it != rng.second) { return it->second; }
  3441. return std::string();
  3442. }
  3443. size_t Request::get_trailer_value_count(const std::string &key) const {
  3444. auto r = trailers.equal_range(key);
  3445. return static_cast<size_t>(std::distance(r.first, r.second));
  3446. }
  3447. bool Request::has_param(const std::string &key) const {
  3448. return params.find(key) != params.end();
  3449. }
  3450. std::string Request::get_param_value(const std::string &key,
  3451. size_t id) const {
  3452. auto rng = params.equal_range(key);
  3453. auto it = rng.first;
  3454. std::advance(it, static_cast<ssize_t>(id));
  3455. if (it != rng.second) { return it->second; }
  3456. return std::string();
  3457. }
  3458. size_t Request::get_param_value_count(const std::string &key) const {
  3459. auto r = params.equal_range(key);
  3460. return static_cast<size_t>(std::distance(r.first, r.second));
  3461. }
  3462. bool Request::is_multipart_form_data() const {
  3463. const auto &content_type = get_header_value("Content-Type");
  3464. return !content_type.rfind("multipart/form-data", 0);
  3465. }
  3466. // Multipart FormData implementation
  3467. std::string MultipartFormData::get_field(const std::string &key,
  3468. size_t id) const {
  3469. auto rng = fields.equal_range(key);
  3470. auto it = rng.first;
  3471. std::advance(it, static_cast<ssize_t>(id));
  3472. if (it != rng.second) { return it->second.content; }
  3473. return std::string();
  3474. }
  3475. std::vector<std::string>
  3476. MultipartFormData::get_fields(const std::string &key) const {
  3477. std::vector<std::string> values;
  3478. auto rng = fields.equal_range(key);
  3479. for (auto it = rng.first; it != rng.second; it++) {
  3480. values.push_back(it->second.content);
  3481. }
  3482. return values;
  3483. }
  3484. bool MultipartFormData::has_field(const std::string &key) const {
  3485. return fields.find(key) != fields.end();
  3486. }
  3487. size_t MultipartFormData::get_field_count(const std::string &key) const {
  3488. auto r = fields.equal_range(key);
  3489. return static_cast<size_t>(std::distance(r.first, r.second));
  3490. }
  3491. FormData MultipartFormData::get_file(const std::string &key,
  3492. size_t id) const {
  3493. auto rng = files.equal_range(key);
  3494. auto it = rng.first;
  3495. std::advance(it, static_cast<ssize_t>(id));
  3496. if (it != rng.second) { return it->second; }
  3497. return FormData();
  3498. }
  3499. std::vector<FormData>
  3500. MultipartFormData::get_files(const std::string &key) const {
  3501. std::vector<FormData> values;
  3502. auto rng = files.equal_range(key);
  3503. for (auto it = rng.first; it != rng.second; it++) {
  3504. values.push_back(it->second);
  3505. }
  3506. return values;
  3507. }
  3508. bool MultipartFormData::has_file(const std::string &key) const {
  3509. return files.find(key) != files.end();
  3510. }
  3511. size_t MultipartFormData::get_file_count(const std::string &key) const {
  3512. auto r = files.equal_range(key);
  3513. return static_cast<size_t>(std::distance(r.first, r.second));
  3514. }
  3515. // Response implementation
  3516. bool Response::has_header(const std::string &key) const {
  3517. return headers.find(key) != headers.end();
  3518. }
  3519. std::string Response::get_header_value(const std::string &key,
  3520. const char *def,
  3521. size_t id) const {
  3522. return detail::get_header_value(headers, key, def, id);
  3523. }
  3524. size_t Response::get_header_value_count(const std::string &key) const {
  3525. auto r = headers.equal_range(key);
  3526. return static_cast<size_t>(std::distance(r.first, r.second));
  3527. }
  3528. void Response::set_header(const std::string &key,
  3529. const std::string &val) {
  3530. if (detail::fields::is_field_name(key) &&
  3531. detail::fields::is_field_value(val)) {
  3532. headers.emplace(key, val);
  3533. }
  3534. }
  3535. bool Response::has_trailer(const std::string &key) const {
  3536. return trailers.find(key) != trailers.end();
  3537. }
  3538. std::string Response::get_trailer_value(const std::string &key,
  3539. size_t id) const {
  3540. auto rng = trailers.equal_range(key);
  3541. auto it = rng.first;
  3542. std::advance(it, static_cast<ssize_t>(id));
  3543. if (it != rng.second) { return it->second; }
  3544. return std::string();
  3545. }
  3546. size_t Response::get_trailer_value_count(const std::string &key) const {
  3547. auto r = trailers.equal_range(key);
  3548. return static_cast<size_t>(std::distance(r.first, r.second));
  3549. }
  3550. void Response::set_redirect(const std::string &url, int stat) {
  3551. if (detail::fields::is_field_value(url)) {
  3552. set_header("Location", url);
  3553. if (300 <= stat && stat < 400) {
  3554. this->status = stat;
  3555. } else {
  3556. this->status = StatusCode::Found_302;
  3557. }
  3558. }
  3559. }
  3560. void Response::set_content(const char *s, size_t n,
  3561. const std::string &content_type) {
  3562. body.assign(s, n);
  3563. auto rng = headers.equal_range("Content-Type");
  3564. headers.erase(rng.first, rng.second);
  3565. set_header("Content-Type", content_type);
  3566. }
  3567. void Response::set_content(const std::string &s,
  3568. const std::string &content_type) {
  3569. set_content(s.data(), s.size(), content_type);
  3570. }
  3571. void Response::set_content(std::string &&s,
  3572. const std::string &content_type) {
  3573. body = std::move(s);
  3574. auto rng = headers.equal_range("Content-Type");
  3575. headers.erase(rng.first, rng.second);
  3576. set_header("Content-Type", content_type);
  3577. }
  3578. void Response::set_content_provider(
  3579. size_t in_length, const std::string &content_type, ContentProvider provider,
  3580. ContentProviderResourceReleaser resource_releaser) {
  3581. set_header("Content-Type", content_type);
  3582. content_length_ = in_length;
  3583. if (in_length > 0) { content_provider_ = std::move(provider); }
  3584. content_provider_resource_releaser_ = std::move(resource_releaser);
  3585. is_chunked_content_provider_ = false;
  3586. }
  3587. void Response::set_content_provider(
  3588. const std::string &content_type, ContentProviderWithoutLength provider,
  3589. ContentProviderResourceReleaser resource_releaser) {
  3590. set_header("Content-Type", content_type);
  3591. content_length_ = 0;
  3592. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  3593. content_provider_resource_releaser_ = std::move(resource_releaser);
  3594. is_chunked_content_provider_ = false;
  3595. }
  3596. void Response::set_chunked_content_provider(
  3597. const std::string &content_type, ContentProviderWithoutLength provider,
  3598. ContentProviderResourceReleaser resource_releaser) {
  3599. set_header("Content-Type", content_type);
  3600. content_length_ = 0;
  3601. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  3602. content_provider_resource_releaser_ = std::move(resource_releaser);
  3603. is_chunked_content_provider_ = true;
  3604. }
  3605. void Response::set_file_content(const std::string &path,
  3606. const std::string &content_type) {
  3607. file_content_path_ = path;
  3608. file_content_content_type_ = content_type;
  3609. }
  3610. void Response::set_file_content(const std::string &path) {
  3611. file_content_path_ = path;
  3612. }
  3613. // Result implementation
  3614. bool Result::has_request_header(const std::string &key) const {
  3615. return request_headers_.find(key) != request_headers_.end();
  3616. }
  3617. std::string Result::get_request_header_value(const std::string &key,
  3618. const char *def,
  3619. size_t id) const {
  3620. return detail::get_header_value(request_headers_, key, def, id);
  3621. }
  3622. size_t
  3623. Result::get_request_header_value_count(const std::string &key) const {
  3624. auto r = request_headers_.equal_range(key);
  3625. return static_cast<size_t>(std::distance(r.first, r.second));
  3626. }
  3627. // Stream implementation
  3628. ssize_t Stream::write(const char *ptr) {
  3629. return write(ptr, strlen(ptr));
  3630. }
  3631. ssize_t Stream::write(const std::string &s) {
  3632. return write(s.data(), s.size());
  3633. }
  3634. namespace detail {
  3635. void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  3636. time_t timeout_sec, time_t timeout_usec,
  3637. time_t &actual_timeout_sec,
  3638. time_t &actual_timeout_usec) {
  3639. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  3640. auto actual_timeout_msec =
  3641. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  3642. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  3643. actual_timeout_sec = actual_timeout_msec / 1000;
  3644. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  3645. }
  3646. // Socket stream implementation
  3647. SocketStream::SocketStream(
  3648. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  3649. time_t write_timeout_sec, time_t write_timeout_usec,
  3650. time_t max_timeout_msec,
  3651. std::chrono::time_point<std::chrono::steady_clock> start_time)
  3652. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  3653. read_timeout_usec_(read_timeout_usec),
  3654. write_timeout_sec_(write_timeout_sec),
  3655. write_timeout_usec_(write_timeout_usec),
  3656. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  3657. read_buff_(read_buff_size_, 0) {}
  3658. SocketStream::~SocketStream() = default;
  3659. bool SocketStream::is_readable() const {
  3660. return read_buff_off_ < read_buff_content_size_;
  3661. }
  3662. bool SocketStream::wait_readable() const {
  3663. if (max_timeout_msec_ <= 0) {
  3664. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  3665. }
  3666. time_t read_timeout_sec;
  3667. time_t read_timeout_usec;
  3668. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  3669. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  3670. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  3671. }
  3672. bool SocketStream::wait_writable() const {
  3673. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  3674. is_socket_alive(sock_);
  3675. }
  3676. ssize_t SocketStream::read(char *ptr, size_t size) {
  3677. #ifdef _WIN32
  3678. size =
  3679. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  3680. #else
  3681. size = (std::min)(size,
  3682. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  3683. #endif
  3684. if (read_buff_off_ < read_buff_content_size_) {
  3685. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  3686. if (size <= remaining_size) {
  3687. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  3688. read_buff_off_ += size;
  3689. return static_cast<ssize_t>(size);
  3690. } else {
  3691. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  3692. read_buff_off_ += remaining_size;
  3693. return static_cast<ssize_t>(remaining_size);
  3694. }
  3695. }
  3696. if (!wait_readable()) { return -1; }
  3697. read_buff_off_ = 0;
  3698. read_buff_content_size_ = 0;
  3699. if (size < read_buff_size_) {
  3700. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  3701. CPPHTTPLIB_RECV_FLAGS);
  3702. if (n <= 0) {
  3703. return n;
  3704. } else if (n <= static_cast<ssize_t>(size)) {
  3705. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  3706. return n;
  3707. } else {
  3708. memcpy(ptr, read_buff_.data(), size);
  3709. read_buff_off_ = size;
  3710. read_buff_content_size_ = static_cast<size_t>(n);
  3711. return static_cast<ssize_t>(size);
  3712. }
  3713. } else {
  3714. return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  3715. }
  3716. }
  3717. ssize_t SocketStream::write(const char *ptr, size_t size) {
  3718. if (!wait_writable()) { return -1; }
  3719. #if defined(_WIN32) && !defined(_WIN64)
  3720. size =
  3721. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  3722. #endif
  3723. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  3724. }
  3725. void SocketStream::get_remote_ip_and_port(std::string &ip,
  3726. int &port) const {
  3727. return detail::get_remote_ip_and_port(sock_, ip, port);
  3728. }
  3729. void SocketStream::get_local_ip_and_port(std::string &ip,
  3730. int &port) const {
  3731. return detail::get_local_ip_and_port(sock_, ip, port);
  3732. }
  3733. socket_t SocketStream::socket() const { return sock_; }
  3734. time_t SocketStream::duration() const {
  3735. return std::chrono::duration_cast<std::chrono::milliseconds>(
  3736. std::chrono::steady_clock::now() - start_time_)
  3737. .count();
  3738. }
  3739. // Buffer stream implementation
  3740. bool BufferStream::is_readable() const { return true; }
  3741. bool BufferStream::wait_readable() const { return true; }
  3742. bool BufferStream::wait_writable() const { return true; }
  3743. ssize_t BufferStream::read(char *ptr, size_t size) {
  3744. #if defined(_MSC_VER) && _MSC_VER < 1910
  3745. auto len_read = buffer._Copy_s(ptr, size, size, position);
  3746. #else
  3747. auto len_read = buffer.copy(ptr, size, position);
  3748. #endif
  3749. position += static_cast<size_t>(len_read);
  3750. return static_cast<ssize_t>(len_read);
  3751. }
  3752. ssize_t BufferStream::write(const char *ptr, size_t size) {
  3753. buffer.append(ptr, size);
  3754. return static_cast<ssize_t>(size);
  3755. }
  3756. void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  3757. int & /*port*/) const {}
  3758. void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  3759. int & /*port*/) const {}
  3760. socket_t BufferStream::socket() const { return 0; }
  3761. time_t BufferStream::duration() const { return 0; }
  3762. const std::string &BufferStream::get_buffer() const { return buffer; }
  3763. PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  3764. : MatcherBase(pattern) {
  3765. constexpr const char marker[] = "/:";
  3766. // One past the last ending position of a path param substring
  3767. std::size_t last_param_end = 0;
  3768. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3769. // Needed to ensure that parameter names are unique during matcher
  3770. // construction
  3771. // If exceptions are disabled, only last duplicate path
  3772. // parameter will be set
  3773. std::unordered_set<std::string> param_name_set;
  3774. #endif
  3775. while (true) {
  3776. const auto marker_pos = pattern.find(
  3777. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  3778. if (marker_pos == std::string::npos) { break; }
  3779. static_fragments_.push_back(
  3780. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  3781. const auto param_name_start = marker_pos + str_len(marker);
  3782. auto sep_pos = pattern.find(separator, param_name_start);
  3783. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  3784. auto param_name =
  3785. pattern.substr(param_name_start, sep_pos - param_name_start);
  3786. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3787. if (param_name_set.find(param_name) != param_name_set.cend()) {
  3788. std::string msg = "Encountered path parameter '" + param_name +
  3789. "' multiple times in route pattern '" + pattern + "'.";
  3790. throw std::invalid_argument(msg);
  3791. }
  3792. #endif
  3793. param_names_.push_back(std::move(param_name));
  3794. last_param_end = sep_pos + 1;
  3795. }
  3796. if (last_param_end < pattern.length()) {
  3797. static_fragments_.push_back(pattern.substr(last_param_end));
  3798. }
  3799. }
  3800. bool PathParamsMatcher::match(Request &request) const {
  3801. request.matches = std::smatch();
  3802. request.path_params.clear();
  3803. request.path_params.reserve(param_names_.size());
  3804. // One past the position at which the path matched the pattern last time
  3805. std::size_t starting_pos = 0;
  3806. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  3807. const auto &fragment = static_fragments_[i];
  3808. if (starting_pos + fragment.length() > request.path.length()) {
  3809. return false;
  3810. }
  3811. // Avoid unnecessary allocation by using strncmp instead of substr +
  3812. // comparison
  3813. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  3814. fragment.length()) != 0) {
  3815. return false;
  3816. }
  3817. starting_pos += fragment.length();
  3818. // Should only happen when we have a static fragment after a param
  3819. // Example: '/users/:id/subscriptions'
  3820. // The 'subscriptions' fragment here does not have a corresponding param
  3821. if (i >= param_names_.size()) { continue; }
  3822. auto sep_pos = request.path.find(separator, starting_pos);
  3823. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  3824. const auto &param_name = param_names_[i];
  3825. request.path_params.emplace(
  3826. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  3827. // Mark everything up to '/' as matched
  3828. starting_pos = sep_pos + 1;
  3829. }
  3830. // Returns false if the path is longer than the pattern
  3831. return starting_pos >= request.path.length();
  3832. }
  3833. bool RegexMatcher::match(Request &request) const {
  3834. request.path_params.clear();
  3835. return std::regex_match(request.path, request.matches, regex_);
  3836. }
  3837. std::string make_host_and_port_string(const std::string &host, int port,
  3838. bool is_ssl) {
  3839. std::string result;
  3840. // Enclose IPv6 address in brackets (but not if already enclosed)
  3841. if (host.find(':') == std::string::npos ||
  3842. (!host.empty() && host[0] == '[')) {
  3843. // IPv4, hostname, or already bracketed IPv6
  3844. result = host;
  3845. } else {
  3846. // IPv6 address without brackets
  3847. result = "[" + host + "]";
  3848. }
  3849. // Append port if not default
  3850. if ((!is_ssl && port == 80) || (is_ssl && port == 443)) {
  3851. ; // do nothing
  3852. } else {
  3853. result += ":" + std::to_string(port);
  3854. }
  3855. return result;
  3856. }
  3857. } // namespace detail
  3858. // HTTP server implementation
  3859. Server::Server()
  3860. : new_task_queue(
  3861. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  3862. #ifndef _WIN32
  3863. signal(SIGPIPE, SIG_IGN);
  3864. #endif
  3865. }
  3866. Server::~Server() = default;
  3867. std::unique_ptr<detail::MatcherBase>
  3868. Server::make_matcher(const std::string &pattern) {
  3869. if (pattern.find("/:") != std::string::npos) {
  3870. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  3871. } else {
  3872. return detail::make_unique<detail::RegexMatcher>(pattern);
  3873. }
  3874. }
  3875. Server &Server::Get(const std::string &pattern, Handler handler) {
  3876. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  3877. return *this;
  3878. }
  3879. Server &Server::Post(const std::string &pattern, Handler handler) {
  3880. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  3881. return *this;
  3882. }
  3883. Server &Server::Post(const std::string &pattern,
  3884. HandlerWithContentReader handler) {
  3885. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  3886. std::move(handler));
  3887. return *this;
  3888. }
  3889. Server &Server::Put(const std::string &pattern, Handler handler) {
  3890. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  3891. return *this;
  3892. }
  3893. Server &Server::Put(const std::string &pattern,
  3894. HandlerWithContentReader handler) {
  3895. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  3896. std::move(handler));
  3897. return *this;
  3898. }
  3899. Server &Server::Patch(const std::string &pattern, Handler handler) {
  3900. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  3901. return *this;
  3902. }
  3903. Server &Server::Patch(const std::string &pattern,
  3904. HandlerWithContentReader handler) {
  3905. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  3906. std::move(handler));
  3907. return *this;
  3908. }
  3909. Server &Server::Delete(const std::string &pattern, Handler handler) {
  3910. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  3911. return *this;
  3912. }
  3913. Server &Server::Delete(const std::string &pattern,
  3914. HandlerWithContentReader handler) {
  3915. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  3916. std::move(handler));
  3917. return *this;
  3918. }
  3919. Server &Server::Options(const std::string &pattern, Handler handler) {
  3920. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  3921. return *this;
  3922. }
  3923. bool Server::set_base_dir(const std::string &dir,
  3924. const std::string &mount_point) {
  3925. return set_mount_point(mount_point, dir);
  3926. }
  3927. bool Server::set_mount_point(const std::string &mount_point,
  3928. const std::string &dir, Headers headers) {
  3929. detail::FileStat stat(dir);
  3930. if (stat.is_dir()) {
  3931. std::string mnt = !mount_point.empty() ? mount_point : "/";
  3932. if (!mnt.empty() && mnt[0] == '/') {
  3933. base_dirs_.push_back({mnt, dir, std::move(headers)});
  3934. return true;
  3935. }
  3936. }
  3937. return false;
  3938. }
  3939. bool Server::remove_mount_point(const std::string &mount_point) {
  3940. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  3941. if (it->mount_point == mount_point) {
  3942. base_dirs_.erase(it);
  3943. return true;
  3944. }
  3945. }
  3946. return false;
  3947. }
  3948. Server &
  3949. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  3950. const std::string &mime) {
  3951. file_extension_and_mimetype_map_[ext] = mime;
  3952. return *this;
  3953. }
  3954. Server &Server::set_default_file_mimetype(const std::string &mime) {
  3955. default_file_mimetype_ = mime;
  3956. return *this;
  3957. }
  3958. Server &Server::set_file_request_handler(Handler handler) {
  3959. file_request_handler_ = std::move(handler);
  3960. return *this;
  3961. }
  3962. Server &Server::set_error_handler_core(HandlerWithResponse handler,
  3963. std::true_type) {
  3964. error_handler_ = std::move(handler);
  3965. return *this;
  3966. }
  3967. Server &Server::set_error_handler_core(Handler handler,
  3968. std::false_type) {
  3969. error_handler_ = [handler](const Request &req, Response &res) {
  3970. handler(req, res);
  3971. return HandlerResponse::Handled;
  3972. };
  3973. return *this;
  3974. }
  3975. Server &Server::set_exception_handler(ExceptionHandler handler) {
  3976. exception_handler_ = std::move(handler);
  3977. return *this;
  3978. }
  3979. Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  3980. pre_routing_handler_ = std::move(handler);
  3981. return *this;
  3982. }
  3983. Server &Server::set_post_routing_handler(Handler handler) {
  3984. post_routing_handler_ = std::move(handler);
  3985. return *this;
  3986. }
  3987. Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  3988. pre_request_handler_ = std::move(handler);
  3989. return *this;
  3990. }
  3991. Server &Server::set_logger(Logger logger) {
  3992. logger_ = std::move(logger);
  3993. return *this;
  3994. }
  3995. Server &Server::set_error_logger(ErrorLogger error_logger) {
  3996. error_logger_ = std::move(error_logger);
  3997. return *this;
  3998. }
  3999. Server &Server::set_pre_compression_logger(Logger logger) {
  4000. pre_compression_logger_ = std::move(logger);
  4001. return *this;
  4002. }
  4003. Server &
  4004. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  4005. expect_100_continue_handler_ = std::move(handler);
  4006. return *this;
  4007. }
  4008. Server &Server::set_address_family(int family) {
  4009. address_family_ = family;
  4010. return *this;
  4011. }
  4012. Server &Server::set_tcp_nodelay(bool on) {
  4013. tcp_nodelay_ = on;
  4014. return *this;
  4015. }
  4016. Server &Server::set_ipv6_v6only(bool on) {
  4017. ipv6_v6only_ = on;
  4018. return *this;
  4019. }
  4020. Server &Server::set_socket_options(SocketOptions socket_options) {
  4021. socket_options_ = std::move(socket_options);
  4022. return *this;
  4023. }
  4024. Server &Server::set_default_headers(Headers headers) {
  4025. default_headers_ = std::move(headers);
  4026. return *this;
  4027. }
  4028. Server &Server::set_header_writer(
  4029. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  4030. header_writer_ = writer;
  4031. return *this;
  4032. }
  4033. Server &
  4034. Server::set_trusted_proxies(const std::vector<std::string> &proxies) {
  4035. trusted_proxies_ = proxies;
  4036. return *this;
  4037. }
  4038. Server &Server::set_keep_alive_max_count(size_t count) {
  4039. keep_alive_max_count_ = count;
  4040. return *this;
  4041. }
  4042. Server &Server::set_keep_alive_timeout(time_t sec) {
  4043. keep_alive_timeout_sec_ = sec;
  4044. return *this;
  4045. }
  4046. Server &Server::set_read_timeout(time_t sec, time_t usec) {
  4047. read_timeout_sec_ = sec;
  4048. read_timeout_usec_ = usec;
  4049. return *this;
  4050. }
  4051. Server &Server::set_write_timeout(time_t sec, time_t usec) {
  4052. write_timeout_sec_ = sec;
  4053. write_timeout_usec_ = usec;
  4054. return *this;
  4055. }
  4056. Server &Server::set_idle_interval(time_t sec, time_t usec) {
  4057. idle_interval_sec_ = sec;
  4058. idle_interval_usec_ = usec;
  4059. return *this;
  4060. }
  4061. Server &Server::set_payload_max_length(size_t length) {
  4062. payload_max_length_ = length;
  4063. return *this;
  4064. }
  4065. bool Server::bind_to_port(const std::string &host, int port,
  4066. int socket_flags) {
  4067. auto ret = bind_internal(host, port, socket_flags);
  4068. if (ret == -1) { is_decommissioned = true; }
  4069. return ret >= 0;
  4070. }
  4071. int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  4072. auto ret = bind_internal(host, 0, socket_flags);
  4073. if (ret == -1) { is_decommissioned = true; }
  4074. return ret;
  4075. }
  4076. bool Server::listen_after_bind() { return listen_internal(); }
  4077. bool Server::listen(const std::string &host, int port,
  4078. int socket_flags) {
  4079. return bind_to_port(host, port, socket_flags) && listen_internal();
  4080. }
  4081. bool Server::is_running() const { return is_running_; }
  4082. void Server::wait_until_ready() const {
  4083. while (!is_running_ && !is_decommissioned) {
  4084. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  4085. }
  4086. }
  4087. void Server::stop() {
  4088. if (is_running_) {
  4089. assert(svr_sock_ != INVALID_SOCKET);
  4090. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  4091. detail::shutdown_socket(sock);
  4092. detail::close_socket(sock);
  4093. }
  4094. is_decommissioned = false;
  4095. }
  4096. void Server::decommission() { is_decommissioned = true; }
  4097. bool Server::parse_request_line(const char *s, Request &req) const {
  4098. auto len = strlen(s);
  4099. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  4100. len -= 2;
  4101. {
  4102. size_t count = 0;
  4103. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  4104. switch (count) {
  4105. case 0: req.method = std::string(b, e); break;
  4106. case 1: req.target = std::string(b, e); break;
  4107. case 2: req.version = std::string(b, e); break;
  4108. default: break;
  4109. }
  4110. count++;
  4111. });
  4112. if (count != 3) { return false; }
  4113. }
  4114. thread_local const std::set<std::string> methods{
  4115. "GET", "HEAD", "POST", "PUT", "DELETE",
  4116. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  4117. if (methods.find(req.method) == methods.end()) {
  4118. output_error_log(Error::InvalidHTTPMethod, &req);
  4119. return false;
  4120. }
  4121. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") {
  4122. output_error_log(Error::InvalidHTTPVersion, &req);
  4123. return false;
  4124. }
  4125. {
  4126. // Skip URL fragment
  4127. for (size_t i = 0; i < req.target.size(); i++) {
  4128. if (req.target[i] == '#') {
  4129. req.target.erase(i);
  4130. break;
  4131. }
  4132. }
  4133. detail::divide(req.target, '?',
  4134. [&](const char *lhs_data, std::size_t lhs_size,
  4135. const char *rhs_data, std::size_t rhs_size) {
  4136. req.path =
  4137. decode_path_component(std::string(lhs_data, lhs_size));
  4138. detail::parse_query_text(rhs_data, rhs_size, req.params);
  4139. });
  4140. }
  4141. return true;
  4142. }
  4143. bool Server::write_response(Stream &strm, bool close_connection,
  4144. Request &req, Response &res) {
  4145. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  4146. // incorrectly to the error content.
  4147. req.ranges.clear();
  4148. return write_response_core(strm, close_connection, req, res, false);
  4149. }
  4150. bool Server::write_response_with_content(Stream &strm,
  4151. bool close_connection,
  4152. const Request &req,
  4153. Response &res) {
  4154. return write_response_core(strm, close_connection, req, res, true);
  4155. }
  4156. bool Server::write_response_core(Stream &strm, bool close_connection,
  4157. const Request &req, Response &res,
  4158. bool need_apply_ranges) {
  4159. assert(res.status != -1);
  4160. if (400 <= res.status && error_handler_ &&
  4161. error_handler_(req, res) == HandlerResponse::Handled) {
  4162. need_apply_ranges = true;
  4163. }
  4164. std::string content_type;
  4165. std::string boundary;
  4166. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  4167. // Prepare additional headers
  4168. if (close_connection || req.get_header_value("Connection") == "close" ||
  4169. 400 <= res.status) { // Don't leave connections open after errors
  4170. res.set_header("Connection", "close");
  4171. } else {
  4172. std::string s = "timeout=";
  4173. s += std::to_string(keep_alive_timeout_sec_);
  4174. s += ", max=";
  4175. s += std::to_string(keep_alive_max_count_);
  4176. res.set_header("Keep-Alive", s);
  4177. }
  4178. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  4179. !res.has_header("Content-Type")) {
  4180. res.set_header("Content-Type", "text/plain");
  4181. }
  4182. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  4183. !res.has_header("Content-Length")) {
  4184. res.set_header("Content-Length", "0");
  4185. }
  4186. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  4187. res.set_header("Accept-Ranges", "bytes");
  4188. }
  4189. if (post_routing_handler_) { post_routing_handler_(req, res); }
  4190. // Response line and headers
  4191. {
  4192. detail::BufferStream bstrm;
  4193. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  4194. if (!header_writer_(bstrm, res.headers)) { return false; }
  4195. // Flush buffer
  4196. auto &data = bstrm.get_buffer();
  4197. detail::write_data(strm, data.data(), data.size());
  4198. }
  4199. // Body
  4200. auto ret = true;
  4201. if (req.method != "HEAD") {
  4202. if (!res.body.empty()) {
  4203. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  4204. ret = false;
  4205. }
  4206. } else if (res.content_provider_) {
  4207. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  4208. res.content_provider_success_ = true;
  4209. } else {
  4210. ret = false;
  4211. }
  4212. }
  4213. }
  4214. // Log
  4215. output_log(req, res);
  4216. return ret;
  4217. }
  4218. bool
  4219. Server::write_content_with_provider(Stream &strm, const Request &req,
  4220. Response &res, const std::string &boundary,
  4221. const std::string &content_type) {
  4222. auto is_shutting_down = [this]() {
  4223. return this->svr_sock_ == INVALID_SOCKET;
  4224. };
  4225. if (res.content_length_ > 0) {
  4226. if (req.ranges.empty()) {
  4227. return detail::write_content(strm, res.content_provider_, 0,
  4228. res.content_length_, is_shutting_down);
  4229. } else if (req.ranges.size() == 1) {
  4230. auto offset_and_length = detail::get_range_offset_and_length(
  4231. req.ranges[0], res.content_length_);
  4232. return detail::write_content(strm, res.content_provider_,
  4233. offset_and_length.first,
  4234. offset_and_length.second, is_shutting_down);
  4235. } else {
  4236. return detail::write_multipart_ranges_data(
  4237. strm, req, res, boundary, content_type, res.content_length_,
  4238. is_shutting_down);
  4239. }
  4240. } else {
  4241. if (res.is_chunked_content_provider_) {
  4242. auto type = detail::encoding_type(req, res);
  4243. std::unique_ptr<detail::compressor> compressor;
  4244. if (type == detail::EncodingType::Gzip) {
  4245. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4246. compressor = detail::make_unique<detail::gzip_compressor>();
  4247. #endif
  4248. } else if (type == detail::EncodingType::Brotli) {
  4249. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4250. compressor = detail::make_unique<detail::brotli_compressor>();
  4251. #endif
  4252. } else if (type == detail::EncodingType::Zstd) {
  4253. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4254. compressor = detail::make_unique<detail::zstd_compressor>();
  4255. #endif
  4256. } else {
  4257. compressor = detail::make_unique<detail::nocompressor>();
  4258. }
  4259. assert(compressor != nullptr);
  4260. return detail::write_content_chunked(strm, res.content_provider_,
  4261. is_shutting_down, *compressor);
  4262. } else {
  4263. return detail::write_content_without_length(strm, res.content_provider_,
  4264. is_shutting_down);
  4265. }
  4266. }
  4267. }
  4268. bool Server::read_content(Stream &strm, Request &req, Response &res) {
  4269. FormFields::iterator cur_field;
  4270. FormFiles::iterator cur_file;
  4271. auto is_text_field = false;
  4272. size_t count = 0;
  4273. if (read_content_core(
  4274. strm, req, res,
  4275. // Regular
  4276. [&](const char *buf, size_t n) {
  4277. if (req.body.size() + n > req.body.max_size()) { return false; }
  4278. req.body.append(buf, n);
  4279. return true;
  4280. },
  4281. // Multipart FormData
  4282. [&](const FormData &file) {
  4283. if (count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  4284. output_error_log(Error::TooManyFormDataFiles, &req);
  4285. return false;
  4286. }
  4287. if (file.filename.empty()) {
  4288. cur_field = req.form.fields.emplace(
  4289. file.name, FormField{file.name, file.content, file.headers});
  4290. is_text_field = true;
  4291. } else {
  4292. cur_file = req.form.files.emplace(file.name, file);
  4293. is_text_field = false;
  4294. }
  4295. return true;
  4296. },
  4297. [&](const char *buf, size_t n) {
  4298. if (is_text_field) {
  4299. auto &content = cur_field->second.content;
  4300. if (content.size() + n > content.max_size()) { return false; }
  4301. content.append(buf, n);
  4302. } else {
  4303. auto &content = cur_file->second.content;
  4304. if (content.size() + n > content.max_size()) { return false; }
  4305. content.append(buf, n);
  4306. }
  4307. return true;
  4308. })) {
  4309. const auto &content_type = req.get_header_value("Content-Type");
  4310. if (!content_type.find("application/x-www-form-urlencoded")) {
  4311. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  4312. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  4313. output_error_log(Error::ExceedMaxPayloadSize, &req);
  4314. return false;
  4315. }
  4316. detail::parse_query_text(req.body, req.params);
  4317. }
  4318. return true;
  4319. }
  4320. return false;
  4321. }
  4322. bool Server::read_content_with_content_receiver(
  4323. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  4324. FormDataHeader multipart_header, ContentReceiver multipart_receiver) {
  4325. return read_content_core(strm, req, res, std::move(receiver),
  4326. std::move(multipart_header),
  4327. std::move(multipart_receiver));
  4328. }
  4329. bool Server::read_content_core(
  4330. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  4331. FormDataHeader multipart_header, ContentReceiver multipart_receiver) const {
  4332. detail::FormDataParser multipart_form_data_parser;
  4333. ContentReceiverWithProgress out;
  4334. if (req.is_multipart_form_data()) {
  4335. const auto &content_type = req.get_header_value("Content-Type");
  4336. std::string boundary;
  4337. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  4338. res.status = StatusCode::BadRequest_400;
  4339. output_error_log(Error::MultipartParsing, &req);
  4340. return false;
  4341. }
  4342. multipart_form_data_parser.set_boundary(std::move(boundary));
  4343. out = [&](const char *buf, size_t n, size_t /*off*/, size_t /*len*/) {
  4344. return multipart_form_data_parser.parse(buf, n, multipart_header,
  4345. multipart_receiver);
  4346. };
  4347. } else {
  4348. out = [receiver](const char *buf, size_t n, size_t /*off*/,
  4349. size_t /*len*/) { return receiver(buf, n); };
  4350. }
  4351. // RFC 7230 Section 3.3.3: If this is a request message and none of the above
  4352. // are true (no Transfer-Encoding and no Content-Length), then the message
  4353. // body length is zero (no message body is present).
  4354. if (!req.has_header("Content-Length") &&
  4355. !detail::is_chunked_transfer_encoding(req.headers)) {
  4356. return true;
  4357. }
  4358. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  4359. out, true)) {
  4360. return false;
  4361. }
  4362. if (req.is_multipart_form_data()) {
  4363. if (!multipart_form_data_parser.is_valid()) {
  4364. res.status = StatusCode::BadRequest_400;
  4365. output_error_log(Error::MultipartParsing, &req);
  4366. return false;
  4367. }
  4368. }
  4369. return true;
  4370. }
  4371. bool Server::handle_file_request(const Request &req, Response &res) {
  4372. for (const auto &entry : base_dirs_) {
  4373. // Prefix match
  4374. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  4375. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  4376. if (detail::is_valid_path(sub_path)) {
  4377. auto path = entry.base_dir + sub_path;
  4378. if (path.back() == '/') { path += "index.html"; }
  4379. detail::FileStat stat(path);
  4380. if (stat.is_dir()) {
  4381. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  4382. return true;
  4383. }
  4384. if (stat.is_file()) {
  4385. for (const auto &kv : entry.headers) {
  4386. res.set_header(kv.first, kv.second);
  4387. }
  4388. auto mm = std::make_shared<detail::mmap>(path.c_str());
  4389. if (!mm->is_open()) {
  4390. output_error_log(Error::OpenFile, &req);
  4391. return false;
  4392. }
  4393. res.set_content_provider(
  4394. mm->size(),
  4395. detail::find_content_type(path, file_extension_and_mimetype_map_,
  4396. default_file_mimetype_),
  4397. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  4398. sink.write(mm->data() + offset, length);
  4399. return true;
  4400. });
  4401. if (req.method != "HEAD" && file_request_handler_) {
  4402. file_request_handler_(req, res);
  4403. }
  4404. return true;
  4405. } else {
  4406. output_error_log(Error::OpenFile, &req);
  4407. }
  4408. }
  4409. }
  4410. }
  4411. return false;
  4412. }
  4413. socket_t
  4414. Server::create_server_socket(const std::string &host, int port,
  4415. int socket_flags,
  4416. SocketOptions socket_options) const {
  4417. return detail::create_socket(
  4418. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  4419. ipv6_v6only_, std::move(socket_options),
  4420. [&](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  4421. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  4422. output_error_log(Error::BindIPAddress, nullptr);
  4423. return false;
  4424. }
  4425. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) {
  4426. output_error_log(Error::Listen, nullptr);
  4427. return false;
  4428. }
  4429. return true;
  4430. });
  4431. }
  4432. int Server::bind_internal(const std::string &host, int port,
  4433. int socket_flags) {
  4434. if (is_decommissioned) { return -1; }
  4435. if (!is_valid()) { return -1; }
  4436. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  4437. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  4438. if (port == 0) {
  4439. struct sockaddr_storage addr;
  4440. socklen_t addr_len = sizeof(addr);
  4441. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  4442. &addr_len) == -1) {
  4443. output_error_log(Error::GetSockName, nullptr);
  4444. return -1;
  4445. }
  4446. if (addr.ss_family == AF_INET) {
  4447. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  4448. } else if (addr.ss_family == AF_INET6) {
  4449. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  4450. } else {
  4451. output_error_log(Error::UnsupportedAddressFamily, nullptr);
  4452. return -1;
  4453. }
  4454. } else {
  4455. return port;
  4456. }
  4457. }
  4458. bool Server::listen_internal() {
  4459. if (is_decommissioned) { return false; }
  4460. auto ret = true;
  4461. is_running_ = true;
  4462. auto se = detail::scope_exit([&]() { is_running_ = false; });
  4463. {
  4464. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  4465. while (svr_sock_ != INVALID_SOCKET) {
  4466. #ifndef _WIN32
  4467. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  4468. #endif
  4469. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  4470. idle_interval_usec_);
  4471. if (val == 0) { // Timeout
  4472. task_queue->on_idle();
  4473. continue;
  4474. }
  4475. #ifndef _WIN32
  4476. }
  4477. #endif
  4478. #if defined _WIN32
  4479. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  4480. // OVERLAPPED
  4481. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  4482. #elif defined SOCK_CLOEXEC
  4483. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  4484. #else
  4485. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  4486. #endif
  4487. if (sock == INVALID_SOCKET) {
  4488. if (errno == EMFILE) {
  4489. // The per-process limit of open file descriptors has been reached.
  4490. // Try to accept new connections after a short sleep.
  4491. std::this_thread::sleep_for(std::chrono::microseconds{1});
  4492. continue;
  4493. } else if (errno == EINTR || errno == EAGAIN) {
  4494. continue;
  4495. }
  4496. if (svr_sock_ != INVALID_SOCKET) {
  4497. detail::close_socket(svr_sock_);
  4498. ret = false;
  4499. output_error_log(Error::Connection, nullptr);
  4500. } else {
  4501. ; // The server socket was closed by user.
  4502. }
  4503. break;
  4504. }
  4505. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  4506. read_timeout_sec_, read_timeout_usec_);
  4507. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  4508. write_timeout_sec_, write_timeout_usec_);
  4509. if (!task_queue->enqueue(
  4510. [this, sock]() { process_and_close_socket(sock); })) {
  4511. output_error_log(Error::ResourceExhaustion, nullptr);
  4512. detail::shutdown_socket(sock);
  4513. detail::close_socket(sock);
  4514. }
  4515. }
  4516. task_queue->shutdown();
  4517. }
  4518. is_decommissioned = !ret;
  4519. return ret;
  4520. }
  4521. bool Server::routing(Request &req, Response &res, Stream &strm) {
  4522. if (pre_routing_handler_ &&
  4523. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  4524. return true;
  4525. }
  4526. // File handler
  4527. if ((req.method == "GET" || req.method == "HEAD") &&
  4528. handle_file_request(req, res)) {
  4529. return true;
  4530. }
  4531. if (detail::expect_content(req)) {
  4532. // Content reader handler
  4533. {
  4534. ContentReader reader(
  4535. [&](ContentReceiver receiver) {
  4536. auto result = read_content_with_content_receiver(
  4537. strm, req, res, std::move(receiver), nullptr, nullptr);
  4538. if (!result) { output_error_log(Error::Read, &req); }
  4539. return result;
  4540. },
  4541. [&](FormDataHeader header, ContentReceiver receiver) {
  4542. auto result = read_content_with_content_receiver(
  4543. strm, req, res, nullptr, std::move(header),
  4544. std::move(receiver));
  4545. if (!result) { output_error_log(Error::Read, &req); }
  4546. return result;
  4547. });
  4548. if (req.method == "POST") {
  4549. if (dispatch_request_for_content_reader(
  4550. req, res, std::move(reader),
  4551. post_handlers_for_content_reader_)) {
  4552. return true;
  4553. }
  4554. } else if (req.method == "PUT") {
  4555. if (dispatch_request_for_content_reader(
  4556. req, res, std::move(reader),
  4557. put_handlers_for_content_reader_)) {
  4558. return true;
  4559. }
  4560. } else if (req.method == "PATCH") {
  4561. if (dispatch_request_for_content_reader(
  4562. req, res, std::move(reader),
  4563. patch_handlers_for_content_reader_)) {
  4564. return true;
  4565. }
  4566. } else if (req.method == "DELETE") {
  4567. if (dispatch_request_for_content_reader(
  4568. req, res, std::move(reader),
  4569. delete_handlers_for_content_reader_)) {
  4570. return true;
  4571. }
  4572. }
  4573. }
  4574. // Read content into `req.body`
  4575. if (!read_content(strm, req, res)) {
  4576. output_error_log(Error::Read, &req);
  4577. return false;
  4578. }
  4579. }
  4580. // Regular handler
  4581. if (req.method == "GET" || req.method == "HEAD") {
  4582. return dispatch_request(req, res, get_handlers_);
  4583. } else if (req.method == "POST") {
  4584. return dispatch_request(req, res, post_handlers_);
  4585. } else if (req.method == "PUT") {
  4586. return dispatch_request(req, res, put_handlers_);
  4587. } else if (req.method == "DELETE") {
  4588. return dispatch_request(req, res, delete_handlers_);
  4589. } else if (req.method == "OPTIONS") {
  4590. return dispatch_request(req, res, options_handlers_);
  4591. } else if (req.method == "PATCH") {
  4592. return dispatch_request(req, res, patch_handlers_);
  4593. }
  4594. res.status = StatusCode::BadRequest_400;
  4595. return false;
  4596. }
  4597. bool Server::dispatch_request(Request &req, Response &res,
  4598. const Handlers &handlers) const {
  4599. for (const auto &x : handlers) {
  4600. const auto &matcher = x.first;
  4601. const auto &handler = x.second;
  4602. if (matcher->match(req)) {
  4603. req.matched_route = matcher->pattern();
  4604. if (!pre_request_handler_ ||
  4605. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  4606. handler(req, res);
  4607. }
  4608. return true;
  4609. }
  4610. }
  4611. return false;
  4612. }
  4613. void Server::apply_ranges(const Request &req, Response &res,
  4614. std::string &content_type,
  4615. std::string &boundary) const {
  4616. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  4617. auto it = res.headers.find("Content-Type");
  4618. if (it != res.headers.end()) {
  4619. content_type = it->second;
  4620. res.headers.erase(it);
  4621. }
  4622. boundary = detail::make_multipart_data_boundary();
  4623. res.set_header("Content-Type",
  4624. "multipart/byteranges; boundary=" + boundary);
  4625. }
  4626. auto type = detail::encoding_type(req, res);
  4627. if (res.body.empty()) {
  4628. if (res.content_length_ > 0) {
  4629. size_t length = 0;
  4630. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  4631. length = res.content_length_;
  4632. } else if (req.ranges.size() == 1) {
  4633. auto offset_and_length = detail::get_range_offset_and_length(
  4634. req.ranges[0], res.content_length_);
  4635. length = offset_and_length.second;
  4636. auto content_range = detail::make_content_range_header_field(
  4637. offset_and_length, res.content_length_);
  4638. res.set_header("Content-Range", content_range);
  4639. } else {
  4640. length = detail::get_multipart_ranges_data_length(
  4641. req, boundary, content_type, res.content_length_);
  4642. }
  4643. res.set_header("Content-Length", std::to_string(length));
  4644. } else {
  4645. if (res.content_provider_) {
  4646. if (res.is_chunked_content_provider_) {
  4647. res.set_header("Transfer-Encoding", "chunked");
  4648. if (type == detail::EncodingType::Gzip) {
  4649. res.set_header("Content-Encoding", "gzip");
  4650. } else if (type == detail::EncodingType::Brotli) {
  4651. res.set_header("Content-Encoding", "br");
  4652. } else if (type == detail::EncodingType::Zstd) {
  4653. res.set_header("Content-Encoding", "zstd");
  4654. }
  4655. }
  4656. }
  4657. }
  4658. } else {
  4659. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  4660. ;
  4661. } else if (req.ranges.size() == 1) {
  4662. auto offset_and_length =
  4663. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  4664. auto offset = offset_and_length.first;
  4665. auto length = offset_and_length.second;
  4666. auto content_range = detail::make_content_range_header_field(
  4667. offset_and_length, res.body.size());
  4668. res.set_header("Content-Range", content_range);
  4669. assert(offset + length <= res.body.size());
  4670. res.body = res.body.substr(offset, length);
  4671. } else {
  4672. std::string data;
  4673. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  4674. res.body.size(), data);
  4675. res.body.swap(data);
  4676. }
  4677. if (type != detail::EncodingType::None) {
  4678. output_pre_compression_log(req, res);
  4679. std::unique_ptr<detail::compressor> compressor;
  4680. std::string content_encoding;
  4681. if (type == detail::EncodingType::Gzip) {
  4682. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4683. compressor = detail::make_unique<detail::gzip_compressor>();
  4684. content_encoding = "gzip";
  4685. #endif
  4686. } else if (type == detail::EncodingType::Brotli) {
  4687. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4688. compressor = detail::make_unique<detail::brotli_compressor>();
  4689. content_encoding = "br";
  4690. #endif
  4691. } else if (type == detail::EncodingType::Zstd) {
  4692. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4693. compressor = detail::make_unique<detail::zstd_compressor>();
  4694. content_encoding = "zstd";
  4695. #endif
  4696. }
  4697. if (compressor) {
  4698. std::string compressed;
  4699. if (compressor->compress(res.body.data(), res.body.size(), true,
  4700. [&](const char *data, size_t data_len) {
  4701. compressed.append(data, data_len);
  4702. return true;
  4703. })) {
  4704. res.body.swap(compressed);
  4705. res.set_header("Content-Encoding", content_encoding);
  4706. }
  4707. }
  4708. }
  4709. auto length = std::to_string(res.body.size());
  4710. res.set_header("Content-Length", length);
  4711. }
  4712. }
  4713. bool Server::dispatch_request_for_content_reader(
  4714. Request &req, Response &res, ContentReader content_reader,
  4715. const HandlersForContentReader &handlers) const {
  4716. for (const auto &x : handlers) {
  4717. const auto &matcher = x.first;
  4718. const auto &handler = x.second;
  4719. if (matcher->match(req)) {
  4720. req.matched_route = matcher->pattern();
  4721. if (!pre_request_handler_ ||
  4722. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  4723. handler(req, res, content_reader);
  4724. }
  4725. return true;
  4726. }
  4727. }
  4728. return false;
  4729. }
  4730. std::string
  4731. get_client_ip(const std::string &x_forwarded_for,
  4732. const std::vector<std::string> &trusted_proxies) {
  4733. // X-Forwarded-For is a comma-separated list per RFC 7239
  4734. std::vector<std::string> ip_list;
  4735. detail::split(x_forwarded_for.data(),
  4736. x_forwarded_for.data() + x_forwarded_for.size(), ',',
  4737. [&](const char *b, const char *e) {
  4738. auto r = detail::trim(b, e, 0, static_cast<size_t>(e - b));
  4739. ip_list.emplace_back(std::string(b + r.first, b + r.second));
  4740. });
  4741. for (size_t i = 0; i < ip_list.size(); ++i) {
  4742. auto ip = ip_list[i];
  4743. auto is_trusted_proxy =
  4744. std::any_of(trusted_proxies.begin(), trusted_proxies.end(),
  4745. [&](const std::string &proxy) { return ip == proxy; });
  4746. if (is_trusted_proxy) {
  4747. if (i == 0) {
  4748. // If the trusted proxy is the first IP, there's no preceding client IP
  4749. return ip;
  4750. } else {
  4751. // Return the IP immediately before the trusted proxy
  4752. return ip_list[i - 1];
  4753. }
  4754. }
  4755. }
  4756. // If no trusted proxy is found, return the first IP in the list
  4757. return ip_list.front();
  4758. }
  4759. bool
  4760. Server::process_request(Stream &strm, const std::string &remote_addr,
  4761. int remote_port, const std::string &local_addr,
  4762. int local_port, bool close_connection,
  4763. bool &connection_closed,
  4764. const std::function<void(Request &)> &setup_request) {
  4765. std::array<char, 2048> buf{};
  4766. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  4767. // Connection has been closed on client
  4768. if (!line_reader.getline()) { return false; }
  4769. Request req;
  4770. req.start_time_ = std::chrono::steady_clock::now();
  4771. Response res;
  4772. res.version = "HTTP/1.1";
  4773. res.headers = default_headers_;
  4774. #ifdef __APPLE__
  4775. // Socket file descriptor exceeded FD_SETSIZE...
  4776. if (strm.socket() >= FD_SETSIZE) {
  4777. Headers dummy;
  4778. detail::read_headers(strm, dummy);
  4779. res.status = StatusCode::InternalServerError_500;
  4780. output_error_log(Error::ExceedMaxSocketDescriptorCount, &req);
  4781. return write_response(strm, close_connection, req, res);
  4782. }
  4783. #endif
  4784. // Request line and headers
  4785. if (!parse_request_line(line_reader.ptr(), req)) {
  4786. res.status = StatusCode::BadRequest_400;
  4787. output_error_log(Error::InvalidRequestLine, &req);
  4788. return write_response(strm, close_connection, req, res);
  4789. }
  4790. // Request headers
  4791. if (!detail::read_headers(strm, req.headers)) {
  4792. res.status = StatusCode::BadRequest_400;
  4793. output_error_log(Error::InvalidHeaders, &req);
  4794. return write_response(strm, close_connection, req, res);
  4795. }
  4796. // Check if the request URI doesn't exceed the limit
  4797. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  4798. res.status = StatusCode::UriTooLong_414;
  4799. output_error_log(Error::ExceedUriMaxLength, &req);
  4800. return write_response(strm, close_connection, req, res);
  4801. }
  4802. if (req.get_header_value("Connection") == "close") {
  4803. connection_closed = true;
  4804. }
  4805. if (req.version == "HTTP/1.0" &&
  4806. req.get_header_value("Connection") != "Keep-Alive") {
  4807. connection_closed = true;
  4808. }
  4809. if (!trusted_proxies_.empty() && req.has_header("X-Forwarded-For")) {
  4810. auto x_forwarded_for = req.get_header_value("X-Forwarded-For");
  4811. req.remote_addr = get_client_ip(x_forwarded_for, trusted_proxies_);
  4812. } else {
  4813. req.remote_addr = remote_addr;
  4814. }
  4815. req.remote_port = remote_port;
  4816. req.local_addr = local_addr;
  4817. req.local_port = local_port;
  4818. if (req.has_header("Accept")) {
  4819. const auto &accept_header = req.get_header_value("Accept");
  4820. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  4821. res.status = StatusCode::BadRequest_400;
  4822. output_error_log(Error::HTTPParsing, &req);
  4823. return write_response(strm, close_connection, req, res);
  4824. }
  4825. }
  4826. if (req.has_header("Range")) {
  4827. const auto &range_header_value = req.get_header_value("Range");
  4828. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  4829. res.status = StatusCode::RangeNotSatisfiable_416;
  4830. output_error_log(Error::InvalidRangeHeader, &req);
  4831. return write_response(strm, close_connection, req, res);
  4832. }
  4833. }
  4834. if (setup_request) { setup_request(req); }
  4835. if (req.get_header_value("Expect") == "100-continue") {
  4836. int status = StatusCode::Continue_100;
  4837. if (expect_100_continue_handler_) {
  4838. status = expect_100_continue_handler_(req, res);
  4839. }
  4840. switch (status) {
  4841. case StatusCode::Continue_100:
  4842. case StatusCode::ExpectationFailed_417:
  4843. detail::write_response_line(strm, status);
  4844. strm.write("\r\n");
  4845. break;
  4846. default:
  4847. connection_closed = true;
  4848. return write_response(strm, true, req, res);
  4849. }
  4850. }
  4851. // Setup `is_connection_closed` method
  4852. auto sock = strm.socket();
  4853. req.is_connection_closed = [sock]() {
  4854. return !detail::is_socket_alive(sock);
  4855. };
  4856. // Routing
  4857. auto routed = false;
  4858. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4859. routed = routing(req, res, strm);
  4860. #else
  4861. try {
  4862. routed = routing(req, res, strm);
  4863. } catch (std::exception &e) {
  4864. if (exception_handler_) {
  4865. auto ep = std::current_exception();
  4866. exception_handler_(req, res, ep);
  4867. routed = true;
  4868. } else {
  4869. res.status = StatusCode::InternalServerError_500;
  4870. std::string val;
  4871. auto s = e.what();
  4872. for (size_t i = 0; s[i]; i++) {
  4873. switch (s[i]) {
  4874. case '\r': val += "\\r"; break;
  4875. case '\n': val += "\\n"; break;
  4876. default: val += s[i]; break;
  4877. }
  4878. }
  4879. res.set_header("EXCEPTION_WHAT", val);
  4880. }
  4881. } catch (...) {
  4882. if (exception_handler_) {
  4883. auto ep = std::current_exception();
  4884. exception_handler_(req, res, ep);
  4885. routed = true;
  4886. } else {
  4887. res.status = StatusCode::InternalServerError_500;
  4888. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  4889. }
  4890. }
  4891. #endif
  4892. if (routed) {
  4893. if (res.status == -1) {
  4894. res.status = req.ranges.empty() ? StatusCode::OK_200
  4895. : StatusCode::PartialContent_206;
  4896. }
  4897. // Serve file content by using a content provider
  4898. if (!res.file_content_path_.empty()) {
  4899. const auto &path = res.file_content_path_;
  4900. auto mm = std::make_shared<detail::mmap>(path.c_str());
  4901. if (!mm->is_open()) {
  4902. res.body.clear();
  4903. res.content_length_ = 0;
  4904. res.content_provider_ = nullptr;
  4905. res.status = StatusCode::NotFound_404;
  4906. output_error_log(Error::OpenFile, &req);
  4907. return write_response(strm, close_connection, req, res);
  4908. }
  4909. auto content_type = res.file_content_content_type_;
  4910. if (content_type.empty()) {
  4911. content_type = detail::find_content_type(
  4912. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  4913. }
  4914. res.set_content_provider(
  4915. mm->size(), content_type,
  4916. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  4917. sink.write(mm->data() + offset, length);
  4918. return true;
  4919. });
  4920. }
  4921. if (detail::range_error(req, res)) {
  4922. res.body.clear();
  4923. res.content_length_ = 0;
  4924. res.content_provider_ = nullptr;
  4925. res.status = StatusCode::RangeNotSatisfiable_416;
  4926. return write_response(strm, close_connection, req, res);
  4927. }
  4928. return write_response_with_content(strm, close_connection, req, res);
  4929. } else {
  4930. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  4931. return write_response(strm, close_connection, req, res);
  4932. }
  4933. }
  4934. bool Server::is_valid() const { return true; }
  4935. bool Server::process_and_close_socket(socket_t sock) {
  4936. std::string remote_addr;
  4937. int remote_port = 0;
  4938. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  4939. std::string local_addr;
  4940. int local_port = 0;
  4941. detail::get_local_ip_and_port(sock, local_addr, local_port);
  4942. auto ret = detail::process_server_socket(
  4943. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  4944. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  4945. write_timeout_usec_,
  4946. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  4947. return process_request(strm, remote_addr, remote_port, local_addr,
  4948. local_port, close_connection, connection_closed,
  4949. nullptr);
  4950. });
  4951. detail::shutdown_socket(sock);
  4952. detail::close_socket(sock);
  4953. return ret;
  4954. }
  4955. void Server::output_log(const Request &req, const Response &res) const {
  4956. if (logger_) {
  4957. std::lock_guard<std::mutex> guard(logger_mutex_);
  4958. logger_(req, res);
  4959. }
  4960. }
  4961. void Server::output_pre_compression_log(const Request &req,
  4962. const Response &res) const {
  4963. if (pre_compression_logger_) {
  4964. std::lock_guard<std::mutex> guard(logger_mutex_);
  4965. pre_compression_logger_(req, res);
  4966. }
  4967. }
  4968. void Server::output_error_log(const Error &err,
  4969. const Request *req) const {
  4970. if (error_logger_) {
  4971. std::lock_guard<std::mutex> guard(logger_mutex_);
  4972. error_logger_(err, req);
  4973. }
  4974. }
  4975. // HTTP client implementation
  4976. ClientImpl::ClientImpl(const std::string &host)
  4977. : ClientImpl(host, 80, std::string(), std::string()) {}
  4978. ClientImpl::ClientImpl(const std::string &host, int port)
  4979. : ClientImpl(host, port, std::string(), std::string()) {}
  4980. ClientImpl::ClientImpl(const std::string &host, int port,
  4981. const std::string &client_cert_path,
  4982. const std::string &client_key_path)
  4983. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  4984. host_and_port_(detail::make_host_and_port_string(host_, port, is_ssl())),
  4985. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  4986. ClientImpl::~ClientImpl() {
  4987. // Wait until all the requests in flight are handled.
  4988. size_t retry_count = 10;
  4989. while (retry_count-- > 0) {
  4990. {
  4991. std::lock_guard<std::mutex> guard(socket_mutex_);
  4992. if (socket_requests_in_flight_ == 0) { break; }
  4993. }
  4994. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  4995. }
  4996. std::lock_guard<std::mutex> guard(socket_mutex_);
  4997. shutdown_socket(socket_);
  4998. close_socket(socket_);
  4999. }
  5000. bool ClientImpl::is_valid() const { return true; }
  5001. void ClientImpl::copy_settings(const ClientImpl &rhs) {
  5002. client_cert_path_ = rhs.client_cert_path_;
  5003. client_key_path_ = rhs.client_key_path_;
  5004. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  5005. read_timeout_sec_ = rhs.read_timeout_sec_;
  5006. read_timeout_usec_ = rhs.read_timeout_usec_;
  5007. write_timeout_sec_ = rhs.write_timeout_sec_;
  5008. write_timeout_usec_ = rhs.write_timeout_usec_;
  5009. max_timeout_msec_ = rhs.max_timeout_msec_;
  5010. basic_auth_username_ = rhs.basic_auth_username_;
  5011. basic_auth_password_ = rhs.basic_auth_password_;
  5012. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  5013. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5014. digest_auth_username_ = rhs.digest_auth_username_;
  5015. digest_auth_password_ = rhs.digest_auth_password_;
  5016. #endif
  5017. keep_alive_ = rhs.keep_alive_;
  5018. follow_location_ = rhs.follow_location_;
  5019. path_encode_ = rhs.path_encode_;
  5020. address_family_ = rhs.address_family_;
  5021. tcp_nodelay_ = rhs.tcp_nodelay_;
  5022. ipv6_v6only_ = rhs.ipv6_v6only_;
  5023. socket_options_ = rhs.socket_options_;
  5024. compress_ = rhs.compress_;
  5025. decompress_ = rhs.decompress_;
  5026. interface_ = rhs.interface_;
  5027. proxy_host_ = rhs.proxy_host_;
  5028. proxy_port_ = rhs.proxy_port_;
  5029. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  5030. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  5031. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  5032. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5033. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  5034. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  5035. #endif
  5036. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5037. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  5038. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  5039. ca_cert_store_ = rhs.ca_cert_store_;
  5040. #endif
  5041. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5042. server_certificate_verification_ = rhs.server_certificate_verification_;
  5043. server_hostname_verification_ = rhs.server_hostname_verification_;
  5044. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  5045. #endif
  5046. logger_ = rhs.logger_;
  5047. error_logger_ = rhs.error_logger_;
  5048. }
  5049. socket_t ClientImpl::create_client_socket(Error &error) const {
  5050. if (!proxy_host_.empty() && proxy_port_ != -1) {
  5051. return detail::create_client_socket(
  5052. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  5053. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  5054. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  5055. write_timeout_sec_, write_timeout_usec_, interface_, error);
  5056. }
  5057. // Check is custom IP specified for host_
  5058. std::string ip;
  5059. auto it = addr_map_.find(host_);
  5060. if (it != addr_map_.end()) { ip = it->second; }
  5061. return detail::create_client_socket(
  5062. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  5063. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  5064. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  5065. write_timeout_usec_, interface_, error);
  5066. }
  5067. bool ClientImpl::create_and_connect_socket(Socket &socket,
  5068. Error &error) {
  5069. auto sock = create_client_socket(error);
  5070. if (sock == INVALID_SOCKET) { return false; }
  5071. socket.sock = sock;
  5072. return true;
  5073. }
  5074. void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  5075. bool /*shutdown_gracefully*/) {
  5076. // If there are any requests in flight from threads other than us, then it's
  5077. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  5078. assert(socket_requests_in_flight_ == 0 ||
  5079. socket_requests_are_from_thread_ == std::this_thread::get_id());
  5080. }
  5081. void ClientImpl::shutdown_socket(Socket &socket) const {
  5082. if (socket.sock == INVALID_SOCKET) { return; }
  5083. detail::shutdown_socket(socket.sock);
  5084. }
  5085. void ClientImpl::close_socket(Socket &socket) {
  5086. // If there are requests in flight in another thread, usually closing
  5087. // the socket will be fine and they will simply receive an error when
  5088. // using the closed socket, but it is still a bug since rarely the OS
  5089. // may reassign the socket id to be used for a new socket, and then
  5090. // suddenly they will be operating on a live socket that is different
  5091. // than the one they intended!
  5092. assert(socket_requests_in_flight_ == 0 ||
  5093. socket_requests_are_from_thread_ == std::this_thread::get_id());
  5094. // It is also a bug if this happens while SSL is still active
  5095. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5096. assert(socket.ssl == nullptr);
  5097. #endif
  5098. if (socket.sock == INVALID_SOCKET) { return; }
  5099. detail::close_socket(socket.sock);
  5100. socket.sock = INVALID_SOCKET;
  5101. }
  5102. bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  5103. Response &res) const {
  5104. std::array<char, 2048> buf{};
  5105. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  5106. if (!line_reader.getline()) { return false; }
  5107. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  5108. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  5109. #else
  5110. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  5111. #endif
  5112. std::cmatch m;
  5113. if (!std::regex_match(line_reader.ptr(), m, re)) {
  5114. return req.method == "CONNECT";
  5115. }
  5116. res.version = std::string(m[1]);
  5117. res.status = std::stoi(std::string(m[2]));
  5118. res.reason = std::string(m[3]);
  5119. // Ignore '100 Continue'
  5120. while (res.status == StatusCode::Continue_100) {
  5121. if (!line_reader.getline()) { return false; } // CRLF
  5122. if (!line_reader.getline()) { return false; } // next response line
  5123. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  5124. res.version = std::string(m[1]);
  5125. res.status = std::stoi(std::string(m[2]));
  5126. res.reason = std::string(m[3]);
  5127. }
  5128. return true;
  5129. }
  5130. bool ClientImpl::send(Request &req, Response &res, Error &error) {
  5131. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  5132. auto ret = send_(req, res, error);
  5133. if (error == Error::SSLPeerCouldBeClosed_) {
  5134. assert(!ret);
  5135. ret = send_(req, res, error);
  5136. }
  5137. return ret;
  5138. }
  5139. bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  5140. {
  5141. std::lock_guard<std::mutex> guard(socket_mutex_);
  5142. // Set this to false immediately - if it ever gets set to true by the end
  5143. // of the request, we know another thread instructed us to close the
  5144. // socket.
  5145. socket_should_be_closed_when_request_is_done_ = false;
  5146. auto is_alive = false;
  5147. if (socket_.is_open()) {
  5148. is_alive = detail::is_socket_alive(socket_.sock);
  5149. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5150. if (is_alive && is_ssl()) {
  5151. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  5152. is_alive = false;
  5153. }
  5154. }
  5155. #endif
  5156. if (!is_alive) {
  5157. // Attempt to avoid sigpipe by shutting down non-gracefully if it
  5158. // seems like the other side has already closed the connection Also,
  5159. // there cannot be any requests in flight from other threads since we
  5160. // locked request_mutex_, so safe to close everything immediately
  5161. const bool shutdown_gracefully = false;
  5162. shutdown_ssl(socket_, shutdown_gracefully);
  5163. shutdown_socket(socket_);
  5164. close_socket(socket_);
  5165. }
  5166. }
  5167. if (!is_alive) {
  5168. if (!create_and_connect_socket(socket_, error)) {
  5169. output_error_log(error, &req);
  5170. return false;
  5171. }
  5172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5173. // TODO: refactoring
  5174. if (is_ssl()) {
  5175. auto &scli = static_cast<SSLClient &>(*this);
  5176. if (!proxy_host_.empty() && proxy_port_ != -1) {
  5177. auto success = false;
  5178. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  5179. error)) {
  5180. if (!success) { output_error_log(error, &req); }
  5181. return success;
  5182. }
  5183. }
  5184. if (!scli.initialize_ssl(socket_, error)) {
  5185. output_error_log(error, &req);
  5186. return false;
  5187. }
  5188. }
  5189. #endif
  5190. }
  5191. // Mark the current socket as being in use so that it cannot be closed by
  5192. // anyone else while this request is ongoing, even though we will be
  5193. // releasing the mutex.
  5194. if (socket_requests_in_flight_ > 1) {
  5195. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  5196. }
  5197. socket_requests_in_flight_ += 1;
  5198. socket_requests_are_from_thread_ = std::this_thread::get_id();
  5199. }
  5200. for (const auto &header : default_headers_) {
  5201. if (req.headers.find(header.first) == req.headers.end()) {
  5202. req.headers.insert(header);
  5203. }
  5204. }
  5205. auto ret = false;
  5206. auto close_connection = !keep_alive_;
  5207. auto se = detail::scope_exit([&]() {
  5208. // Briefly lock mutex in order to mark that a request is no longer ongoing
  5209. std::lock_guard<std::mutex> guard(socket_mutex_);
  5210. socket_requests_in_flight_ -= 1;
  5211. if (socket_requests_in_flight_ <= 0) {
  5212. assert(socket_requests_in_flight_ == 0);
  5213. socket_requests_are_from_thread_ = std::thread::id();
  5214. }
  5215. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  5216. !ret) {
  5217. shutdown_ssl(socket_, true);
  5218. shutdown_socket(socket_);
  5219. close_socket(socket_);
  5220. }
  5221. });
  5222. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  5223. return handle_request(strm, req, res, close_connection, error);
  5224. });
  5225. if (!ret) {
  5226. if (error == Error::Success) {
  5227. error = Error::Unknown;
  5228. output_error_log(error, &req);
  5229. }
  5230. }
  5231. return ret;
  5232. }
  5233. Result ClientImpl::send(const Request &req) {
  5234. auto req2 = req;
  5235. return send_(std::move(req2));
  5236. }
  5237. Result ClientImpl::send_(Request &&req) {
  5238. auto res = detail::make_unique<Response>();
  5239. auto error = Error::Success;
  5240. auto ret = send(req, *res, error);
  5241. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5242. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  5243. last_ssl_error_, last_openssl_error_};
  5244. #else
  5245. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  5246. #endif
  5247. }
  5248. bool ClientImpl::handle_request(Stream &strm, Request &req,
  5249. Response &res, bool close_connection,
  5250. Error &error) {
  5251. if (req.path.empty()) {
  5252. error = Error::Connection;
  5253. output_error_log(error, &req);
  5254. return false;
  5255. }
  5256. auto req_save = req;
  5257. bool ret;
  5258. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  5259. auto req2 = req;
  5260. req2.path = "http://" + host_and_port_ + req.path;
  5261. ret = process_request(strm, req2, res, close_connection, error);
  5262. req = req2;
  5263. req.path = req_save.path;
  5264. } else {
  5265. ret = process_request(strm, req, res, close_connection, error);
  5266. }
  5267. if (!ret) { return false; }
  5268. if (res.get_header_value("Connection") == "close" ||
  5269. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  5270. // TODO this requires a not-entirely-obvious chain of calls to be correct
  5271. // for this to be safe.
  5272. // This is safe to call because handle_request is only called by send_
  5273. // which locks the request mutex during the process. It would be a bug
  5274. // to call it from a different thread since it's a thread-safety issue
  5275. // to do these things to the socket if another thread is using the socket.
  5276. std::lock_guard<std::mutex> guard(socket_mutex_);
  5277. shutdown_ssl(socket_, true);
  5278. shutdown_socket(socket_);
  5279. close_socket(socket_);
  5280. }
  5281. if (300 < res.status && res.status < 400 && follow_location_) {
  5282. req = req_save;
  5283. ret = redirect(req, res, error);
  5284. }
  5285. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5286. if ((res.status == StatusCode::Unauthorized_401 ||
  5287. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  5288. req.authorization_count_ < 5) {
  5289. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  5290. const auto &username =
  5291. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  5292. const auto &password =
  5293. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  5294. if (!username.empty() && !password.empty()) {
  5295. std::map<std::string, std::string> auth;
  5296. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  5297. Request new_req = req;
  5298. new_req.authorization_count_ += 1;
  5299. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  5300. : "Authorization");
  5301. new_req.headers.insert(detail::make_digest_authentication_header(
  5302. req, auth, new_req.authorization_count_, detail::random_string(10),
  5303. username, password, is_proxy));
  5304. Response new_res;
  5305. ret = send(new_req, new_res, error);
  5306. if (ret) { res = new_res; }
  5307. }
  5308. }
  5309. }
  5310. #endif
  5311. return ret;
  5312. }
  5313. bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  5314. if (req.redirect_count_ == 0) {
  5315. error = Error::ExceedRedirectCount;
  5316. output_error_log(error, &req);
  5317. return false;
  5318. }
  5319. auto location = res.get_header_value("location");
  5320. if (location.empty()) { return false; }
  5321. thread_local const std::regex re(
  5322. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  5323. std::smatch m;
  5324. if (!std::regex_match(location, m, re)) { return false; }
  5325. auto scheme = is_ssl() ? "https" : "http";
  5326. auto next_scheme = m[1].str();
  5327. auto next_host = m[2].str();
  5328. if (next_host.empty()) { next_host = m[3].str(); }
  5329. auto port_str = m[4].str();
  5330. auto next_path = m[5].str();
  5331. auto next_query = m[6].str();
  5332. auto next_port = port_;
  5333. if (!port_str.empty()) {
  5334. next_port = std::stoi(port_str);
  5335. } else if (!next_scheme.empty()) {
  5336. next_port = next_scheme == "https" ? 443 : 80;
  5337. }
  5338. if (next_scheme.empty()) { next_scheme = scheme; }
  5339. if (next_host.empty()) { next_host = host_; }
  5340. if (next_path.empty()) { next_path = "/"; }
  5341. auto path = decode_query_component(next_path, true) + next_query;
  5342. // Same host redirect - use current client
  5343. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  5344. return detail::redirect(*this, req, res, path, location, error);
  5345. }
  5346. // Cross-host/scheme redirect - create new client with robust setup
  5347. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  5348. path, location, error);
  5349. }
  5350. // New method for robust redirect client creation
  5351. bool ClientImpl::create_redirect_client(
  5352. const std::string &scheme, const std::string &host, int port, Request &req,
  5353. Response &res, const std::string &path, const std::string &location,
  5354. Error &error) {
  5355. // Determine if we need SSL
  5356. auto need_ssl = (scheme == "https");
  5357. // Clean up request headers that are host/client specific
  5358. // Remove headers that should not be carried over to new host
  5359. auto headers_to_remove =
  5360. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  5361. for (const auto &header_name : headers_to_remove) {
  5362. auto it = req.headers.find(header_name);
  5363. while (it != req.headers.end()) {
  5364. it = req.headers.erase(it);
  5365. it = req.headers.find(header_name);
  5366. }
  5367. }
  5368. // Create appropriate client type and handle redirect
  5369. if (need_ssl) {
  5370. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5371. // Create SSL client for HTTPS redirect
  5372. SSLClient redirect_client(host, port);
  5373. // Setup basic client configuration first
  5374. setup_redirect_client(redirect_client);
  5375. // SSL-specific configuration for proxy environments
  5376. if (!proxy_host_.empty() && proxy_port_ != -1) {
  5377. // Critical: Disable SSL verification for proxy environments
  5378. redirect_client.enable_server_certificate_verification(false);
  5379. redirect_client.enable_server_hostname_verification(false);
  5380. } else {
  5381. // For direct SSL connections, copy SSL verification settings
  5382. redirect_client.enable_server_certificate_verification(
  5383. server_certificate_verification_);
  5384. redirect_client.enable_server_hostname_verification(
  5385. server_hostname_verification_);
  5386. }
  5387. // Handle CA certificate store and paths if available
  5388. if (ca_cert_store_ && X509_STORE_up_ref(ca_cert_store_)) {
  5389. redirect_client.set_ca_cert_store(ca_cert_store_);
  5390. }
  5391. if (!ca_cert_file_path_.empty()) {
  5392. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  5393. }
  5394. // Client certificates are set through constructor for SSLClient
  5395. // NOTE: SSLClient constructor already takes client_cert_path and
  5396. // client_key_path so we need to create it properly if client certs are
  5397. // needed
  5398. // Execute the redirect
  5399. return detail::redirect(redirect_client, req, res, path, location, error);
  5400. #else
  5401. // SSL not supported - set appropriate error
  5402. error = Error::SSLConnection;
  5403. output_error_log(error, &req);
  5404. return false;
  5405. #endif
  5406. } else {
  5407. // HTTP redirect
  5408. ClientImpl redirect_client(host, port);
  5409. // Setup client with robust configuration
  5410. setup_redirect_client(redirect_client);
  5411. // Execute the redirect
  5412. return detail::redirect(redirect_client, req, res, path, location, error);
  5413. }
  5414. }
  5415. // New method for robust client setup (based on basic_manual_redirect.cpp
  5416. // logic)
  5417. template <typename ClientType>
  5418. void ClientImpl::setup_redirect_client(ClientType &client) {
  5419. // Copy basic settings first
  5420. client.set_connection_timeout(connection_timeout_sec_);
  5421. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  5422. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  5423. client.set_keep_alive(keep_alive_);
  5424. client.set_follow_location(
  5425. true); // Enable redirects to handle multi-step redirects
  5426. client.set_path_encode(path_encode_);
  5427. client.set_compress(compress_);
  5428. client.set_decompress(decompress_);
  5429. // Copy authentication settings BEFORE proxy setup
  5430. if (!basic_auth_username_.empty()) {
  5431. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  5432. }
  5433. if (!bearer_token_auth_token_.empty()) {
  5434. client.set_bearer_token_auth(bearer_token_auth_token_);
  5435. }
  5436. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5437. if (!digest_auth_username_.empty()) {
  5438. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  5439. }
  5440. #endif
  5441. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  5442. // before proxy auth)
  5443. if (!proxy_host_.empty() && proxy_port_ != -1) {
  5444. // First set proxy host and port
  5445. client.set_proxy(proxy_host_, proxy_port_);
  5446. // Then set proxy authentication (order matters!)
  5447. if (!proxy_basic_auth_username_.empty()) {
  5448. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  5449. proxy_basic_auth_password_);
  5450. }
  5451. if (!proxy_bearer_token_auth_token_.empty()) {
  5452. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  5453. }
  5454. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5455. if (!proxy_digest_auth_username_.empty()) {
  5456. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  5457. proxy_digest_auth_password_);
  5458. }
  5459. #endif
  5460. }
  5461. // Copy network and socket settings
  5462. client.set_address_family(address_family_);
  5463. client.set_tcp_nodelay(tcp_nodelay_);
  5464. client.set_ipv6_v6only(ipv6_v6only_);
  5465. if (socket_options_) { client.set_socket_options(socket_options_); }
  5466. if (!interface_.empty()) { client.set_interface(interface_); }
  5467. // Copy logging and headers
  5468. if (logger_) { client.set_logger(logger_); }
  5469. if (error_logger_) { client.set_error_logger(error_logger_); }
  5470. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  5471. // Each new client should generate its own headers based on its target host
  5472. }
  5473. bool ClientImpl::write_content_with_provider(Stream &strm,
  5474. const Request &req,
  5475. Error &error) const {
  5476. auto is_shutting_down = []() { return false; };
  5477. if (req.is_chunked_content_provider_) {
  5478. // TODO: Brotli support
  5479. std::unique_ptr<detail::compressor> compressor;
  5480. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5481. if (compress_) {
  5482. compressor = detail::make_unique<detail::gzip_compressor>();
  5483. } else
  5484. #endif
  5485. {
  5486. compressor = detail::make_unique<detail::nocompressor>();
  5487. }
  5488. return detail::write_content_chunked(strm, req.content_provider_,
  5489. is_shutting_down, *compressor, error);
  5490. } else {
  5491. return detail::write_content_with_progress(
  5492. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  5493. req.upload_progress, error);
  5494. }
  5495. }
  5496. bool ClientImpl::write_request(Stream &strm, Request &req,
  5497. bool close_connection, Error &error) {
  5498. // Prepare additional headers
  5499. if (close_connection) {
  5500. if (!req.has_header("Connection")) {
  5501. req.set_header("Connection", "close");
  5502. }
  5503. }
  5504. if (!req.has_header("Host")) {
  5505. // For Unix socket connections, use "localhost" as Host header (similar to
  5506. // curl behavior)
  5507. if (address_family_ == AF_UNIX) {
  5508. req.set_header("Host", "localhost");
  5509. } else {
  5510. req.set_header("Host", host_and_port_);
  5511. }
  5512. }
  5513. if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); }
  5514. if (!req.content_receiver) {
  5515. if (!req.has_header("Accept-Encoding")) {
  5516. std::string accept_encoding;
  5517. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5518. accept_encoding = "br";
  5519. #endif
  5520. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5521. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  5522. accept_encoding += "gzip, deflate";
  5523. #endif
  5524. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5525. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  5526. accept_encoding += "zstd";
  5527. #endif
  5528. req.set_header("Accept-Encoding", accept_encoding);
  5529. }
  5530. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  5531. if (!req.has_header("User-Agent")) {
  5532. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  5533. req.set_header("User-Agent", agent);
  5534. }
  5535. #endif
  5536. };
  5537. if (req.body.empty()) {
  5538. if (req.content_provider_) {
  5539. if (!req.is_chunked_content_provider_) {
  5540. if (!req.has_header("Content-Length")) {
  5541. auto length = std::to_string(req.content_length_);
  5542. req.set_header("Content-Length", length);
  5543. }
  5544. }
  5545. } else {
  5546. if (req.method == "POST" || req.method == "PUT" ||
  5547. req.method == "PATCH") {
  5548. req.set_header("Content-Length", "0");
  5549. }
  5550. }
  5551. } else {
  5552. if (!req.has_header("Content-Type")) {
  5553. req.set_header("Content-Type", "text/plain");
  5554. }
  5555. if (!req.has_header("Content-Length")) {
  5556. auto length = std::to_string(req.body.size());
  5557. req.set_header("Content-Length", length);
  5558. }
  5559. }
  5560. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  5561. if (!req.has_header("Authorization")) {
  5562. req.headers.insert(make_basic_authentication_header(
  5563. basic_auth_username_, basic_auth_password_, false));
  5564. }
  5565. }
  5566. if (!proxy_basic_auth_username_.empty() &&
  5567. !proxy_basic_auth_password_.empty()) {
  5568. if (!req.has_header("Proxy-Authorization")) {
  5569. req.headers.insert(make_basic_authentication_header(
  5570. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  5571. }
  5572. }
  5573. if (!bearer_token_auth_token_.empty()) {
  5574. if (!req.has_header("Authorization")) {
  5575. req.headers.insert(make_bearer_token_authentication_header(
  5576. bearer_token_auth_token_, false));
  5577. }
  5578. }
  5579. if (!proxy_bearer_token_auth_token_.empty()) {
  5580. if (!req.has_header("Proxy-Authorization")) {
  5581. req.headers.insert(make_bearer_token_authentication_header(
  5582. proxy_bearer_token_auth_token_, true));
  5583. }
  5584. }
  5585. // Request line and headers
  5586. {
  5587. detail::BufferStream bstrm;
  5588. // Extract path and query from req.path
  5589. std::string path_part, query_part;
  5590. auto query_pos = req.path.find('?');
  5591. if (query_pos != std::string::npos) {
  5592. path_part = req.path.substr(0, query_pos);
  5593. query_part = req.path.substr(query_pos + 1);
  5594. } else {
  5595. path_part = req.path;
  5596. query_part = "";
  5597. }
  5598. // Encode path and query
  5599. auto path_with_query =
  5600. path_encode_ ? detail::encode_path(path_part) : path_part;
  5601. detail::parse_query_text(query_part, req.params);
  5602. if (!req.params.empty()) {
  5603. path_with_query = append_query_params(path_with_query, req.params);
  5604. }
  5605. // Write request line and headers
  5606. detail::write_request_line(bstrm, req.method, path_with_query);
  5607. header_writer_(bstrm, req.headers);
  5608. // Flush buffer
  5609. auto &data = bstrm.get_buffer();
  5610. if (!detail::write_data(strm, data.data(), data.size())) {
  5611. error = Error::Write;
  5612. output_error_log(error, &req);
  5613. return false;
  5614. }
  5615. }
  5616. // Body
  5617. if (req.body.empty()) {
  5618. return write_content_with_provider(strm, req, error);
  5619. }
  5620. if (req.upload_progress) {
  5621. auto body_size = req.body.size();
  5622. size_t written = 0;
  5623. auto data = req.body.data();
  5624. while (written < body_size) {
  5625. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  5626. if (!detail::write_data(strm, data + written, to_write)) {
  5627. error = Error::Write;
  5628. output_error_log(error, &req);
  5629. return false;
  5630. }
  5631. written += to_write;
  5632. if (!req.upload_progress(written, body_size)) {
  5633. error = Error::Canceled;
  5634. output_error_log(error, &req);
  5635. return false;
  5636. }
  5637. }
  5638. } else {
  5639. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  5640. error = Error::Write;
  5641. output_error_log(error, &req);
  5642. return false;
  5643. }
  5644. }
  5645. return true;
  5646. }
  5647. std::unique_ptr<Response>
  5648. ClientImpl::send_with_content_provider_and_receiver(
  5649. Request &req, const char *body, size_t content_length,
  5650. ContentProvider content_provider,
  5651. ContentProviderWithoutLength content_provider_without_length,
  5652. const std::string &content_type, ContentReceiver content_receiver,
  5653. Error &error) {
  5654. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  5655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5656. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  5657. #endif
  5658. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5659. if (compress_ && !content_provider_without_length) {
  5660. // TODO: Brotli support
  5661. detail::gzip_compressor compressor;
  5662. if (content_provider) {
  5663. auto ok = true;
  5664. size_t offset = 0;
  5665. DataSink data_sink;
  5666. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  5667. if (ok) {
  5668. auto last = offset + data_len == content_length;
  5669. auto ret = compressor.compress(
  5670. data, data_len, last,
  5671. [&](const char *compressed_data, size_t compressed_data_len) {
  5672. req.body.append(compressed_data, compressed_data_len);
  5673. return true;
  5674. });
  5675. if (ret) {
  5676. offset += data_len;
  5677. } else {
  5678. ok = false;
  5679. }
  5680. }
  5681. return ok;
  5682. };
  5683. while (ok && offset < content_length) {
  5684. if (!content_provider(offset, content_length - offset, data_sink)) {
  5685. error = Error::Canceled;
  5686. output_error_log(error, &req);
  5687. return nullptr;
  5688. }
  5689. }
  5690. } else {
  5691. if (!compressor.compress(body, content_length, true,
  5692. [&](const char *data, size_t data_len) {
  5693. req.body.append(data, data_len);
  5694. return true;
  5695. })) {
  5696. error = Error::Compression;
  5697. output_error_log(error, &req);
  5698. return nullptr;
  5699. }
  5700. }
  5701. } else
  5702. #endif
  5703. {
  5704. if (content_provider) {
  5705. req.content_length_ = content_length;
  5706. req.content_provider_ = std::move(content_provider);
  5707. req.is_chunked_content_provider_ = false;
  5708. } else if (content_provider_without_length) {
  5709. req.content_length_ = 0;
  5710. req.content_provider_ = detail::ContentProviderAdapter(
  5711. std::move(content_provider_without_length));
  5712. req.is_chunked_content_provider_ = true;
  5713. req.set_header("Transfer-Encoding", "chunked");
  5714. } else {
  5715. req.body.assign(body, content_length);
  5716. }
  5717. }
  5718. if (content_receiver) {
  5719. req.content_receiver =
  5720. [content_receiver](const char *data, size_t data_length,
  5721. size_t /*offset*/, size_t /*total_length*/) {
  5722. return content_receiver(data, data_length);
  5723. };
  5724. }
  5725. auto res = detail::make_unique<Response>();
  5726. return send(req, *res, error) ? std::move(res) : nullptr;
  5727. }
  5728. Result ClientImpl::send_with_content_provider_and_receiver(
  5729. const std::string &method, const std::string &path, const Headers &headers,
  5730. const char *body, size_t content_length, ContentProvider content_provider,
  5731. ContentProviderWithoutLength content_provider_without_length,
  5732. const std::string &content_type, ContentReceiver content_receiver,
  5733. UploadProgress progress) {
  5734. Request req;
  5735. req.method = method;
  5736. req.headers = headers;
  5737. req.path = path;
  5738. req.upload_progress = std::move(progress);
  5739. if (max_timeout_msec_ > 0) {
  5740. req.start_time_ = std::chrono::steady_clock::now();
  5741. }
  5742. auto error = Error::Success;
  5743. auto res = send_with_content_provider_and_receiver(
  5744. req, body, content_length, std::move(content_provider),
  5745. std::move(content_provider_without_length), content_type,
  5746. std::move(content_receiver), error);
  5747. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5748. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  5749. last_openssl_error_};
  5750. #else
  5751. return Result{std::move(res), error, std::move(req.headers)};
  5752. #endif
  5753. }
  5754. void ClientImpl::output_log(const Request &req,
  5755. const Response &res) const {
  5756. if (logger_) {
  5757. std::lock_guard<std::mutex> guard(logger_mutex_);
  5758. logger_(req, res);
  5759. }
  5760. }
  5761. void ClientImpl::output_error_log(const Error &err,
  5762. const Request *req) const {
  5763. if (error_logger_) {
  5764. std::lock_guard<std::mutex> guard(logger_mutex_);
  5765. error_logger_(err, req);
  5766. }
  5767. }
  5768. bool ClientImpl::process_request(Stream &strm, Request &req,
  5769. Response &res, bool close_connection,
  5770. Error &error) {
  5771. // Send request
  5772. if (!write_request(strm, req, close_connection, error)) { return false; }
  5773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5774. if (is_ssl()) {
  5775. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  5776. if (!is_proxy_enabled) {
  5777. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  5778. error = Error::SSLPeerCouldBeClosed_;
  5779. output_error_log(error, &req);
  5780. return false;
  5781. }
  5782. }
  5783. }
  5784. #endif
  5785. // Receive response and headers
  5786. if (!read_response_line(strm, req, res) ||
  5787. !detail::read_headers(strm, res.headers)) {
  5788. error = Error::Read;
  5789. output_error_log(error, &req);
  5790. return false;
  5791. }
  5792. // Body
  5793. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  5794. req.method != "CONNECT") {
  5795. auto redirect = 300 < res.status && res.status < 400 &&
  5796. res.status != StatusCode::NotModified_304 &&
  5797. follow_location_;
  5798. if (req.response_handler && !redirect) {
  5799. if (!req.response_handler(res)) {
  5800. error = Error::Canceled;
  5801. output_error_log(error, &req);
  5802. return false;
  5803. }
  5804. }
  5805. auto out =
  5806. req.content_receiver
  5807. ? static_cast<ContentReceiverWithProgress>(
  5808. [&](const char *buf, size_t n, size_t off, size_t len) {
  5809. if (redirect) { return true; }
  5810. auto ret = req.content_receiver(buf, n, off, len);
  5811. if (!ret) {
  5812. error = Error::Canceled;
  5813. output_error_log(error, &req);
  5814. }
  5815. return ret;
  5816. })
  5817. : static_cast<ContentReceiverWithProgress>(
  5818. [&](const char *buf, size_t n, size_t /*off*/,
  5819. size_t /*len*/) {
  5820. assert(res.body.size() + n <= res.body.max_size());
  5821. res.body.append(buf, n);
  5822. return true;
  5823. });
  5824. auto progress = [&](size_t current, size_t total) {
  5825. if (!req.download_progress || redirect) { return true; }
  5826. auto ret = req.download_progress(current, total);
  5827. if (!ret) {
  5828. error = Error::Canceled;
  5829. output_error_log(error, &req);
  5830. }
  5831. return ret;
  5832. };
  5833. if (res.has_header("Content-Length")) {
  5834. if (!req.content_receiver) {
  5835. auto len = res.get_header_value_u64("Content-Length");
  5836. if (len > res.body.max_size()) {
  5837. error = Error::Read;
  5838. output_error_log(error, &req);
  5839. return false;
  5840. }
  5841. res.body.reserve(static_cast<size_t>(len));
  5842. }
  5843. }
  5844. if (res.status != StatusCode::NotModified_304) {
  5845. int dummy_status;
  5846. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  5847. dummy_status, std::move(progress),
  5848. std::move(out), decompress_)) {
  5849. if (error != Error::Canceled) { error = Error::Read; }
  5850. output_error_log(error, &req);
  5851. return false;
  5852. }
  5853. }
  5854. }
  5855. // Log
  5856. output_log(req, res);
  5857. return true;
  5858. }
  5859. ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  5860. const std::string &boundary, const UploadFormDataItems &items,
  5861. const FormDataProviderItems &provider_items) const {
  5862. size_t cur_item = 0;
  5863. size_t cur_start = 0;
  5864. // cur_item and cur_start are copied to within the std::function and
  5865. // maintain state between successive calls
  5866. return [&, cur_item, cur_start](size_t offset,
  5867. DataSink &sink) mutable -> bool {
  5868. if (!offset && !items.empty()) {
  5869. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  5870. return true;
  5871. } else if (cur_item < provider_items.size()) {
  5872. if (!cur_start) {
  5873. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  5874. provider_items[cur_item], boundary);
  5875. offset += begin.size();
  5876. cur_start = offset;
  5877. sink.os << begin;
  5878. }
  5879. DataSink cur_sink;
  5880. auto has_data = true;
  5881. cur_sink.write = sink.write;
  5882. cur_sink.done = [&]() { has_data = false; };
  5883. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  5884. return false;
  5885. }
  5886. if (!has_data) {
  5887. sink.os << detail::serialize_multipart_formdata_item_end();
  5888. cur_item++;
  5889. cur_start = 0;
  5890. }
  5891. return true;
  5892. } else {
  5893. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  5894. sink.done();
  5895. return true;
  5896. }
  5897. };
  5898. }
  5899. bool ClientImpl::process_socket(
  5900. const Socket &socket,
  5901. std::chrono::time_point<std::chrono::steady_clock> start_time,
  5902. std::function<bool(Stream &strm)> callback) {
  5903. return detail::process_client_socket(
  5904. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  5905. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  5906. }
  5907. bool ClientImpl::is_ssl() const { return false; }
  5908. Result ClientImpl::Get(const std::string &path,
  5909. DownloadProgress progress) {
  5910. return Get(path, Headers(), std::move(progress));
  5911. }
  5912. Result ClientImpl::Get(const std::string &path, const Params &params,
  5913. const Headers &headers,
  5914. DownloadProgress progress) {
  5915. if (params.empty()) { return Get(path, headers); }
  5916. std::string path_with_query = append_query_params(path, params);
  5917. return Get(path_with_query, headers, std::move(progress));
  5918. }
  5919. Result ClientImpl::Get(const std::string &path, const Headers &headers,
  5920. DownloadProgress progress) {
  5921. Request req;
  5922. req.method = "GET";
  5923. req.path = path;
  5924. req.headers = headers;
  5925. req.download_progress = std::move(progress);
  5926. if (max_timeout_msec_ > 0) {
  5927. req.start_time_ = std::chrono::steady_clock::now();
  5928. }
  5929. return send_(std::move(req));
  5930. }
  5931. Result ClientImpl::Get(const std::string &path,
  5932. ContentReceiver content_receiver,
  5933. DownloadProgress progress) {
  5934. return Get(path, Headers(), nullptr, std::move(content_receiver),
  5935. std::move(progress));
  5936. }
  5937. Result ClientImpl::Get(const std::string &path, const Headers &headers,
  5938. ContentReceiver content_receiver,
  5939. DownloadProgress progress) {
  5940. return Get(path, headers, nullptr, std::move(content_receiver),
  5941. std::move(progress));
  5942. }
  5943. Result ClientImpl::Get(const std::string &path,
  5944. ResponseHandler response_handler,
  5945. ContentReceiver content_receiver,
  5946. DownloadProgress progress) {
  5947. return Get(path, Headers(), std::move(response_handler),
  5948. std::move(content_receiver), std::move(progress));
  5949. }
  5950. Result ClientImpl::Get(const std::string &path, const Headers &headers,
  5951. ResponseHandler response_handler,
  5952. ContentReceiver content_receiver,
  5953. DownloadProgress progress) {
  5954. Request req;
  5955. req.method = "GET";
  5956. req.path = path;
  5957. req.headers = headers;
  5958. req.response_handler = std::move(response_handler);
  5959. req.content_receiver =
  5960. [content_receiver](const char *data, size_t data_length,
  5961. size_t /*offset*/, size_t /*total_length*/) {
  5962. return content_receiver(data, data_length);
  5963. };
  5964. req.download_progress = std::move(progress);
  5965. if (max_timeout_msec_ > 0) {
  5966. req.start_time_ = std::chrono::steady_clock::now();
  5967. }
  5968. return send_(std::move(req));
  5969. }
  5970. Result ClientImpl::Get(const std::string &path, const Params &params,
  5971. const Headers &headers,
  5972. ContentReceiver content_receiver,
  5973. DownloadProgress progress) {
  5974. return Get(path, params, headers, nullptr, std::move(content_receiver),
  5975. std::move(progress));
  5976. }
  5977. Result ClientImpl::Get(const std::string &path, const Params &params,
  5978. const Headers &headers,
  5979. ResponseHandler response_handler,
  5980. ContentReceiver content_receiver,
  5981. DownloadProgress progress) {
  5982. if (params.empty()) {
  5983. return Get(path, headers, std::move(response_handler),
  5984. std::move(content_receiver), std::move(progress));
  5985. }
  5986. std::string path_with_query = append_query_params(path, params);
  5987. return Get(path_with_query, headers, std::move(response_handler),
  5988. std::move(content_receiver), std::move(progress));
  5989. }
  5990. Result ClientImpl::Head(const std::string &path) {
  5991. return Head(path, Headers());
  5992. }
  5993. Result ClientImpl::Head(const std::string &path,
  5994. const Headers &headers) {
  5995. Request req;
  5996. req.method = "HEAD";
  5997. req.headers = headers;
  5998. req.path = path;
  5999. if (max_timeout_msec_ > 0) {
  6000. req.start_time_ = std::chrono::steady_clock::now();
  6001. }
  6002. return send_(std::move(req));
  6003. }
  6004. Result ClientImpl::Post(const std::string &path) {
  6005. return Post(path, std::string(), std::string());
  6006. }
  6007. Result ClientImpl::Post(const std::string &path,
  6008. const Headers &headers) {
  6009. return Post(path, headers, nullptr, 0, std::string());
  6010. }
  6011. Result ClientImpl::Post(const std::string &path, const char *body,
  6012. size_t content_length,
  6013. const std::string &content_type,
  6014. UploadProgress progress) {
  6015. return Post(path, Headers(), body, content_length, content_type, progress);
  6016. }
  6017. Result ClientImpl::Post(const std::string &path, const std::string &body,
  6018. const std::string &content_type,
  6019. UploadProgress progress) {
  6020. return Post(path, Headers(), body, content_type, progress);
  6021. }
  6022. Result ClientImpl::Post(const std::string &path, const Params &params) {
  6023. return Post(path, Headers(), params);
  6024. }
  6025. Result ClientImpl::Post(const std::string &path, size_t content_length,
  6026. ContentProvider content_provider,
  6027. const std::string &content_type,
  6028. UploadProgress progress) {
  6029. return Post(path, Headers(), content_length, std::move(content_provider),
  6030. content_type, progress);
  6031. }
  6032. Result ClientImpl::Post(const std::string &path, size_t content_length,
  6033. ContentProvider content_provider,
  6034. const std::string &content_type,
  6035. ContentReceiver content_receiver,
  6036. UploadProgress progress) {
  6037. return Post(path, Headers(), content_length, std::move(content_provider),
  6038. content_type, std::move(content_receiver), progress);
  6039. }
  6040. Result ClientImpl::Post(const std::string &path,
  6041. ContentProviderWithoutLength content_provider,
  6042. const std::string &content_type,
  6043. UploadProgress progress) {
  6044. return Post(path, Headers(), std::move(content_provider), content_type,
  6045. progress);
  6046. }
  6047. Result ClientImpl::Post(const std::string &path,
  6048. ContentProviderWithoutLength content_provider,
  6049. const std::string &content_type,
  6050. ContentReceiver content_receiver,
  6051. UploadProgress progress) {
  6052. return Post(path, Headers(), std::move(content_provider), content_type,
  6053. std::move(content_receiver), progress);
  6054. }
  6055. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6056. const Params &params) {
  6057. auto query = detail::params_to_query_str(params);
  6058. return Post(path, headers, query, "application/x-www-form-urlencoded");
  6059. }
  6060. Result ClientImpl::Post(const std::string &path,
  6061. const UploadFormDataItems &items,
  6062. UploadProgress progress) {
  6063. return Post(path, Headers(), items, progress);
  6064. }
  6065. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6066. const UploadFormDataItems &items,
  6067. UploadProgress progress) {
  6068. const auto &boundary = detail::make_multipart_data_boundary();
  6069. const auto &content_type =
  6070. detail::serialize_multipart_formdata_get_content_type(boundary);
  6071. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6072. return Post(path, headers, body, content_type, progress);
  6073. }
  6074. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6075. const UploadFormDataItems &items,
  6076. const std::string &boundary,
  6077. UploadProgress progress) {
  6078. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  6079. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  6080. }
  6081. const auto &content_type =
  6082. detail::serialize_multipart_formdata_get_content_type(boundary);
  6083. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6084. return Post(path, headers, body, content_type, progress);
  6085. }
  6086. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6087. const char *body, size_t content_length,
  6088. const std::string &content_type,
  6089. UploadProgress progress) {
  6090. return send_with_content_provider_and_receiver(
  6091. "POST", path, headers, body, content_length, nullptr, nullptr,
  6092. content_type, nullptr, progress);
  6093. }
  6094. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6095. const std::string &body,
  6096. const std::string &content_type,
  6097. UploadProgress progress) {
  6098. return send_with_content_provider_and_receiver(
  6099. "POST", path, headers, body.data(), body.size(), nullptr, nullptr,
  6100. content_type, nullptr, progress);
  6101. }
  6102. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6103. size_t content_length,
  6104. ContentProvider content_provider,
  6105. const std::string &content_type,
  6106. UploadProgress progress) {
  6107. return send_with_content_provider_and_receiver(
  6108. "POST", path, headers, nullptr, content_length,
  6109. std::move(content_provider), nullptr, content_type, nullptr, progress);
  6110. }
  6111. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6112. size_t content_length,
  6113. ContentProvider content_provider,
  6114. const std::string &content_type,
  6115. ContentReceiver content_receiver,
  6116. DownloadProgress progress) {
  6117. return send_with_content_provider_and_receiver(
  6118. "POST", path, headers, nullptr, content_length,
  6119. std::move(content_provider), nullptr, content_type,
  6120. std::move(content_receiver), std::move(progress));
  6121. }
  6122. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6123. ContentProviderWithoutLength content_provider,
  6124. const std::string &content_type,
  6125. UploadProgress progress) {
  6126. return send_with_content_provider_and_receiver(
  6127. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  6128. content_type, nullptr, progress);
  6129. }
  6130. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6131. ContentProviderWithoutLength content_provider,
  6132. const std::string &content_type,
  6133. ContentReceiver content_receiver,
  6134. DownloadProgress progress) {
  6135. return send_with_content_provider_and_receiver(
  6136. "POST", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  6137. content_type, std::move(content_receiver), std::move(progress));
  6138. }
  6139. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6140. const UploadFormDataItems &items,
  6141. const FormDataProviderItems &provider_items,
  6142. UploadProgress progress) {
  6143. const auto &boundary = detail::make_multipart_data_boundary();
  6144. const auto &content_type =
  6145. detail::serialize_multipart_formdata_get_content_type(boundary);
  6146. return send_with_content_provider_and_receiver(
  6147. "POST", path, headers, nullptr, 0, nullptr,
  6148. get_multipart_content_provider(boundary, items, provider_items),
  6149. content_type, nullptr, progress);
  6150. }
  6151. Result ClientImpl::Post(const std::string &path, const Headers &headers,
  6152. const std::string &body,
  6153. const std::string &content_type,
  6154. ContentReceiver content_receiver,
  6155. DownloadProgress progress) {
  6156. Request req;
  6157. req.method = "POST";
  6158. req.path = path;
  6159. req.headers = headers;
  6160. req.body = body;
  6161. req.content_receiver =
  6162. [content_receiver](const char *data, size_t data_length,
  6163. size_t /*offset*/, size_t /*total_length*/) {
  6164. return content_receiver(data, data_length);
  6165. };
  6166. req.download_progress = std::move(progress);
  6167. if (max_timeout_msec_ > 0) {
  6168. req.start_time_ = std::chrono::steady_clock::now();
  6169. }
  6170. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  6171. return send_(std::move(req));
  6172. }
  6173. Result ClientImpl::Put(const std::string &path) {
  6174. return Put(path, std::string(), std::string());
  6175. }
  6176. Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  6177. return Put(path, headers, nullptr, 0, std::string());
  6178. }
  6179. Result ClientImpl::Put(const std::string &path, const char *body,
  6180. size_t content_length,
  6181. const std::string &content_type,
  6182. UploadProgress progress) {
  6183. return Put(path, Headers(), body, content_length, content_type, progress);
  6184. }
  6185. Result ClientImpl::Put(const std::string &path, const std::string &body,
  6186. const std::string &content_type,
  6187. UploadProgress progress) {
  6188. return Put(path, Headers(), body, content_type, progress);
  6189. }
  6190. Result ClientImpl::Put(const std::string &path, const Params &params) {
  6191. return Put(path, Headers(), params);
  6192. }
  6193. Result ClientImpl::Put(const std::string &path, size_t content_length,
  6194. ContentProvider content_provider,
  6195. const std::string &content_type,
  6196. UploadProgress progress) {
  6197. return Put(path, Headers(), content_length, std::move(content_provider),
  6198. content_type, progress);
  6199. }
  6200. Result ClientImpl::Put(const std::string &path, size_t content_length,
  6201. ContentProvider content_provider,
  6202. const std::string &content_type,
  6203. ContentReceiver content_receiver,
  6204. UploadProgress progress) {
  6205. return Put(path, Headers(), content_length, std::move(content_provider),
  6206. content_type, std::move(content_receiver), progress);
  6207. }
  6208. Result ClientImpl::Put(const std::string &path,
  6209. ContentProviderWithoutLength content_provider,
  6210. const std::string &content_type,
  6211. UploadProgress progress) {
  6212. return Put(path, Headers(), std::move(content_provider), content_type,
  6213. progress);
  6214. }
  6215. Result ClientImpl::Put(const std::string &path,
  6216. ContentProviderWithoutLength content_provider,
  6217. const std::string &content_type,
  6218. ContentReceiver content_receiver,
  6219. UploadProgress progress) {
  6220. return Put(path, Headers(), std::move(content_provider), content_type,
  6221. std::move(content_receiver), progress);
  6222. }
  6223. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6224. const Params &params) {
  6225. auto query = detail::params_to_query_str(params);
  6226. return Put(path, headers, query, "application/x-www-form-urlencoded");
  6227. }
  6228. Result ClientImpl::Put(const std::string &path,
  6229. const UploadFormDataItems &items,
  6230. UploadProgress progress) {
  6231. return Put(path, Headers(), items, progress);
  6232. }
  6233. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6234. const UploadFormDataItems &items,
  6235. UploadProgress progress) {
  6236. const auto &boundary = detail::make_multipart_data_boundary();
  6237. const auto &content_type =
  6238. detail::serialize_multipart_formdata_get_content_type(boundary);
  6239. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6240. return Put(path, headers, body, content_type, progress);
  6241. }
  6242. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6243. const UploadFormDataItems &items,
  6244. const std::string &boundary,
  6245. UploadProgress progress) {
  6246. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  6247. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  6248. }
  6249. const auto &content_type =
  6250. detail::serialize_multipart_formdata_get_content_type(boundary);
  6251. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6252. return Put(path, headers, body, content_type, progress);
  6253. }
  6254. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6255. const char *body, size_t content_length,
  6256. const std::string &content_type,
  6257. UploadProgress progress) {
  6258. return send_with_content_provider_and_receiver(
  6259. "PUT", path, headers, body, content_length, nullptr, nullptr,
  6260. content_type, nullptr, progress);
  6261. }
  6262. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6263. const std::string &body,
  6264. const std::string &content_type,
  6265. UploadProgress progress) {
  6266. return send_with_content_provider_and_receiver(
  6267. "PUT", path, headers, body.data(), body.size(), nullptr, nullptr,
  6268. content_type, nullptr, progress);
  6269. }
  6270. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6271. size_t content_length,
  6272. ContentProvider content_provider,
  6273. const std::string &content_type,
  6274. UploadProgress progress) {
  6275. return send_with_content_provider_and_receiver(
  6276. "PUT", path, headers, nullptr, content_length,
  6277. std::move(content_provider), nullptr, content_type, nullptr, progress);
  6278. }
  6279. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6280. size_t content_length,
  6281. ContentProvider content_provider,
  6282. const std::string &content_type,
  6283. ContentReceiver content_receiver,
  6284. UploadProgress progress) {
  6285. return send_with_content_provider_and_receiver(
  6286. "PUT", path, headers, nullptr, content_length,
  6287. std::move(content_provider), nullptr, content_type,
  6288. std::move(content_receiver), progress);
  6289. }
  6290. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6291. ContentProviderWithoutLength content_provider,
  6292. const std::string &content_type,
  6293. UploadProgress progress) {
  6294. return send_with_content_provider_and_receiver(
  6295. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  6296. content_type, nullptr, progress);
  6297. }
  6298. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6299. ContentProviderWithoutLength content_provider,
  6300. const std::string &content_type,
  6301. ContentReceiver content_receiver,
  6302. UploadProgress progress) {
  6303. return send_with_content_provider_and_receiver(
  6304. "PUT", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  6305. content_type, std::move(content_receiver), progress);
  6306. }
  6307. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6308. const UploadFormDataItems &items,
  6309. const FormDataProviderItems &provider_items,
  6310. UploadProgress progress) {
  6311. const auto &boundary = detail::make_multipart_data_boundary();
  6312. const auto &content_type =
  6313. detail::serialize_multipart_formdata_get_content_type(boundary);
  6314. return send_with_content_provider_and_receiver(
  6315. "PUT", path, headers, nullptr, 0, nullptr,
  6316. get_multipart_content_provider(boundary, items, provider_items),
  6317. content_type, nullptr, progress);
  6318. }
  6319. Result ClientImpl::Put(const std::string &path, const Headers &headers,
  6320. const std::string &body,
  6321. const std::string &content_type,
  6322. ContentReceiver content_receiver,
  6323. DownloadProgress progress) {
  6324. Request req;
  6325. req.method = "PUT";
  6326. req.path = path;
  6327. req.headers = headers;
  6328. req.body = body;
  6329. req.content_receiver =
  6330. [content_receiver](const char *data, size_t data_length,
  6331. size_t /*offset*/, size_t /*total_length*/) {
  6332. return content_receiver(data, data_length);
  6333. };
  6334. req.download_progress = std::move(progress);
  6335. if (max_timeout_msec_ > 0) {
  6336. req.start_time_ = std::chrono::steady_clock::now();
  6337. }
  6338. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  6339. return send_(std::move(req));
  6340. }
  6341. Result ClientImpl::Patch(const std::string &path) {
  6342. return Patch(path, std::string(), std::string());
  6343. }
  6344. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6345. UploadProgress progress) {
  6346. return Patch(path, headers, nullptr, 0, std::string(), progress);
  6347. }
  6348. Result ClientImpl::Patch(const std::string &path, const char *body,
  6349. size_t content_length,
  6350. const std::string &content_type,
  6351. UploadProgress progress) {
  6352. return Patch(path, Headers(), body, content_length, content_type, progress);
  6353. }
  6354. Result ClientImpl::Patch(const std::string &path,
  6355. const std::string &body,
  6356. const std::string &content_type,
  6357. UploadProgress progress) {
  6358. return Patch(path, Headers(), body, content_type, progress);
  6359. }
  6360. Result ClientImpl::Patch(const std::string &path, const Params &params) {
  6361. return Patch(path, Headers(), params);
  6362. }
  6363. Result ClientImpl::Patch(const std::string &path, size_t content_length,
  6364. ContentProvider content_provider,
  6365. const std::string &content_type,
  6366. UploadProgress progress) {
  6367. return Patch(path, Headers(), content_length, std::move(content_provider),
  6368. content_type, progress);
  6369. }
  6370. Result ClientImpl::Patch(const std::string &path, size_t content_length,
  6371. ContentProvider content_provider,
  6372. const std::string &content_type,
  6373. ContentReceiver content_receiver,
  6374. UploadProgress progress) {
  6375. return Patch(path, Headers(), content_length, std::move(content_provider),
  6376. content_type, std::move(content_receiver), progress);
  6377. }
  6378. Result ClientImpl::Patch(const std::string &path,
  6379. ContentProviderWithoutLength content_provider,
  6380. const std::string &content_type,
  6381. UploadProgress progress) {
  6382. return Patch(path, Headers(), std::move(content_provider), content_type,
  6383. progress);
  6384. }
  6385. Result ClientImpl::Patch(const std::string &path,
  6386. ContentProviderWithoutLength content_provider,
  6387. const std::string &content_type,
  6388. ContentReceiver content_receiver,
  6389. UploadProgress progress) {
  6390. return Patch(path, Headers(), std::move(content_provider), content_type,
  6391. std::move(content_receiver), progress);
  6392. }
  6393. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6394. const Params &params) {
  6395. auto query = detail::params_to_query_str(params);
  6396. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  6397. }
  6398. Result ClientImpl::Patch(const std::string &path,
  6399. const UploadFormDataItems &items,
  6400. UploadProgress progress) {
  6401. return Patch(path, Headers(), items, progress);
  6402. }
  6403. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6404. const UploadFormDataItems &items,
  6405. UploadProgress progress) {
  6406. const auto &boundary = detail::make_multipart_data_boundary();
  6407. const auto &content_type =
  6408. detail::serialize_multipart_formdata_get_content_type(boundary);
  6409. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6410. return Patch(path, headers, body, content_type, progress);
  6411. }
  6412. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6413. const UploadFormDataItems &items,
  6414. const std::string &boundary,
  6415. UploadProgress progress) {
  6416. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  6417. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  6418. }
  6419. const auto &content_type =
  6420. detail::serialize_multipart_formdata_get_content_type(boundary);
  6421. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  6422. return Patch(path, headers, body, content_type, progress);
  6423. }
  6424. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6425. const char *body, size_t content_length,
  6426. const std::string &content_type,
  6427. UploadProgress progress) {
  6428. return send_with_content_provider_and_receiver(
  6429. "PATCH", path, headers, body, content_length, nullptr, nullptr,
  6430. content_type, nullptr, progress);
  6431. }
  6432. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6433. const std::string &body,
  6434. const std::string &content_type,
  6435. UploadProgress progress) {
  6436. return send_with_content_provider_and_receiver(
  6437. "PATCH", path, headers, body.data(), body.size(), nullptr, nullptr,
  6438. content_type, nullptr, progress);
  6439. }
  6440. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6441. size_t content_length,
  6442. ContentProvider content_provider,
  6443. const std::string &content_type,
  6444. UploadProgress progress) {
  6445. return send_with_content_provider_and_receiver(
  6446. "PATCH", path, headers, nullptr, content_length,
  6447. std::move(content_provider), nullptr, content_type, nullptr, progress);
  6448. }
  6449. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6450. size_t content_length,
  6451. ContentProvider content_provider,
  6452. const std::string &content_type,
  6453. ContentReceiver content_receiver,
  6454. UploadProgress progress) {
  6455. return send_with_content_provider_and_receiver(
  6456. "PATCH", path, headers, nullptr, content_length,
  6457. std::move(content_provider), nullptr, content_type,
  6458. std::move(content_receiver), progress);
  6459. }
  6460. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6461. ContentProviderWithoutLength content_provider,
  6462. const std::string &content_type,
  6463. UploadProgress progress) {
  6464. return send_with_content_provider_and_receiver(
  6465. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  6466. content_type, nullptr, progress);
  6467. }
  6468. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6469. ContentProviderWithoutLength content_provider,
  6470. const std::string &content_type,
  6471. ContentReceiver content_receiver,
  6472. UploadProgress progress) {
  6473. return send_with_content_provider_and_receiver(
  6474. "PATCH", path, headers, nullptr, 0, nullptr, std::move(content_provider),
  6475. content_type, std::move(content_receiver), progress);
  6476. }
  6477. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6478. const UploadFormDataItems &items,
  6479. const FormDataProviderItems &provider_items,
  6480. UploadProgress progress) {
  6481. const auto &boundary = detail::make_multipart_data_boundary();
  6482. const auto &content_type =
  6483. detail::serialize_multipart_formdata_get_content_type(boundary);
  6484. return send_with_content_provider_and_receiver(
  6485. "PATCH", path, headers, nullptr, 0, nullptr,
  6486. get_multipart_content_provider(boundary, items, provider_items),
  6487. content_type, nullptr, progress);
  6488. }
  6489. Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  6490. const std::string &body,
  6491. const std::string &content_type,
  6492. ContentReceiver content_receiver,
  6493. DownloadProgress progress) {
  6494. Request req;
  6495. req.method = "PATCH";
  6496. req.path = path;
  6497. req.headers = headers;
  6498. req.body = body;
  6499. req.content_receiver =
  6500. [content_receiver](const char *data, size_t data_length,
  6501. size_t /*offset*/, size_t /*total_length*/) {
  6502. return content_receiver(data, data_length);
  6503. };
  6504. req.download_progress = std::move(progress);
  6505. if (max_timeout_msec_ > 0) {
  6506. req.start_time_ = std::chrono::steady_clock::now();
  6507. }
  6508. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  6509. return send_(std::move(req));
  6510. }
  6511. Result ClientImpl::Delete(const std::string &path,
  6512. DownloadProgress progress) {
  6513. return Delete(path, Headers(), std::string(), std::string(), progress);
  6514. }
  6515. Result ClientImpl::Delete(const std::string &path,
  6516. const Headers &headers,
  6517. DownloadProgress progress) {
  6518. return Delete(path, headers, std::string(), std::string(), progress);
  6519. }
  6520. Result ClientImpl::Delete(const std::string &path, const char *body,
  6521. size_t content_length,
  6522. const std::string &content_type,
  6523. DownloadProgress progress) {
  6524. return Delete(path, Headers(), body, content_length, content_type, progress);
  6525. }
  6526. Result ClientImpl::Delete(const std::string &path,
  6527. const std::string &body,
  6528. const std::string &content_type,
  6529. DownloadProgress progress) {
  6530. return Delete(path, Headers(), body.data(), body.size(), content_type,
  6531. progress);
  6532. }
  6533. Result ClientImpl::Delete(const std::string &path,
  6534. const Headers &headers,
  6535. const std::string &body,
  6536. const std::string &content_type,
  6537. DownloadProgress progress) {
  6538. return Delete(path, headers, body.data(), body.size(), content_type,
  6539. progress);
  6540. }
  6541. Result ClientImpl::Delete(const std::string &path, const Params &params,
  6542. DownloadProgress progress) {
  6543. return Delete(path, Headers(), params, progress);
  6544. }
  6545. Result ClientImpl::Delete(const std::string &path,
  6546. const Headers &headers, const Params &params,
  6547. DownloadProgress progress) {
  6548. auto query = detail::params_to_query_str(params);
  6549. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  6550. progress);
  6551. }
  6552. Result ClientImpl::Delete(const std::string &path,
  6553. const Headers &headers, const char *body,
  6554. size_t content_length,
  6555. const std::string &content_type,
  6556. DownloadProgress progress) {
  6557. Request req;
  6558. req.method = "DELETE";
  6559. req.headers = headers;
  6560. req.path = path;
  6561. req.download_progress = std::move(progress);
  6562. if (max_timeout_msec_ > 0) {
  6563. req.start_time_ = std::chrono::steady_clock::now();
  6564. }
  6565. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  6566. req.body.assign(body, content_length);
  6567. return send_(std::move(req));
  6568. }
  6569. Result ClientImpl::Options(const std::string &path) {
  6570. return Options(path, Headers());
  6571. }
  6572. Result ClientImpl::Options(const std::string &path,
  6573. const Headers &headers) {
  6574. Request req;
  6575. req.method = "OPTIONS";
  6576. req.headers = headers;
  6577. req.path = path;
  6578. if (max_timeout_msec_ > 0) {
  6579. req.start_time_ = std::chrono::steady_clock::now();
  6580. }
  6581. return send_(std::move(req));
  6582. }
  6583. void ClientImpl::stop() {
  6584. std::lock_guard<std::mutex> guard(socket_mutex_);
  6585. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  6586. // do is to shutdown_socket, so that threads using this socket suddenly
  6587. // discover they can't read/write any more and error out. Everything else
  6588. // (closing the socket, shutting ssl down) is unsafe because these actions
  6589. // are not thread-safe.
  6590. if (socket_requests_in_flight_ > 0) {
  6591. shutdown_socket(socket_);
  6592. // Aside from that, we set a flag for the socket to be closed when we're
  6593. // done.
  6594. socket_should_be_closed_when_request_is_done_ = true;
  6595. return;
  6596. }
  6597. // Otherwise, still holding the mutex, we can shut everything down ourselves
  6598. shutdown_ssl(socket_, true);
  6599. shutdown_socket(socket_);
  6600. close_socket(socket_);
  6601. }
  6602. std::string ClientImpl::host() const { return host_; }
  6603. int ClientImpl::port() const { return port_; }
  6604. size_t ClientImpl::is_socket_open() const {
  6605. std::lock_guard<std::mutex> guard(socket_mutex_);
  6606. return socket_.is_open();
  6607. }
  6608. socket_t ClientImpl::socket() const { return socket_.sock; }
  6609. void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  6610. connection_timeout_sec_ = sec;
  6611. connection_timeout_usec_ = usec;
  6612. }
  6613. void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  6614. read_timeout_sec_ = sec;
  6615. read_timeout_usec_ = usec;
  6616. }
  6617. void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  6618. write_timeout_sec_ = sec;
  6619. write_timeout_usec_ = usec;
  6620. }
  6621. void ClientImpl::set_max_timeout(time_t msec) {
  6622. max_timeout_msec_ = msec;
  6623. }
  6624. void ClientImpl::set_basic_auth(const std::string &username,
  6625. const std::string &password) {
  6626. basic_auth_username_ = username;
  6627. basic_auth_password_ = password;
  6628. }
  6629. void ClientImpl::set_bearer_token_auth(const std::string &token) {
  6630. bearer_token_auth_token_ = token;
  6631. }
  6632. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6633. void ClientImpl::set_digest_auth(const std::string &username,
  6634. const std::string &password) {
  6635. digest_auth_username_ = username;
  6636. digest_auth_password_ = password;
  6637. }
  6638. #endif
  6639. void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  6640. void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  6641. void ClientImpl::set_path_encode(bool on) { path_encode_ = on; }
  6642. void
  6643. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  6644. addr_map_ = std::move(addr_map);
  6645. }
  6646. void ClientImpl::set_default_headers(Headers headers) {
  6647. default_headers_ = std::move(headers);
  6648. }
  6649. void ClientImpl::set_header_writer(
  6650. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  6651. header_writer_ = writer;
  6652. }
  6653. void ClientImpl::set_address_family(int family) {
  6654. address_family_ = family;
  6655. }
  6656. void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  6657. void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  6658. void ClientImpl::set_socket_options(SocketOptions socket_options) {
  6659. socket_options_ = std::move(socket_options);
  6660. }
  6661. void ClientImpl::set_compress(bool on) { compress_ = on; }
  6662. void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  6663. void ClientImpl::set_interface(const std::string &intf) {
  6664. interface_ = intf;
  6665. }
  6666. void ClientImpl::set_proxy(const std::string &host, int port) {
  6667. proxy_host_ = host;
  6668. proxy_port_ = port;
  6669. }
  6670. void ClientImpl::set_proxy_basic_auth(const std::string &username,
  6671. const std::string &password) {
  6672. proxy_basic_auth_username_ = username;
  6673. proxy_basic_auth_password_ = password;
  6674. }
  6675. void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  6676. proxy_bearer_token_auth_token_ = token;
  6677. }
  6678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6679. void ClientImpl::set_proxy_digest_auth(const std::string &username,
  6680. const std::string &password) {
  6681. proxy_digest_auth_username_ = username;
  6682. proxy_digest_auth_password_ = password;
  6683. }
  6684. void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  6685. const std::string &ca_cert_dir_path) {
  6686. ca_cert_file_path_ = ca_cert_file_path;
  6687. ca_cert_dir_path_ = ca_cert_dir_path;
  6688. }
  6689. void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  6690. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  6691. ca_cert_store_ = ca_cert_store;
  6692. }
  6693. }
  6694. X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  6695. std::size_t size) const {
  6696. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  6697. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  6698. if (!mem) { return nullptr; }
  6699. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  6700. if (!inf) { return nullptr; }
  6701. auto cts = X509_STORE_new();
  6702. if (cts) {
  6703. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  6704. auto itmp = sk_X509_INFO_value(inf, i);
  6705. if (!itmp) { continue; }
  6706. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  6707. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  6708. }
  6709. }
  6710. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  6711. return cts;
  6712. }
  6713. void ClientImpl::enable_server_certificate_verification(bool enabled) {
  6714. server_certificate_verification_ = enabled;
  6715. }
  6716. void ClientImpl::enable_server_hostname_verification(bool enabled) {
  6717. server_hostname_verification_ = enabled;
  6718. }
  6719. void ClientImpl::set_server_certificate_verifier(
  6720. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  6721. server_certificate_verifier_ = verifier;
  6722. }
  6723. #endif
  6724. void ClientImpl::set_logger(Logger logger) {
  6725. logger_ = std::move(logger);
  6726. }
  6727. void ClientImpl::set_error_logger(ErrorLogger error_logger) {
  6728. error_logger_ = std::move(error_logger);
  6729. }
  6730. /*
  6731. * SSL Implementation
  6732. */
  6733. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6734. namespace detail {
  6735. bool is_ip_address(const std::string &host) {
  6736. struct in_addr addr4;
  6737. struct in6_addr addr6;
  6738. return inet_pton(AF_INET, host.c_str(), &addr4) == 1 ||
  6739. inet_pton(AF_INET6, host.c_str(), &addr6) == 1;
  6740. }
  6741. template <typename U, typename V>
  6742. SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  6743. U SSL_connect_or_accept, V setup) {
  6744. SSL *ssl = nullptr;
  6745. {
  6746. std::lock_guard<std::mutex> guard(ctx_mutex);
  6747. ssl = SSL_new(ctx);
  6748. }
  6749. if (ssl) {
  6750. set_nonblocking(sock, true);
  6751. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  6752. BIO_set_nbio(bio, 1);
  6753. SSL_set_bio(ssl, bio, bio);
  6754. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  6755. SSL_shutdown(ssl);
  6756. {
  6757. std::lock_guard<std::mutex> guard(ctx_mutex);
  6758. SSL_free(ssl);
  6759. }
  6760. set_nonblocking(sock, false);
  6761. return nullptr;
  6762. }
  6763. BIO_set_nbio(bio, 0);
  6764. set_nonblocking(sock, false);
  6765. }
  6766. return ssl;
  6767. }
  6768. void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock,
  6769. bool shutdown_gracefully) {
  6770. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  6771. // the remote has closed the network connection
  6772. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  6773. // best-efforts.
  6774. if (shutdown_gracefully) {
  6775. (void)(sock);
  6776. // SSL_shutdown() returns 0 on first call (indicating close_notify alert
  6777. // sent) and 1 on subsequent call (indicating close_notify alert received)
  6778. if (SSL_shutdown(ssl) == 0) {
  6779. // Expected to return 1, but even if it doesn't, we free ssl
  6780. SSL_shutdown(ssl);
  6781. }
  6782. }
  6783. std::lock_guard<std::mutex> guard(ctx_mutex);
  6784. SSL_free(ssl);
  6785. }
  6786. template <typename U>
  6787. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  6788. U ssl_connect_or_accept,
  6789. time_t timeout_sec, time_t timeout_usec,
  6790. int *ssl_error) {
  6791. auto res = 0;
  6792. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  6793. auto err = SSL_get_error(ssl, res);
  6794. switch (err) {
  6795. case SSL_ERROR_WANT_READ:
  6796. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  6797. break;
  6798. case SSL_ERROR_WANT_WRITE:
  6799. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  6800. break;
  6801. default: break;
  6802. }
  6803. if (ssl_error) { *ssl_error = err; }
  6804. return false;
  6805. }
  6806. return true;
  6807. }
  6808. template <typename T>
  6809. bool process_server_socket_ssl(
  6810. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  6811. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  6812. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  6813. time_t write_timeout_usec, T callback) {
  6814. return process_server_socket_core(
  6815. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  6816. [&](bool close_connection, bool &connection_closed) {
  6817. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  6818. write_timeout_sec, write_timeout_usec);
  6819. return callback(strm, close_connection, connection_closed);
  6820. });
  6821. }
  6822. template <typename T>
  6823. bool process_client_socket_ssl(
  6824. SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  6825. time_t write_timeout_sec, time_t write_timeout_usec,
  6826. time_t max_timeout_msec,
  6827. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  6828. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  6829. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  6830. start_time);
  6831. return callback(strm);
  6832. }
  6833. // SSL socket stream implementation
  6834. SSLSocketStream::SSLSocketStream(
  6835. socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
  6836. time_t write_timeout_sec, time_t write_timeout_usec,
  6837. time_t max_timeout_msec,
  6838. std::chrono::time_point<std::chrono::steady_clock> start_time)
  6839. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  6840. read_timeout_usec_(read_timeout_usec),
  6841. write_timeout_sec_(write_timeout_sec),
  6842. write_timeout_usec_(write_timeout_usec),
  6843. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  6844. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  6845. }
  6846. SSLSocketStream::~SSLSocketStream() = default;
  6847. bool SSLSocketStream::is_readable() const {
  6848. return SSL_pending(ssl_) > 0;
  6849. }
  6850. bool SSLSocketStream::wait_readable() const {
  6851. if (max_timeout_msec_ <= 0) {
  6852. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  6853. }
  6854. time_t read_timeout_sec;
  6855. time_t read_timeout_usec;
  6856. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  6857. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  6858. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  6859. }
  6860. bool SSLSocketStream::wait_writable() const {
  6861. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  6862. is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_);
  6863. }
  6864. ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  6865. if (SSL_pending(ssl_) > 0) {
  6866. return SSL_read(ssl_, ptr, static_cast<int>(size));
  6867. } else if (wait_readable()) {
  6868. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  6869. if (ret < 0) {
  6870. auto err = SSL_get_error(ssl_, ret);
  6871. auto n = 1000;
  6872. #ifdef _WIN32
  6873. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  6874. (err == SSL_ERROR_SYSCALL &&
  6875. WSAGetLastError() == WSAETIMEDOUT))) {
  6876. #else
  6877. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  6878. #endif
  6879. if (SSL_pending(ssl_) > 0) {
  6880. return SSL_read(ssl_, ptr, static_cast<int>(size));
  6881. } else if (wait_readable()) {
  6882. std::this_thread::sleep_for(std::chrono::microseconds{10});
  6883. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  6884. if (ret >= 0) { return ret; }
  6885. err = SSL_get_error(ssl_, ret);
  6886. } else {
  6887. break;
  6888. }
  6889. }
  6890. assert(ret < 0);
  6891. }
  6892. return ret;
  6893. } else {
  6894. return -1;
  6895. }
  6896. }
  6897. ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  6898. if (wait_writable()) {
  6899. auto handle_size = static_cast<int>(
  6900. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  6901. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  6902. if (ret < 0) {
  6903. auto err = SSL_get_error(ssl_, ret);
  6904. auto n = 1000;
  6905. #ifdef _WIN32
  6906. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  6907. (err == SSL_ERROR_SYSCALL &&
  6908. WSAGetLastError() == WSAETIMEDOUT))) {
  6909. #else
  6910. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  6911. #endif
  6912. if (wait_writable()) {
  6913. std::this_thread::sleep_for(std::chrono::microseconds{10});
  6914. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  6915. if (ret >= 0) { return ret; }
  6916. err = SSL_get_error(ssl_, ret);
  6917. } else {
  6918. break;
  6919. }
  6920. }
  6921. assert(ret < 0);
  6922. }
  6923. return ret;
  6924. }
  6925. return -1;
  6926. }
  6927. void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  6928. int &port) const {
  6929. detail::get_remote_ip_and_port(sock_, ip, port);
  6930. }
  6931. void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  6932. int &port) const {
  6933. detail::get_local_ip_and_port(sock_, ip, port);
  6934. }
  6935. socket_t SSLSocketStream::socket() const { return sock_; }
  6936. time_t SSLSocketStream::duration() const {
  6937. return std::chrono::duration_cast<std::chrono::milliseconds>(
  6938. std::chrono::steady_clock::now() - start_time_)
  6939. .count();
  6940. }
  6941. } // namespace detail
  6942. // SSL HTTP server implementation
  6943. SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  6944. const char *client_ca_cert_file_path,
  6945. const char *client_ca_cert_dir_path,
  6946. const char *private_key_password) {
  6947. ctx_ = SSL_CTX_new(TLS_server_method());
  6948. if (ctx_) {
  6949. SSL_CTX_set_options(ctx_,
  6950. SSL_OP_NO_COMPRESSION |
  6951. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6952. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  6953. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  6954. SSL_CTX_set_default_passwd_cb_userdata(
  6955. ctx_,
  6956. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  6957. }
  6958. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  6959. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  6960. 1 ||
  6961. SSL_CTX_check_private_key(ctx_) != 1) {
  6962. last_ssl_error_ = static_cast<int>(ERR_get_error());
  6963. SSL_CTX_free(ctx_);
  6964. ctx_ = nullptr;
  6965. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  6966. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  6967. client_ca_cert_dir_path);
  6968. // Set client CA list to be sent to clients during TLS handshake
  6969. if (client_ca_cert_file_path) {
  6970. auto ca_list = SSL_load_client_CA_file(client_ca_cert_file_path);
  6971. if (ca_list != nullptr) {
  6972. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  6973. } else {
  6974. // Failed to load client CA list, but we continue since
  6975. // SSL_CTX_load_verify_locations already succeeded and
  6976. // certificate verification will still work
  6977. last_ssl_error_ = static_cast<int>(ERR_get_error());
  6978. }
  6979. }
  6980. SSL_CTX_set_verify(
  6981. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  6982. }
  6983. }
  6984. }
  6985. SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  6986. X509_STORE *client_ca_cert_store) {
  6987. ctx_ = SSL_CTX_new(TLS_server_method());
  6988. if (ctx_) {
  6989. SSL_CTX_set_options(ctx_,
  6990. SSL_OP_NO_COMPRESSION |
  6991. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6992. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  6993. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  6994. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  6995. SSL_CTX_free(ctx_);
  6996. ctx_ = nullptr;
  6997. } else if (client_ca_cert_store) {
  6998. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  6999. // Extract CA names from the store and set them as the client CA list
  7000. auto ca_list = extract_ca_names_from_x509_store(client_ca_cert_store);
  7001. if (ca_list) {
  7002. SSL_CTX_set_client_CA_list(ctx_, ca_list);
  7003. } else {
  7004. // Failed to extract CA names, record the error
  7005. last_ssl_error_ = static_cast<int>(ERR_get_error());
  7006. }
  7007. SSL_CTX_set_verify(
  7008. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  7009. }
  7010. }
  7011. }
  7012. SSLServer::SSLServer(
  7013. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  7014. ctx_ = SSL_CTX_new(TLS_method());
  7015. if (ctx_) {
  7016. if (!setup_ssl_ctx_callback(*ctx_)) {
  7017. SSL_CTX_free(ctx_);
  7018. ctx_ = nullptr;
  7019. }
  7020. }
  7021. }
  7022. SSLServer::~SSLServer() {
  7023. if (ctx_) { SSL_CTX_free(ctx_); }
  7024. }
  7025. bool SSLServer::is_valid() const { return ctx_; }
  7026. SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  7027. void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  7028. X509_STORE *client_ca_cert_store) {
  7029. std::lock_guard<std::mutex> guard(ctx_mutex_);
  7030. SSL_CTX_use_certificate(ctx_, cert);
  7031. SSL_CTX_use_PrivateKey(ctx_, private_key);
  7032. if (client_ca_cert_store != nullptr) {
  7033. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  7034. }
  7035. }
  7036. bool SSLServer::process_and_close_socket(socket_t sock) {
  7037. auto ssl = detail::ssl_new(
  7038. sock, ctx_, ctx_mutex_,
  7039. [&](SSL *ssl2) {
  7040. return detail::ssl_connect_or_accept_nonblocking(
  7041. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_,
  7042. &last_ssl_error_);
  7043. },
  7044. [](SSL * /*ssl2*/) { return true; });
  7045. auto ret = false;
  7046. if (ssl) {
  7047. std::string remote_addr;
  7048. int remote_port = 0;
  7049. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  7050. std::string local_addr;
  7051. int local_port = 0;
  7052. detail::get_local_ip_and_port(sock, local_addr, local_port);
  7053. ret = detail::process_server_socket_ssl(
  7054. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  7055. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  7056. write_timeout_usec_,
  7057. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  7058. return process_request(strm, remote_addr, remote_port, local_addr,
  7059. local_port, close_connection,
  7060. connection_closed,
  7061. [&](Request &req) { req.ssl = ssl; });
  7062. });
  7063. // Shutdown gracefully if the result seemed successful, non-gracefully if
  7064. // the connection appeared to be closed.
  7065. const bool shutdown_gracefully = ret;
  7066. detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
  7067. }
  7068. detail::shutdown_socket(sock);
  7069. detail::close_socket(sock);
  7070. return ret;
  7071. }
  7072. STACK_OF(X509_NAME) * SSLServer::extract_ca_names_from_x509_store(
  7073. X509_STORE *store) {
  7074. if (!store) { return nullptr; }
  7075. auto ca_list = sk_X509_NAME_new_null();
  7076. if (!ca_list) { return nullptr; }
  7077. // Get all objects from the store
  7078. auto objs = X509_STORE_get0_objects(store);
  7079. if (!objs) {
  7080. sk_X509_NAME_free(ca_list);
  7081. return nullptr;
  7082. }
  7083. // Iterate through objects and extract certificate subject names
  7084. for (int i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  7085. auto obj = sk_X509_OBJECT_value(objs, i);
  7086. if (X509_OBJECT_get_type(obj) == X509_LU_X509) {
  7087. auto cert = X509_OBJECT_get0_X509(obj);
  7088. if (cert) {
  7089. auto subject = X509_get_subject_name(cert);
  7090. if (subject) {
  7091. auto name_dup = X509_NAME_dup(subject);
  7092. if (name_dup) { sk_X509_NAME_push(ca_list, name_dup); }
  7093. }
  7094. }
  7095. }
  7096. }
  7097. // If no names were extracted, free the list and return nullptr
  7098. if (sk_X509_NAME_num(ca_list) == 0) {
  7099. sk_X509_NAME_free(ca_list);
  7100. return nullptr;
  7101. }
  7102. return ca_list;
  7103. }
  7104. // SSL HTTP client implementation
  7105. SSLClient::SSLClient(const std::string &host)
  7106. : SSLClient(host, 443, std::string(), std::string()) {}
  7107. SSLClient::SSLClient(const std::string &host, int port)
  7108. : SSLClient(host, port, std::string(), std::string()) {}
  7109. SSLClient::SSLClient(const std::string &host, int port,
  7110. const std::string &client_cert_path,
  7111. const std::string &client_key_path,
  7112. const std::string &private_key_password)
  7113. : ClientImpl(host, port, client_cert_path, client_key_path) {
  7114. ctx_ = SSL_CTX_new(TLS_client_method());
  7115. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  7116. detail::split(&host_[0], &host_[host_.size()], '.',
  7117. [&](const char *b, const char *e) {
  7118. host_components_.emplace_back(b, e);
  7119. });
  7120. if (!client_cert_path.empty() && !client_key_path.empty()) {
  7121. if (!private_key_password.empty()) {
  7122. SSL_CTX_set_default_passwd_cb_userdata(
  7123. ctx_, reinterpret_cast<void *>(
  7124. const_cast<char *>(private_key_password.c_str())));
  7125. }
  7126. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  7127. SSL_FILETYPE_PEM) != 1 ||
  7128. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  7129. SSL_FILETYPE_PEM) != 1) {
  7130. last_openssl_error_ = ERR_get_error();
  7131. SSL_CTX_free(ctx_);
  7132. ctx_ = nullptr;
  7133. }
  7134. }
  7135. }
  7136. SSLClient::SSLClient(const std::string &host, int port,
  7137. X509 *client_cert, EVP_PKEY *client_key,
  7138. const std::string &private_key_password)
  7139. : ClientImpl(host, port) {
  7140. ctx_ = SSL_CTX_new(TLS_client_method());
  7141. detail::split(&host_[0], &host_[host_.size()], '.',
  7142. [&](const char *b, const char *e) {
  7143. host_components_.emplace_back(b, e);
  7144. });
  7145. if (client_cert != nullptr && client_key != nullptr) {
  7146. if (!private_key_password.empty()) {
  7147. SSL_CTX_set_default_passwd_cb_userdata(
  7148. ctx_, reinterpret_cast<void *>(
  7149. const_cast<char *>(private_key_password.c_str())));
  7150. }
  7151. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  7152. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  7153. last_openssl_error_ = ERR_get_error();
  7154. SSL_CTX_free(ctx_);
  7155. ctx_ = nullptr;
  7156. }
  7157. }
  7158. }
  7159. SSLClient::~SSLClient() {
  7160. if (ctx_) { SSL_CTX_free(ctx_); }
  7161. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  7162. // base function rather than the derived function once we get to the
  7163. // base class destructor, and won't free the SSL (causing a leak).
  7164. shutdown_ssl_impl(socket_, true);
  7165. }
  7166. bool SSLClient::is_valid() const { return ctx_; }
  7167. void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  7168. if (ca_cert_store) {
  7169. if (ctx_) {
  7170. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  7171. // Free memory allocated for old cert and use new store
  7172. // `ca_cert_store`
  7173. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  7174. ca_cert_store_ = ca_cert_store;
  7175. }
  7176. } else {
  7177. X509_STORE_free(ca_cert_store);
  7178. }
  7179. }
  7180. }
  7181. void SSLClient::load_ca_cert_store(const char *ca_cert,
  7182. std::size_t size) {
  7183. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  7184. }
  7185. long SSLClient::get_openssl_verify_result() const {
  7186. return verify_result_;
  7187. }
  7188. SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  7189. bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  7190. if (!is_valid()) {
  7191. error = Error::SSLConnection;
  7192. return false;
  7193. }
  7194. return ClientImpl::create_and_connect_socket(socket, error);
  7195. }
  7196. // Assumes that socket_mutex_ is locked and that there are no requests in
  7197. // flight
  7198. bool SSLClient::connect_with_proxy(
  7199. Socket &socket,
  7200. std::chrono::time_point<std::chrono::steady_clock> start_time,
  7201. Response &res, bool &success, Error &error) {
  7202. success = true;
  7203. Response proxy_res;
  7204. if (!detail::process_client_socket(
  7205. socket.sock, read_timeout_sec_, read_timeout_usec_,
  7206. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  7207. start_time, [&](Stream &strm) {
  7208. Request req2;
  7209. req2.method = "CONNECT";
  7210. req2.path = host_and_port_;
  7211. if (max_timeout_msec_ > 0) {
  7212. req2.start_time_ = std::chrono::steady_clock::now();
  7213. }
  7214. return process_request(strm, req2, proxy_res, false, error);
  7215. })) {
  7216. // Thread-safe to close everything because we are assuming there are no
  7217. // requests in flight
  7218. shutdown_ssl(socket, true);
  7219. shutdown_socket(socket);
  7220. close_socket(socket);
  7221. success = false;
  7222. return false;
  7223. }
  7224. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  7225. if (!proxy_digest_auth_username_.empty() &&
  7226. !proxy_digest_auth_password_.empty()) {
  7227. std::map<std::string, std::string> auth;
  7228. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  7229. // Close the current socket and create a new one for the authenticated
  7230. // request
  7231. shutdown_ssl(socket, true);
  7232. shutdown_socket(socket);
  7233. close_socket(socket);
  7234. // Create a new socket for the authenticated CONNECT request
  7235. if (!create_and_connect_socket(socket, error)) {
  7236. success = false;
  7237. output_error_log(error, nullptr);
  7238. return false;
  7239. }
  7240. proxy_res = Response();
  7241. if (!detail::process_client_socket(
  7242. socket.sock, read_timeout_sec_, read_timeout_usec_,
  7243. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  7244. start_time, [&](Stream &strm) {
  7245. Request req3;
  7246. req3.method = "CONNECT";
  7247. req3.path = host_and_port_;
  7248. req3.headers.insert(detail::make_digest_authentication_header(
  7249. req3, auth, 1, detail::random_string(10),
  7250. proxy_digest_auth_username_, proxy_digest_auth_password_,
  7251. true));
  7252. if (max_timeout_msec_ > 0) {
  7253. req3.start_time_ = std::chrono::steady_clock::now();
  7254. }
  7255. return process_request(strm, req3, proxy_res, false, error);
  7256. })) {
  7257. // Thread-safe to close everything because we are assuming there are
  7258. // no requests in flight
  7259. shutdown_ssl(socket, true);
  7260. shutdown_socket(socket);
  7261. close_socket(socket);
  7262. success = false;
  7263. return false;
  7264. }
  7265. }
  7266. }
  7267. }
  7268. // If status code is not 200, proxy request is failed.
  7269. // Set error to ProxyConnection and return proxy response
  7270. // as the response of the request
  7271. if (proxy_res.status != StatusCode::OK_200) {
  7272. error = Error::ProxyConnection;
  7273. output_error_log(error, nullptr);
  7274. res = std::move(proxy_res);
  7275. // Thread-safe to close everything because we are assuming there are
  7276. // no requests in flight
  7277. shutdown_ssl(socket, true);
  7278. shutdown_socket(socket);
  7279. close_socket(socket);
  7280. return false;
  7281. }
  7282. return true;
  7283. }
  7284. bool SSLClient::load_certs() {
  7285. auto ret = true;
  7286. std::call_once(initialize_cert_, [&]() {
  7287. std::lock_guard<std::mutex> guard(ctx_mutex_);
  7288. if (!ca_cert_file_path_.empty()) {
  7289. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  7290. nullptr)) {
  7291. last_openssl_error_ = ERR_get_error();
  7292. ret = false;
  7293. }
  7294. } else if (!ca_cert_dir_path_.empty()) {
  7295. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  7296. ca_cert_dir_path_.c_str())) {
  7297. last_openssl_error_ = ERR_get_error();
  7298. ret = false;
  7299. }
  7300. } else {
  7301. auto loaded = false;
  7302. #ifdef _WIN32
  7303. loaded =
  7304. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  7305. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && TARGET_OS_MAC
  7306. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  7307. #endif // _WIN32
  7308. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  7309. }
  7310. });
  7311. return ret;
  7312. }
  7313. bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  7314. auto ssl = detail::ssl_new(
  7315. socket.sock, ctx_, ctx_mutex_,
  7316. [&](SSL *ssl2) {
  7317. if (server_certificate_verification_) {
  7318. if (!load_certs()) {
  7319. error = Error::SSLLoadingCerts;
  7320. output_error_log(error, nullptr);
  7321. return false;
  7322. }
  7323. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  7324. }
  7325. if (!detail::ssl_connect_or_accept_nonblocking(
  7326. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  7327. connection_timeout_usec_, &last_ssl_error_)) {
  7328. error = Error::SSLConnection;
  7329. output_error_log(error, nullptr);
  7330. return false;
  7331. }
  7332. if (server_certificate_verification_) {
  7333. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  7334. if (server_certificate_verifier_) {
  7335. verification_status = server_certificate_verifier_(ssl2);
  7336. }
  7337. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  7338. last_openssl_error_ = ERR_get_error();
  7339. error = Error::SSLServerVerification;
  7340. output_error_log(error, nullptr);
  7341. return false;
  7342. }
  7343. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  7344. verify_result_ = SSL_get_verify_result(ssl2);
  7345. if (verify_result_ != X509_V_OK) {
  7346. last_openssl_error_ = static_cast<unsigned long>(verify_result_);
  7347. error = Error::SSLServerVerification;
  7348. output_error_log(error, nullptr);
  7349. return false;
  7350. }
  7351. auto server_cert = SSL_get1_peer_certificate(ssl2);
  7352. auto se = detail::scope_exit([&] { X509_free(server_cert); });
  7353. if (server_cert == nullptr) {
  7354. last_openssl_error_ = ERR_get_error();
  7355. error = Error::SSLServerVerification;
  7356. output_error_log(error, nullptr);
  7357. return false;
  7358. }
  7359. if (server_hostname_verification_) {
  7360. if (!verify_host(server_cert)) {
  7361. last_openssl_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  7362. error = Error::SSLServerHostnameVerification;
  7363. output_error_log(error, nullptr);
  7364. return false;
  7365. }
  7366. }
  7367. }
  7368. }
  7369. return true;
  7370. },
  7371. [&](SSL *ssl2) {
  7372. // Set SNI only if host is not IP address
  7373. if (!detail::is_ip_address(host_)) {
  7374. #if defined(OPENSSL_IS_BORINGSSL)
  7375. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  7376. #else
  7377. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  7378. // -Wold-style-cast warning
  7379. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME,
  7380. TLSEXT_NAMETYPE_host_name,
  7381. static_cast<void *>(const_cast<char *>(host_.c_str())));
  7382. #endif
  7383. }
  7384. return true;
  7385. });
  7386. if (ssl) {
  7387. socket.ssl = ssl;
  7388. return true;
  7389. }
  7390. if (ctx_ == nullptr) {
  7391. error = Error::SSLConnection;
  7392. last_openssl_error_ = ERR_get_error();
  7393. }
  7394. shutdown_socket(socket);
  7395. close_socket(socket);
  7396. return false;
  7397. }
  7398. void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  7399. shutdown_ssl_impl(socket, shutdown_gracefully);
  7400. }
  7401. void SSLClient::shutdown_ssl_impl(Socket &socket,
  7402. bool shutdown_gracefully) {
  7403. if (socket.sock == INVALID_SOCKET) {
  7404. assert(socket.ssl == nullptr);
  7405. return;
  7406. }
  7407. if (socket.ssl) {
  7408. detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock,
  7409. shutdown_gracefully);
  7410. socket.ssl = nullptr;
  7411. }
  7412. assert(socket.ssl == nullptr);
  7413. }
  7414. bool SSLClient::process_socket(
  7415. const Socket &socket,
  7416. std::chrono::time_point<std::chrono::steady_clock> start_time,
  7417. std::function<bool(Stream &strm)> callback) {
  7418. assert(socket.ssl);
  7419. return detail::process_client_socket_ssl(
  7420. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  7421. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  7422. std::move(callback));
  7423. }
  7424. bool SSLClient::is_ssl() const { return true; }
  7425. bool SSLClient::verify_host(X509 *server_cert) const {
  7426. /* Quote from RFC2818 section 3.1 "Server Identity"
  7427. If a subjectAltName extension of type dNSName is present, that MUST
  7428. be used as the identity. Otherwise, the (most specific) Common Name
  7429. field in the Subject field of the certificate MUST be used. Although
  7430. the use of the Common Name is existing practice, it is deprecated and
  7431. Certification Authorities are encouraged to use the dNSName instead.
  7432. Matching is performed using the matching rules specified by
  7433. [RFC2459]. If more than one identity of a given type is present in
  7434. the certificate (e.g., more than one dNSName name, a match in any one
  7435. of the set is considered acceptable.) Names may contain the wildcard
  7436. character * which is considered to match any single domain name
  7437. component or component fragment. E.g., *.a.com matches foo.a.com but
  7438. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  7439. In some cases, the URI is specified as an IP address rather than a
  7440. hostname. In this case, the iPAddress subjectAltName must be present
  7441. in the certificate and must exactly match the IP in the URI.
  7442. */
  7443. return verify_host_with_subject_alt_name(server_cert) ||
  7444. verify_host_with_common_name(server_cert);
  7445. }
  7446. bool
  7447. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  7448. auto ret = false;
  7449. auto type = GEN_DNS;
  7450. struct in6_addr addr6 = {};
  7451. struct in_addr addr = {};
  7452. size_t addr_len = 0;
  7453. #ifndef __MINGW32__
  7454. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  7455. type = GEN_IPADD;
  7456. addr_len = sizeof(struct in6_addr);
  7457. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  7458. type = GEN_IPADD;
  7459. addr_len = sizeof(struct in_addr);
  7460. }
  7461. #endif
  7462. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  7463. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  7464. if (alt_names) {
  7465. auto dsn_matched = false;
  7466. auto ip_matched = false;
  7467. auto count = sk_GENERAL_NAME_num(alt_names);
  7468. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  7469. auto val = sk_GENERAL_NAME_value(alt_names, i);
  7470. if (!val || val->type != type) { continue; }
  7471. auto name =
  7472. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  7473. if (name == nullptr) { continue; }
  7474. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  7475. switch (type) {
  7476. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  7477. case GEN_IPADD:
  7478. if (!memcmp(&addr6, name, addr_len) || !memcmp(&addr, name, addr_len)) {
  7479. ip_matched = true;
  7480. }
  7481. break;
  7482. }
  7483. }
  7484. if (dsn_matched || ip_matched) { ret = true; }
  7485. }
  7486. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  7487. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  7488. return ret;
  7489. }
  7490. bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  7491. const auto subject_name = X509_get_subject_name(server_cert);
  7492. if (subject_name != nullptr) {
  7493. char name[BUFSIZ];
  7494. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7495. name, sizeof(name));
  7496. if (name_len != -1) {
  7497. return check_host_name(name, static_cast<size_t>(name_len));
  7498. }
  7499. }
  7500. return false;
  7501. }
  7502. bool SSLClient::check_host_name(const char *pattern,
  7503. size_t pattern_len) const {
  7504. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  7505. // Wildcard match
  7506. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  7507. std::vector<std::string> pattern_components;
  7508. detail::split(&pattern[0], &pattern[pattern_len], '.',
  7509. [&](const char *b, const char *e) {
  7510. pattern_components.emplace_back(b, e);
  7511. });
  7512. if (host_components_.size() != pattern_components.size()) { return false; }
  7513. auto itr = pattern_components.begin();
  7514. for (const auto &h : host_components_) {
  7515. auto &p = *itr;
  7516. if (p != h && p != "*") {
  7517. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  7518. !p.compare(0, p.size() - 1, h));
  7519. if (!partial_match) { return false; }
  7520. }
  7521. ++itr;
  7522. }
  7523. return true;
  7524. }
  7525. #endif
  7526. // Universal client implementation
  7527. Client::Client(const std::string &scheme_host_port)
  7528. : Client(scheme_host_port, std::string(), std::string()) {}
  7529. Client::Client(const std::string &scheme_host_port,
  7530. const std::string &client_cert_path,
  7531. const std::string &client_key_path) {
  7532. const static std::regex re(
  7533. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  7534. std::smatch m;
  7535. if (std::regex_match(scheme_host_port, m, re)) {
  7536. auto scheme = m[1].str();
  7537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7538. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  7539. #else
  7540. if (!scheme.empty() && scheme != "http") {
  7541. #endif
  7542. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7543. std::string msg = "'" + scheme + "' scheme is not supported.";
  7544. throw std::invalid_argument(msg);
  7545. #endif
  7546. return;
  7547. }
  7548. auto is_ssl = scheme == "https";
  7549. auto host = m[2].str();
  7550. if (host.empty()) { host = m[3].str(); }
  7551. auto port_str = m[4].str();
  7552. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  7553. if (is_ssl) {
  7554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7555. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  7556. client_key_path);
  7557. is_ssl_ = is_ssl;
  7558. #endif
  7559. } else {
  7560. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  7561. client_key_path);
  7562. }
  7563. } else {
  7564. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  7565. // if port param below changes.
  7566. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  7567. client_cert_path, client_key_path);
  7568. }
  7569. } // namespace detail
  7570. Client::Client(const std::string &host, int port)
  7571. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  7572. Client::Client(const std::string &host, int port,
  7573. const std::string &client_cert_path,
  7574. const std::string &client_key_path)
  7575. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  7576. client_key_path)) {}
  7577. Client::~Client() = default;
  7578. bool Client::is_valid() const {
  7579. return cli_ != nullptr && cli_->is_valid();
  7580. }
  7581. Result Client::Get(const std::string &path, DownloadProgress progress) {
  7582. return cli_->Get(path, std::move(progress));
  7583. }
  7584. Result Client::Get(const std::string &path, const Headers &headers,
  7585. DownloadProgress progress) {
  7586. return cli_->Get(path, headers, std::move(progress));
  7587. }
  7588. Result Client::Get(const std::string &path,
  7589. ContentReceiver content_receiver,
  7590. DownloadProgress progress) {
  7591. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  7592. }
  7593. Result Client::Get(const std::string &path, const Headers &headers,
  7594. ContentReceiver content_receiver,
  7595. DownloadProgress progress) {
  7596. return cli_->Get(path, headers, std::move(content_receiver),
  7597. std::move(progress));
  7598. }
  7599. Result Client::Get(const std::string &path,
  7600. ResponseHandler response_handler,
  7601. ContentReceiver content_receiver,
  7602. DownloadProgress progress) {
  7603. return cli_->Get(path, std::move(response_handler),
  7604. std::move(content_receiver), std::move(progress));
  7605. }
  7606. Result Client::Get(const std::string &path, const Headers &headers,
  7607. ResponseHandler response_handler,
  7608. ContentReceiver content_receiver,
  7609. DownloadProgress progress) {
  7610. return cli_->Get(path, headers, std::move(response_handler),
  7611. std::move(content_receiver), std::move(progress));
  7612. }
  7613. Result Client::Get(const std::string &path, const Params &params,
  7614. const Headers &headers, DownloadProgress progress) {
  7615. return cli_->Get(path, params, headers, std::move(progress));
  7616. }
  7617. Result Client::Get(const std::string &path, const Params &params,
  7618. const Headers &headers,
  7619. ContentReceiver content_receiver,
  7620. DownloadProgress progress) {
  7621. return cli_->Get(path, params, headers, std::move(content_receiver),
  7622. std::move(progress));
  7623. }
  7624. Result Client::Get(const std::string &path, const Params &params,
  7625. const Headers &headers,
  7626. ResponseHandler response_handler,
  7627. ContentReceiver content_receiver,
  7628. DownloadProgress progress) {
  7629. return cli_->Get(path, params, headers, std::move(response_handler),
  7630. std::move(content_receiver), std::move(progress));
  7631. }
  7632. Result Client::Head(const std::string &path) { return cli_->Head(path); }
  7633. Result Client::Head(const std::string &path, const Headers &headers) {
  7634. return cli_->Head(path, headers);
  7635. }
  7636. Result Client::Post(const std::string &path) { return cli_->Post(path); }
  7637. Result Client::Post(const std::string &path, const Headers &headers) {
  7638. return cli_->Post(path, headers);
  7639. }
  7640. Result Client::Post(const std::string &path, const char *body,
  7641. size_t content_length,
  7642. const std::string &content_type,
  7643. UploadProgress progress) {
  7644. return cli_->Post(path, body, content_length, content_type, progress);
  7645. }
  7646. Result Client::Post(const std::string &path, const Headers &headers,
  7647. const char *body, size_t content_length,
  7648. const std::string &content_type,
  7649. UploadProgress progress) {
  7650. return cli_->Post(path, headers, body, content_length, content_type,
  7651. progress);
  7652. }
  7653. Result Client::Post(const std::string &path, const std::string &body,
  7654. const std::string &content_type,
  7655. UploadProgress progress) {
  7656. return cli_->Post(path, body, content_type, progress);
  7657. }
  7658. Result Client::Post(const std::string &path, const Headers &headers,
  7659. const std::string &body,
  7660. const std::string &content_type,
  7661. UploadProgress progress) {
  7662. return cli_->Post(path, headers, body, content_type, progress);
  7663. }
  7664. Result Client::Post(const std::string &path, size_t content_length,
  7665. ContentProvider content_provider,
  7666. const std::string &content_type,
  7667. UploadProgress progress) {
  7668. return cli_->Post(path, content_length, std::move(content_provider),
  7669. content_type, progress);
  7670. }
  7671. Result Client::Post(const std::string &path, size_t content_length,
  7672. ContentProvider content_provider,
  7673. const std::string &content_type,
  7674. ContentReceiver content_receiver,
  7675. UploadProgress progress) {
  7676. return cli_->Post(path, content_length, std::move(content_provider),
  7677. content_type, std::move(content_receiver), progress);
  7678. }
  7679. Result Client::Post(const std::string &path,
  7680. ContentProviderWithoutLength content_provider,
  7681. const std::string &content_type,
  7682. UploadProgress progress) {
  7683. return cli_->Post(path, std::move(content_provider), content_type, progress);
  7684. }
  7685. Result Client::Post(const std::string &path,
  7686. ContentProviderWithoutLength content_provider,
  7687. const std::string &content_type,
  7688. ContentReceiver content_receiver,
  7689. UploadProgress progress) {
  7690. return cli_->Post(path, std::move(content_provider), content_type,
  7691. std::move(content_receiver), progress);
  7692. }
  7693. Result Client::Post(const std::string &path, const Headers &headers,
  7694. size_t content_length,
  7695. ContentProvider content_provider,
  7696. const std::string &content_type,
  7697. UploadProgress progress) {
  7698. return cli_->Post(path, headers, content_length, std::move(content_provider),
  7699. content_type, progress);
  7700. }
  7701. Result Client::Post(const std::string &path, const Headers &headers,
  7702. size_t content_length,
  7703. ContentProvider content_provider,
  7704. const std::string &content_type,
  7705. ContentReceiver content_receiver,
  7706. DownloadProgress progress) {
  7707. return cli_->Post(path, headers, content_length, std::move(content_provider),
  7708. content_type, std::move(content_receiver), progress);
  7709. }
  7710. Result Client::Post(const std::string &path, const Headers &headers,
  7711. ContentProviderWithoutLength content_provider,
  7712. const std::string &content_type,
  7713. UploadProgress progress) {
  7714. return cli_->Post(path, headers, std::move(content_provider), content_type,
  7715. progress);
  7716. }
  7717. Result Client::Post(const std::string &path, const Headers &headers,
  7718. ContentProviderWithoutLength content_provider,
  7719. const std::string &content_type,
  7720. ContentReceiver content_receiver,
  7721. DownloadProgress progress) {
  7722. return cli_->Post(path, headers, std::move(content_provider), content_type,
  7723. std::move(content_receiver), progress);
  7724. }
  7725. Result Client::Post(const std::string &path, const Params &params) {
  7726. return cli_->Post(path, params);
  7727. }
  7728. Result Client::Post(const std::string &path, const Headers &headers,
  7729. const Params &params) {
  7730. return cli_->Post(path, headers, params);
  7731. }
  7732. Result Client::Post(const std::string &path,
  7733. const UploadFormDataItems &items,
  7734. UploadProgress progress) {
  7735. return cli_->Post(path, items, progress);
  7736. }
  7737. Result Client::Post(const std::string &path, const Headers &headers,
  7738. const UploadFormDataItems &items,
  7739. UploadProgress progress) {
  7740. return cli_->Post(path, headers, items, progress);
  7741. }
  7742. Result Client::Post(const std::string &path, const Headers &headers,
  7743. const UploadFormDataItems &items,
  7744. const std::string &boundary,
  7745. UploadProgress progress) {
  7746. return cli_->Post(path, headers, items, boundary, progress);
  7747. }
  7748. Result Client::Post(const std::string &path, const Headers &headers,
  7749. const UploadFormDataItems &items,
  7750. const FormDataProviderItems &provider_items,
  7751. UploadProgress progress) {
  7752. return cli_->Post(path, headers, items, provider_items, progress);
  7753. }
  7754. Result Client::Post(const std::string &path, const Headers &headers,
  7755. const std::string &body,
  7756. const std::string &content_type,
  7757. ContentReceiver content_receiver,
  7758. DownloadProgress progress) {
  7759. return cli_->Post(path, headers, body, content_type,
  7760. std::move(content_receiver), progress);
  7761. }
  7762. Result Client::Put(const std::string &path) { return cli_->Put(path); }
  7763. Result Client::Put(const std::string &path, const Headers &headers) {
  7764. return cli_->Put(path, headers);
  7765. }
  7766. Result Client::Put(const std::string &path, const char *body,
  7767. size_t content_length,
  7768. const std::string &content_type,
  7769. UploadProgress progress) {
  7770. return cli_->Put(path, body, content_length, content_type, progress);
  7771. }
  7772. Result Client::Put(const std::string &path, const Headers &headers,
  7773. const char *body, size_t content_length,
  7774. const std::string &content_type,
  7775. UploadProgress progress) {
  7776. return cli_->Put(path, headers, body, content_length, content_type, progress);
  7777. }
  7778. Result Client::Put(const std::string &path, const std::string &body,
  7779. const std::string &content_type,
  7780. UploadProgress progress) {
  7781. return cli_->Put(path, body, content_type, progress);
  7782. }
  7783. Result Client::Put(const std::string &path, const Headers &headers,
  7784. const std::string &body,
  7785. const std::string &content_type,
  7786. UploadProgress progress) {
  7787. return cli_->Put(path, headers, body, content_type, progress);
  7788. }
  7789. Result Client::Put(const std::string &path, size_t content_length,
  7790. ContentProvider content_provider,
  7791. const std::string &content_type,
  7792. UploadProgress progress) {
  7793. return cli_->Put(path, content_length, std::move(content_provider),
  7794. content_type, progress);
  7795. }
  7796. Result Client::Put(const std::string &path, size_t content_length,
  7797. ContentProvider content_provider,
  7798. const std::string &content_type,
  7799. ContentReceiver content_receiver,
  7800. UploadProgress progress) {
  7801. return cli_->Put(path, content_length, std::move(content_provider),
  7802. content_type, std::move(content_receiver), progress);
  7803. }
  7804. Result Client::Put(const std::string &path,
  7805. ContentProviderWithoutLength content_provider,
  7806. const std::string &content_type,
  7807. UploadProgress progress) {
  7808. return cli_->Put(path, std::move(content_provider), content_type, progress);
  7809. }
  7810. Result Client::Put(const std::string &path,
  7811. ContentProviderWithoutLength content_provider,
  7812. const std::string &content_type,
  7813. ContentReceiver content_receiver,
  7814. UploadProgress progress) {
  7815. return cli_->Put(path, std::move(content_provider), content_type,
  7816. std::move(content_receiver), progress);
  7817. }
  7818. Result Client::Put(const std::string &path, const Headers &headers,
  7819. size_t content_length,
  7820. ContentProvider content_provider,
  7821. const std::string &content_type,
  7822. UploadProgress progress) {
  7823. return cli_->Put(path, headers, content_length, std::move(content_provider),
  7824. content_type, progress);
  7825. }
  7826. Result Client::Put(const std::string &path, const Headers &headers,
  7827. size_t content_length,
  7828. ContentProvider content_provider,
  7829. const std::string &content_type,
  7830. ContentReceiver content_receiver,
  7831. UploadProgress progress) {
  7832. return cli_->Put(path, headers, content_length, std::move(content_provider),
  7833. content_type, std::move(content_receiver), progress);
  7834. }
  7835. Result Client::Put(const std::string &path, const Headers &headers,
  7836. ContentProviderWithoutLength content_provider,
  7837. const std::string &content_type,
  7838. UploadProgress progress) {
  7839. return cli_->Put(path, headers, std::move(content_provider), content_type,
  7840. progress);
  7841. }
  7842. Result Client::Put(const std::string &path, const Headers &headers,
  7843. ContentProviderWithoutLength content_provider,
  7844. const std::string &content_type,
  7845. ContentReceiver content_receiver,
  7846. UploadProgress progress) {
  7847. return cli_->Put(path, headers, std::move(content_provider), content_type,
  7848. std::move(content_receiver), progress);
  7849. }
  7850. Result Client::Put(const std::string &path, const Params &params) {
  7851. return cli_->Put(path, params);
  7852. }
  7853. Result Client::Put(const std::string &path, const Headers &headers,
  7854. const Params &params) {
  7855. return cli_->Put(path, headers, params);
  7856. }
  7857. Result Client::Put(const std::string &path,
  7858. const UploadFormDataItems &items,
  7859. UploadProgress progress) {
  7860. return cli_->Put(path, items, progress);
  7861. }
  7862. Result Client::Put(const std::string &path, const Headers &headers,
  7863. const UploadFormDataItems &items,
  7864. UploadProgress progress) {
  7865. return cli_->Put(path, headers, items, progress);
  7866. }
  7867. Result Client::Put(const std::string &path, const Headers &headers,
  7868. const UploadFormDataItems &items,
  7869. const std::string &boundary,
  7870. UploadProgress progress) {
  7871. return cli_->Put(path, headers, items, boundary, progress);
  7872. }
  7873. Result Client::Put(const std::string &path, const Headers &headers,
  7874. const UploadFormDataItems &items,
  7875. const FormDataProviderItems &provider_items,
  7876. UploadProgress progress) {
  7877. return cli_->Put(path, headers, items, provider_items, progress);
  7878. }
  7879. Result Client::Put(const std::string &path, const Headers &headers,
  7880. const std::string &body,
  7881. const std::string &content_type,
  7882. ContentReceiver content_receiver,
  7883. DownloadProgress progress) {
  7884. return cli_->Put(path, headers, body, content_type, content_receiver,
  7885. progress);
  7886. }
  7887. Result Client::Patch(const std::string &path) {
  7888. return cli_->Patch(path);
  7889. }
  7890. Result Client::Patch(const std::string &path, const Headers &headers) {
  7891. return cli_->Patch(path, headers);
  7892. }
  7893. Result Client::Patch(const std::string &path, const char *body,
  7894. size_t content_length,
  7895. const std::string &content_type,
  7896. UploadProgress progress) {
  7897. return cli_->Patch(path, body, content_length, content_type, progress);
  7898. }
  7899. Result Client::Patch(const std::string &path, const Headers &headers,
  7900. const char *body, size_t content_length,
  7901. const std::string &content_type,
  7902. UploadProgress progress) {
  7903. return cli_->Patch(path, headers, body, content_length, content_type,
  7904. progress);
  7905. }
  7906. Result Client::Patch(const std::string &path, const std::string &body,
  7907. const std::string &content_type,
  7908. UploadProgress progress) {
  7909. return cli_->Patch(path, body, content_type, progress);
  7910. }
  7911. Result Client::Patch(const std::string &path, const Headers &headers,
  7912. const std::string &body,
  7913. const std::string &content_type,
  7914. UploadProgress progress) {
  7915. return cli_->Patch(path, headers, body, content_type, progress);
  7916. }
  7917. Result Client::Patch(const std::string &path, size_t content_length,
  7918. ContentProvider content_provider,
  7919. const std::string &content_type,
  7920. UploadProgress progress) {
  7921. return cli_->Patch(path, content_length, std::move(content_provider),
  7922. content_type, progress);
  7923. }
  7924. Result Client::Patch(const std::string &path, size_t content_length,
  7925. ContentProvider content_provider,
  7926. const std::string &content_type,
  7927. ContentReceiver content_receiver,
  7928. UploadProgress progress) {
  7929. return cli_->Patch(path, content_length, std::move(content_provider),
  7930. content_type, std::move(content_receiver), progress);
  7931. }
  7932. Result Client::Patch(const std::string &path,
  7933. ContentProviderWithoutLength content_provider,
  7934. const std::string &content_type,
  7935. UploadProgress progress) {
  7936. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  7937. }
  7938. Result Client::Patch(const std::string &path,
  7939. ContentProviderWithoutLength content_provider,
  7940. const std::string &content_type,
  7941. ContentReceiver content_receiver,
  7942. UploadProgress progress) {
  7943. return cli_->Patch(path, std::move(content_provider), content_type,
  7944. std::move(content_receiver), progress);
  7945. }
  7946. Result Client::Patch(const std::string &path, const Headers &headers,
  7947. size_t content_length,
  7948. ContentProvider content_provider,
  7949. const std::string &content_type,
  7950. UploadProgress progress) {
  7951. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  7952. content_type, progress);
  7953. }
  7954. Result Client::Patch(const std::string &path, const Headers &headers,
  7955. size_t content_length,
  7956. ContentProvider content_provider,
  7957. const std::string &content_type,
  7958. ContentReceiver content_receiver,
  7959. UploadProgress progress) {
  7960. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  7961. content_type, std::move(content_receiver), progress);
  7962. }
  7963. Result Client::Patch(const std::string &path, const Headers &headers,
  7964. ContentProviderWithoutLength content_provider,
  7965. const std::string &content_type,
  7966. UploadProgress progress) {
  7967. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  7968. progress);
  7969. }
  7970. Result Client::Patch(const std::string &path, const Headers &headers,
  7971. ContentProviderWithoutLength content_provider,
  7972. const std::string &content_type,
  7973. ContentReceiver content_receiver,
  7974. UploadProgress progress) {
  7975. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  7976. std::move(content_receiver), progress);
  7977. }
  7978. Result Client::Patch(const std::string &path, const Params &params) {
  7979. return cli_->Patch(path, params);
  7980. }
  7981. Result Client::Patch(const std::string &path, const Headers &headers,
  7982. const Params &params) {
  7983. return cli_->Patch(path, headers, params);
  7984. }
  7985. Result Client::Patch(const std::string &path,
  7986. const UploadFormDataItems &items,
  7987. UploadProgress progress) {
  7988. return cli_->Patch(path, items, progress);
  7989. }
  7990. Result Client::Patch(const std::string &path, const Headers &headers,
  7991. const UploadFormDataItems &items,
  7992. UploadProgress progress) {
  7993. return cli_->Patch(path, headers, items, progress);
  7994. }
  7995. Result Client::Patch(const std::string &path, const Headers &headers,
  7996. const UploadFormDataItems &items,
  7997. const std::string &boundary,
  7998. UploadProgress progress) {
  7999. return cli_->Patch(path, headers, items, boundary, progress);
  8000. }
  8001. Result Client::Patch(const std::string &path, const Headers &headers,
  8002. const UploadFormDataItems &items,
  8003. const FormDataProviderItems &provider_items,
  8004. UploadProgress progress) {
  8005. return cli_->Patch(path, headers, items, provider_items, progress);
  8006. }
  8007. Result Client::Patch(const std::string &path, const Headers &headers,
  8008. const std::string &body,
  8009. const std::string &content_type,
  8010. ContentReceiver content_receiver,
  8011. DownloadProgress progress) {
  8012. return cli_->Patch(path, headers, body, content_type, content_receiver,
  8013. progress);
  8014. }
  8015. Result Client::Delete(const std::string &path,
  8016. DownloadProgress progress) {
  8017. return cli_->Delete(path, progress);
  8018. }
  8019. Result Client::Delete(const std::string &path, const Headers &headers,
  8020. DownloadProgress progress) {
  8021. return cli_->Delete(path, headers, progress);
  8022. }
  8023. Result Client::Delete(const std::string &path, const char *body,
  8024. size_t content_length,
  8025. const std::string &content_type,
  8026. DownloadProgress progress) {
  8027. return cli_->Delete(path, body, content_length, content_type, progress);
  8028. }
  8029. Result Client::Delete(const std::string &path, const Headers &headers,
  8030. const char *body, size_t content_length,
  8031. const std::string &content_type,
  8032. DownloadProgress progress) {
  8033. return cli_->Delete(path, headers, body, content_length, content_type,
  8034. progress);
  8035. }
  8036. Result Client::Delete(const std::string &path, const std::string &body,
  8037. const std::string &content_type,
  8038. DownloadProgress progress) {
  8039. return cli_->Delete(path, body, content_type, progress);
  8040. }
  8041. Result Client::Delete(const std::string &path, const Headers &headers,
  8042. const std::string &body,
  8043. const std::string &content_type,
  8044. DownloadProgress progress) {
  8045. return cli_->Delete(path, headers, body, content_type, progress);
  8046. }
  8047. Result Client::Delete(const std::string &path, const Params &params,
  8048. DownloadProgress progress) {
  8049. return cli_->Delete(path, params, progress);
  8050. }
  8051. Result Client::Delete(const std::string &path, const Headers &headers,
  8052. const Params &params, DownloadProgress progress) {
  8053. return cli_->Delete(path, headers, params, progress);
  8054. }
  8055. Result Client::Options(const std::string &path) {
  8056. return cli_->Options(path);
  8057. }
  8058. Result Client::Options(const std::string &path, const Headers &headers) {
  8059. return cli_->Options(path, headers);
  8060. }
  8061. bool Client::send(Request &req, Response &res, Error &error) {
  8062. return cli_->send(req, res, error);
  8063. }
  8064. Result Client::send(const Request &req) { return cli_->send(req); }
  8065. void Client::stop() { cli_->stop(); }
  8066. std::string Client::host() const { return cli_->host(); }
  8067. int Client::port() const { return cli_->port(); }
  8068. size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  8069. socket_t Client::socket() const { return cli_->socket(); }
  8070. void
  8071. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  8072. cli_->set_hostname_addr_map(std::move(addr_map));
  8073. }
  8074. void Client::set_default_headers(Headers headers) {
  8075. cli_->set_default_headers(std::move(headers));
  8076. }
  8077. void Client::set_header_writer(
  8078. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  8079. cli_->set_header_writer(writer);
  8080. }
  8081. void Client::set_address_family(int family) {
  8082. cli_->set_address_family(family);
  8083. }
  8084. void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  8085. void Client::set_socket_options(SocketOptions socket_options) {
  8086. cli_->set_socket_options(std::move(socket_options));
  8087. }
  8088. void Client::set_connection_timeout(time_t sec, time_t usec) {
  8089. cli_->set_connection_timeout(sec, usec);
  8090. }
  8091. void Client::set_read_timeout(time_t sec, time_t usec) {
  8092. cli_->set_read_timeout(sec, usec);
  8093. }
  8094. void Client::set_write_timeout(time_t sec, time_t usec) {
  8095. cli_->set_write_timeout(sec, usec);
  8096. }
  8097. void Client::set_basic_auth(const std::string &username,
  8098. const std::string &password) {
  8099. cli_->set_basic_auth(username, password);
  8100. }
  8101. void Client::set_bearer_token_auth(const std::string &token) {
  8102. cli_->set_bearer_token_auth(token);
  8103. }
  8104. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8105. void Client::set_digest_auth(const std::string &username,
  8106. const std::string &password) {
  8107. cli_->set_digest_auth(username, password);
  8108. }
  8109. #endif
  8110. void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  8111. void Client::set_follow_location(bool on) {
  8112. cli_->set_follow_location(on);
  8113. }
  8114. void Client::set_path_encode(bool on) { cli_->set_path_encode(on); }
  8115. [[deprecated("Use set_path_encode instead")]]
  8116. void Client::set_url_encode(bool on) {
  8117. cli_->set_path_encode(on);
  8118. }
  8119. void Client::set_compress(bool on) { cli_->set_compress(on); }
  8120. void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  8121. void Client::set_interface(const std::string &intf) {
  8122. cli_->set_interface(intf);
  8123. }
  8124. void Client::set_proxy(const std::string &host, int port) {
  8125. cli_->set_proxy(host, port);
  8126. }
  8127. void Client::set_proxy_basic_auth(const std::string &username,
  8128. const std::string &password) {
  8129. cli_->set_proxy_basic_auth(username, password);
  8130. }
  8131. void Client::set_proxy_bearer_token_auth(const std::string &token) {
  8132. cli_->set_proxy_bearer_token_auth(token);
  8133. }
  8134. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8135. void Client::set_proxy_digest_auth(const std::string &username,
  8136. const std::string &password) {
  8137. cli_->set_proxy_digest_auth(username, password);
  8138. }
  8139. #endif
  8140. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8141. void Client::enable_server_certificate_verification(bool enabled) {
  8142. cli_->enable_server_certificate_verification(enabled);
  8143. }
  8144. void Client::enable_server_hostname_verification(bool enabled) {
  8145. cli_->enable_server_hostname_verification(enabled);
  8146. }
  8147. void Client::set_server_certificate_verifier(
  8148. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  8149. cli_->set_server_certificate_verifier(verifier);
  8150. }
  8151. #endif
  8152. void Client::set_logger(Logger logger) {
  8153. cli_->set_logger(std::move(logger));
  8154. }
  8155. void Client::set_error_logger(ErrorLogger error_logger) {
  8156. cli_->set_error_logger(std::move(error_logger));
  8157. }
  8158. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8159. void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  8160. const std::string &ca_cert_dir_path) {
  8161. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  8162. }
  8163. void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  8164. if (is_ssl_) {
  8165. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  8166. } else {
  8167. cli_->set_ca_cert_store(ca_cert_store);
  8168. }
  8169. }
  8170. void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  8171. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  8172. }
  8173. long Client::get_openssl_verify_result() const {
  8174. if (is_ssl_) {
  8175. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  8176. }
  8177. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  8178. }
  8179. SSL_CTX *Client::ssl_context() const {
  8180. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  8181. return nullptr;
  8182. }
  8183. #endif
  8184. } // namespace httplib