httplib.h 353 KB

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