httplib.h 361 KB

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