httplib.h 345 KB

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