httplib.h 373 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2025 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. #define CPPHTTPLIB_VERSION "0.22.0"
  10. /*
  11. * Configuration
  12. */
  13. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  14. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  15. #endif
  16. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND
  17. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000
  18. #endif
  19. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  20. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100
  21. #endif
  22. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  23. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  24. #endif
  25. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  26. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  27. #endif
  28. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND
  29. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5
  30. #endif
  31. #ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND
  32. #define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0
  33. #endif
  34. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND
  35. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5
  36. #endif
  37. #ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND
  38. #define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0
  39. #endif
  40. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND
  41. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300
  42. #endif
  43. #ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND
  44. #define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0
  45. #endif
  46. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND
  47. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5
  48. #endif
  49. #ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND
  50. #define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0
  51. #endif
  52. #ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND
  53. #define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0
  54. #endif
  55. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  56. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  57. #endif
  58. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  59. #ifdef _WIN32
  60. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 1000
  61. #else
  62. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  63. #endif
  64. #endif
  65. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  66. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  67. #endif
  68. #ifndef CPPHTTPLIB_HEADER_MAX_LENGTH
  69. #define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
  70. #endif
  71. #ifndef CPPHTTPLIB_HEADER_MAX_COUNT
  72. #define CPPHTTPLIB_HEADER_MAX_COUNT 100
  73. #endif
  74. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  75. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  76. #endif
  77. #ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT
  78. #define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024
  79. #endif
  80. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  81. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  82. #endif
  83. #ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH
  84. #define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192
  85. #endif
  86. #ifndef CPPHTTPLIB_RANGE_MAX_COUNT
  87. #define CPPHTTPLIB_RANGE_MAX_COUNT 1024
  88. #endif
  89. #ifndef CPPHTTPLIB_TCP_NODELAY
  90. #define CPPHTTPLIB_TCP_NODELAY false
  91. #endif
  92. #ifndef CPPHTTPLIB_IPV6_V6ONLY
  93. #define CPPHTTPLIB_IPV6_V6ONLY false
  94. #endif
  95. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  96. #define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u)
  97. #endif
  98. #ifndef CPPHTTPLIB_SEND_BUFSIZ
  99. #define CPPHTTPLIB_SEND_BUFSIZ size_t(16384u)
  100. #endif
  101. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  102. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  103. #endif
  104. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  105. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  106. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  107. ? std::thread::hardware_concurrency() - 1 \
  108. : 0))
  109. #endif
  110. #ifndef CPPHTTPLIB_RECV_FLAGS
  111. #define CPPHTTPLIB_RECV_FLAGS 0
  112. #endif
  113. #ifndef CPPHTTPLIB_SEND_FLAGS
  114. #define CPPHTTPLIB_SEND_FLAGS 0
  115. #endif
  116. #ifndef CPPHTTPLIB_LISTEN_BACKLOG
  117. #define CPPHTTPLIB_LISTEN_BACKLOG 5
  118. #endif
  119. #ifndef CPPHTTPLIB_MAX_LINE_LENGTH
  120. #define CPPHTTPLIB_MAX_LINE_LENGTH 32768
  121. #endif
  122. /*
  123. * Headers
  124. */
  125. #ifdef _WIN32
  126. #ifndef _CRT_SECURE_NO_WARNINGS
  127. #define _CRT_SECURE_NO_WARNINGS
  128. #endif //_CRT_SECURE_NO_WARNINGS
  129. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  130. #define _CRT_NONSTDC_NO_DEPRECATE
  131. #endif //_CRT_NONSTDC_NO_DEPRECATE
  132. #if defined(_MSC_VER)
  133. #if _MSC_VER < 1900
  134. #error Sorry, Visual Studio versions prior to 2015 are not supported
  135. #endif
  136. #pragma comment(lib, "ws2_32.lib")
  137. #ifdef _WIN64
  138. using ssize_t = __int64;
  139. #else
  140. using ssize_t = long;
  141. #endif
  142. #endif // _MSC_VER
  143. #ifndef S_ISREG
  144. #define S_ISREG(m) (((m) & S_IFREG) == S_IFREG)
  145. #endif // S_ISREG
  146. #ifndef S_ISDIR
  147. #define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR)
  148. #endif // S_ISDIR
  149. #ifndef NOMINMAX
  150. #define NOMINMAX
  151. #endif // NOMINMAX
  152. #include <io.h>
  153. #include <winsock2.h>
  154. #include <ws2tcpip.h>
  155. #if defined(__has_include)
  156. #if __has_include(<afunix.h>)
  157. // afunix.h uses types declared in winsock2.h, so has to be included after it.
  158. #include <afunix.h>
  159. #define CPPHTTPLIB_HAVE_AFUNIX_H 1
  160. #endif
  161. #endif
  162. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  163. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  164. #endif
  165. using nfds_t = unsigned long;
  166. using socket_t = SOCKET;
  167. using socklen_t = int;
  168. #else // not _WIN32
  169. #include <arpa/inet.h>
  170. #if !defined(_AIX) && !defined(__MVS__)
  171. #include <ifaddrs.h>
  172. #endif
  173. #ifdef __MVS__
  174. #include <strings.h>
  175. #ifndef NI_MAXHOST
  176. #define NI_MAXHOST 1025
  177. #endif
  178. #endif
  179. #include <net/if.h>
  180. #include <netdb.h>
  181. #include <netinet/in.h>
  182. #ifdef __linux__
  183. #include <resolv.h>
  184. #endif
  185. #include <csignal>
  186. #include <netinet/tcp.h>
  187. #include <poll.h>
  188. #include <pthread.h>
  189. #include <sys/mman.h>
  190. #include <sys/socket.h>
  191. #include <sys/un.h>
  192. #include <unistd.h>
  193. using socket_t = int;
  194. #ifndef INVALID_SOCKET
  195. #define INVALID_SOCKET (-1)
  196. #endif
  197. #endif //_WIN32
  198. #if defined(__APPLE__)
  199. #include <TargetConditionals.h>
  200. #endif
  201. #include <algorithm>
  202. #include <array>
  203. #include <atomic>
  204. #include <cassert>
  205. #include <cctype>
  206. #include <climits>
  207. #include <condition_variable>
  208. #include <cstring>
  209. #include <errno.h>
  210. #include <exception>
  211. #include <fcntl.h>
  212. #include <functional>
  213. #include <iomanip>
  214. #include <iostream>
  215. #include <list>
  216. #include <map>
  217. #include <memory>
  218. #include <mutex>
  219. #include <random>
  220. #include <regex>
  221. #include <set>
  222. #include <sstream>
  223. #include <string>
  224. #include <sys/stat.h>
  225. #include <thread>
  226. #include <unordered_map>
  227. #include <unordered_set>
  228. #include <utility>
  229. #if defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO) || \
  230. defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  231. #if TARGET_OS_OSX
  232. #include <CFNetwork/CFHost.h>
  233. #include <CoreFoundation/CoreFoundation.h>
  234. #endif
  235. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO or
  236. // CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  237. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  238. #ifdef _WIN32
  239. #include <wincrypt.h>
  240. // these are defined in wincrypt.h and it breaks compilation if BoringSSL is
  241. // used
  242. #undef X509_NAME
  243. #undef X509_CERT_PAIR
  244. #undef X509_EXTENSIONS
  245. #undef PKCS7_SIGNER_INFO
  246. #ifdef _MSC_VER
  247. #pragma comment(lib, "crypt32.lib")
  248. #endif
  249. #endif // _WIN32
  250. #if defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN)
  251. #if TARGET_OS_OSX
  252. #include <Security/Security.h>
  253. #endif
  254. #endif // CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  255. #include <openssl/err.h>
  256. #include <openssl/evp.h>
  257. #include <openssl/ssl.h>
  258. #include <openssl/x509v3.h>
  259. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  260. #include <openssl/applink.c>
  261. #endif
  262. #include <iostream>
  263. #include <sstream>
  264. #if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER)
  265. #if OPENSSL_VERSION_NUMBER < 0x1010107f
  266. #error Please use OpenSSL or a current version of BoringSSL
  267. #endif
  268. #define SSL_get1_peer_certificate SSL_get_peer_certificate
  269. #elif OPENSSL_VERSION_NUMBER < 0x30000000L
  270. #error Sorry, OpenSSL versions prior to 3.0.0 are not supported
  271. #endif
  272. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  273. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  274. #include <zlib.h>
  275. #endif
  276. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  277. #include <brotli/decode.h>
  278. #include <brotli/encode.h>
  279. #endif
  280. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  281. #include <zstd.h>
  282. #endif
  283. /*
  284. * Declaration
  285. */
  286. namespace httplib {
  287. namespace detail {
  288. /*
  289. * Backport std::make_unique from C++14.
  290. *
  291. * NOTE: This code came up with the following stackoverflow post:
  292. * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
  293. *
  294. */
  295. template <class T, class... Args>
  296. typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
  297. make_unique(Args &&...args) {
  298. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  299. }
  300. template <class T>
  301. typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
  302. make_unique(std::size_t n) {
  303. typedef typename std::remove_extent<T>::type RT;
  304. return std::unique_ptr<T>(new RT[n]);
  305. }
  306. namespace case_ignore {
  307. inline unsigned char to_lower(int c) {
  308. const static unsigned char table[256] = {
  309. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  310. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  311. 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  312. 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  313. 60, 61, 62, 63, 64, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
  314. 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
  315. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  316. 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  317. 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  318. 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  319. 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  320. 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  321. 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 224, 225, 226,
  322. 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
  323. 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 223, 224,
  324. 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
  325. 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
  326. 255,
  327. };
  328. return table[(unsigned char)(char)c];
  329. }
  330. inline bool equal(const std::string &a, const std::string &b) {
  331. return a.size() == b.size() &&
  332. std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) {
  333. return to_lower(ca) == to_lower(cb);
  334. });
  335. }
  336. struct equal_to {
  337. bool operator()(const std::string &a, const std::string &b) const {
  338. return equal(a, b);
  339. }
  340. };
  341. struct hash {
  342. size_t operator()(const std::string &key) const {
  343. return hash_core(key.data(), key.size(), 0);
  344. }
  345. size_t hash_core(const char *s, size_t l, size_t h) const {
  346. return (l == 0) ? h
  347. : hash_core(s + 1, l - 1,
  348. // Unsets the 6 high bits of h, therefore no
  349. // overflow happens
  350. (((std::numeric_limits<size_t>::max)() >> 6) &
  351. h * 33) ^
  352. static_cast<unsigned char>(to_lower(*s)));
  353. }
  354. };
  355. } // namespace case_ignore
  356. // This is based on
  357. // "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189".
  358. struct scope_exit {
  359. explicit scope_exit(std::function<void(void)> &&f)
  360. : exit_function(std::move(f)), execute_on_destruction{true} {}
  361. scope_exit(scope_exit &&rhs) noexcept
  362. : exit_function(std::move(rhs.exit_function)),
  363. execute_on_destruction{rhs.execute_on_destruction} {
  364. rhs.release();
  365. }
  366. ~scope_exit() {
  367. if (execute_on_destruction) { this->exit_function(); }
  368. }
  369. void release() { this->execute_on_destruction = false; }
  370. private:
  371. scope_exit(const scope_exit &) = delete;
  372. void operator=(const scope_exit &) = delete;
  373. scope_exit &operator=(scope_exit &&) = delete;
  374. std::function<void(void)> exit_function;
  375. bool execute_on_destruction;
  376. };
  377. } // namespace detail
  378. enum SSLVerifierResponse {
  379. // no decision has been made, use the built-in certificate verifier
  380. NoDecisionMade,
  381. // connection certificate is verified and accepted
  382. CertificateAccepted,
  383. // connection certificate was processed but is rejected
  384. CertificateRejected
  385. };
  386. enum StatusCode {
  387. // Information responses
  388. Continue_100 = 100,
  389. SwitchingProtocol_101 = 101,
  390. Processing_102 = 102,
  391. EarlyHints_103 = 103,
  392. // Successful responses
  393. OK_200 = 200,
  394. Created_201 = 201,
  395. Accepted_202 = 202,
  396. NonAuthoritativeInformation_203 = 203,
  397. NoContent_204 = 204,
  398. ResetContent_205 = 205,
  399. PartialContent_206 = 206,
  400. MultiStatus_207 = 207,
  401. AlreadyReported_208 = 208,
  402. IMUsed_226 = 226,
  403. // Redirection messages
  404. MultipleChoices_300 = 300,
  405. MovedPermanently_301 = 301,
  406. Found_302 = 302,
  407. SeeOther_303 = 303,
  408. NotModified_304 = 304,
  409. UseProxy_305 = 305,
  410. unused_306 = 306,
  411. TemporaryRedirect_307 = 307,
  412. PermanentRedirect_308 = 308,
  413. // Client error responses
  414. BadRequest_400 = 400,
  415. Unauthorized_401 = 401,
  416. PaymentRequired_402 = 402,
  417. Forbidden_403 = 403,
  418. NotFound_404 = 404,
  419. MethodNotAllowed_405 = 405,
  420. NotAcceptable_406 = 406,
  421. ProxyAuthenticationRequired_407 = 407,
  422. RequestTimeout_408 = 408,
  423. Conflict_409 = 409,
  424. Gone_410 = 410,
  425. LengthRequired_411 = 411,
  426. PreconditionFailed_412 = 412,
  427. PayloadTooLarge_413 = 413,
  428. UriTooLong_414 = 414,
  429. UnsupportedMediaType_415 = 415,
  430. RangeNotSatisfiable_416 = 416,
  431. ExpectationFailed_417 = 417,
  432. ImATeapot_418 = 418,
  433. MisdirectedRequest_421 = 421,
  434. UnprocessableContent_422 = 422,
  435. Locked_423 = 423,
  436. FailedDependency_424 = 424,
  437. TooEarly_425 = 425,
  438. UpgradeRequired_426 = 426,
  439. PreconditionRequired_428 = 428,
  440. TooManyRequests_429 = 429,
  441. RequestHeaderFieldsTooLarge_431 = 431,
  442. UnavailableForLegalReasons_451 = 451,
  443. // Server error responses
  444. InternalServerError_500 = 500,
  445. NotImplemented_501 = 501,
  446. BadGateway_502 = 502,
  447. ServiceUnavailable_503 = 503,
  448. GatewayTimeout_504 = 504,
  449. HttpVersionNotSupported_505 = 505,
  450. VariantAlsoNegotiates_506 = 506,
  451. InsufficientStorage_507 = 507,
  452. LoopDetected_508 = 508,
  453. NotExtended_510 = 510,
  454. NetworkAuthenticationRequired_511 = 511,
  455. };
  456. using Headers =
  457. std::unordered_multimap<std::string, std::string, detail::case_ignore::hash,
  458. detail::case_ignore::equal_to>;
  459. using Params = std::multimap<std::string, std::string>;
  460. using Match = std::smatch;
  461. using DownloadProgress = std::function<bool(uint64_t current, uint64_t total)>;
  462. using UploadProgress = std::function<bool(uint64_t current, uint64_t total)>;
  463. struct Response;
  464. using ResponseHandler = std::function<bool(const Response &response)>;
  465. struct MultipartFormData {
  466. std::string name;
  467. std::string content;
  468. std::string filename;
  469. std::string content_type;
  470. Headers headers;
  471. };
  472. using MultipartFormDataItems = std::vector<MultipartFormData>;
  473. using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
  474. struct MultipartFormDataForClientInput {
  475. std::string name;
  476. std::string content;
  477. std::string filename;
  478. std::string content_type;
  479. };
  480. using MultipartFormDataItemsForClientInput =
  481. std::vector<MultipartFormDataForClientInput>;
  482. class DataSink {
  483. public:
  484. DataSink() : os(&sb_), sb_(*this) {}
  485. DataSink(const DataSink &) = delete;
  486. DataSink &operator=(const DataSink &) = delete;
  487. DataSink(DataSink &&) = delete;
  488. DataSink &operator=(DataSink &&) = delete;
  489. std::function<bool(const char *data, size_t data_len)> write;
  490. std::function<bool()> is_writable;
  491. std::function<void()> done;
  492. std::function<void(const Headers &trailer)> done_with_trailer;
  493. std::ostream os;
  494. private:
  495. class data_sink_streambuf final : public std::streambuf {
  496. public:
  497. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  498. protected:
  499. std::streamsize xsputn(const char *s, std::streamsize n) override {
  500. sink_.write(s, static_cast<size_t>(n));
  501. return n;
  502. }
  503. private:
  504. DataSink &sink_;
  505. };
  506. data_sink_streambuf sb_;
  507. };
  508. using ContentProvider =
  509. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  510. using ContentProviderWithoutLength =
  511. std::function<bool(size_t offset, DataSink &sink)>;
  512. using ContentProviderResourceReleaser = std::function<void(bool success)>;
  513. struct MultipartFormDataProvider {
  514. std::string name;
  515. ContentProviderWithoutLength provider;
  516. std::string filename;
  517. std::string content_type;
  518. };
  519. using MultipartFormDataProviderItems = std::vector<MultipartFormDataProvider>;
  520. using ContentReceiverWithProgress =
  521. std::function<bool(const char *data, size_t data_length, uint64_t offset,
  522. uint64_t total_length)>;
  523. using ContentReceiver =
  524. std::function<bool(const char *data, size_t data_length)>;
  525. using MultipartContentHeader =
  526. std::function<bool(const MultipartFormData &file)>;
  527. class ContentReader {
  528. public:
  529. using Reader = std::function<bool(ContentReceiver receiver)>;
  530. using MultipartReader = std::function<bool(MultipartContentHeader header,
  531. ContentReceiver receiver)>;
  532. ContentReader(Reader reader, MultipartReader multipart_reader)
  533. : reader_(std::move(reader)),
  534. multipart_reader_(std::move(multipart_reader)) {}
  535. bool operator()(MultipartContentHeader header,
  536. ContentReceiver receiver) const {
  537. return multipart_reader_(std::move(header), std::move(receiver));
  538. }
  539. bool operator()(ContentReceiver receiver) const {
  540. return reader_(std::move(receiver));
  541. }
  542. Reader reader_;
  543. MultipartReader multipart_reader_;
  544. };
  545. using Range = std::pair<ssize_t, ssize_t>;
  546. using Ranges = std::vector<Range>;
  547. struct Request {
  548. std::string method;
  549. std::string path;
  550. std::string matched_route;
  551. Params params;
  552. Headers headers;
  553. std::string body;
  554. std::string remote_addr;
  555. int remote_port = -1;
  556. std::string local_addr;
  557. int local_port = -1;
  558. // for server
  559. std::string version;
  560. std::string target;
  561. MultipartFormDataMap files;
  562. Ranges ranges;
  563. Match matches;
  564. std::unordered_map<std::string, std::string> path_params;
  565. std::function<bool()> is_connection_closed = []() { return true; };
  566. // for client
  567. std::vector<std::string> accept_content_types;
  568. ResponseHandler response_handler;
  569. ContentReceiverWithProgress content_receiver;
  570. DownloadProgress download_progress;
  571. UploadProgress upload_progress;
  572. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  573. const SSL *ssl = nullptr;
  574. #endif
  575. bool has_header(const std::string &key) const;
  576. std::string get_header_value(const std::string &key, const char *def = "",
  577. size_t id = 0) const;
  578. uint64_t get_header_value_u64(const std::string &key, uint64_t def = 0,
  579. size_t id = 0) const;
  580. size_t get_header_value_count(const std::string &key) const;
  581. void set_header(const std::string &key, const std::string &val);
  582. bool has_param(const std::string &key) const;
  583. std::string get_param_value(const std::string &key, size_t id = 0) const;
  584. size_t get_param_value_count(const std::string &key) const;
  585. bool is_multipart_form_data() const;
  586. bool has_file(const std::string &key) const;
  587. MultipartFormData get_file_value(const std::string &key) const;
  588. std::vector<MultipartFormData> get_file_values(const std::string &key) const;
  589. // private members...
  590. size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  591. size_t content_length_ = 0;
  592. ContentProvider content_provider_;
  593. bool is_chunked_content_provider_ = false;
  594. size_t authorization_count_ = 0;
  595. std::chrono::time_point<std::chrono::steady_clock> start_time_ =
  596. (std::chrono::steady_clock::time_point::min)();
  597. };
  598. struct Response {
  599. std::string version;
  600. int status = -1;
  601. std::string reason;
  602. Headers headers;
  603. std::string body;
  604. std::string location; // Redirect location
  605. bool has_header(const std::string &key) const;
  606. std::string get_header_value(const std::string &key, const char *def = "",
  607. size_t id = 0) const;
  608. uint64_t get_header_value_u64(const std::string &key, uint64_t def = 0,
  609. size_t id = 0) const;
  610. size_t get_header_value_count(const std::string &key) const;
  611. void set_header(const std::string &key, const std::string &val);
  612. void set_redirect(const std::string &url, int status = StatusCode::Found_302);
  613. void set_content(const char *s, size_t n, const std::string &content_type);
  614. void set_content(const std::string &s, const std::string &content_type);
  615. void set_content(std::string &&s, const std::string &content_type);
  616. void set_content_provider(
  617. size_t length, const std::string &content_type, ContentProvider provider,
  618. ContentProviderResourceReleaser resource_releaser = nullptr);
  619. void set_content_provider(
  620. const std::string &content_type, ContentProviderWithoutLength provider,
  621. ContentProviderResourceReleaser resource_releaser = nullptr);
  622. void set_chunked_content_provider(
  623. const std::string &content_type, ContentProviderWithoutLength provider,
  624. ContentProviderResourceReleaser resource_releaser = nullptr);
  625. void set_file_content(const std::string &path,
  626. const std::string &content_type);
  627. void set_file_content(const std::string &path);
  628. Response() = default;
  629. Response(const Response &) = default;
  630. Response &operator=(const Response &) = default;
  631. Response(Response &&) = default;
  632. Response &operator=(Response &&) = default;
  633. ~Response() {
  634. if (content_provider_resource_releaser_) {
  635. content_provider_resource_releaser_(content_provider_success_);
  636. }
  637. }
  638. // private members...
  639. size_t content_length_ = 0;
  640. ContentProvider content_provider_;
  641. ContentProviderResourceReleaser content_provider_resource_releaser_;
  642. bool is_chunked_content_provider_ = false;
  643. bool content_provider_success_ = false;
  644. std::string file_content_path_;
  645. std::string file_content_content_type_;
  646. };
  647. class Stream {
  648. public:
  649. virtual ~Stream() = default;
  650. virtual bool is_readable() const = 0;
  651. virtual bool wait_readable() const = 0;
  652. virtual bool wait_writable() const = 0;
  653. virtual ssize_t read(char *ptr, size_t size) = 0;
  654. virtual ssize_t write(const char *ptr, size_t size) = 0;
  655. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  656. virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0;
  657. virtual socket_t socket() const = 0;
  658. virtual time_t duration() const = 0;
  659. ssize_t write(const char *ptr);
  660. ssize_t write(const std::string &s);
  661. };
  662. class TaskQueue {
  663. public:
  664. TaskQueue() = default;
  665. virtual ~TaskQueue() = default;
  666. virtual bool enqueue(std::function<void()> fn) = 0;
  667. virtual void shutdown() = 0;
  668. virtual void on_idle() {}
  669. };
  670. class ThreadPool final : public TaskQueue {
  671. public:
  672. explicit ThreadPool(size_t n, size_t mqr = 0)
  673. : shutdown_(false), max_queued_requests_(mqr) {
  674. while (n) {
  675. threads_.emplace_back(worker(*this));
  676. n--;
  677. }
  678. }
  679. ThreadPool(const ThreadPool &) = delete;
  680. ~ThreadPool() override = default;
  681. bool enqueue(std::function<void()> fn) override {
  682. {
  683. std::unique_lock<std::mutex> lock(mutex_);
  684. if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) {
  685. return false;
  686. }
  687. jobs_.push_back(std::move(fn));
  688. }
  689. cond_.notify_one();
  690. return true;
  691. }
  692. void shutdown() override {
  693. // Stop all worker threads...
  694. {
  695. std::unique_lock<std::mutex> lock(mutex_);
  696. shutdown_ = true;
  697. }
  698. cond_.notify_all();
  699. // Join...
  700. for (auto &t : threads_) {
  701. t.join();
  702. }
  703. }
  704. private:
  705. struct worker {
  706. explicit worker(ThreadPool &pool) : pool_(pool) {}
  707. void operator()() {
  708. for (;;) {
  709. std::function<void()> fn;
  710. {
  711. std::unique_lock<std::mutex> lock(pool_.mutex_);
  712. pool_.cond_.wait(
  713. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  714. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  715. fn = pool_.jobs_.front();
  716. pool_.jobs_.pop_front();
  717. }
  718. assert(true == static_cast<bool>(fn));
  719. fn();
  720. }
  721. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \
  722. !defined(LIBRESSL_VERSION_NUMBER)
  723. OPENSSL_thread_stop();
  724. #endif
  725. }
  726. ThreadPool &pool_;
  727. };
  728. friend struct worker;
  729. std::vector<std::thread> threads_;
  730. std::list<std::function<void()>> jobs_;
  731. bool shutdown_;
  732. size_t max_queued_requests_ = 0;
  733. std::condition_variable cond_;
  734. std::mutex mutex_;
  735. };
  736. using Logger = std::function<void(const Request &, const Response &)>;
  737. using SocketOptions = std::function<void(socket_t sock)>;
  738. namespace detail {
  739. bool set_socket_opt_impl(socket_t sock, int level, int optname,
  740. const void *optval, socklen_t optlen);
  741. bool set_socket_opt(socket_t sock, int level, int optname, int opt);
  742. bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec,
  743. time_t usec);
  744. } // namespace detail
  745. void default_socket_options(socket_t sock);
  746. const char *status_message(int status);
  747. std::string get_bearer_token_auth(const Request &req);
  748. namespace detail {
  749. class MatcherBase {
  750. public:
  751. MatcherBase(std::string pattern) : pattern_(pattern) {}
  752. virtual ~MatcherBase() = default;
  753. const std::string &pattern() const { return pattern_; }
  754. // Match request path and populate its matches and
  755. virtual bool match(Request &request) const = 0;
  756. private:
  757. std::string pattern_;
  758. };
  759. /**
  760. * Captures parameters in request path and stores them in Request::path_params
  761. *
  762. * Capture name is a substring of a pattern from : to /.
  763. * The rest of the pattern is matched against the request path directly
  764. * Parameters are captured starting from the next character after
  765. * the end of the last matched static pattern fragment until the next /.
  766. *
  767. * Example pattern:
  768. * "/path/fragments/:capture/more/fragments/:second_capture"
  769. * Static fragments:
  770. * "/path/fragments/", "more/fragments/"
  771. *
  772. * Given the following request path:
  773. * "/path/fragments/:1/more/fragments/:2"
  774. * the resulting capture will be
  775. * {{"capture", "1"}, {"second_capture", "2"}}
  776. */
  777. class PathParamsMatcher final : public MatcherBase {
  778. public:
  779. PathParamsMatcher(const std::string &pattern);
  780. bool match(Request &request) const override;
  781. private:
  782. // Treat segment separators as the end of path parameter capture
  783. // Does not need to handle query parameters as they are parsed before path
  784. // matching
  785. static constexpr char separator = '/';
  786. // Contains static path fragments to match against, excluding the '/' after
  787. // path params
  788. // Fragments are separated by path params
  789. std::vector<std::string> static_fragments_;
  790. // Stores the names of the path parameters to be used as keys in the
  791. // Request::path_params map
  792. std::vector<std::string> param_names_;
  793. };
  794. /**
  795. * Performs std::regex_match on request path
  796. * and stores the result in Request::matches
  797. *
  798. * Note that regex match is performed directly on the whole request.
  799. * This means that wildcard patterns may match multiple path segments with /:
  800. * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end".
  801. */
  802. class RegexMatcher final : public MatcherBase {
  803. public:
  804. RegexMatcher(const std::string &pattern)
  805. : MatcherBase(pattern), regex_(pattern) {}
  806. bool match(Request &request) const override;
  807. private:
  808. std::regex regex_;
  809. };
  810. ssize_t write_headers(Stream &strm, const Headers &headers);
  811. } // namespace detail
  812. class Server {
  813. public:
  814. using Handler = std::function<void(const Request &, Response &)>;
  815. using ExceptionHandler =
  816. std::function<void(const Request &, Response &, std::exception_ptr ep)>;
  817. enum class HandlerResponse {
  818. Handled,
  819. Unhandled,
  820. };
  821. using HandlerWithResponse =
  822. std::function<HandlerResponse(const Request &, Response &)>;
  823. using HandlerWithContentReader = std::function<void(
  824. const Request &, Response &, const ContentReader &content_reader)>;
  825. using Expect100ContinueHandler =
  826. std::function<int(const Request &, Response &)>;
  827. Server();
  828. virtual ~Server();
  829. virtual bool is_valid() const;
  830. Server &Get(const std::string &pattern, Handler handler);
  831. Server &Post(const std::string &pattern, Handler handler);
  832. Server &Post(const std::string &pattern, HandlerWithContentReader handler);
  833. Server &Put(const std::string &pattern, Handler handler);
  834. Server &Put(const std::string &pattern, HandlerWithContentReader handler);
  835. Server &Patch(const std::string &pattern, Handler handler);
  836. Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
  837. Server &Delete(const std::string &pattern, Handler handler);
  838. Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
  839. Server &Options(const std::string &pattern, Handler handler);
  840. bool set_base_dir(const std::string &dir,
  841. const std::string &mount_point = std::string());
  842. bool set_mount_point(const std::string &mount_point, const std::string &dir,
  843. Headers headers = Headers());
  844. bool remove_mount_point(const std::string &mount_point);
  845. Server &set_file_extension_and_mimetype_mapping(const std::string &ext,
  846. const std::string &mime);
  847. Server &set_default_file_mimetype(const std::string &mime);
  848. Server &set_file_request_handler(Handler handler);
  849. template <class ErrorHandlerFunc>
  850. Server &set_error_handler(ErrorHandlerFunc &&handler) {
  851. return set_error_handler_core(
  852. std::forward<ErrorHandlerFunc>(handler),
  853. std::is_convertible<ErrorHandlerFunc, HandlerWithResponse>{});
  854. }
  855. Server &set_exception_handler(ExceptionHandler handler);
  856. Server &set_pre_routing_handler(HandlerWithResponse handler);
  857. Server &set_post_routing_handler(Handler handler);
  858. Server &set_pre_request_handler(HandlerWithResponse handler);
  859. Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
  860. Server &set_logger(Logger logger);
  861. Server &set_address_family(int family);
  862. Server &set_tcp_nodelay(bool on);
  863. Server &set_ipv6_v6only(bool on);
  864. Server &set_socket_options(SocketOptions socket_options);
  865. Server &set_default_headers(Headers headers);
  866. Server &
  867. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  868. Server &set_keep_alive_max_count(size_t count);
  869. Server &set_keep_alive_timeout(time_t sec);
  870. Server &set_read_timeout(time_t sec, time_t usec = 0);
  871. template <class Rep, class Period>
  872. Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  873. Server &set_write_timeout(time_t sec, time_t usec = 0);
  874. template <class Rep, class Period>
  875. Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  876. Server &set_idle_interval(time_t sec, time_t usec = 0);
  877. template <class Rep, class Period>
  878. Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
  879. Server &set_payload_max_length(size_t length);
  880. bool bind_to_port(const std::string &host, int port, int socket_flags = 0);
  881. int bind_to_any_port(const std::string &host, int socket_flags = 0);
  882. bool listen_after_bind();
  883. bool listen(const std::string &host, int port, int socket_flags = 0);
  884. bool is_running() const;
  885. void wait_until_ready() const;
  886. void stop();
  887. void decommission();
  888. std::function<TaskQueue *(void)> new_task_queue;
  889. protected:
  890. bool process_request(Stream &strm, const std::string &remote_addr,
  891. int remote_port, const std::string &local_addr,
  892. int local_port, bool close_connection,
  893. bool &connection_closed,
  894. const std::function<void(Request &)> &setup_request);
  895. std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
  896. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  897. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  898. time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND;
  899. time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND;
  900. time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND;
  901. time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND;
  902. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  903. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  904. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  905. private:
  906. using Handlers =
  907. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>, Handler>>;
  908. using HandlersForContentReader =
  909. std::vector<std::pair<std::unique_ptr<detail::MatcherBase>,
  910. HandlerWithContentReader>>;
  911. static std::unique_ptr<detail::MatcherBase>
  912. make_matcher(const std::string &pattern);
  913. Server &set_error_handler_core(HandlerWithResponse handler, std::true_type);
  914. Server &set_error_handler_core(Handler handler, std::false_type);
  915. socket_t create_server_socket(const std::string &host, int port,
  916. int socket_flags,
  917. SocketOptions socket_options) const;
  918. int bind_internal(const std::string &host, int port, int socket_flags);
  919. bool listen_internal();
  920. bool routing(Request &req, Response &res, Stream &strm);
  921. bool handle_file_request(const Request &req, Response &res);
  922. bool dispatch_request(Request &req, Response &res,
  923. const Handlers &handlers) const;
  924. bool dispatch_request_for_content_reader(
  925. Request &req, Response &res, ContentReader content_reader,
  926. const HandlersForContentReader &handlers) const;
  927. bool parse_request_line(const char *s, Request &req) const;
  928. void apply_ranges(const Request &req, Response &res,
  929. std::string &content_type, std::string &boundary) const;
  930. bool write_response(Stream &strm, bool close_connection, Request &req,
  931. Response &res);
  932. bool write_response_with_content(Stream &strm, bool close_connection,
  933. const Request &req, Response &res);
  934. bool write_response_core(Stream &strm, bool close_connection,
  935. const Request &req, Response &res,
  936. bool need_apply_ranges);
  937. bool write_content_with_provider(Stream &strm, const Request &req,
  938. Response &res, const std::string &boundary,
  939. const std::string &content_type);
  940. bool read_content(Stream &strm, Request &req, Response &res);
  941. bool
  942. read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
  943. ContentReceiver receiver,
  944. MultipartContentHeader multipart_header,
  945. ContentReceiver multipart_receiver);
  946. bool read_content_core(Stream &strm, Request &req, Response &res,
  947. ContentReceiver receiver,
  948. MultipartContentHeader multipart_header,
  949. ContentReceiver multipart_receiver) const;
  950. virtual bool process_and_close_socket(socket_t sock);
  951. std::atomic<bool> is_running_{false};
  952. std::atomic<bool> is_decommissioned{false};
  953. struct MountPointEntry {
  954. std::string mount_point;
  955. std::string base_dir;
  956. Headers headers;
  957. };
  958. std::vector<MountPointEntry> base_dirs_;
  959. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  960. std::string default_file_mimetype_ = "application/octet-stream";
  961. Handler file_request_handler_;
  962. Handlers get_handlers_;
  963. Handlers post_handlers_;
  964. HandlersForContentReader post_handlers_for_content_reader_;
  965. Handlers put_handlers_;
  966. HandlersForContentReader put_handlers_for_content_reader_;
  967. Handlers patch_handlers_;
  968. HandlersForContentReader patch_handlers_for_content_reader_;
  969. Handlers delete_handlers_;
  970. HandlersForContentReader delete_handlers_for_content_reader_;
  971. Handlers options_handlers_;
  972. HandlerWithResponse error_handler_;
  973. ExceptionHandler exception_handler_;
  974. HandlerWithResponse pre_routing_handler_;
  975. Handler post_routing_handler_;
  976. HandlerWithResponse pre_request_handler_;
  977. Expect100ContinueHandler expect_100_continue_handler_;
  978. Logger logger_;
  979. int address_family_ = AF_UNSPEC;
  980. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  981. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  982. SocketOptions socket_options_ = default_socket_options;
  983. Headers default_headers_;
  984. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  985. detail::write_headers;
  986. };
  987. enum class Error {
  988. Success = 0,
  989. Unknown,
  990. Connection,
  991. BindIPAddress,
  992. Read,
  993. Write,
  994. ExceedRedirectCount,
  995. Canceled,
  996. SSLConnection,
  997. SSLLoadingCerts,
  998. SSLServerVerification,
  999. SSLServerHostnameVerification,
  1000. UnsupportedMultipartBoundaryChars,
  1001. Compression,
  1002. ConnectionTimeout,
  1003. ProxyConnection,
  1004. // For internal use only
  1005. SSLPeerCouldBeClosed_,
  1006. };
  1007. std::string to_string(Error error);
  1008. std::ostream &operator<<(std::ostream &os, const Error &obj);
  1009. class Result {
  1010. public:
  1011. Result() = default;
  1012. Result(std::unique_ptr<Response> &&res, Error err,
  1013. Headers &&request_headers = Headers{})
  1014. : res_(std::move(res)), err_(err),
  1015. request_headers_(std::move(request_headers)) {}
  1016. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1017. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1018. int ssl_error)
  1019. : res_(std::move(res)), err_(err),
  1020. request_headers_(std::move(request_headers)), ssl_error_(ssl_error) {}
  1021. Result(std::unique_ptr<Response> &&res, Error err, Headers &&request_headers,
  1022. int ssl_error, unsigned long ssl_openssl_error)
  1023. : res_(std::move(res)), err_(err),
  1024. request_headers_(std::move(request_headers)), ssl_error_(ssl_error),
  1025. ssl_openssl_error_(ssl_openssl_error) {}
  1026. #endif
  1027. // Response
  1028. operator bool() const { return res_ != nullptr; }
  1029. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  1030. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  1031. const Response &value() const { return *res_; }
  1032. Response &value() { return *res_; }
  1033. const Response &operator*() const { return *res_; }
  1034. Response &operator*() { return *res_; }
  1035. const Response *operator->() const { return res_.get(); }
  1036. Response *operator->() { return res_.get(); }
  1037. // Error
  1038. Error error() const { return err_; }
  1039. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1040. // SSL Error
  1041. int ssl_error() const { return ssl_error_; }
  1042. // OpenSSL Error
  1043. unsigned long ssl_openssl_error() const { return ssl_openssl_error_; }
  1044. #endif
  1045. // Request Headers
  1046. bool has_request_header(const std::string &key) const;
  1047. std::string get_request_header_value(const std::string &key,
  1048. const char *def = "",
  1049. size_t id = 0) const;
  1050. uint64_t get_request_header_value_u64(const std::string &key,
  1051. uint64_t def = 0, size_t id = 0) const;
  1052. size_t get_request_header_value_count(const std::string &key) const;
  1053. private:
  1054. std::unique_ptr<Response> res_;
  1055. Error err_ = Error::Unknown;
  1056. Headers request_headers_;
  1057. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1058. int ssl_error_ = 0;
  1059. unsigned long ssl_openssl_error_ = 0;
  1060. #endif
  1061. };
  1062. class ClientImpl {
  1063. public:
  1064. explicit ClientImpl(const std::string &host);
  1065. explicit ClientImpl(const std::string &host, int port);
  1066. explicit ClientImpl(const std::string &host, int port,
  1067. const std::string &client_cert_path,
  1068. const std::string &client_key_path);
  1069. virtual ~ClientImpl();
  1070. virtual bool is_valid() const;
  1071. // clang-format off
  1072. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1073. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1074. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1075. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1076. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1077. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1078. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1079. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1080. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1081. Result Head(const std::string &path);
  1082. Result Head(const std::string &path, const Headers &headers);
  1083. Result Post(const std::string &path);
  1084. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1085. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1086. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1087. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1088. Result Post(const std::string &path, const Params &params);
  1089. Result Post(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1090. Result Post(const std::string &path, const Headers &headers);
  1091. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1092. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1093. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1094. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1095. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1096. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1097. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1098. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1099. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1100. Result Put(const std::string &path);
  1101. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1102. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1103. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1104. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1105. Result Put(const std::string &path, const Params &params);
  1106. Result Put(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1107. Result Put(const std::string &path, const Headers &headers);
  1108. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1109. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1110. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1111. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1112. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1113. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1114. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1115. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1116. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1117. Result Patch(const std::string &path);
  1118. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1119. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1120. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1121. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1122. Result Patch(const std::string &path, const Params &params);
  1123. Result Patch(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1124. Result Patch(const std::string &path, const Headers &headers, UploadProgress progress = nullptr);
  1125. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1126. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1127. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1128. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1129. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1130. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1131. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1132. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1133. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1134. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1135. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1136. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1137. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1138. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1139. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1140. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1141. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1142. Result Options(const std::string &path);
  1143. Result Options(const std::string &path, const Headers &headers);
  1144. // clang-format on
  1145. bool send(Request &req, Response &res, Error &error);
  1146. Result send(const Request &req);
  1147. void stop();
  1148. std::string host() const;
  1149. int port() const;
  1150. size_t is_socket_open() const;
  1151. socket_t socket() const;
  1152. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1153. void set_default_headers(Headers headers);
  1154. void
  1155. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1156. void set_address_family(int family);
  1157. void set_tcp_nodelay(bool on);
  1158. void set_ipv6_v6only(bool on);
  1159. void set_socket_options(SocketOptions socket_options);
  1160. void set_connection_timeout(time_t sec, time_t usec = 0);
  1161. template <class Rep, class Period>
  1162. void
  1163. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1164. void set_read_timeout(time_t sec, time_t usec = 0);
  1165. template <class Rep, class Period>
  1166. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1167. void set_write_timeout(time_t sec, time_t usec = 0);
  1168. template <class Rep, class Period>
  1169. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1170. void set_max_timeout(time_t msec);
  1171. template <class Rep, class Period>
  1172. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1173. void set_basic_auth(const std::string &username, const std::string &password);
  1174. void set_bearer_token_auth(const std::string &token);
  1175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1176. void set_digest_auth(const std::string &username,
  1177. const std::string &password);
  1178. #endif
  1179. void set_keep_alive(bool on);
  1180. void set_follow_location(bool on);
  1181. void set_url_encode(bool on);
  1182. void set_compress(bool on);
  1183. void set_decompress(bool on);
  1184. void set_interface(const std::string &intf);
  1185. void set_proxy(const std::string &host, int port);
  1186. void set_proxy_basic_auth(const std::string &username,
  1187. const std::string &password);
  1188. void set_proxy_bearer_token_auth(const std::string &token);
  1189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1190. void set_proxy_digest_auth(const std::string &username,
  1191. const std::string &password);
  1192. #endif
  1193. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1194. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1195. const std::string &ca_cert_dir_path = std::string());
  1196. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1197. X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const;
  1198. #endif
  1199. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1200. void enable_server_certificate_verification(bool enabled);
  1201. void enable_server_hostname_verification(bool enabled);
  1202. void set_server_certificate_verifier(
  1203. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1204. #endif
  1205. void set_logger(Logger logger);
  1206. protected:
  1207. struct Socket {
  1208. socket_t sock = INVALID_SOCKET;
  1209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1210. SSL *ssl = nullptr;
  1211. #endif
  1212. bool is_open() const { return sock != INVALID_SOCKET; }
  1213. };
  1214. virtual bool create_and_connect_socket(Socket &socket, Error &error);
  1215. // All of:
  1216. // shutdown_ssl
  1217. // shutdown_socket
  1218. // close_socket
  1219. // should ONLY be called when socket_mutex_ is locked.
  1220. // Also, shutdown_ssl and close_socket should also NOT be called concurrently
  1221. // with a DIFFERENT thread sending requests using that socket.
  1222. virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
  1223. void shutdown_socket(Socket &socket) const;
  1224. void close_socket(Socket &socket);
  1225. bool process_request(Stream &strm, Request &req, Response &res,
  1226. bool close_connection, Error &error);
  1227. bool write_content_with_provider(Stream &strm, const Request &req,
  1228. Error &error) const;
  1229. void copy_settings(const ClientImpl &rhs);
  1230. // Socket endpoint information
  1231. const std::string host_;
  1232. const int port_;
  1233. const std::string host_and_port_;
  1234. // Current open socket
  1235. Socket socket_;
  1236. mutable std::mutex socket_mutex_;
  1237. std::recursive_mutex request_mutex_;
  1238. // These are all protected under socket_mutex
  1239. size_t socket_requests_in_flight_ = 0;
  1240. std::thread::id socket_requests_are_from_thread_ = std::thread::id();
  1241. bool socket_should_be_closed_when_request_is_done_ = false;
  1242. // Hostname-IP map
  1243. std::map<std::string, std::string> addr_map_;
  1244. // Default headers
  1245. Headers default_headers_;
  1246. // Header writer
  1247. std::function<ssize_t(Stream &, Headers &)> header_writer_ =
  1248. detail::write_headers;
  1249. // Settings
  1250. std::string client_cert_path_;
  1251. std::string client_key_path_;
  1252. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  1253. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  1254. time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND;
  1255. time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND;
  1256. time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND;
  1257. time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND;
  1258. time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND;
  1259. std::string basic_auth_username_;
  1260. std::string basic_auth_password_;
  1261. std::string bearer_token_auth_token_;
  1262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1263. std::string digest_auth_username_;
  1264. std::string digest_auth_password_;
  1265. #endif
  1266. bool keep_alive_ = false;
  1267. bool follow_location_ = false;
  1268. bool url_encode_ = true;
  1269. int address_family_ = AF_UNSPEC;
  1270. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  1271. bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY;
  1272. SocketOptions socket_options_ = nullptr;
  1273. bool compress_ = false;
  1274. bool decompress_ = true;
  1275. std::string interface_;
  1276. std::string proxy_host_;
  1277. int proxy_port_ = -1;
  1278. std::string proxy_basic_auth_username_;
  1279. std::string proxy_basic_auth_password_;
  1280. std::string proxy_bearer_token_auth_token_;
  1281. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1282. std::string proxy_digest_auth_username_;
  1283. std::string proxy_digest_auth_password_;
  1284. #endif
  1285. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1286. std::string ca_cert_file_path_;
  1287. std::string ca_cert_dir_path_;
  1288. X509_STORE *ca_cert_store_ = nullptr;
  1289. #endif
  1290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1291. bool server_certificate_verification_ = true;
  1292. bool server_hostname_verification_ = true;
  1293. std::function<SSLVerifierResponse(SSL *ssl)> server_certificate_verifier_;
  1294. #endif
  1295. Logger logger_;
  1296. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1297. int last_ssl_error_ = 0;
  1298. unsigned long last_openssl_error_ = 0;
  1299. #endif
  1300. private:
  1301. bool send_(Request &req, Response &res, Error &error);
  1302. Result send_(Request &&req);
  1303. socket_t create_client_socket(Error &error) const;
  1304. bool read_response_line(Stream &strm, const Request &req,
  1305. Response &res) const;
  1306. bool write_request(Stream &strm, Request &req, bool close_connection,
  1307. Error &error);
  1308. bool redirect(Request &req, Response &res, Error &error);
  1309. bool create_redirect_client(const std::string &scheme,
  1310. const std::string &host, int port, Request &req,
  1311. Response &res, const std::string &path,
  1312. const std::string &location, Error &error);
  1313. template <typename ClientType> void setup_redirect_client(ClientType &client);
  1314. bool handle_request(Stream &strm, Request &req, Response &res,
  1315. bool close_connection, Error &error);
  1316. std::unique_ptr<Response> send_with_content_provider(
  1317. Request &req, const char *body, size_t content_length,
  1318. ContentProvider content_provider,
  1319. ContentProviderWithoutLength content_provider_without_length,
  1320. const std::string &content_type, Error &error);
  1321. Result send_with_content_provider(
  1322. const std::string &method, const std::string &path,
  1323. const Headers &headers, const char *body, size_t content_length,
  1324. ContentProvider content_provider,
  1325. ContentProviderWithoutLength content_provider_without_length,
  1326. const std::string &content_type, UploadProgress progress);
  1327. ContentProviderWithoutLength get_multipart_content_provider(
  1328. const std::string &boundary,
  1329. const MultipartFormDataItemsForClientInput &items,
  1330. const MultipartFormDataProviderItems &provider_items) const;
  1331. std::string adjust_host_string(const std::string &host) const;
  1332. virtual bool
  1333. process_socket(const Socket &socket,
  1334. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1335. std::function<bool(Stream &strm)> callback);
  1336. virtual bool is_ssl() const;
  1337. };
  1338. class Client {
  1339. public:
  1340. // Universal interface
  1341. explicit Client(const std::string &scheme_host_port);
  1342. explicit Client(const std::string &scheme_host_port,
  1343. const std::string &client_cert_path,
  1344. const std::string &client_key_path);
  1345. // HTTP only interface
  1346. explicit Client(const std::string &host, int port);
  1347. explicit Client(const std::string &host, int port,
  1348. const std::string &client_cert_path,
  1349. const std::string &client_key_path);
  1350. Client(Client &&) = default;
  1351. Client &operator=(Client &&) = default;
  1352. ~Client();
  1353. bool is_valid() const;
  1354. // clang-format off
  1355. Result Get(const std::string &path, DownloadProgress progress = nullptr);
  1356. Result Get(const std::string &path, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1357. Result Get(const std::string &path, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1358. Result Get(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1359. Result Get(const std::string &path, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1360. Result Get(const std::string &path, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1361. Result Get(const std::string &path, const Params &params, const Headers &headers, DownloadProgress progress = nullptr);
  1362. Result Get(const std::string &path, const Params &params, const Headers &headers, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1363. Result Get(const std::string &path, const Params &params, const Headers &headers, ResponseHandler response_handler, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1364. Result Head(const std::string &path);
  1365. Result Head(const std::string &path, const Headers &headers);
  1366. Result Post(const std::string &path);
  1367. Result Post(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1368. Result Post(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1369. Result Post(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1370. Result Post(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1371. Result Post(const std::string &path, const Params &params);
  1372. Result Post(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1373. Result Post(const std::string &path, const Headers &headers);
  1374. Result Post(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1375. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1376. Result Post(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1377. Result Post(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1378. Result Post(const std::string &path, const Headers &headers, const Params &params);
  1379. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1380. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1381. Result Post(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1382. Result Post(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1383. Result Put(const std::string &path);
  1384. Result Put(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1385. Result Put(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1386. Result Put(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1387. Result Put(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1388. Result Put(const std::string &path, const Params &params);
  1389. Result Put(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1390. Result Put(const std::string &path, const Headers &headers);
  1391. Result Put(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1392. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1393. Result Put(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1394. Result Put(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1395. Result Put(const std::string &path, const Headers &headers, const Params &params);
  1396. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1397. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1398. Result Put(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1399. Result Put(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1400. Result Patch(const std::string &path);
  1401. Result Patch(const std::string &path, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1402. Result Patch(const std::string &path, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1403. Result Patch(const std::string &path, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1404. Result Patch(const std::string &path, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1405. Result Patch(const std::string &path, const Params &params);
  1406. Result Patch(const std::string &path, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1407. Result Patch(const std::string &path, const Headers &headers);
  1408. Result Patch(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, UploadProgress progress = nullptr);
  1409. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, UploadProgress progress = nullptr);
  1410. Result Patch(const std::string &path, const Headers &headers, size_t content_length, ContentProvider content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1411. Result Patch(const std::string &path, const Headers &headers, ContentProviderWithoutLength content_provider, const std::string &content_type, UploadProgress progress = nullptr);
  1412. Result Patch(const std::string &path, const Headers &headers, const Params &params);
  1413. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, UploadProgress progress = nullptr);
  1414. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const std::string &boundary, UploadProgress progress = nullptr);
  1415. Result Patch(const std::string &path, const Headers &headers, const MultipartFormDataItemsForClientInput &items, const MultipartFormDataProviderItems &provider_items, UploadProgress progress = nullptr);
  1416. Result Patch(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, ContentReceiver content_receiver, DownloadProgress progress = nullptr);
  1417. Result Delete(const std::string &path, DownloadProgress progress = nullptr);
  1418. Result Delete(const std::string &path, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1419. Result Delete(const std::string &path, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1420. Result Delete(const std::string &path, const Params &params, DownloadProgress progress = nullptr);
  1421. Result Delete(const std::string &path, const Headers &headers, DownloadProgress progress = nullptr);
  1422. Result Delete(const std::string &path, const Headers &headers, const char *body, size_t content_length, const std::string &content_type, DownloadProgress progress = nullptr);
  1423. Result Delete(const std::string &path, const Headers &headers, const std::string &body, const std::string &content_type, DownloadProgress progress = nullptr);
  1424. Result Delete(const std::string &path, const Headers &headers, const Params &params, DownloadProgress progress = nullptr);
  1425. Result Options(const std::string &path);
  1426. Result Options(const std::string &path, const Headers &headers);
  1427. // clang-format on
  1428. bool send(Request &req, Response &res, Error &error);
  1429. Result send(const Request &req);
  1430. void stop();
  1431. std::string host() const;
  1432. int port() const;
  1433. size_t is_socket_open() const;
  1434. socket_t socket() const;
  1435. void set_hostname_addr_map(std::map<std::string, std::string> addr_map);
  1436. void set_default_headers(Headers headers);
  1437. void
  1438. set_header_writer(std::function<ssize_t(Stream &, Headers &)> const &writer);
  1439. void set_address_family(int family);
  1440. void set_tcp_nodelay(bool on);
  1441. void set_socket_options(SocketOptions socket_options);
  1442. void set_connection_timeout(time_t sec, time_t usec = 0);
  1443. template <class Rep, class Period>
  1444. void
  1445. set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
  1446. void set_read_timeout(time_t sec, time_t usec = 0);
  1447. template <class Rep, class Period>
  1448. void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
  1449. void set_write_timeout(time_t sec, time_t usec = 0);
  1450. template <class Rep, class Period>
  1451. void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
  1452. void set_max_timeout(time_t msec);
  1453. template <class Rep, class Period>
  1454. void set_max_timeout(const std::chrono::duration<Rep, Period> &duration);
  1455. void set_basic_auth(const std::string &username, const std::string &password);
  1456. void set_bearer_token_auth(const std::string &token);
  1457. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1458. void set_digest_auth(const std::string &username,
  1459. const std::string &password);
  1460. #endif
  1461. void set_keep_alive(bool on);
  1462. void set_follow_location(bool on);
  1463. void set_url_encode(bool on);
  1464. void set_compress(bool on);
  1465. void set_decompress(bool on);
  1466. void set_interface(const std::string &intf);
  1467. void set_proxy(const std::string &host, int port);
  1468. void set_proxy_basic_auth(const std::string &username,
  1469. const std::string &password);
  1470. void set_proxy_bearer_token_auth(const std::string &token);
  1471. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1472. void set_proxy_digest_auth(const std::string &username,
  1473. const std::string &password);
  1474. #endif
  1475. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1476. void enable_server_certificate_verification(bool enabled);
  1477. void enable_server_hostname_verification(bool enabled);
  1478. void set_server_certificate_verifier(
  1479. std::function<SSLVerifierResponse(SSL *ssl)> verifier);
  1480. #endif
  1481. void set_logger(Logger logger);
  1482. // SSL
  1483. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1484. void set_ca_cert_path(const std::string &ca_cert_file_path,
  1485. const std::string &ca_cert_dir_path = std::string());
  1486. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1487. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1488. long get_openssl_verify_result() const;
  1489. SSL_CTX *ssl_context() const;
  1490. #endif
  1491. private:
  1492. std::unique_ptr<ClientImpl> cli_;
  1493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1494. bool is_ssl_ = false;
  1495. #endif
  1496. };
  1497. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1498. class SSLServer : public Server {
  1499. public:
  1500. SSLServer(const char *cert_path, const char *private_key_path,
  1501. const char *client_ca_cert_file_path = nullptr,
  1502. const char *client_ca_cert_dir_path = nullptr,
  1503. const char *private_key_password = nullptr);
  1504. SSLServer(X509 *cert, EVP_PKEY *private_key,
  1505. X509_STORE *client_ca_cert_store = nullptr);
  1506. SSLServer(
  1507. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback);
  1508. ~SSLServer() override;
  1509. bool is_valid() const override;
  1510. SSL_CTX *ssl_context() const;
  1511. void update_certs(X509 *cert, EVP_PKEY *private_key,
  1512. X509_STORE *client_ca_cert_store = nullptr);
  1513. private:
  1514. bool process_and_close_socket(socket_t sock) override;
  1515. SSL_CTX *ctx_;
  1516. std::mutex ctx_mutex_;
  1517. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1518. int last_ssl_error_ = 0;
  1519. #endif
  1520. };
  1521. class SSLClient final : public ClientImpl {
  1522. public:
  1523. explicit SSLClient(const std::string &host);
  1524. explicit SSLClient(const std::string &host, int port);
  1525. explicit SSLClient(const std::string &host, int port,
  1526. const std::string &client_cert_path,
  1527. const std::string &client_key_path,
  1528. const std::string &private_key_password = std::string());
  1529. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  1530. EVP_PKEY *client_key,
  1531. const std::string &private_key_password = std::string());
  1532. ~SSLClient() override;
  1533. bool is_valid() const override;
  1534. void set_ca_cert_store(X509_STORE *ca_cert_store);
  1535. void load_ca_cert_store(const char *ca_cert, std::size_t size);
  1536. long get_openssl_verify_result() const;
  1537. SSL_CTX *ssl_context() const;
  1538. private:
  1539. bool create_and_connect_socket(Socket &socket, Error &error) override;
  1540. void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
  1541. void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully);
  1542. bool
  1543. process_socket(const Socket &socket,
  1544. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1545. std::function<bool(Stream &strm)> callback) override;
  1546. bool is_ssl() const override;
  1547. bool connect_with_proxy(
  1548. Socket &sock,
  1549. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1550. Response &res, bool &success, Error &error);
  1551. bool initialize_ssl(Socket &socket, Error &error);
  1552. bool load_certs();
  1553. bool verify_host(X509 *server_cert) const;
  1554. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  1555. bool verify_host_with_common_name(X509 *server_cert) const;
  1556. bool check_host_name(const char *pattern, size_t pattern_len) const;
  1557. SSL_CTX *ctx_;
  1558. std::mutex ctx_mutex_;
  1559. std::once_flag initialize_cert_;
  1560. std::vector<std::string> host_components_;
  1561. long verify_result_ = 0;
  1562. friend class ClientImpl;
  1563. };
  1564. #endif
  1565. /*
  1566. * Implementation of template methods.
  1567. */
  1568. namespace detail {
  1569. template <typename T, typename U>
  1570. inline void duration_to_sec_and_usec(const T &duration, U callback) {
  1571. auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
  1572. auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
  1573. duration - std::chrono::seconds(sec))
  1574. .count();
  1575. callback(static_cast<time_t>(sec), static_cast<time_t>(usec));
  1576. }
  1577. template <size_t N> inline constexpr size_t str_len(const char (&)[N]) {
  1578. return N - 1;
  1579. }
  1580. inline bool is_numeric(const std::string &str) {
  1581. return !str.empty() &&
  1582. std::all_of(str.cbegin(), str.cend(),
  1583. [](unsigned char c) { return std::isdigit(c); });
  1584. }
  1585. inline uint64_t get_header_value_u64(const Headers &headers,
  1586. const std::string &key, uint64_t def,
  1587. size_t id, bool &is_invalid_value) {
  1588. is_invalid_value = false;
  1589. auto rng = headers.equal_range(key);
  1590. auto it = rng.first;
  1591. std::advance(it, static_cast<ssize_t>(id));
  1592. if (it != rng.second) {
  1593. if (is_numeric(it->second)) {
  1594. return std::strtoull(it->second.data(), nullptr, 10);
  1595. } else {
  1596. is_invalid_value = true;
  1597. }
  1598. }
  1599. return def;
  1600. }
  1601. inline uint64_t get_header_value_u64(const Headers &headers,
  1602. const std::string &key, uint64_t def,
  1603. size_t id) {
  1604. bool dummy = false;
  1605. return get_header_value_u64(headers, key, def, id, dummy);
  1606. }
  1607. } // namespace detail
  1608. inline uint64_t Request::get_header_value_u64(const std::string &key,
  1609. uint64_t def, size_t id) const {
  1610. return detail::get_header_value_u64(headers, key, def, id);
  1611. }
  1612. inline uint64_t Response::get_header_value_u64(const std::string &key,
  1613. uint64_t def, size_t id) const {
  1614. return detail::get_header_value_u64(headers, key, def, id);
  1615. }
  1616. namespace detail {
  1617. inline bool set_socket_opt_impl(socket_t sock, int level, int optname,
  1618. const void *optval, socklen_t optlen) {
  1619. return setsockopt(sock, level, optname,
  1620. #ifdef _WIN32
  1621. reinterpret_cast<const char *>(optval),
  1622. #else
  1623. optval,
  1624. #endif
  1625. optlen) == 0;
  1626. }
  1627. inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
  1628. return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval));
  1629. }
  1630. inline bool set_socket_opt_time(socket_t sock, int level, int optname,
  1631. time_t sec, time_t usec) {
  1632. #ifdef _WIN32
  1633. auto timeout = static_cast<uint32_t>(sec * 1000 + usec / 1000);
  1634. #else
  1635. timeval timeout;
  1636. timeout.tv_sec = static_cast<long>(sec);
  1637. timeout.tv_usec = static_cast<decltype(timeout.tv_usec)>(usec);
  1638. #endif
  1639. return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout));
  1640. }
  1641. } // namespace detail
  1642. inline void default_socket_options(socket_t sock) {
  1643. detail::set_socket_opt(sock, SOL_SOCKET,
  1644. #ifdef SO_REUSEPORT
  1645. SO_REUSEPORT,
  1646. #else
  1647. SO_REUSEADDR,
  1648. #endif
  1649. 1);
  1650. }
  1651. inline const char *status_message(int status) {
  1652. switch (status) {
  1653. case StatusCode::Continue_100: return "Continue";
  1654. case StatusCode::SwitchingProtocol_101: return "Switching Protocol";
  1655. case StatusCode::Processing_102: return "Processing";
  1656. case StatusCode::EarlyHints_103: return "Early Hints";
  1657. case StatusCode::OK_200: return "OK";
  1658. case StatusCode::Created_201: return "Created";
  1659. case StatusCode::Accepted_202: return "Accepted";
  1660. case StatusCode::NonAuthoritativeInformation_203:
  1661. return "Non-Authoritative Information";
  1662. case StatusCode::NoContent_204: return "No Content";
  1663. case StatusCode::ResetContent_205: return "Reset Content";
  1664. case StatusCode::PartialContent_206: return "Partial Content";
  1665. case StatusCode::MultiStatus_207: return "Multi-Status";
  1666. case StatusCode::AlreadyReported_208: return "Already Reported";
  1667. case StatusCode::IMUsed_226: return "IM Used";
  1668. case StatusCode::MultipleChoices_300: return "Multiple Choices";
  1669. case StatusCode::MovedPermanently_301: return "Moved Permanently";
  1670. case StatusCode::Found_302: return "Found";
  1671. case StatusCode::SeeOther_303: return "See Other";
  1672. case StatusCode::NotModified_304: return "Not Modified";
  1673. case StatusCode::UseProxy_305: return "Use Proxy";
  1674. case StatusCode::unused_306: return "unused";
  1675. case StatusCode::TemporaryRedirect_307: return "Temporary Redirect";
  1676. case StatusCode::PermanentRedirect_308: return "Permanent Redirect";
  1677. case StatusCode::BadRequest_400: return "Bad Request";
  1678. case StatusCode::Unauthorized_401: return "Unauthorized";
  1679. case StatusCode::PaymentRequired_402: return "Payment Required";
  1680. case StatusCode::Forbidden_403: return "Forbidden";
  1681. case StatusCode::NotFound_404: return "Not Found";
  1682. case StatusCode::MethodNotAllowed_405: return "Method Not Allowed";
  1683. case StatusCode::NotAcceptable_406: return "Not Acceptable";
  1684. case StatusCode::ProxyAuthenticationRequired_407:
  1685. return "Proxy Authentication Required";
  1686. case StatusCode::RequestTimeout_408: return "Request Timeout";
  1687. case StatusCode::Conflict_409: return "Conflict";
  1688. case StatusCode::Gone_410: return "Gone";
  1689. case StatusCode::LengthRequired_411: return "Length Required";
  1690. case StatusCode::PreconditionFailed_412: return "Precondition Failed";
  1691. case StatusCode::PayloadTooLarge_413: return "Payload Too Large";
  1692. case StatusCode::UriTooLong_414: return "URI Too Long";
  1693. case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type";
  1694. case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable";
  1695. case StatusCode::ExpectationFailed_417: return "Expectation Failed";
  1696. case StatusCode::ImATeapot_418: return "I'm a teapot";
  1697. case StatusCode::MisdirectedRequest_421: return "Misdirected Request";
  1698. case StatusCode::UnprocessableContent_422: return "Unprocessable Content";
  1699. case StatusCode::Locked_423: return "Locked";
  1700. case StatusCode::FailedDependency_424: return "Failed Dependency";
  1701. case StatusCode::TooEarly_425: return "Too Early";
  1702. case StatusCode::UpgradeRequired_426: return "Upgrade Required";
  1703. case StatusCode::PreconditionRequired_428: return "Precondition Required";
  1704. case StatusCode::TooManyRequests_429: return "Too Many Requests";
  1705. case StatusCode::RequestHeaderFieldsTooLarge_431:
  1706. return "Request Header Fields Too Large";
  1707. case StatusCode::UnavailableForLegalReasons_451:
  1708. return "Unavailable For Legal Reasons";
  1709. case StatusCode::NotImplemented_501: return "Not Implemented";
  1710. case StatusCode::BadGateway_502: return "Bad Gateway";
  1711. case StatusCode::ServiceUnavailable_503: return "Service Unavailable";
  1712. case StatusCode::GatewayTimeout_504: return "Gateway Timeout";
  1713. case StatusCode::HttpVersionNotSupported_505:
  1714. return "HTTP Version Not Supported";
  1715. case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates";
  1716. case StatusCode::InsufficientStorage_507: return "Insufficient Storage";
  1717. case StatusCode::LoopDetected_508: return "Loop Detected";
  1718. case StatusCode::NotExtended_510: return "Not Extended";
  1719. case StatusCode::NetworkAuthenticationRequired_511:
  1720. return "Network Authentication Required";
  1721. default:
  1722. case StatusCode::InternalServerError_500: return "Internal Server Error";
  1723. }
  1724. }
  1725. inline std::string get_bearer_token_auth(const Request &req) {
  1726. if (req.has_header("Authorization")) {
  1727. constexpr auto bearer_header_prefix_len = detail::str_len("Bearer ");
  1728. return req.get_header_value("Authorization")
  1729. .substr(bearer_header_prefix_len);
  1730. }
  1731. return "";
  1732. }
  1733. template <class Rep, class Period>
  1734. inline Server &
  1735. Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1736. detail::duration_to_sec_and_usec(
  1737. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1738. return *this;
  1739. }
  1740. template <class Rep, class Period>
  1741. inline Server &
  1742. Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1743. detail::duration_to_sec_and_usec(
  1744. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1745. return *this;
  1746. }
  1747. template <class Rep, class Period>
  1748. inline Server &
  1749. Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
  1750. detail::duration_to_sec_and_usec(
  1751. duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
  1752. return *this;
  1753. }
  1754. inline std::string to_string(const Error error) {
  1755. switch (error) {
  1756. case Error::Success: return "Success (no error)";
  1757. case Error::Connection: return "Could not establish connection";
  1758. case Error::BindIPAddress: return "Failed to bind IP address";
  1759. case Error::Read: return "Failed to read connection";
  1760. case Error::Write: return "Failed to write connection";
  1761. case Error::ExceedRedirectCount: return "Maximum redirect count exceeded";
  1762. case Error::Canceled: return "Connection handling canceled";
  1763. case Error::SSLConnection: return "SSL connection failed";
  1764. case Error::SSLLoadingCerts: return "SSL certificate loading failed";
  1765. case Error::SSLServerVerification: return "SSL server verification failed";
  1766. case Error::SSLServerHostnameVerification:
  1767. return "SSL server hostname verification failed";
  1768. case Error::UnsupportedMultipartBoundaryChars:
  1769. return "Unsupported HTTP multipart boundary characters";
  1770. case Error::Compression: return "Compression failed";
  1771. case Error::ConnectionTimeout: return "Connection timed out";
  1772. case Error::ProxyConnection: return "Proxy connection failed";
  1773. case Error::Unknown: return "Unknown";
  1774. default: break;
  1775. }
  1776. return "Invalid";
  1777. }
  1778. inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
  1779. os << to_string(obj);
  1780. os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
  1781. return os;
  1782. }
  1783. inline uint64_t Result::get_request_header_value_u64(const std::string &key,
  1784. uint64_t def,
  1785. size_t id) const {
  1786. return detail::get_header_value_u64(request_headers_, key, def, id);
  1787. }
  1788. template <class Rep, class Period>
  1789. inline void ClientImpl::set_connection_timeout(
  1790. const std::chrono::duration<Rep, Period> &duration) {
  1791. detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
  1792. set_connection_timeout(sec, usec);
  1793. });
  1794. }
  1795. template <class Rep, class Period>
  1796. inline void ClientImpl::set_read_timeout(
  1797. const std::chrono::duration<Rep, Period> &duration) {
  1798. detail::duration_to_sec_and_usec(
  1799. duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
  1800. }
  1801. template <class Rep, class Period>
  1802. inline void ClientImpl::set_write_timeout(
  1803. const std::chrono::duration<Rep, Period> &duration) {
  1804. detail::duration_to_sec_and_usec(
  1805. duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
  1806. }
  1807. template <class Rep, class Period>
  1808. inline void ClientImpl::set_max_timeout(
  1809. const std::chrono::duration<Rep, Period> &duration) {
  1810. auto msec =
  1811. std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
  1812. set_max_timeout(msec);
  1813. }
  1814. template <class Rep, class Period>
  1815. inline void Client::set_connection_timeout(
  1816. const std::chrono::duration<Rep, Period> &duration) {
  1817. cli_->set_connection_timeout(duration);
  1818. }
  1819. template <class Rep, class Period>
  1820. inline void
  1821. Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1822. cli_->set_read_timeout(duration);
  1823. }
  1824. template <class Rep, class Period>
  1825. inline void
  1826. Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1827. cli_->set_write_timeout(duration);
  1828. }
  1829. template <class Rep, class Period>
  1830. inline void
  1831. Client::set_max_timeout(const std::chrono::duration<Rep, Period> &duration) {
  1832. cli_->set_max_timeout(duration);
  1833. }
  1834. /*
  1835. * Forward declarations and types that will be part of the .h file if split into
  1836. * .h + .cc.
  1837. */
  1838. std::string hosted_at(const std::string &hostname);
  1839. void hosted_at(const std::string &hostname, std::vector<std::string> &addrs);
  1840. std::string append_query_params(const std::string &path, const Params &params);
  1841. std::pair<std::string, std::string> make_range_header(const Ranges &ranges);
  1842. std::pair<std::string, std::string>
  1843. make_basic_authentication_header(const std::string &username,
  1844. const std::string &password,
  1845. bool is_proxy = false);
  1846. namespace detail {
  1847. #if defined(_WIN32)
  1848. inline std::wstring u8string_to_wstring(const char *s) {
  1849. std::wstring ws;
  1850. auto len = static_cast<int>(strlen(s));
  1851. auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0);
  1852. if (wlen > 0) {
  1853. ws.resize(wlen);
  1854. wlen = ::MultiByteToWideChar(
  1855. CP_UTF8, 0, s, len,
  1856. const_cast<LPWSTR>(reinterpret_cast<LPCWSTR>(ws.data())), wlen);
  1857. if (wlen != static_cast<int>(ws.size())) { ws.clear(); }
  1858. }
  1859. return ws;
  1860. }
  1861. #endif
  1862. struct FileStat {
  1863. FileStat(const std::string &path);
  1864. bool is_file() const;
  1865. bool is_dir() const;
  1866. private:
  1867. #if defined(_WIN32)
  1868. struct _stat st_;
  1869. #else
  1870. struct stat st_;
  1871. #endif
  1872. int ret_ = -1;
  1873. };
  1874. std::string encode_query_param(const std::string &value);
  1875. std::string decode_url(const std::string &s, bool convert_plus_to_space);
  1876. std::string trim_copy(const std::string &s);
  1877. void divide(
  1878. const char *data, std::size_t size, char d,
  1879. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1880. fn);
  1881. void divide(
  1882. const std::string &str, char d,
  1883. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  1884. fn);
  1885. void split(const char *b, const char *e, char d,
  1886. std::function<void(const char *, const char *)> fn);
  1887. void split(const char *b, const char *e, char d, size_t m,
  1888. std::function<void(const char *, const char *)> fn);
  1889. bool process_client_socket(
  1890. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  1891. time_t write_timeout_sec, time_t write_timeout_usec,
  1892. time_t max_timeout_msec,
  1893. std::chrono::time_point<std::chrono::steady_clock> start_time,
  1894. std::function<bool(Stream &)> callback);
  1895. socket_t create_client_socket(const std::string &host, const std::string &ip,
  1896. int port, int address_family, bool tcp_nodelay,
  1897. bool ipv6_v6only, SocketOptions socket_options,
  1898. time_t connection_timeout_sec,
  1899. time_t connection_timeout_usec,
  1900. time_t read_timeout_sec, time_t read_timeout_usec,
  1901. time_t write_timeout_sec,
  1902. time_t write_timeout_usec,
  1903. const std::string &intf, Error &error);
  1904. const char *get_header_value(const Headers &headers, const std::string &key,
  1905. const char *def, size_t id);
  1906. std::string params_to_query_str(const Params &params);
  1907. void parse_query_text(const char *data, std::size_t size, Params &params);
  1908. void parse_query_text(const std::string &s, Params &params);
  1909. bool parse_multipart_boundary(const std::string &content_type,
  1910. std::string &boundary);
  1911. bool parse_range_header(const std::string &s, Ranges &ranges);
  1912. bool parse_accept_header(const std::string &s,
  1913. std::vector<std::string> &content_types);
  1914. int close_socket(socket_t sock);
  1915. ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
  1916. ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags);
  1917. enum class EncodingType { None = 0, Gzip, Brotli, Zstd };
  1918. EncodingType encoding_type(const Request &req, const Response &res);
  1919. class BufferStream final : public Stream {
  1920. public:
  1921. BufferStream() = default;
  1922. ~BufferStream() override = default;
  1923. bool is_readable() const override;
  1924. bool wait_readable() const override;
  1925. bool wait_writable() const override;
  1926. ssize_t read(char *ptr, size_t size) override;
  1927. ssize_t write(const char *ptr, size_t size) override;
  1928. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1929. void get_local_ip_and_port(std::string &ip, int &port) const override;
  1930. socket_t socket() const override;
  1931. time_t duration() const override;
  1932. const std::string &get_buffer() const;
  1933. private:
  1934. std::string buffer;
  1935. size_t position = 0;
  1936. };
  1937. class compressor {
  1938. public:
  1939. virtual ~compressor() = default;
  1940. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1941. virtual bool compress(const char *data, size_t data_length, bool last,
  1942. Callback callback) = 0;
  1943. };
  1944. class decompressor {
  1945. public:
  1946. virtual ~decompressor() = default;
  1947. virtual bool is_valid() const = 0;
  1948. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1949. virtual bool decompress(const char *data, size_t data_length,
  1950. Callback callback) = 0;
  1951. };
  1952. class nocompressor final : public compressor {
  1953. public:
  1954. ~nocompressor() override = default;
  1955. bool compress(const char *data, size_t data_length, bool /*last*/,
  1956. Callback callback) override;
  1957. };
  1958. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1959. class gzip_compressor final : public compressor {
  1960. public:
  1961. gzip_compressor();
  1962. ~gzip_compressor() override;
  1963. bool compress(const char *data, size_t data_length, bool last,
  1964. Callback callback) override;
  1965. private:
  1966. bool is_valid_ = false;
  1967. z_stream strm_;
  1968. };
  1969. class gzip_decompressor final : public decompressor {
  1970. public:
  1971. gzip_decompressor();
  1972. ~gzip_decompressor() override;
  1973. bool is_valid() const override;
  1974. bool decompress(const char *data, size_t data_length,
  1975. Callback callback) override;
  1976. private:
  1977. bool is_valid_ = false;
  1978. z_stream strm_;
  1979. };
  1980. #endif
  1981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1982. class brotli_compressor final : public compressor {
  1983. public:
  1984. brotli_compressor();
  1985. ~brotli_compressor();
  1986. bool compress(const char *data, size_t data_length, bool last,
  1987. Callback callback) override;
  1988. private:
  1989. BrotliEncoderState *state_ = nullptr;
  1990. };
  1991. class brotli_decompressor final : public decompressor {
  1992. public:
  1993. brotli_decompressor();
  1994. ~brotli_decompressor();
  1995. bool is_valid() const override;
  1996. bool decompress(const char *data, size_t data_length,
  1997. Callback callback) override;
  1998. private:
  1999. BrotliDecoderResult decoder_r;
  2000. BrotliDecoderState *decoder_s = nullptr;
  2001. };
  2002. #endif
  2003. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  2004. class zstd_compressor : public compressor {
  2005. public:
  2006. zstd_compressor();
  2007. ~zstd_compressor();
  2008. bool compress(const char *data, size_t data_length, bool last,
  2009. Callback callback) override;
  2010. private:
  2011. ZSTD_CCtx *ctx_ = nullptr;
  2012. };
  2013. class zstd_decompressor : public decompressor {
  2014. public:
  2015. zstd_decompressor();
  2016. ~zstd_decompressor();
  2017. bool is_valid() const override;
  2018. bool decompress(const char *data, size_t data_length,
  2019. Callback callback) override;
  2020. private:
  2021. ZSTD_DCtx *ctx_ = nullptr;
  2022. };
  2023. #endif
  2024. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  2025. // to store data. The call can set memory on stack for performance.
  2026. class stream_line_reader {
  2027. public:
  2028. stream_line_reader(Stream &strm, char *fixed_buffer,
  2029. size_t fixed_buffer_size);
  2030. const char *ptr() const;
  2031. size_t size() const;
  2032. bool end_with_crlf() const;
  2033. bool getline();
  2034. private:
  2035. void append(char c);
  2036. Stream &strm_;
  2037. char *fixed_buffer_;
  2038. const size_t fixed_buffer_size_;
  2039. size_t fixed_buffer_used_size_ = 0;
  2040. std::string growable_buffer_;
  2041. };
  2042. class mmap {
  2043. public:
  2044. mmap(const char *path);
  2045. ~mmap();
  2046. bool open(const char *path);
  2047. void close();
  2048. bool is_open() const;
  2049. size_t size() const;
  2050. const char *data() const;
  2051. private:
  2052. #if defined(_WIN32)
  2053. HANDLE hFile_ = NULL;
  2054. HANDLE hMapping_ = NULL;
  2055. #else
  2056. int fd_ = -1;
  2057. #endif
  2058. size_t size_ = 0;
  2059. void *addr_ = nullptr;
  2060. bool is_open_empty_file = false;
  2061. };
  2062. // NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5
  2063. namespace fields {
  2064. inline bool is_token_char(char c) {
  2065. return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' ||
  2066. c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' ||
  2067. c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~';
  2068. }
  2069. inline bool is_token(const std::string &s) {
  2070. if (s.empty()) { return false; }
  2071. for (auto c : s) {
  2072. if (!is_token_char(c)) { return false; }
  2073. }
  2074. return true;
  2075. }
  2076. inline bool is_field_name(const std::string &s) { return is_token(s); }
  2077. inline bool is_vchar(char c) { return c >= 33 && c <= 126; }
  2078. inline bool is_obs_text(char c) { return 128 <= static_cast<unsigned char>(c); }
  2079. inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); }
  2080. inline bool is_field_content(const std::string &s) {
  2081. if (s.empty()) { return true; }
  2082. if (s.size() == 1) {
  2083. return is_field_vchar(s[0]);
  2084. } else if (s.size() == 2) {
  2085. return is_field_vchar(s[0]) && is_field_vchar(s[1]);
  2086. } else {
  2087. size_t i = 0;
  2088. if (!is_field_vchar(s[i])) { return false; }
  2089. i++;
  2090. while (i < s.size() - 1) {
  2091. auto c = s[i++];
  2092. if (c == ' ' || c == '\t' || is_field_vchar(c)) {
  2093. } else {
  2094. return false;
  2095. }
  2096. }
  2097. return is_field_vchar(s[i]);
  2098. }
  2099. }
  2100. inline bool is_field_value(const std::string &s) { return is_field_content(s); }
  2101. } // namespace fields
  2102. } // namespace detail
  2103. // ----------------------------------------------------------------------------
  2104. /*
  2105. * Implementation that will be part of the .cc file if split into .h + .cc.
  2106. */
  2107. namespace detail {
  2108. inline bool is_hex(char c, int &v) {
  2109. if (0x20 <= c && isdigit(c)) {
  2110. v = c - '0';
  2111. return true;
  2112. } else if ('A' <= c && c <= 'F') {
  2113. v = c - 'A' + 10;
  2114. return true;
  2115. } else if ('a' <= c && c <= 'f') {
  2116. v = c - 'a' + 10;
  2117. return true;
  2118. }
  2119. return false;
  2120. }
  2121. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  2122. int &val) {
  2123. if (i >= s.size()) { return false; }
  2124. val = 0;
  2125. for (; cnt; i++, cnt--) {
  2126. if (!s[i]) { return false; }
  2127. auto v = 0;
  2128. if (is_hex(s[i], v)) {
  2129. val = val * 16 + v;
  2130. } else {
  2131. return false;
  2132. }
  2133. }
  2134. return true;
  2135. }
  2136. inline std::string from_i_to_hex(size_t n) {
  2137. static const auto charset = "0123456789abcdef";
  2138. std::string ret;
  2139. do {
  2140. ret = charset[n & 15] + ret;
  2141. n >>= 4;
  2142. } while (n > 0);
  2143. return ret;
  2144. }
  2145. inline size_t to_utf8(int code, char *buff) {
  2146. if (code < 0x0080) {
  2147. buff[0] = static_cast<char>(code & 0x7F);
  2148. return 1;
  2149. } else if (code < 0x0800) {
  2150. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  2151. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  2152. return 2;
  2153. } else if (code < 0xD800) {
  2154. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2155. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2156. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2157. return 3;
  2158. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  2159. return 0;
  2160. } else if (code < 0x10000) {
  2161. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  2162. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2163. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  2164. return 3;
  2165. } else if (code < 0x110000) {
  2166. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  2167. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  2168. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  2169. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  2170. return 4;
  2171. }
  2172. // NOTREACHED
  2173. return 0;
  2174. }
  2175. // NOTE: This code came up with the following stackoverflow post:
  2176. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  2177. inline std::string base64_encode(const std::string &in) {
  2178. static const auto lookup =
  2179. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2180. std::string out;
  2181. out.reserve(in.size());
  2182. auto val = 0;
  2183. auto valb = -6;
  2184. for (auto c : in) {
  2185. val = (val << 8) + static_cast<uint8_t>(c);
  2186. valb += 8;
  2187. while (valb >= 0) {
  2188. out.push_back(lookup[(val >> valb) & 0x3F]);
  2189. valb -= 6;
  2190. }
  2191. }
  2192. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  2193. while (out.size() % 4) {
  2194. out.push_back('=');
  2195. }
  2196. return out;
  2197. }
  2198. inline bool is_valid_path(const std::string &path) {
  2199. size_t level = 0;
  2200. size_t i = 0;
  2201. // Skip slash
  2202. while (i < path.size() && path[i] == '/') {
  2203. i++;
  2204. }
  2205. while (i < path.size()) {
  2206. // Read component
  2207. auto beg = i;
  2208. while (i < path.size() && path[i] != '/') {
  2209. if (path[i] == '\0') {
  2210. return false;
  2211. } else if (path[i] == '\\') {
  2212. return false;
  2213. }
  2214. i++;
  2215. }
  2216. auto len = i - beg;
  2217. assert(len > 0);
  2218. if (!path.compare(beg, len, ".")) {
  2219. ;
  2220. } else if (!path.compare(beg, len, "..")) {
  2221. if (level == 0) { return false; }
  2222. level--;
  2223. } else {
  2224. level++;
  2225. }
  2226. // Skip slash
  2227. while (i < path.size() && path[i] == '/') {
  2228. i++;
  2229. }
  2230. }
  2231. return true;
  2232. }
  2233. inline FileStat::FileStat(const std::string &path) {
  2234. #if defined(_WIN32)
  2235. auto wpath = u8string_to_wstring(path.c_str());
  2236. ret_ = _wstat(wpath.c_str(), &st_);
  2237. #else
  2238. ret_ = stat(path.c_str(), &st_);
  2239. #endif
  2240. }
  2241. inline bool FileStat::is_file() const {
  2242. return ret_ >= 0 && S_ISREG(st_.st_mode);
  2243. }
  2244. inline bool FileStat::is_dir() const {
  2245. return ret_ >= 0 && S_ISDIR(st_.st_mode);
  2246. }
  2247. inline std::string encode_query_param(const std::string &value) {
  2248. std::ostringstream escaped;
  2249. escaped.fill('0');
  2250. escaped << std::hex;
  2251. for (auto c : value) {
  2252. if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
  2253. c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
  2254. c == ')') {
  2255. escaped << c;
  2256. } else {
  2257. escaped << std::uppercase;
  2258. escaped << '%' << std::setw(2)
  2259. << static_cast<int>(static_cast<unsigned char>(c));
  2260. escaped << std::nouppercase;
  2261. }
  2262. }
  2263. return escaped.str();
  2264. }
  2265. inline std::string encode_url(const std::string &s) {
  2266. std::string result;
  2267. result.reserve(s.size());
  2268. for (size_t i = 0; s[i]; i++) {
  2269. switch (s[i]) {
  2270. case ' ': result += "%20"; break;
  2271. case '+': result += "%2B"; break;
  2272. case '\r': result += "%0D"; break;
  2273. case '\n': result += "%0A"; break;
  2274. case '\'': result += "%27"; break;
  2275. case ',': result += "%2C"; break;
  2276. // case ':': result += "%3A"; break; // ok? probably...
  2277. case ';': result += "%3B"; break;
  2278. default:
  2279. auto c = static_cast<uint8_t>(s[i]);
  2280. if (c >= 0x80) {
  2281. result += '%';
  2282. char hex[4];
  2283. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  2284. assert(len == 2);
  2285. result.append(hex, static_cast<size_t>(len));
  2286. } else {
  2287. result += s[i];
  2288. }
  2289. break;
  2290. }
  2291. }
  2292. return result;
  2293. }
  2294. inline std::string decode_url(const std::string &s,
  2295. bool convert_plus_to_space) {
  2296. std::string result;
  2297. for (size_t i = 0; i < s.size(); i++) {
  2298. if (s[i] == '%' && i + 1 < s.size()) {
  2299. if (s[i + 1] == 'u') {
  2300. auto val = 0;
  2301. if (from_hex_to_i(s, i + 2, 4, val)) {
  2302. // 4 digits Unicode codes
  2303. char buff[4];
  2304. size_t len = to_utf8(val, buff);
  2305. if (len > 0) { result.append(buff, len); }
  2306. i += 5; // 'u0000'
  2307. } else {
  2308. result += s[i];
  2309. }
  2310. } else {
  2311. auto val = 0;
  2312. if (from_hex_to_i(s, i + 1, 2, val)) {
  2313. // 2 digits hex codes
  2314. result += static_cast<char>(val);
  2315. i += 2; // '00'
  2316. } else {
  2317. result += s[i];
  2318. }
  2319. }
  2320. } else if (convert_plus_to_space && s[i] == '+') {
  2321. result += ' ';
  2322. } else {
  2323. result += s[i];
  2324. }
  2325. }
  2326. return result;
  2327. }
  2328. inline std::string file_extension(const std::string &path) {
  2329. std::smatch m;
  2330. thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  2331. if (std::regex_search(path, m, re)) { return m[1].str(); }
  2332. return std::string();
  2333. }
  2334. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  2335. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  2336. size_t right) {
  2337. while (b + left < e && is_space_or_tab(b[left])) {
  2338. left++;
  2339. }
  2340. while (right > 0 && is_space_or_tab(b[right - 1])) {
  2341. right--;
  2342. }
  2343. return std::make_pair(left, right);
  2344. }
  2345. inline std::string trim_copy(const std::string &s) {
  2346. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  2347. return s.substr(r.first, r.second - r.first);
  2348. }
  2349. inline std::string trim_double_quotes_copy(const std::string &s) {
  2350. if (s.length() >= 2 && s.front() == '"' && s.back() == '"') {
  2351. return s.substr(1, s.size() - 2);
  2352. }
  2353. return s;
  2354. }
  2355. inline void
  2356. divide(const char *data, std::size_t size, char d,
  2357. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2358. fn) {
  2359. const auto it = std::find(data, data + size, d);
  2360. const auto found = static_cast<std::size_t>(it != data + size);
  2361. const auto lhs_data = data;
  2362. const auto lhs_size = static_cast<std::size_t>(it - data);
  2363. const auto rhs_data = it + found;
  2364. const auto rhs_size = size - lhs_size - found;
  2365. fn(lhs_data, lhs_size, rhs_data, rhs_size);
  2366. }
  2367. inline void
  2368. divide(const std::string &str, char d,
  2369. std::function<void(const char *, std::size_t, const char *, std::size_t)>
  2370. fn) {
  2371. divide(str.data(), str.size(), d, std::move(fn));
  2372. }
  2373. inline void split(const char *b, const char *e, char d,
  2374. std::function<void(const char *, const char *)> fn) {
  2375. return split(b, e, d, (std::numeric_limits<size_t>::max)(), std::move(fn));
  2376. }
  2377. inline void split(const char *b, const char *e, char d, size_t m,
  2378. std::function<void(const char *, const char *)> fn) {
  2379. size_t i = 0;
  2380. size_t beg = 0;
  2381. size_t count = 1;
  2382. while (e ? (b + i < e) : (b[i] != '\0')) {
  2383. if (b[i] == d && count < m) {
  2384. auto r = trim(b, e, beg, i);
  2385. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2386. beg = i + 1;
  2387. count++;
  2388. }
  2389. i++;
  2390. }
  2391. if (i) {
  2392. auto r = trim(b, e, beg, i);
  2393. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  2394. }
  2395. }
  2396. inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
  2397. size_t fixed_buffer_size)
  2398. : strm_(strm), fixed_buffer_(fixed_buffer),
  2399. fixed_buffer_size_(fixed_buffer_size) {}
  2400. inline const char *stream_line_reader::ptr() const {
  2401. if (growable_buffer_.empty()) {
  2402. return fixed_buffer_;
  2403. } else {
  2404. return growable_buffer_.data();
  2405. }
  2406. }
  2407. inline size_t stream_line_reader::size() const {
  2408. if (growable_buffer_.empty()) {
  2409. return fixed_buffer_used_size_;
  2410. } else {
  2411. return growable_buffer_.size();
  2412. }
  2413. }
  2414. inline bool stream_line_reader::end_with_crlf() const {
  2415. auto end = ptr() + size();
  2416. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  2417. }
  2418. inline bool stream_line_reader::getline() {
  2419. fixed_buffer_used_size_ = 0;
  2420. growable_buffer_.clear();
  2421. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2422. char prev_byte = 0;
  2423. #endif
  2424. for (size_t i = 0;; i++) {
  2425. if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) {
  2426. // Treat exceptionally long lines as an error to
  2427. // prevent infinite loops/memory exhaustion
  2428. return false;
  2429. }
  2430. char byte;
  2431. auto n = strm_.read(&byte, 1);
  2432. if (n < 0) {
  2433. return false;
  2434. } else if (n == 0) {
  2435. if (i == 0) {
  2436. return false;
  2437. } else {
  2438. break;
  2439. }
  2440. }
  2441. append(byte);
  2442. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  2443. if (byte == '\n') { break; }
  2444. #else
  2445. if (prev_byte == '\r' && byte == '\n') { break; }
  2446. prev_byte = byte;
  2447. #endif
  2448. }
  2449. return true;
  2450. }
  2451. inline void stream_line_reader::append(char c) {
  2452. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  2453. fixed_buffer_[fixed_buffer_used_size_++] = c;
  2454. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  2455. } else {
  2456. if (growable_buffer_.empty()) {
  2457. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  2458. growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  2459. }
  2460. growable_buffer_ += c;
  2461. }
  2462. }
  2463. inline mmap::mmap(const char *path) { open(path); }
  2464. inline mmap::~mmap() { close(); }
  2465. inline bool mmap::open(const char *path) {
  2466. close();
  2467. #if defined(_WIN32)
  2468. auto wpath = u8string_to_wstring(path);
  2469. if (wpath.empty()) { return false; }
  2470. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  2471. hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ,
  2472. OPEN_EXISTING, NULL);
  2473. #else
  2474. hFile_ = ::CreateFileW(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL,
  2475. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  2476. #endif
  2477. if (hFile_ == INVALID_HANDLE_VALUE) { return false; }
  2478. LARGE_INTEGER size{};
  2479. if (!::GetFileSizeEx(hFile_, &size)) { return false; }
  2480. // If the following line doesn't compile due to QuadPart, update Windows SDK.
  2481. // See:
  2482. // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721
  2483. if (static_cast<ULONGLONG>(size.QuadPart) >
  2484. (std::numeric_limits<decltype(size_)>::max)()) {
  2485. // `size_t` might be 32-bits, on 32-bits Windows.
  2486. return false;
  2487. }
  2488. size_ = static_cast<size_t>(size.QuadPart);
  2489. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  2490. hMapping_ =
  2491. ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL);
  2492. #else
  2493. hMapping_ = ::CreateFileMappingW(hFile_, NULL, PAGE_READONLY, 0, 0, NULL);
  2494. #endif
  2495. // Special treatment for an empty file...
  2496. if (hMapping_ == NULL && size_ == 0) {
  2497. close();
  2498. is_open_empty_file = true;
  2499. return true;
  2500. }
  2501. if (hMapping_ == NULL) {
  2502. close();
  2503. return false;
  2504. }
  2505. #if _WIN32_WINNT >= _WIN32_WINNT_WIN8
  2506. addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0);
  2507. #else
  2508. addr_ = ::MapViewOfFile(hMapping_, FILE_MAP_READ, 0, 0, 0);
  2509. #endif
  2510. if (addr_ == nullptr) {
  2511. close();
  2512. return false;
  2513. }
  2514. #else
  2515. fd_ = ::open(path, O_RDONLY);
  2516. if (fd_ == -1) { return false; }
  2517. struct stat sb;
  2518. if (fstat(fd_, &sb) == -1) {
  2519. close();
  2520. return false;
  2521. }
  2522. size_ = static_cast<size_t>(sb.st_size);
  2523. addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
  2524. // Special treatment for an empty file...
  2525. if (addr_ == MAP_FAILED && size_ == 0) {
  2526. close();
  2527. is_open_empty_file = true;
  2528. return false;
  2529. }
  2530. #endif
  2531. return true;
  2532. }
  2533. inline bool mmap::is_open() const {
  2534. return is_open_empty_file ? true : addr_ != nullptr;
  2535. }
  2536. inline size_t mmap::size() const { return size_; }
  2537. inline const char *mmap::data() const {
  2538. return is_open_empty_file ? "" : static_cast<const char *>(addr_);
  2539. }
  2540. inline void mmap::close() {
  2541. #if defined(_WIN32)
  2542. if (addr_) {
  2543. ::UnmapViewOfFile(addr_);
  2544. addr_ = nullptr;
  2545. }
  2546. if (hMapping_) {
  2547. ::CloseHandle(hMapping_);
  2548. hMapping_ = NULL;
  2549. }
  2550. if (hFile_ != INVALID_HANDLE_VALUE) {
  2551. ::CloseHandle(hFile_);
  2552. hFile_ = INVALID_HANDLE_VALUE;
  2553. }
  2554. is_open_empty_file = false;
  2555. #else
  2556. if (addr_ != nullptr) {
  2557. munmap(addr_, size_);
  2558. addr_ = nullptr;
  2559. }
  2560. if (fd_ != -1) {
  2561. ::close(fd_);
  2562. fd_ = -1;
  2563. }
  2564. #endif
  2565. size_ = 0;
  2566. }
  2567. inline int close_socket(socket_t sock) {
  2568. #ifdef _WIN32
  2569. return closesocket(sock);
  2570. #else
  2571. return close(sock);
  2572. #endif
  2573. }
  2574. template <typename T> inline ssize_t handle_EINTR(T fn) {
  2575. ssize_t res = 0;
  2576. while (true) {
  2577. res = fn();
  2578. if (res < 0 && errno == EINTR) {
  2579. std::this_thread::sleep_for(std::chrono::microseconds{1});
  2580. continue;
  2581. }
  2582. break;
  2583. }
  2584. return res;
  2585. }
  2586. inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) {
  2587. return handle_EINTR([&]() {
  2588. return recv(sock,
  2589. #ifdef _WIN32
  2590. static_cast<char *>(ptr), static_cast<int>(size),
  2591. #else
  2592. ptr, size,
  2593. #endif
  2594. flags);
  2595. });
  2596. }
  2597. inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size,
  2598. int flags) {
  2599. return handle_EINTR([&]() {
  2600. return send(sock,
  2601. #ifdef _WIN32
  2602. static_cast<const char *>(ptr), static_cast<int>(size),
  2603. #else
  2604. ptr, size,
  2605. #endif
  2606. flags);
  2607. });
  2608. }
  2609. inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) {
  2610. #ifdef _WIN32
  2611. return ::WSAPoll(fds, nfds, timeout);
  2612. #else
  2613. return ::poll(fds, nfds, timeout);
  2614. #endif
  2615. }
  2616. template <bool Read>
  2617. inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) {
  2618. struct pollfd pfd;
  2619. pfd.fd = sock;
  2620. pfd.events = (Read ? POLLIN : POLLOUT);
  2621. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2622. return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); });
  2623. }
  2624. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  2625. return select_impl<true>(sock, sec, usec);
  2626. }
  2627. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  2628. return select_impl<false>(sock, sec, usec);
  2629. }
  2630. inline Error wait_until_socket_is_ready(socket_t sock, time_t sec,
  2631. time_t usec) {
  2632. struct pollfd pfd_read;
  2633. pfd_read.fd = sock;
  2634. pfd_read.events = POLLIN | POLLOUT;
  2635. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  2636. auto poll_res =
  2637. handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); });
  2638. if (poll_res == 0) { return Error::ConnectionTimeout; }
  2639. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  2640. auto error = 0;
  2641. socklen_t len = sizeof(error);
  2642. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  2643. reinterpret_cast<char *>(&error), &len);
  2644. auto successful = res >= 0 && !error;
  2645. return successful ? Error::Success : Error::Connection;
  2646. }
  2647. return Error::Connection;
  2648. }
  2649. inline bool is_socket_alive(socket_t sock) {
  2650. const auto val = detail::select_read(sock, 0, 0);
  2651. if (val == 0) {
  2652. return true;
  2653. } else if (val < 0 && errno == EBADF) {
  2654. return false;
  2655. }
  2656. char buf[1];
  2657. return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0;
  2658. }
  2659. class SocketStream final : public Stream {
  2660. public:
  2661. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2662. time_t write_timeout_sec, time_t write_timeout_usec,
  2663. time_t max_timeout_msec = 0,
  2664. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2665. (std::chrono::steady_clock::time_point::min)());
  2666. ~SocketStream() override;
  2667. bool is_readable() const override;
  2668. bool wait_readable() const override;
  2669. bool wait_writable() const override;
  2670. ssize_t read(char *ptr, size_t size) override;
  2671. ssize_t write(const char *ptr, size_t size) override;
  2672. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2673. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2674. socket_t socket() const override;
  2675. time_t duration() const override;
  2676. private:
  2677. socket_t sock_;
  2678. time_t read_timeout_sec_;
  2679. time_t read_timeout_usec_;
  2680. time_t write_timeout_sec_;
  2681. time_t write_timeout_usec_;
  2682. time_t max_timeout_msec_;
  2683. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2684. std::vector<char> read_buff_;
  2685. size_t read_buff_off_ = 0;
  2686. size_t read_buff_content_size_ = 0;
  2687. static const size_t read_buff_size_ = 1024l * 4;
  2688. };
  2689. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2690. class SSLSocketStream final : public Stream {
  2691. public:
  2692. SSLSocketStream(
  2693. socket_t sock, SSL *ssl, time_t read_timeout_sec,
  2694. time_t read_timeout_usec, time_t write_timeout_sec,
  2695. time_t write_timeout_usec, time_t max_timeout_msec = 0,
  2696. std::chrono::time_point<std::chrono::steady_clock> start_time =
  2697. (std::chrono::steady_clock::time_point::min)());
  2698. ~SSLSocketStream() override;
  2699. bool is_readable() const override;
  2700. bool wait_readable() const override;
  2701. bool wait_writable() const override;
  2702. ssize_t read(char *ptr, size_t size) override;
  2703. ssize_t write(const char *ptr, size_t size) override;
  2704. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  2705. void get_local_ip_and_port(std::string &ip, int &port) const override;
  2706. socket_t socket() const override;
  2707. time_t duration() const override;
  2708. private:
  2709. socket_t sock_;
  2710. SSL *ssl_;
  2711. time_t read_timeout_sec_;
  2712. time_t read_timeout_usec_;
  2713. time_t write_timeout_sec_;
  2714. time_t write_timeout_usec_;
  2715. time_t max_timeout_msec_;
  2716. const std::chrono::time_point<std::chrono::steady_clock> start_time_;
  2717. };
  2718. #endif
  2719. inline bool keep_alive(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2720. time_t keep_alive_timeout_sec) {
  2721. using namespace std::chrono;
  2722. const auto interval_usec =
  2723. CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND;
  2724. // Avoid expensive `steady_clock::now()` call for the first time
  2725. if (select_read(sock, 0, interval_usec) > 0) { return true; }
  2726. const auto start = steady_clock::now() - microseconds{interval_usec};
  2727. const auto timeout = seconds{keep_alive_timeout_sec};
  2728. while (true) {
  2729. if (svr_sock == INVALID_SOCKET) {
  2730. break; // Server socket is closed
  2731. }
  2732. auto val = select_read(sock, 0, interval_usec);
  2733. if (val < 0) {
  2734. break; // Ssocket error
  2735. } else if (val == 0) {
  2736. if (steady_clock::now() - start > timeout) {
  2737. break; // Timeout
  2738. }
  2739. } else {
  2740. return true; // Ready for read
  2741. }
  2742. }
  2743. return false;
  2744. }
  2745. template <typename T>
  2746. inline bool
  2747. process_server_socket_core(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2748. size_t keep_alive_max_count,
  2749. time_t keep_alive_timeout_sec, T callback) {
  2750. assert(keep_alive_max_count > 0);
  2751. auto ret = false;
  2752. auto count = keep_alive_max_count;
  2753. while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) {
  2754. auto close_connection = count == 1;
  2755. auto connection_closed = false;
  2756. ret = callback(close_connection, connection_closed);
  2757. if (!ret || connection_closed) { break; }
  2758. count--;
  2759. }
  2760. return ret;
  2761. }
  2762. template <typename T>
  2763. inline bool
  2764. process_server_socket(const std::atomic<socket_t> &svr_sock, socket_t sock,
  2765. size_t keep_alive_max_count,
  2766. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  2767. time_t read_timeout_usec, time_t write_timeout_sec,
  2768. time_t write_timeout_usec, T callback) {
  2769. return process_server_socket_core(
  2770. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  2771. [&](bool close_connection, bool &connection_closed) {
  2772. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2773. write_timeout_sec, write_timeout_usec);
  2774. return callback(strm, close_connection, connection_closed);
  2775. });
  2776. }
  2777. inline bool process_client_socket(
  2778. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  2779. time_t write_timeout_sec, time_t write_timeout_usec,
  2780. time_t max_timeout_msec,
  2781. std::chrono::time_point<std::chrono::steady_clock> start_time,
  2782. std::function<bool(Stream &)> callback) {
  2783. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  2784. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  2785. start_time);
  2786. return callback(strm);
  2787. }
  2788. inline int shutdown_socket(socket_t sock) {
  2789. #ifdef _WIN32
  2790. return shutdown(sock, SD_BOTH);
  2791. #else
  2792. return shutdown(sock, SHUT_RDWR);
  2793. #endif
  2794. }
  2795. inline std::string escape_abstract_namespace_unix_domain(const std::string &s) {
  2796. if (s.size() > 1 && s[0] == '\0') {
  2797. auto ret = s;
  2798. ret[0] = '@';
  2799. return ret;
  2800. }
  2801. return s;
  2802. }
  2803. inline std::string
  2804. unescape_abstract_namespace_unix_domain(const std::string &s) {
  2805. if (s.size() > 1 && s[0] == '@') {
  2806. auto ret = s;
  2807. ret[0] = '\0';
  2808. return ret;
  2809. }
  2810. return s;
  2811. }
  2812. inline int getaddrinfo_with_timeout(const char *node, const char *service,
  2813. const struct addrinfo *hints,
  2814. struct addrinfo **res, time_t timeout_sec) {
  2815. #ifdef CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2816. if (timeout_sec <= 0) {
  2817. // No timeout specified, use standard getaddrinfo
  2818. return getaddrinfo(node, service, hints, res);
  2819. }
  2820. #ifdef _WIN32
  2821. // Windows-specific implementation using GetAddrInfoEx with overlapped I/O
  2822. OVERLAPPED overlapped = {0};
  2823. HANDLE event = CreateEventW(nullptr, TRUE, FALSE, nullptr);
  2824. if (!event) { return EAI_FAIL; }
  2825. overlapped.hEvent = event;
  2826. PADDRINFOEXW result_addrinfo = nullptr;
  2827. HANDLE cancel_handle = nullptr;
  2828. ADDRINFOEXW hints_ex = {0};
  2829. if (hints) {
  2830. hints_ex.ai_flags = hints->ai_flags;
  2831. hints_ex.ai_family = hints->ai_family;
  2832. hints_ex.ai_socktype = hints->ai_socktype;
  2833. hints_ex.ai_protocol = hints->ai_protocol;
  2834. }
  2835. auto wnode = u8string_to_wstring(node);
  2836. auto wservice = u8string_to_wstring(service);
  2837. auto ret = ::GetAddrInfoExW(wnode.data(), wservice.data(), NS_DNS, nullptr,
  2838. hints ? &hints_ex : nullptr, &result_addrinfo,
  2839. nullptr, &overlapped, nullptr, &cancel_handle);
  2840. if (ret == WSA_IO_PENDING) {
  2841. auto wait_result =
  2842. ::WaitForSingleObject(event, static_cast<DWORD>(timeout_sec * 1000));
  2843. if (wait_result == WAIT_TIMEOUT) {
  2844. if (cancel_handle) { ::GetAddrInfoExCancel(&cancel_handle); }
  2845. ::CloseHandle(event);
  2846. return EAI_AGAIN;
  2847. }
  2848. DWORD bytes_returned;
  2849. if (!::GetOverlappedResult((HANDLE)INVALID_SOCKET, &overlapped,
  2850. &bytes_returned, FALSE)) {
  2851. ::CloseHandle(event);
  2852. return ::WSAGetLastError();
  2853. }
  2854. }
  2855. ::CloseHandle(event);
  2856. if (ret == NO_ERROR || ret == WSA_IO_PENDING) {
  2857. *res = reinterpret_cast<struct addrinfo *>(result_addrinfo);
  2858. return 0;
  2859. }
  2860. return ret;
  2861. #elif defined(TARGET_OS_OSX)
  2862. // macOS implementation using CFHost API for asynchronous DNS resolution
  2863. CFStringRef hostname_ref = CFStringCreateWithCString(
  2864. kCFAllocatorDefault, node, kCFStringEncodingUTF8);
  2865. if (!hostname_ref) { return EAI_MEMORY; }
  2866. CFHostRef host_ref = CFHostCreateWithName(kCFAllocatorDefault, hostname_ref);
  2867. CFRelease(hostname_ref);
  2868. if (!host_ref) { return EAI_MEMORY; }
  2869. // Set up context for callback
  2870. struct CFHostContext {
  2871. bool completed = false;
  2872. bool success = false;
  2873. CFArrayRef addresses = nullptr;
  2874. std::mutex mutex;
  2875. std::condition_variable cv;
  2876. } context;
  2877. CFHostClientContext client_context;
  2878. memset(&client_context, 0, sizeof(client_context));
  2879. client_context.info = &context;
  2880. // Set callback
  2881. auto callback = [](CFHostRef theHost, CFHostInfoType /*typeInfo*/,
  2882. const CFStreamError *error, void *info) {
  2883. auto ctx = static_cast<CFHostContext *>(info);
  2884. std::lock_guard<std::mutex> lock(ctx->mutex);
  2885. if (error && error->error != 0) {
  2886. ctx->success = false;
  2887. } else {
  2888. Boolean hasBeenResolved;
  2889. ctx->addresses = CFHostGetAddressing(theHost, &hasBeenResolved);
  2890. if (ctx->addresses && hasBeenResolved) {
  2891. CFRetain(ctx->addresses);
  2892. ctx->success = true;
  2893. } else {
  2894. ctx->success = false;
  2895. }
  2896. }
  2897. ctx->completed = true;
  2898. ctx->cv.notify_one();
  2899. };
  2900. if (!CFHostSetClient(host_ref, callback, &client_context)) {
  2901. CFRelease(host_ref);
  2902. return EAI_SYSTEM;
  2903. }
  2904. // Schedule on run loop
  2905. CFRunLoopRef run_loop = CFRunLoopGetCurrent();
  2906. CFHostScheduleWithRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2907. // Start resolution
  2908. CFStreamError stream_error;
  2909. if (!CFHostStartInfoResolution(host_ref, kCFHostAddresses, &stream_error)) {
  2910. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2911. CFRelease(host_ref);
  2912. return EAI_FAIL;
  2913. }
  2914. // Wait for completion with timeout
  2915. auto timeout_time =
  2916. std::chrono::steady_clock::now() + std::chrono::seconds(timeout_sec);
  2917. bool timed_out = false;
  2918. {
  2919. std::unique_lock<std::mutex> lock(context.mutex);
  2920. while (!context.completed) {
  2921. auto now = std::chrono::steady_clock::now();
  2922. if (now >= timeout_time) {
  2923. timed_out = true;
  2924. break;
  2925. }
  2926. // Run the runloop for a short time
  2927. lock.unlock();
  2928. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, true);
  2929. lock.lock();
  2930. }
  2931. }
  2932. // Clean up
  2933. CFHostUnscheduleFromRunLoop(host_ref, run_loop, kCFRunLoopDefaultMode);
  2934. CFHostSetClient(host_ref, nullptr, nullptr);
  2935. if (timed_out || !context.completed) {
  2936. CFHostCancelInfoResolution(host_ref, kCFHostAddresses);
  2937. CFRelease(host_ref);
  2938. return EAI_AGAIN;
  2939. }
  2940. if (!context.success || !context.addresses) {
  2941. CFRelease(host_ref);
  2942. return EAI_NODATA;
  2943. }
  2944. // Convert CFArray to addrinfo
  2945. CFIndex count = CFArrayGetCount(context.addresses);
  2946. if (count == 0) {
  2947. CFRelease(context.addresses);
  2948. CFRelease(host_ref);
  2949. return EAI_NODATA;
  2950. }
  2951. struct addrinfo *result_addrinfo = nullptr;
  2952. struct addrinfo **current = &result_addrinfo;
  2953. for (CFIndex i = 0; i < count; i++) {
  2954. CFDataRef addr_data =
  2955. static_cast<CFDataRef>(CFArrayGetValueAtIndex(context.addresses, i));
  2956. if (!addr_data) continue;
  2957. const struct sockaddr *sockaddr_ptr =
  2958. reinterpret_cast<const struct sockaddr *>(CFDataGetBytePtr(addr_data));
  2959. socklen_t sockaddr_len = static_cast<socklen_t>(CFDataGetLength(addr_data));
  2960. // Allocate addrinfo structure
  2961. *current = static_cast<struct addrinfo *>(malloc(sizeof(struct addrinfo)));
  2962. if (!*current) {
  2963. freeaddrinfo(result_addrinfo);
  2964. CFRelease(context.addresses);
  2965. CFRelease(host_ref);
  2966. return EAI_MEMORY;
  2967. }
  2968. memset(*current, 0, sizeof(struct addrinfo));
  2969. // Set up addrinfo fields
  2970. (*current)->ai_family = sockaddr_ptr->sa_family;
  2971. (*current)->ai_socktype = hints ? hints->ai_socktype : SOCK_STREAM;
  2972. (*current)->ai_protocol = hints ? hints->ai_protocol : IPPROTO_TCP;
  2973. (*current)->ai_addrlen = sockaddr_len;
  2974. // Copy sockaddr
  2975. (*current)->ai_addr = static_cast<struct sockaddr *>(malloc(sockaddr_len));
  2976. if (!(*current)->ai_addr) {
  2977. freeaddrinfo(result_addrinfo);
  2978. CFRelease(context.addresses);
  2979. CFRelease(host_ref);
  2980. return EAI_MEMORY;
  2981. }
  2982. memcpy((*current)->ai_addr, sockaddr_ptr, sockaddr_len);
  2983. // Set port if service is specified
  2984. if (service && strlen(service) > 0) {
  2985. int port = atoi(service);
  2986. if (port > 0) {
  2987. if (sockaddr_ptr->sa_family == AF_INET) {
  2988. reinterpret_cast<struct sockaddr_in *>((*current)->ai_addr)
  2989. ->sin_port = htons(static_cast<uint16_t>(port));
  2990. } else if (sockaddr_ptr->sa_family == AF_INET6) {
  2991. reinterpret_cast<struct sockaddr_in6 *>((*current)->ai_addr)
  2992. ->sin6_port = htons(static_cast<uint16_t>(port));
  2993. }
  2994. }
  2995. }
  2996. current = &((*current)->ai_next);
  2997. }
  2998. CFRelease(context.addresses);
  2999. CFRelease(host_ref);
  3000. *res = result_addrinfo;
  3001. return 0;
  3002. #elif defined(_GNU_SOURCE) && defined(__GLIBC__) && \
  3003. (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
  3004. // Linux implementation using getaddrinfo_a for asynchronous DNS resolution
  3005. struct gaicb request;
  3006. struct gaicb *requests[1] = {&request};
  3007. struct sigevent sevp;
  3008. struct timespec timeout;
  3009. // Initialize the request structure
  3010. memset(&request, 0, sizeof(request));
  3011. request.ar_name = node;
  3012. request.ar_service = service;
  3013. request.ar_request = hints;
  3014. // Set up timeout
  3015. timeout.tv_sec = timeout_sec;
  3016. timeout.tv_nsec = 0;
  3017. // Initialize sigevent structure (not used, but required)
  3018. memset(&sevp, 0, sizeof(sevp));
  3019. sevp.sigev_notify = SIGEV_NONE;
  3020. // Start asynchronous resolution
  3021. int start_result = getaddrinfo_a(GAI_NOWAIT, requests, 1, &sevp);
  3022. if (start_result != 0) { return start_result; }
  3023. // Wait for completion with timeout
  3024. int wait_result =
  3025. gai_suspend((const struct gaicb *const *)requests, 1, &timeout);
  3026. if (wait_result == 0) {
  3027. // Completed successfully, get the result
  3028. int gai_result = gai_error(&request);
  3029. if (gai_result == 0) {
  3030. *res = request.ar_result;
  3031. return 0;
  3032. } else {
  3033. // Clean up on error
  3034. if (request.ar_result) { freeaddrinfo(request.ar_result); }
  3035. return gai_result;
  3036. }
  3037. } else if (wait_result == EAI_AGAIN) {
  3038. // Timeout occurred, cancel the request
  3039. gai_cancel(&request);
  3040. return EAI_AGAIN;
  3041. } else {
  3042. // Other error occurred
  3043. gai_cancel(&request);
  3044. return wait_result;
  3045. }
  3046. #else
  3047. // Fallback implementation using thread-based timeout for other Unix systems
  3048. std::mutex result_mutex;
  3049. std::condition_variable result_cv;
  3050. auto completed = false;
  3051. auto result = EAI_SYSTEM;
  3052. struct addrinfo *result_addrinfo = nullptr;
  3053. std::thread resolve_thread([&]() {
  3054. auto thread_result = getaddrinfo(node, service, hints, &result_addrinfo);
  3055. std::lock_guard<std::mutex> lock(result_mutex);
  3056. result = thread_result;
  3057. completed = true;
  3058. result_cv.notify_one();
  3059. });
  3060. // Wait for completion or timeout
  3061. std::unique_lock<std::mutex> lock(result_mutex);
  3062. auto finished = result_cv.wait_for(lock, std::chrono::seconds(timeout_sec),
  3063. [&] { return completed; });
  3064. if (finished) {
  3065. // Operation completed within timeout
  3066. resolve_thread.join();
  3067. *res = result_addrinfo;
  3068. return result;
  3069. } else {
  3070. // Timeout occurred
  3071. resolve_thread.detach(); // Let the thread finish in background
  3072. return EAI_AGAIN; // Return timeout error
  3073. }
  3074. #endif
  3075. #else
  3076. (void)(timeout_sec); // Unused parameter for non-blocking getaddrinfo
  3077. return getaddrinfo(node, service, hints, res);
  3078. #endif
  3079. }
  3080. template <typename BindOrConnect>
  3081. socket_t create_socket(const std::string &host, const std::string &ip, int port,
  3082. int address_family, int socket_flags, bool tcp_nodelay,
  3083. bool ipv6_v6only, SocketOptions socket_options,
  3084. BindOrConnect bind_or_connect, time_t timeout_sec = 0) {
  3085. // Get address info
  3086. const char *node = nullptr;
  3087. struct addrinfo hints;
  3088. struct addrinfo *result;
  3089. memset(&hints, 0, sizeof(struct addrinfo));
  3090. hints.ai_socktype = SOCK_STREAM;
  3091. hints.ai_protocol = IPPROTO_IP;
  3092. if (!ip.empty()) {
  3093. node = ip.c_str();
  3094. // Ask getaddrinfo to convert IP in c-string to address
  3095. hints.ai_family = AF_UNSPEC;
  3096. hints.ai_flags = AI_NUMERICHOST;
  3097. } else {
  3098. if (!host.empty()) { node = host.c_str(); }
  3099. hints.ai_family = address_family;
  3100. hints.ai_flags = socket_flags;
  3101. }
  3102. #if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H)
  3103. if (hints.ai_family == AF_UNIX) {
  3104. const auto addrlen = host.length();
  3105. if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; }
  3106. #ifdef SOCK_CLOEXEC
  3107. auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC,
  3108. hints.ai_protocol);
  3109. #else
  3110. auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol);
  3111. #endif
  3112. if (sock != INVALID_SOCKET) {
  3113. sockaddr_un addr{};
  3114. addr.sun_family = AF_UNIX;
  3115. auto unescaped_host = unescape_abstract_namespace_unix_domain(host);
  3116. std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path);
  3117. hints.ai_addr = reinterpret_cast<sockaddr *>(&addr);
  3118. hints.ai_addrlen = static_cast<socklen_t>(
  3119. sizeof(addr) - sizeof(addr.sun_path) + addrlen);
  3120. #ifndef SOCK_CLOEXEC
  3121. #ifndef _WIN32
  3122. fcntl(sock, F_SETFD, FD_CLOEXEC);
  3123. #endif
  3124. #endif
  3125. if (socket_options) { socket_options(sock); }
  3126. #ifdef _WIN32
  3127. // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so
  3128. // remove the option.
  3129. detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0);
  3130. #endif
  3131. bool dummy;
  3132. if (!bind_or_connect(sock, hints, dummy)) {
  3133. close_socket(sock);
  3134. sock = INVALID_SOCKET;
  3135. }
  3136. }
  3137. return sock;
  3138. }
  3139. #endif
  3140. auto service = std::to_string(port);
  3141. if (getaddrinfo_with_timeout(node, service.c_str(), &hints, &result,
  3142. timeout_sec)) {
  3143. #if defined __linux__ && !defined __ANDROID__
  3144. res_init();
  3145. #endif
  3146. return INVALID_SOCKET;
  3147. }
  3148. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  3149. for (auto rp = result; rp; rp = rp->ai_next) {
  3150. // Create a socket
  3151. #ifdef _WIN32
  3152. auto sock =
  3153. WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
  3154. WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
  3155. /**
  3156. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  3157. * and above the socket creation fails on older Windows Systems.
  3158. *
  3159. * Let's try to create a socket the old way in this case.
  3160. *
  3161. * Reference:
  3162. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  3163. *
  3164. * WSA_FLAG_NO_HANDLE_INHERIT:
  3165. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  3166. * SP1, and later
  3167. *
  3168. */
  3169. if (sock == INVALID_SOCKET) {
  3170. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  3171. }
  3172. #else
  3173. #ifdef SOCK_CLOEXEC
  3174. auto sock =
  3175. socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol);
  3176. #else
  3177. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  3178. #endif
  3179. #endif
  3180. if (sock == INVALID_SOCKET) { continue; }
  3181. #if !defined _WIN32 && !defined SOCK_CLOEXEC
  3182. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) {
  3183. close_socket(sock);
  3184. continue;
  3185. }
  3186. #endif
  3187. if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); }
  3188. if (rp->ai_family == AF_INET6) {
  3189. set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0);
  3190. }
  3191. if (socket_options) { socket_options(sock); }
  3192. // bind or connect
  3193. auto quit = false;
  3194. if (bind_or_connect(sock, *rp, quit)) { return sock; }
  3195. close_socket(sock);
  3196. if (quit) { break; }
  3197. }
  3198. return INVALID_SOCKET;
  3199. }
  3200. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  3201. #ifdef _WIN32
  3202. auto flags = nonblocking ? 1UL : 0UL;
  3203. ioctlsocket(sock, FIONBIO, &flags);
  3204. #else
  3205. auto flags = fcntl(sock, F_GETFL, 0);
  3206. fcntl(sock, F_SETFL,
  3207. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  3208. #endif
  3209. }
  3210. inline bool is_connection_error() {
  3211. #ifdef _WIN32
  3212. return WSAGetLastError() != WSAEWOULDBLOCK;
  3213. #else
  3214. return errno != EINPROGRESS;
  3215. #endif
  3216. }
  3217. inline bool bind_ip_address(socket_t sock, const std::string &host) {
  3218. struct addrinfo hints;
  3219. struct addrinfo *result;
  3220. memset(&hints, 0, sizeof(struct addrinfo));
  3221. hints.ai_family = AF_UNSPEC;
  3222. hints.ai_socktype = SOCK_STREAM;
  3223. hints.ai_protocol = 0;
  3224. if (getaddrinfo_with_timeout(host.c_str(), "0", &hints, &result, 0)) {
  3225. return false;
  3226. }
  3227. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  3228. auto ret = false;
  3229. for (auto rp = result; rp; rp = rp->ai_next) {
  3230. const auto &ai = *rp;
  3231. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  3232. ret = true;
  3233. break;
  3234. }
  3235. }
  3236. return ret;
  3237. }
  3238. #if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__
  3239. #define USE_IF2IP
  3240. #endif
  3241. #ifdef USE_IF2IP
  3242. inline std::string if2ip(int address_family, const std::string &ifn) {
  3243. struct ifaddrs *ifap;
  3244. getifaddrs(&ifap);
  3245. auto se = detail::scope_exit([&] { freeifaddrs(ifap); });
  3246. std::string addr_candidate;
  3247. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  3248. if (ifa->ifa_addr && ifn == ifa->ifa_name &&
  3249. (AF_UNSPEC == address_family ||
  3250. ifa->ifa_addr->sa_family == address_family)) {
  3251. if (ifa->ifa_addr->sa_family == AF_INET) {
  3252. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  3253. char buf[INET_ADDRSTRLEN];
  3254. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  3255. return std::string(buf, INET_ADDRSTRLEN);
  3256. }
  3257. } else if (ifa->ifa_addr->sa_family == AF_INET6) {
  3258. auto sa = reinterpret_cast<struct sockaddr_in6 *>(ifa->ifa_addr);
  3259. if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) {
  3260. char buf[INET6_ADDRSTRLEN] = {};
  3261. if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) {
  3262. // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL
  3263. auto s6_addr_head = sa->sin6_addr.s6_addr[0];
  3264. if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) {
  3265. addr_candidate = std::string(buf, INET6_ADDRSTRLEN);
  3266. } else {
  3267. return std::string(buf, INET6_ADDRSTRLEN);
  3268. }
  3269. }
  3270. }
  3271. }
  3272. }
  3273. }
  3274. return addr_candidate;
  3275. }
  3276. #endif
  3277. inline socket_t create_client_socket(
  3278. const std::string &host, const std::string &ip, int port,
  3279. int address_family, bool tcp_nodelay, bool ipv6_v6only,
  3280. SocketOptions socket_options, time_t connection_timeout_sec,
  3281. time_t connection_timeout_usec, time_t read_timeout_sec,
  3282. time_t read_timeout_usec, time_t write_timeout_sec,
  3283. time_t write_timeout_usec, const std::string &intf, Error &error) {
  3284. auto sock = create_socket(
  3285. host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only,
  3286. std::move(socket_options),
  3287. [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool {
  3288. if (!intf.empty()) {
  3289. #ifdef USE_IF2IP
  3290. auto ip_from_if = if2ip(address_family, intf);
  3291. if (ip_from_if.empty()) { ip_from_if = intf; }
  3292. if (!bind_ip_address(sock2, ip_from_if)) {
  3293. error = Error::BindIPAddress;
  3294. return false;
  3295. }
  3296. #endif
  3297. }
  3298. set_nonblocking(sock2, true);
  3299. auto ret =
  3300. ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  3301. if (ret < 0) {
  3302. if (is_connection_error()) {
  3303. error = Error::Connection;
  3304. return false;
  3305. }
  3306. error = wait_until_socket_is_ready(sock2, connection_timeout_sec,
  3307. connection_timeout_usec);
  3308. if (error != Error::Success) {
  3309. if (error == Error::ConnectionTimeout) { quit = true; }
  3310. return false;
  3311. }
  3312. }
  3313. set_nonblocking(sock2, false);
  3314. set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec,
  3315. read_timeout_usec);
  3316. set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec,
  3317. write_timeout_usec);
  3318. error = Error::Success;
  3319. return true;
  3320. },
  3321. connection_timeout_sec); // Pass DNS timeout
  3322. if (sock != INVALID_SOCKET) {
  3323. error = Error::Success;
  3324. } else {
  3325. if (error == Error::Success) { error = Error::Connection; }
  3326. }
  3327. return sock;
  3328. }
  3329. inline bool get_ip_and_port(const struct sockaddr_storage &addr,
  3330. socklen_t addr_len, std::string &ip, int &port) {
  3331. if (addr.ss_family == AF_INET) {
  3332. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  3333. } else if (addr.ss_family == AF_INET6) {
  3334. port =
  3335. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  3336. } else {
  3337. return false;
  3338. }
  3339. std::array<char, NI_MAXHOST> ipstr{};
  3340. if (getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  3341. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  3342. 0, NI_NUMERICHOST)) {
  3343. return false;
  3344. }
  3345. ip = ipstr.data();
  3346. return true;
  3347. }
  3348. inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3349. struct sockaddr_storage addr;
  3350. socklen_t addr_len = sizeof(addr);
  3351. if (!getsockname(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3352. &addr_len)) {
  3353. get_ip_and_port(addr, addr_len, ip, port);
  3354. }
  3355. }
  3356. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  3357. struct sockaddr_storage addr;
  3358. socklen_t addr_len = sizeof(addr);
  3359. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  3360. &addr_len)) {
  3361. #ifndef _WIN32
  3362. if (addr.ss_family == AF_UNIX) {
  3363. #if defined(__linux__)
  3364. struct ucred ucred;
  3365. socklen_t len = sizeof(ucred);
  3366. if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) {
  3367. port = ucred.pid;
  3368. }
  3369. #elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__
  3370. pid_t pid;
  3371. socklen_t len = sizeof(pid);
  3372. if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) {
  3373. port = pid;
  3374. }
  3375. #endif
  3376. return;
  3377. }
  3378. #endif
  3379. get_ip_and_port(addr, addr_len, ip, port);
  3380. }
  3381. }
  3382. inline constexpr unsigned int str2tag_core(const char *s, size_t l,
  3383. unsigned int h) {
  3384. return (l == 0)
  3385. ? h
  3386. : str2tag_core(
  3387. s + 1, l - 1,
  3388. // Unsets the 6 high bits of h, therefore no overflow happens
  3389. (((std::numeric_limits<unsigned int>::max)() >> 6) &
  3390. h * 33) ^
  3391. static_cast<unsigned char>(*s));
  3392. }
  3393. inline unsigned int str2tag(const std::string &s) {
  3394. return str2tag_core(s.data(), s.size(), 0);
  3395. }
  3396. namespace udl {
  3397. inline constexpr unsigned int operator""_t(const char *s, size_t l) {
  3398. return str2tag_core(s, l, 0);
  3399. }
  3400. } // namespace udl
  3401. inline std::string
  3402. find_content_type(const std::string &path,
  3403. const std::map<std::string, std::string> &user_data,
  3404. const std::string &default_content_type) {
  3405. auto ext = file_extension(path);
  3406. auto it = user_data.find(ext);
  3407. if (it != user_data.end()) { return it->second; }
  3408. using udl::operator""_t;
  3409. switch (str2tag(ext)) {
  3410. default: return default_content_type;
  3411. case "css"_t: return "text/css";
  3412. case "csv"_t: return "text/csv";
  3413. case "htm"_t:
  3414. case "html"_t: return "text/html";
  3415. case "js"_t:
  3416. case "mjs"_t: return "text/javascript";
  3417. case "txt"_t: return "text/plain";
  3418. case "vtt"_t: return "text/vtt";
  3419. case "apng"_t: return "image/apng";
  3420. case "avif"_t: return "image/avif";
  3421. case "bmp"_t: return "image/bmp";
  3422. case "gif"_t: return "image/gif";
  3423. case "png"_t: return "image/png";
  3424. case "svg"_t: return "image/svg+xml";
  3425. case "webp"_t: return "image/webp";
  3426. case "ico"_t: return "image/x-icon";
  3427. case "tif"_t: return "image/tiff";
  3428. case "tiff"_t: return "image/tiff";
  3429. case "jpg"_t:
  3430. case "jpeg"_t: return "image/jpeg";
  3431. case "mp4"_t: return "video/mp4";
  3432. case "mpeg"_t: return "video/mpeg";
  3433. case "webm"_t: return "video/webm";
  3434. case "mp3"_t: return "audio/mp3";
  3435. case "mpga"_t: return "audio/mpeg";
  3436. case "weba"_t: return "audio/webm";
  3437. case "wav"_t: return "audio/wave";
  3438. case "otf"_t: return "font/otf";
  3439. case "ttf"_t: return "font/ttf";
  3440. case "woff"_t: return "font/woff";
  3441. case "woff2"_t: return "font/woff2";
  3442. case "7z"_t: return "application/x-7z-compressed";
  3443. case "atom"_t: return "application/atom+xml";
  3444. case "pdf"_t: return "application/pdf";
  3445. case "json"_t: return "application/json";
  3446. case "rss"_t: return "application/rss+xml";
  3447. case "tar"_t: return "application/x-tar";
  3448. case "xht"_t:
  3449. case "xhtml"_t: return "application/xhtml+xml";
  3450. case "xslt"_t: return "application/xslt+xml";
  3451. case "xml"_t: return "application/xml";
  3452. case "gz"_t: return "application/gzip";
  3453. case "zip"_t: return "application/zip";
  3454. case "wasm"_t: return "application/wasm";
  3455. }
  3456. }
  3457. inline bool can_compress_content_type(const std::string &content_type) {
  3458. using udl::operator""_t;
  3459. auto tag = str2tag(content_type);
  3460. switch (tag) {
  3461. case "image/svg+xml"_t:
  3462. case "application/javascript"_t:
  3463. case "application/json"_t:
  3464. case "application/xml"_t:
  3465. case "application/protobuf"_t:
  3466. case "application/xhtml+xml"_t: return true;
  3467. case "text/event-stream"_t: return false;
  3468. default: return !content_type.rfind("text/", 0);
  3469. }
  3470. }
  3471. inline EncodingType encoding_type(const Request &req, const Response &res) {
  3472. auto ret =
  3473. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  3474. if (!ret) { return EncodingType::None; }
  3475. const auto &s = req.get_header_value("Accept-Encoding");
  3476. (void)(s);
  3477. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3478. // TODO: 'Accept-Encoding' has br, not br;q=0
  3479. ret = s.find("br") != std::string::npos;
  3480. if (ret) { return EncodingType::Brotli; }
  3481. #endif
  3482. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3483. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  3484. ret = s.find("gzip") != std::string::npos;
  3485. if (ret) { return EncodingType::Gzip; }
  3486. #endif
  3487. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3488. // TODO: 'Accept-Encoding' has zstd, not zstd;q=0
  3489. ret = s.find("zstd") != std::string::npos;
  3490. if (ret) { return EncodingType::Zstd; }
  3491. #endif
  3492. return EncodingType::None;
  3493. }
  3494. inline bool nocompressor::compress(const char *data, size_t data_length,
  3495. bool /*last*/, Callback callback) {
  3496. if (!data_length) { return true; }
  3497. return callback(data, data_length);
  3498. }
  3499. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3500. inline gzip_compressor::gzip_compressor() {
  3501. std::memset(&strm_, 0, sizeof(strm_));
  3502. strm_.zalloc = Z_NULL;
  3503. strm_.zfree = Z_NULL;
  3504. strm_.opaque = Z_NULL;
  3505. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  3506. Z_DEFAULT_STRATEGY) == Z_OK;
  3507. }
  3508. inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
  3509. inline bool gzip_compressor::compress(const char *data, size_t data_length,
  3510. bool last, Callback callback) {
  3511. assert(is_valid_);
  3512. do {
  3513. constexpr size_t max_avail_in =
  3514. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3515. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3516. (std::min)(data_length, max_avail_in));
  3517. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3518. data_length -= strm_.avail_in;
  3519. data += strm_.avail_in;
  3520. auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
  3521. auto ret = Z_OK;
  3522. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3523. do {
  3524. strm_.avail_out = static_cast<uInt>(buff.size());
  3525. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3526. ret = deflate(&strm_, flush);
  3527. if (ret == Z_STREAM_ERROR) { return false; }
  3528. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3529. return false;
  3530. }
  3531. } while (strm_.avail_out == 0);
  3532. assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
  3533. (flush == Z_NO_FLUSH && ret == Z_OK));
  3534. assert(strm_.avail_in == 0);
  3535. } while (data_length > 0);
  3536. return true;
  3537. }
  3538. inline gzip_decompressor::gzip_decompressor() {
  3539. std::memset(&strm_, 0, sizeof(strm_));
  3540. strm_.zalloc = Z_NULL;
  3541. strm_.zfree = Z_NULL;
  3542. strm_.opaque = Z_NULL;
  3543. // 15 is the value of wbits, which should be at the maximum possible value
  3544. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  3545. // that the stream type should be automatically detected either gzip or
  3546. // deflate.
  3547. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  3548. }
  3549. inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
  3550. inline bool gzip_decompressor::is_valid() const { return is_valid_; }
  3551. inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
  3552. Callback callback) {
  3553. assert(is_valid_);
  3554. auto ret = Z_OK;
  3555. do {
  3556. constexpr size_t max_avail_in =
  3557. (std::numeric_limits<decltype(strm_.avail_in)>::max)();
  3558. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
  3559. (std::min)(data_length, max_avail_in));
  3560. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  3561. data_length -= strm_.avail_in;
  3562. data += strm_.avail_in;
  3563. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3564. while (strm_.avail_in > 0 && ret == Z_OK) {
  3565. strm_.avail_out = static_cast<uInt>(buff.size());
  3566. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  3567. ret = inflate(&strm_, Z_NO_FLUSH);
  3568. assert(ret != Z_STREAM_ERROR);
  3569. switch (ret) {
  3570. case Z_NEED_DICT:
  3571. case Z_DATA_ERROR:
  3572. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  3573. }
  3574. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  3575. return false;
  3576. }
  3577. }
  3578. if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
  3579. } while (data_length > 0);
  3580. return true;
  3581. }
  3582. #endif
  3583. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3584. inline brotli_compressor::brotli_compressor() {
  3585. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  3586. }
  3587. inline brotli_compressor::~brotli_compressor() {
  3588. BrotliEncoderDestroyInstance(state_);
  3589. }
  3590. inline bool brotli_compressor::compress(const char *data, size_t data_length,
  3591. bool last, Callback callback) {
  3592. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3593. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  3594. auto available_in = data_length;
  3595. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3596. for (;;) {
  3597. if (last) {
  3598. if (BrotliEncoderIsFinished(state_)) { break; }
  3599. } else {
  3600. if (!available_in) { break; }
  3601. }
  3602. auto available_out = buff.size();
  3603. auto next_out = buff.data();
  3604. if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
  3605. &available_out, &next_out, nullptr)) {
  3606. return false;
  3607. }
  3608. auto output_bytes = buff.size() - available_out;
  3609. if (output_bytes) {
  3610. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  3611. }
  3612. }
  3613. return true;
  3614. }
  3615. inline brotli_decompressor::brotli_decompressor() {
  3616. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  3617. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  3618. : BROTLI_DECODER_RESULT_ERROR;
  3619. }
  3620. inline brotli_decompressor::~brotli_decompressor() {
  3621. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  3622. }
  3623. inline bool brotli_decompressor::is_valid() const { return decoder_s; }
  3624. inline bool brotli_decompressor::decompress(const char *data,
  3625. size_t data_length,
  3626. Callback callback) {
  3627. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3628. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  3629. return 0;
  3630. }
  3631. auto next_in = reinterpret_cast<const uint8_t *>(data);
  3632. size_t avail_in = data_length;
  3633. size_t total_out;
  3634. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  3635. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3636. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  3637. char *next_out = buff.data();
  3638. size_t avail_out = buff.size();
  3639. decoder_r = BrotliDecoderDecompressStream(
  3640. decoder_s, &avail_in, &next_in, &avail_out,
  3641. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  3642. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  3643. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  3644. }
  3645. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  3646. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  3647. }
  3648. #endif
  3649. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3650. inline zstd_compressor::zstd_compressor() {
  3651. ctx_ = ZSTD_createCCtx();
  3652. ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast);
  3653. }
  3654. inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); }
  3655. inline bool zstd_compressor::compress(const char *data, size_t data_length,
  3656. bool last, Callback callback) {
  3657. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3658. ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue;
  3659. ZSTD_inBuffer input = {data, data_length, 0};
  3660. bool finished;
  3661. do {
  3662. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3663. size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode);
  3664. if (ZSTD_isError(remaining)) { return false; }
  3665. if (!callback(buff.data(), output.pos)) { return false; }
  3666. finished = last ? (remaining == 0) : (input.pos == input.size);
  3667. } while (!finished);
  3668. return true;
  3669. }
  3670. inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); }
  3671. inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); }
  3672. inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; }
  3673. inline bool zstd_decompressor::decompress(const char *data, size_t data_length,
  3674. Callback callback) {
  3675. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  3676. ZSTD_inBuffer input = {data, data_length, 0};
  3677. while (input.pos < input.size) {
  3678. ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0};
  3679. size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input);
  3680. if (ZSTD_isError(remaining)) { return false; }
  3681. if (!callback(buff.data(), output.pos)) { return false; }
  3682. }
  3683. return true;
  3684. }
  3685. #endif
  3686. inline bool has_header(const Headers &headers, const std::string &key) {
  3687. return headers.find(key) != headers.end();
  3688. }
  3689. inline const char *get_header_value(const Headers &headers,
  3690. const std::string &key, const char *def,
  3691. size_t id) {
  3692. auto rng = headers.equal_range(key);
  3693. auto it = rng.first;
  3694. std::advance(it, static_cast<ssize_t>(id));
  3695. if (it != rng.second) { return it->second.c_str(); }
  3696. return def;
  3697. }
  3698. template <typename T>
  3699. inline bool parse_header(const char *beg, const char *end, T fn) {
  3700. // Skip trailing spaces and tabs.
  3701. while (beg < end && is_space_or_tab(end[-1])) {
  3702. end--;
  3703. }
  3704. auto p = beg;
  3705. while (p < end && *p != ':') {
  3706. p++;
  3707. }
  3708. auto name = std::string(beg, p);
  3709. if (!detail::fields::is_field_name(name)) { return false; }
  3710. if (p == end) { return false; }
  3711. auto key_end = p;
  3712. if (*p++ != ':') { return false; }
  3713. while (p < end && is_space_or_tab(*p)) {
  3714. p++;
  3715. }
  3716. if (p <= end) {
  3717. auto key_len = key_end - beg;
  3718. if (!key_len) { return false; }
  3719. auto key = std::string(beg, key_end);
  3720. auto val = std::string(p, end);
  3721. if (!detail::fields::is_field_value(val)) { return false; }
  3722. if (case_ignore::equal(key, "Location") ||
  3723. case_ignore::equal(key, "Referer")) {
  3724. fn(key, val);
  3725. } else {
  3726. fn(key, decode_url(val, false));
  3727. }
  3728. return true;
  3729. }
  3730. return false;
  3731. }
  3732. inline bool read_headers(Stream &strm, Headers &headers) {
  3733. const auto bufsiz = 2048;
  3734. char buf[bufsiz];
  3735. stream_line_reader line_reader(strm, buf, bufsiz);
  3736. size_t header_count = 0;
  3737. for (;;) {
  3738. if (!line_reader.getline()) { return false; }
  3739. // Check if the line ends with CRLF.
  3740. auto line_terminator_len = 2;
  3741. if (line_reader.end_with_crlf()) {
  3742. // Blank line indicates end of headers.
  3743. if (line_reader.size() == 2) { break; }
  3744. } else {
  3745. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  3746. // Blank line indicates end of headers.
  3747. if (line_reader.size() == 1) { break; }
  3748. line_terminator_len = 1;
  3749. #else
  3750. continue; // Skip invalid line.
  3751. #endif
  3752. }
  3753. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3754. // Check header count limit
  3755. if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3756. // Exclude line terminator
  3757. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3758. if (!parse_header(line_reader.ptr(), end,
  3759. [&](const std::string &key, const std::string &val) {
  3760. headers.emplace(key, val);
  3761. })) {
  3762. return false;
  3763. }
  3764. header_count++;
  3765. }
  3766. return true;
  3767. }
  3768. inline bool read_content_with_length(Stream &strm, uint64_t len,
  3769. DownloadProgress progress,
  3770. ContentReceiverWithProgress out) {
  3771. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3772. uint64_t r = 0;
  3773. while (r < len) {
  3774. auto read_len = static_cast<size_t>(len - r);
  3775. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3776. if (n <= 0) { return false; }
  3777. if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
  3778. r += static_cast<uint64_t>(n);
  3779. if (progress) {
  3780. if (!progress(r, len)) { return false; }
  3781. }
  3782. }
  3783. return true;
  3784. }
  3785. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  3786. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3787. uint64_t r = 0;
  3788. while (r < len) {
  3789. auto read_len = static_cast<size_t>(len - r);
  3790. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  3791. if (n <= 0) { return; }
  3792. r += static_cast<uint64_t>(n);
  3793. }
  3794. }
  3795. inline bool read_content_without_length(Stream &strm,
  3796. ContentReceiverWithProgress out) {
  3797. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  3798. uint64_t r = 0;
  3799. for (;;) {
  3800. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  3801. if (n == 0) { return true; }
  3802. if (n < 0) { return false; }
  3803. if (!out(buf, static_cast<size_t>(n), r, 0)) { return false; }
  3804. r += static_cast<uint64_t>(n);
  3805. }
  3806. return true;
  3807. }
  3808. template <typename T>
  3809. inline bool read_content_chunked(Stream &strm, T &x,
  3810. ContentReceiverWithProgress out) {
  3811. const auto bufsiz = 16;
  3812. char buf[bufsiz];
  3813. stream_line_reader line_reader(strm, buf, bufsiz);
  3814. if (!line_reader.getline()) { return false; }
  3815. unsigned long chunk_len;
  3816. while (true) {
  3817. char *end_ptr;
  3818. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  3819. if (end_ptr == line_reader.ptr()) { return false; }
  3820. if (chunk_len == ULONG_MAX) { return false; }
  3821. if (chunk_len == 0) { break; }
  3822. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  3823. return false;
  3824. }
  3825. if (!line_reader.getline()) { return false; }
  3826. if (strcmp(line_reader.ptr(), "\r\n") != 0) { return false; }
  3827. if (!line_reader.getline()) { return false; }
  3828. }
  3829. assert(chunk_len == 0);
  3830. // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked
  3831. // transfer coding is complete when a chunk with a chunk-size of zero is
  3832. // received, possibly followed by a trailer section, and finally terminated by
  3833. // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1
  3834. //
  3835. // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section
  3836. // does't care for the existence of the final CRLF. In other words, it seems
  3837. // to be ok whether the final CRLF exists or not in the chunked data.
  3838. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3
  3839. //
  3840. // According to the reference code in RFC 9112, cpp-httplib now allows
  3841. // chunked transfer coding data without the final CRLF.
  3842. if (!line_reader.getline()) { return true; }
  3843. size_t trailer_header_count = 0;
  3844. while (strcmp(line_reader.ptr(), "\r\n") != 0) {
  3845. if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  3846. // Check trailer header count limit
  3847. if (trailer_header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
  3848. // Exclude line terminator
  3849. constexpr auto line_terminator_len = 2;
  3850. auto end = line_reader.ptr() + line_reader.size() - line_terminator_len;
  3851. parse_header(line_reader.ptr(), end,
  3852. [&](const std::string &key, const std::string &val) {
  3853. x.headers.emplace(key, val);
  3854. });
  3855. trailer_header_count++;
  3856. if (!line_reader.getline()) { return false; }
  3857. }
  3858. return true;
  3859. }
  3860. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  3861. return case_ignore::equal(
  3862. get_header_value(headers, "Transfer-Encoding", "", 0), "chunked");
  3863. }
  3864. template <typename T, typename U>
  3865. bool prepare_content_receiver(T &x, int &status,
  3866. ContentReceiverWithProgress receiver,
  3867. bool decompress, U callback) {
  3868. if (decompress) {
  3869. std::string encoding = x.get_header_value("Content-Encoding");
  3870. std::unique_ptr<decompressor> decompressor;
  3871. if (encoding == "gzip" || encoding == "deflate") {
  3872. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3873. decompressor = detail::make_unique<gzip_decompressor>();
  3874. #else
  3875. status = StatusCode::UnsupportedMediaType_415;
  3876. return false;
  3877. #endif
  3878. } else if (encoding.find("br") != std::string::npos) {
  3879. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3880. decompressor = detail::make_unique<brotli_decompressor>();
  3881. #else
  3882. status = StatusCode::UnsupportedMediaType_415;
  3883. return false;
  3884. #endif
  3885. } else if (encoding == "zstd") {
  3886. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  3887. decompressor = detail::make_unique<zstd_decompressor>();
  3888. #else
  3889. status = StatusCode::UnsupportedMediaType_415;
  3890. return false;
  3891. #endif
  3892. }
  3893. if (decompressor) {
  3894. if (decompressor->is_valid()) {
  3895. ContentReceiverWithProgress out = [&](const char *buf, size_t n,
  3896. uint64_t off, uint64_t len) {
  3897. return decompressor->decompress(buf, n,
  3898. [&](const char *buf2, size_t n2) {
  3899. return receiver(buf2, n2, off, len);
  3900. });
  3901. };
  3902. return callback(std::move(out));
  3903. } else {
  3904. status = StatusCode::InternalServerError_500;
  3905. return false;
  3906. }
  3907. }
  3908. }
  3909. ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off,
  3910. uint64_t len) {
  3911. return receiver(buf, n, off, len);
  3912. };
  3913. return callback(std::move(out));
  3914. }
  3915. template <typename T>
  3916. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  3917. DownloadProgress progress,
  3918. ContentReceiverWithProgress receiver, bool decompress) {
  3919. return prepare_content_receiver(
  3920. x, status, std::move(receiver), decompress,
  3921. [&](const ContentReceiverWithProgress &out) {
  3922. auto ret = true;
  3923. auto exceed_payload_max_length = false;
  3924. if (is_chunked_transfer_encoding(x.headers)) {
  3925. ret = read_content_chunked(strm, x, out);
  3926. } else if (!has_header(x.headers, "Content-Length")) {
  3927. ret = read_content_without_length(strm, out);
  3928. } else {
  3929. auto is_invalid_value = false;
  3930. auto len = get_header_value_u64(
  3931. x.headers, "Content-Length",
  3932. (std::numeric_limits<uint64_t>::max)(), 0, is_invalid_value);
  3933. if (is_invalid_value) {
  3934. ret = false;
  3935. } else if (len > payload_max_length) {
  3936. exceed_payload_max_length = true;
  3937. skip_content_with_length(strm, len);
  3938. ret = false;
  3939. } else if (len > 0) {
  3940. ret = read_content_with_length(strm, len, std::move(progress), out);
  3941. }
  3942. }
  3943. if (!ret) {
  3944. status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413
  3945. : StatusCode::BadRequest_400;
  3946. }
  3947. return ret;
  3948. });
  3949. }
  3950. inline ssize_t write_request_line(Stream &strm, const std::string &method,
  3951. const std::string &path) {
  3952. std::string s = method;
  3953. s += " ";
  3954. s += path;
  3955. s += " HTTP/1.1\r\n";
  3956. return strm.write(s.data(), s.size());
  3957. }
  3958. inline ssize_t write_response_line(Stream &strm, int status) {
  3959. std::string s = "HTTP/1.1 ";
  3960. s += std::to_string(status);
  3961. s += " ";
  3962. s += httplib::status_message(status);
  3963. s += "\r\n";
  3964. return strm.write(s.data(), s.size());
  3965. }
  3966. inline ssize_t write_headers(Stream &strm, const Headers &headers) {
  3967. ssize_t write_len = 0;
  3968. for (const auto &x : headers) {
  3969. std::string s;
  3970. s = x.first;
  3971. s += ": ";
  3972. s += x.second;
  3973. s += "\r\n";
  3974. auto len = strm.write(s.data(), s.size());
  3975. if (len < 0) { return len; }
  3976. write_len += len;
  3977. }
  3978. auto len = strm.write("\r\n");
  3979. if (len < 0) { return len; }
  3980. write_len += len;
  3981. return write_len;
  3982. }
  3983. inline bool write_data(Stream &strm, const char *d, size_t l) {
  3984. size_t offset = 0;
  3985. while (offset < l) {
  3986. auto length = strm.write(d + offset, l - offset);
  3987. if (length < 0) { return false; }
  3988. offset += static_cast<size_t>(length);
  3989. }
  3990. return true;
  3991. }
  3992. template <typename T>
  3993. inline bool write_content_with_progress(Stream &strm,
  3994. const ContentProvider &content_provider,
  3995. size_t offset, size_t length,
  3996. T is_shutting_down,
  3997. const UploadProgress &upload_progress,
  3998. Error &error) {
  3999. size_t end_offset = offset + length;
  4000. size_t start_offset = offset;
  4001. auto ok = true;
  4002. DataSink data_sink;
  4003. data_sink.write = [&](const char *d, size_t l) -> bool {
  4004. if (ok) {
  4005. if (write_data(strm, d, l)) {
  4006. offset += l;
  4007. if (upload_progress && length > 0) {
  4008. size_t current_written = offset - start_offset;
  4009. if (!upload_progress(current_written, length)) {
  4010. ok = false;
  4011. return false;
  4012. }
  4013. }
  4014. } else {
  4015. ok = false;
  4016. }
  4017. }
  4018. return ok;
  4019. };
  4020. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4021. while (offset < end_offset && !is_shutting_down()) {
  4022. if (!strm.wait_writable()) {
  4023. error = Error::Write;
  4024. return false;
  4025. } else if (!content_provider(offset, end_offset - offset, data_sink)) {
  4026. error = Error::Canceled;
  4027. return false;
  4028. } else if (!ok) {
  4029. error = Error::Write;
  4030. return false;
  4031. }
  4032. }
  4033. error = Error::Success;
  4034. return true;
  4035. }
  4036. template <typename T>
  4037. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4038. size_t offset, size_t length, T is_shutting_down,
  4039. Error &error) {
  4040. return write_content_with_progress<T>(strm, content_provider, offset, length,
  4041. is_shutting_down, nullptr, error);
  4042. }
  4043. template <typename T>
  4044. inline bool write_content(Stream &strm, const ContentProvider &content_provider,
  4045. size_t offset, size_t length,
  4046. const T &is_shutting_down) {
  4047. auto error = Error::Success;
  4048. return write_content(strm, content_provider, offset, length, is_shutting_down,
  4049. error);
  4050. }
  4051. template <typename T>
  4052. inline bool
  4053. write_content_without_length(Stream &strm,
  4054. const ContentProvider &content_provider,
  4055. const T &is_shutting_down) {
  4056. size_t offset = 0;
  4057. auto data_available = true;
  4058. auto ok = true;
  4059. DataSink data_sink;
  4060. data_sink.write = [&](const char *d, size_t l) -> bool {
  4061. if (ok) {
  4062. offset += l;
  4063. if (!write_data(strm, d, l)) { ok = false; }
  4064. }
  4065. return ok;
  4066. };
  4067. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4068. data_sink.done = [&](void) { data_available = false; };
  4069. while (data_available && !is_shutting_down()) {
  4070. if (!strm.wait_writable()) {
  4071. return false;
  4072. } else if (!content_provider(offset, 0, data_sink)) {
  4073. return false;
  4074. } else if (!ok) {
  4075. return false;
  4076. }
  4077. }
  4078. return true;
  4079. }
  4080. template <typename T, typename U>
  4081. inline bool
  4082. write_content_chunked(Stream &strm, const ContentProvider &content_provider,
  4083. const T &is_shutting_down, U &compressor, Error &error) {
  4084. size_t offset = 0;
  4085. auto data_available = true;
  4086. auto ok = true;
  4087. DataSink data_sink;
  4088. data_sink.write = [&](const char *d, size_t l) -> bool {
  4089. if (ok) {
  4090. data_available = l > 0;
  4091. offset += l;
  4092. std::string payload;
  4093. if (compressor.compress(d, l, false,
  4094. [&](const char *data, size_t data_len) {
  4095. payload.append(data, data_len);
  4096. return true;
  4097. })) {
  4098. if (!payload.empty()) {
  4099. // Emit chunked response header and footer for each chunk
  4100. auto chunk =
  4101. from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  4102. if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
  4103. }
  4104. } else {
  4105. ok = false;
  4106. }
  4107. }
  4108. return ok;
  4109. };
  4110. data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); };
  4111. auto done_with_trailer = [&](const Headers *trailer) {
  4112. if (!ok) { return; }
  4113. data_available = false;
  4114. std::string payload;
  4115. if (!compressor.compress(nullptr, 0, true,
  4116. [&](const char *data, size_t data_len) {
  4117. payload.append(data, data_len);
  4118. return true;
  4119. })) {
  4120. ok = false;
  4121. return;
  4122. }
  4123. if (!payload.empty()) {
  4124. // Emit chunked response header and footer for each chunk
  4125. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  4126. if (!write_data(strm, chunk.data(), chunk.size())) {
  4127. ok = false;
  4128. return;
  4129. }
  4130. }
  4131. constexpr const char done_marker[] = "0\r\n";
  4132. if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; }
  4133. // Trailer
  4134. if (trailer) {
  4135. for (const auto &kv : *trailer) {
  4136. std::string field_line = kv.first + ": " + kv.second + "\r\n";
  4137. if (!write_data(strm, field_line.data(), field_line.size())) {
  4138. ok = false;
  4139. }
  4140. }
  4141. }
  4142. constexpr const char crlf[] = "\r\n";
  4143. if (!write_data(strm, crlf, str_len(crlf))) { ok = false; }
  4144. };
  4145. data_sink.done = [&](void) { done_with_trailer(nullptr); };
  4146. data_sink.done_with_trailer = [&](const Headers &trailer) {
  4147. done_with_trailer(&trailer);
  4148. };
  4149. while (data_available && !is_shutting_down()) {
  4150. if (!strm.wait_writable()) {
  4151. error = Error::Write;
  4152. return false;
  4153. } else if (!content_provider(offset, 0, data_sink)) {
  4154. error = Error::Canceled;
  4155. return false;
  4156. } else if (!ok) {
  4157. error = Error::Write;
  4158. return false;
  4159. }
  4160. }
  4161. error = Error::Success;
  4162. return true;
  4163. }
  4164. template <typename T, typename U>
  4165. inline bool write_content_chunked(Stream &strm,
  4166. const ContentProvider &content_provider,
  4167. const T &is_shutting_down, U &compressor) {
  4168. auto error = Error::Success;
  4169. return write_content_chunked(strm, content_provider, is_shutting_down,
  4170. compressor, error);
  4171. }
  4172. template <typename T>
  4173. inline bool redirect(T &cli, Request &req, Response &res,
  4174. const std::string &path, const std::string &location,
  4175. Error &error) {
  4176. Request new_req = req;
  4177. new_req.path = path;
  4178. new_req.redirect_count_ -= 1;
  4179. if (res.status == StatusCode::SeeOther_303 &&
  4180. (req.method != "GET" && req.method != "HEAD")) {
  4181. new_req.method = "GET";
  4182. new_req.body.clear();
  4183. new_req.headers.clear();
  4184. }
  4185. Response new_res;
  4186. auto ret = cli.send(new_req, new_res, error);
  4187. if (ret) {
  4188. req = new_req;
  4189. res = new_res;
  4190. if (res.location.empty()) { res.location = location; }
  4191. }
  4192. return ret;
  4193. }
  4194. inline std::string params_to_query_str(const Params &params) {
  4195. std::string query;
  4196. for (auto it = params.begin(); it != params.end(); ++it) {
  4197. if (it != params.begin()) { query += "&"; }
  4198. query += it->first;
  4199. query += "=";
  4200. query += encode_query_param(it->second);
  4201. }
  4202. return query;
  4203. }
  4204. inline void parse_query_text(const char *data, std::size_t size,
  4205. Params &params) {
  4206. std::set<std::string> cache;
  4207. split(data, data + size, '&', [&](const char *b, const char *e) {
  4208. std::string kv(b, e);
  4209. if (cache.find(kv) != cache.end()) { return; }
  4210. cache.insert(std::move(kv));
  4211. std::string key;
  4212. std::string val;
  4213. divide(b, static_cast<std::size_t>(e - b), '=',
  4214. [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data,
  4215. std::size_t rhs_size) {
  4216. key.assign(lhs_data, lhs_size);
  4217. val.assign(rhs_data, rhs_size);
  4218. });
  4219. if (!key.empty()) {
  4220. params.emplace(decode_url(key, true), decode_url(val, true));
  4221. }
  4222. });
  4223. }
  4224. inline void parse_query_text(const std::string &s, Params &params) {
  4225. parse_query_text(s.data(), s.size(), params);
  4226. }
  4227. inline bool parse_multipart_boundary(const std::string &content_type,
  4228. std::string &boundary) {
  4229. auto boundary_keyword = "boundary=";
  4230. auto pos = content_type.find(boundary_keyword);
  4231. if (pos == std::string::npos) { return false; }
  4232. auto end = content_type.find(';', pos);
  4233. auto beg = pos + strlen(boundary_keyword);
  4234. boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg));
  4235. return !boundary.empty();
  4236. }
  4237. inline void parse_disposition_params(const std::string &s, Params &params) {
  4238. std::set<std::string> cache;
  4239. split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) {
  4240. std::string kv(b, e);
  4241. if (cache.find(kv) != cache.end()) { return; }
  4242. cache.insert(kv);
  4243. std::string key;
  4244. std::string val;
  4245. split(b, e, '=', [&](const char *b2, const char *e2) {
  4246. if (key.empty()) {
  4247. key.assign(b2, e2);
  4248. } else {
  4249. val.assign(b2, e2);
  4250. }
  4251. });
  4252. if (!key.empty()) {
  4253. params.emplace(trim_double_quotes_copy((key)),
  4254. trim_double_quotes_copy((val)));
  4255. }
  4256. });
  4257. }
  4258. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4259. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  4260. #else
  4261. inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
  4262. #endif
  4263. auto is_valid = [](const std::string &str) {
  4264. return std::all_of(str.cbegin(), str.cend(),
  4265. [](unsigned char c) { return std::isdigit(c); });
  4266. };
  4267. if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) {
  4268. const auto pos = static_cast<size_t>(6);
  4269. const auto len = static_cast<size_t>(s.size() - 6);
  4270. auto all_valid_ranges = true;
  4271. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  4272. if (!all_valid_ranges) { return; }
  4273. const auto it = std::find(b, e, '-');
  4274. if (it == e) {
  4275. all_valid_ranges = false;
  4276. return;
  4277. }
  4278. const auto lhs = std::string(b, it);
  4279. const auto rhs = std::string(it + 1, e);
  4280. if (!is_valid(lhs) || !is_valid(rhs)) {
  4281. all_valid_ranges = false;
  4282. return;
  4283. }
  4284. const auto first =
  4285. static_cast<ssize_t>(lhs.empty() ? -1 : std::stoll(lhs));
  4286. const auto last =
  4287. static_cast<ssize_t>(rhs.empty() ? -1 : std::stoll(rhs));
  4288. if ((first == -1 && last == -1) ||
  4289. (first != -1 && last != -1 && first > last)) {
  4290. all_valid_ranges = false;
  4291. return;
  4292. }
  4293. ranges.emplace_back(first, last);
  4294. });
  4295. return all_valid_ranges && !ranges.empty();
  4296. }
  4297. return false;
  4298. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  4299. }
  4300. #else
  4301. } catch (...) { return false; }
  4302. #endif
  4303. inline bool parse_accept_header(const std::string &s,
  4304. std::vector<std::string> &content_types) {
  4305. content_types.clear();
  4306. // Empty string is considered valid (no preference)
  4307. if (s.empty()) { return true; }
  4308. // Check for invalid patterns: leading/trailing commas or consecutive commas
  4309. if (s.front() == ',' || s.back() == ',' ||
  4310. s.find(",,") != std::string::npos) {
  4311. return false;
  4312. }
  4313. struct AcceptEntry {
  4314. std::string media_type;
  4315. double quality;
  4316. int order; // Original order in header
  4317. };
  4318. std::vector<AcceptEntry> entries;
  4319. int order = 0;
  4320. bool has_invalid_entry = false;
  4321. // Split by comma and parse each entry
  4322. split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
  4323. std::string entry(b, e);
  4324. entry = trim_copy(entry);
  4325. if (entry.empty()) {
  4326. has_invalid_entry = true;
  4327. return;
  4328. }
  4329. AcceptEntry accept_entry;
  4330. accept_entry.quality = 1.0; // Default quality
  4331. accept_entry.order = order++;
  4332. // Find q= parameter
  4333. auto q_pos = entry.find(";q=");
  4334. if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
  4335. if (q_pos != std::string::npos) {
  4336. // Extract media type (before q parameter)
  4337. accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
  4338. // Extract quality value
  4339. auto q_start = entry.find('=', q_pos) + 1;
  4340. auto q_end = entry.find(';', q_start);
  4341. if (q_end == std::string::npos) { q_end = entry.length(); }
  4342. std::string quality_str =
  4343. trim_copy(entry.substr(q_start, q_end - q_start));
  4344. if (quality_str.empty()) {
  4345. has_invalid_entry = true;
  4346. return;
  4347. }
  4348. try {
  4349. accept_entry.quality = std::stod(quality_str);
  4350. // Check if quality is in valid range [0.0, 1.0]
  4351. if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
  4352. has_invalid_entry = true;
  4353. return;
  4354. }
  4355. } catch (...) {
  4356. has_invalid_entry = true;
  4357. return;
  4358. }
  4359. } else {
  4360. // No quality parameter, use entire entry as media type
  4361. accept_entry.media_type = entry;
  4362. }
  4363. // Remove additional parameters from media type
  4364. auto param_pos = accept_entry.media_type.find(';');
  4365. if (param_pos != std::string::npos) {
  4366. accept_entry.media_type =
  4367. trim_copy(accept_entry.media_type.substr(0, param_pos));
  4368. }
  4369. // Basic validation of media type format
  4370. if (accept_entry.media_type.empty()) {
  4371. has_invalid_entry = true;
  4372. return;
  4373. }
  4374. // Check for basic media type format (should contain '/' or be '*')
  4375. if (accept_entry.media_type != "*" &&
  4376. accept_entry.media_type.find('/') == std::string::npos) {
  4377. has_invalid_entry = true;
  4378. return;
  4379. }
  4380. entries.push_back(accept_entry);
  4381. });
  4382. // Return false if any invalid entry was found
  4383. if (has_invalid_entry) { return false; }
  4384. // Sort by quality (descending), then by original order (ascending)
  4385. std::sort(entries.begin(), entries.end(),
  4386. [](const AcceptEntry &a, const AcceptEntry &b) {
  4387. if (a.quality != b.quality) {
  4388. return a.quality > b.quality; // Higher quality first
  4389. }
  4390. return a.order < b.order; // Earlier order first for same quality
  4391. });
  4392. // Extract sorted media types
  4393. content_types.reserve(entries.size());
  4394. for (const auto &entry : entries) {
  4395. content_types.push_back(entry.media_type);
  4396. }
  4397. return true;
  4398. }
  4399. class MultipartFormDataParser {
  4400. public:
  4401. MultipartFormDataParser() = default;
  4402. void set_boundary(std::string &&boundary) {
  4403. boundary_ = boundary;
  4404. dash_boundary_crlf_ = dash_ + boundary_ + crlf_;
  4405. crlf_dash_boundary_ = crlf_ + dash_ + boundary_;
  4406. }
  4407. bool is_valid() const { return is_valid_; }
  4408. bool parse(const char *buf, size_t n, const ContentReceiver &content_callback,
  4409. const MultipartContentHeader &header_callback) {
  4410. buf_append(buf, n);
  4411. while (buf_size() > 0) {
  4412. switch (state_) {
  4413. case 0: { // Initial boundary
  4414. auto pos = buf_find(dash_boundary_crlf_);
  4415. if (pos == buf_size()) { return true; }
  4416. buf_erase(pos + dash_boundary_crlf_.size());
  4417. state_ = 1;
  4418. break;
  4419. }
  4420. case 1: { // New entry
  4421. clear_file_info();
  4422. state_ = 2;
  4423. break;
  4424. }
  4425. case 2: { // Headers
  4426. auto pos = buf_find(crlf_);
  4427. if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
  4428. while (pos < buf_size()) {
  4429. // Empty line
  4430. if (pos == 0) {
  4431. if (!header_callback(file_)) {
  4432. is_valid_ = false;
  4433. return false;
  4434. }
  4435. buf_erase(crlf_.size());
  4436. state_ = 3;
  4437. break;
  4438. }
  4439. const auto header = buf_head(pos);
  4440. if (!parse_header(header.data(), header.data() + header.size(),
  4441. [&](const std::string &, const std::string &) {})) {
  4442. is_valid_ = false;
  4443. return false;
  4444. }
  4445. // parse and emplace space trimmed headers into a map
  4446. if (!parse_header(
  4447. header.data(), header.data() + header.size(),
  4448. [&](const std::string &key, const std::string &val) {
  4449. file_.headers.emplace(key, val);
  4450. })) {
  4451. is_valid_ = false;
  4452. return false;
  4453. }
  4454. constexpr const char header_content_type[] = "Content-Type:";
  4455. if (start_with_case_ignore(header, header_content_type)) {
  4456. file_.content_type =
  4457. trim_copy(header.substr(str_len(header_content_type)));
  4458. } else {
  4459. thread_local const std::regex re_content_disposition(
  4460. R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~",
  4461. std::regex_constants::icase);
  4462. std::smatch m;
  4463. if (std::regex_match(header, m, re_content_disposition)) {
  4464. Params params;
  4465. parse_disposition_params(m[1], params);
  4466. auto it = params.find("name");
  4467. if (it != params.end()) {
  4468. file_.name = it->second;
  4469. } else {
  4470. is_valid_ = false;
  4471. return false;
  4472. }
  4473. it = params.find("filename");
  4474. if (it != params.end()) { file_.filename = it->second; }
  4475. it = params.find("filename*");
  4476. if (it != params.end()) {
  4477. // Only allow UTF-8 encoding...
  4478. thread_local const std::regex re_rfc5987_encoding(
  4479. R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase);
  4480. std::smatch m2;
  4481. if (std::regex_match(it->second, m2, re_rfc5987_encoding)) {
  4482. file_.filename = decode_url(m2[1], false); // override...
  4483. } else {
  4484. is_valid_ = false;
  4485. return false;
  4486. }
  4487. }
  4488. }
  4489. }
  4490. buf_erase(pos + crlf_.size());
  4491. pos = buf_find(crlf_);
  4492. }
  4493. if (state_ != 3) { return true; }
  4494. break;
  4495. }
  4496. case 3: { // Body
  4497. if (crlf_dash_boundary_.size() > buf_size()) { return true; }
  4498. auto pos = buf_find(crlf_dash_boundary_);
  4499. if (pos < buf_size()) {
  4500. if (!content_callback(buf_data(), pos)) {
  4501. is_valid_ = false;
  4502. return false;
  4503. }
  4504. buf_erase(pos + crlf_dash_boundary_.size());
  4505. state_ = 4;
  4506. } else {
  4507. auto len = buf_size() - crlf_dash_boundary_.size();
  4508. if (len > 0) {
  4509. if (!content_callback(buf_data(), len)) {
  4510. is_valid_ = false;
  4511. return false;
  4512. }
  4513. buf_erase(len);
  4514. }
  4515. return true;
  4516. }
  4517. break;
  4518. }
  4519. case 4: { // Boundary
  4520. if (crlf_.size() > buf_size()) { return true; }
  4521. if (buf_start_with(crlf_)) {
  4522. buf_erase(crlf_.size());
  4523. state_ = 1;
  4524. } else {
  4525. if (dash_.size() > buf_size()) { return true; }
  4526. if (buf_start_with(dash_)) {
  4527. buf_erase(dash_.size());
  4528. is_valid_ = true;
  4529. buf_erase(buf_size()); // Remove epilogue
  4530. } else {
  4531. return true;
  4532. }
  4533. }
  4534. break;
  4535. }
  4536. }
  4537. }
  4538. return true;
  4539. }
  4540. private:
  4541. void clear_file_info() {
  4542. file_.name.clear();
  4543. file_.filename.clear();
  4544. file_.content_type.clear();
  4545. file_.headers.clear();
  4546. }
  4547. bool start_with_case_ignore(const std::string &a, const char *b) const {
  4548. const auto b_len = strlen(b);
  4549. if (a.size() < b_len) { return false; }
  4550. for (size_t i = 0; i < b_len; i++) {
  4551. if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) {
  4552. return false;
  4553. }
  4554. }
  4555. return true;
  4556. }
  4557. const std::string dash_ = "--";
  4558. const std::string crlf_ = "\r\n";
  4559. std::string boundary_;
  4560. std::string dash_boundary_crlf_;
  4561. std::string crlf_dash_boundary_;
  4562. size_t state_ = 0;
  4563. bool is_valid_ = false;
  4564. MultipartFormData file_;
  4565. // Buffer
  4566. bool start_with(const std::string &a, size_t spos, size_t epos,
  4567. const std::string &b) const {
  4568. if (epos - spos < b.size()) { return false; }
  4569. for (size_t i = 0; i < b.size(); i++) {
  4570. if (a[i + spos] != b[i]) { return false; }
  4571. }
  4572. return true;
  4573. }
  4574. size_t buf_size() const { return buf_epos_ - buf_spos_; }
  4575. const char *buf_data() const { return &buf_[buf_spos_]; }
  4576. std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); }
  4577. bool buf_start_with(const std::string &s) const {
  4578. return start_with(buf_, buf_spos_, buf_epos_, s);
  4579. }
  4580. size_t buf_find(const std::string &s) const {
  4581. auto c = s.front();
  4582. size_t off = buf_spos_;
  4583. while (off < buf_epos_) {
  4584. auto pos = off;
  4585. while (true) {
  4586. if (pos == buf_epos_) { return buf_size(); }
  4587. if (buf_[pos] == c) { break; }
  4588. pos++;
  4589. }
  4590. auto remaining_size = buf_epos_ - pos;
  4591. if (s.size() > remaining_size) { return buf_size(); }
  4592. if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; }
  4593. off = pos + 1;
  4594. }
  4595. return buf_size();
  4596. }
  4597. void buf_append(const char *data, size_t n) {
  4598. auto remaining_size = buf_size();
  4599. if (remaining_size > 0 && buf_spos_ > 0) {
  4600. for (size_t i = 0; i < remaining_size; i++) {
  4601. buf_[i] = buf_[buf_spos_ + i];
  4602. }
  4603. }
  4604. buf_spos_ = 0;
  4605. buf_epos_ = remaining_size;
  4606. if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); }
  4607. for (size_t i = 0; i < n; i++) {
  4608. buf_[buf_epos_ + i] = data[i];
  4609. }
  4610. buf_epos_ += n;
  4611. }
  4612. void buf_erase(size_t size) { buf_spos_ += size; }
  4613. std::string buf_;
  4614. size_t buf_spos_ = 0;
  4615. size_t buf_epos_ = 0;
  4616. };
  4617. inline std::string random_string(size_t length) {
  4618. constexpr const char data[] =
  4619. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  4620. thread_local auto engine([]() {
  4621. // std::random_device might actually be deterministic on some
  4622. // platforms, but due to lack of support in the c++ standard library,
  4623. // doing better requires either some ugly hacks or breaking portability.
  4624. std::random_device seed_gen;
  4625. // Request 128 bits of entropy for initialization
  4626. std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
  4627. return std::mt19937(seed_sequence);
  4628. }());
  4629. std::string result;
  4630. for (size_t i = 0; i < length; i++) {
  4631. result += data[engine() % (sizeof(data) - 1)];
  4632. }
  4633. return result;
  4634. }
  4635. inline std::string make_multipart_data_boundary() {
  4636. return "--cpp-httplib-multipart-data-" + detail::random_string(16);
  4637. }
  4638. inline bool is_multipart_boundary_chars_valid(const std::string &boundary) {
  4639. auto valid = true;
  4640. for (size_t i = 0; i < boundary.size(); i++) {
  4641. auto c = boundary[i];
  4642. if (!std::isalnum(c) && c != '-' && c != '_') {
  4643. valid = false;
  4644. break;
  4645. }
  4646. }
  4647. return valid;
  4648. }
  4649. template <typename T>
  4650. inline std::string
  4651. serialize_multipart_formdata_item_begin(const T &item,
  4652. const std::string &boundary) {
  4653. std::string body = "--" + boundary + "\r\n";
  4654. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4655. if (!item.filename.empty()) {
  4656. body += "; filename=\"" + item.filename + "\"";
  4657. }
  4658. body += "\r\n";
  4659. if (!item.content_type.empty()) {
  4660. body += "Content-Type: " + item.content_type + "\r\n";
  4661. }
  4662. body += "\r\n";
  4663. return body;
  4664. }
  4665. inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; }
  4666. inline std::string
  4667. serialize_multipart_formdata_finish(const std::string &boundary) {
  4668. return "--" + boundary + "--\r\n";
  4669. }
  4670. inline std::string
  4671. serialize_multipart_formdata_get_content_type(const std::string &boundary) {
  4672. return "multipart/form-data; boundary=" + boundary;
  4673. }
  4674. inline std::string
  4675. serialize_multipart_formdata(const MultipartFormDataItemsForClientInput &items,
  4676. const std::string &boundary, bool finish = true) {
  4677. std::string body;
  4678. for (const auto &item : items) {
  4679. body += serialize_multipart_formdata_item_begin(item, boundary);
  4680. body += item.content + serialize_multipart_formdata_item_end();
  4681. }
  4682. if (finish) { body += serialize_multipart_formdata_finish(boundary); }
  4683. return body;
  4684. }
  4685. inline void coalesce_ranges(Ranges &ranges, size_t content_length) {
  4686. if (ranges.size() <= 1) return;
  4687. // Sort ranges by start position
  4688. std::sort(ranges.begin(), ranges.end(),
  4689. [](const Range &a, const Range &b) { return a.first < b.first; });
  4690. Ranges coalesced;
  4691. coalesced.reserve(ranges.size());
  4692. for (auto &r : ranges) {
  4693. auto first_pos = r.first;
  4694. auto last_pos = r.second;
  4695. // Handle special cases like in range_error
  4696. if (first_pos == -1 && last_pos == -1) {
  4697. first_pos = 0;
  4698. last_pos = static_cast<ssize_t>(content_length);
  4699. }
  4700. if (first_pos == -1) {
  4701. first_pos = static_cast<ssize_t>(content_length) - last_pos;
  4702. last_pos = static_cast<ssize_t>(content_length) - 1;
  4703. }
  4704. if (last_pos == -1 || last_pos >= static_cast<ssize_t>(content_length)) {
  4705. last_pos = static_cast<ssize_t>(content_length) - 1;
  4706. }
  4707. // Skip invalid ranges
  4708. if (!(0 <= first_pos && first_pos <= last_pos &&
  4709. last_pos < static_cast<ssize_t>(content_length))) {
  4710. continue;
  4711. }
  4712. // Coalesce with previous range if overlapping or adjacent (but not
  4713. // identical)
  4714. if (!coalesced.empty()) {
  4715. auto &prev = coalesced.back();
  4716. // Check if current range overlaps or is adjacent to previous range
  4717. // but don't coalesce identical ranges (allow duplicates)
  4718. if (first_pos <= prev.second + 1 &&
  4719. !(first_pos == prev.first && last_pos == prev.second)) {
  4720. // Extend the previous range
  4721. prev.second = (std::max)(prev.second, last_pos);
  4722. continue;
  4723. }
  4724. }
  4725. // Add new range
  4726. coalesced.emplace_back(first_pos, last_pos);
  4727. }
  4728. ranges = std::move(coalesced);
  4729. }
  4730. inline bool range_error(Request &req, Response &res) {
  4731. if (!req.ranges.empty() && 200 <= res.status && res.status < 300) {
  4732. ssize_t content_len = static_cast<ssize_t>(
  4733. res.content_length_ ? res.content_length_ : res.body.size());
  4734. std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
  4735. size_t overwrapping_count = 0;
  4736. // NOTE: The following Range check is based on '14.2. Range' in RFC 9110
  4737. // 'HTTP Semantics' to avoid potential denial-of-service attacks.
  4738. // https://www.rfc-editor.org/rfc/rfc9110#section-14.2
  4739. // Too many ranges
  4740. if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; }
  4741. for (auto &r : req.ranges) {
  4742. auto &first_pos = r.first;
  4743. auto &last_pos = r.second;
  4744. if (first_pos == -1 && last_pos == -1) {
  4745. first_pos = 0;
  4746. last_pos = content_len;
  4747. }
  4748. if (first_pos == -1) {
  4749. first_pos = content_len - last_pos;
  4750. last_pos = content_len - 1;
  4751. }
  4752. // NOTE: RFC-9110 '14.1.2. Byte Ranges':
  4753. // A client can limit the number of bytes requested without knowing the
  4754. // size of the selected representation. If the last-pos value is absent,
  4755. // or if the value is greater than or equal to the current length of the
  4756. // representation data, the byte range is interpreted as the remainder of
  4757. // the representation (i.e., the server replaces the value of last-pos
  4758. // with a value that is one less than the current length of the selected
  4759. // representation).
  4760. // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6
  4761. if (last_pos == -1 || last_pos >= content_len) {
  4762. last_pos = content_len - 1;
  4763. }
  4764. // Range must be within content length
  4765. if (!(0 <= first_pos && first_pos <= last_pos &&
  4766. last_pos <= content_len - 1)) {
  4767. return true;
  4768. }
  4769. // Request must not have more than two overlapping ranges
  4770. for (const auto &processed_range : processed_ranges) {
  4771. if (!(last_pos < processed_range.first ||
  4772. first_pos > processed_range.second)) {
  4773. overwrapping_count++;
  4774. if (overwrapping_count > 2) { return true; }
  4775. break; // Only count once per range
  4776. }
  4777. }
  4778. processed_ranges.emplace_back(first_pos, last_pos);
  4779. }
  4780. // After validation, coalesce overlapping ranges as per RFC 9110
  4781. coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
  4782. }
  4783. return false;
  4784. }
  4785. inline std::pair<size_t, size_t>
  4786. get_range_offset_and_length(Range r, size_t content_length) {
  4787. assert(r.first != -1 && r.second != -1);
  4788. assert(0 <= r.first && r.first < static_cast<ssize_t>(content_length));
  4789. assert(r.first <= r.second &&
  4790. r.second < static_cast<ssize_t>(content_length));
  4791. (void)(content_length);
  4792. return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
  4793. }
  4794. inline std::string make_content_range_header_field(
  4795. const std::pair<size_t, size_t> &offset_and_length, size_t content_length) {
  4796. auto st = offset_and_length.first;
  4797. auto ed = st + offset_and_length.second - 1;
  4798. std::string field = "bytes ";
  4799. field += std::to_string(st);
  4800. field += "-";
  4801. field += std::to_string(ed);
  4802. field += "/";
  4803. field += std::to_string(content_length);
  4804. return field;
  4805. }
  4806. template <typename SToken, typename CToken, typename Content>
  4807. bool process_multipart_ranges_data(const Request &req,
  4808. const std::string &boundary,
  4809. const std::string &content_type,
  4810. size_t content_length, SToken stoken,
  4811. CToken ctoken, Content content) {
  4812. for (size_t i = 0; i < req.ranges.size(); i++) {
  4813. ctoken("--");
  4814. stoken(boundary);
  4815. ctoken("\r\n");
  4816. if (!content_type.empty()) {
  4817. ctoken("Content-Type: ");
  4818. stoken(content_type);
  4819. ctoken("\r\n");
  4820. }
  4821. auto offset_and_length =
  4822. get_range_offset_and_length(req.ranges[i], content_length);
  4823. ctoken("Content-Range: ");
  4824. stoken(make_content_range_header_field(offset_and_length, content_length));
  4825. ctoken("\r\n");
  4826. ctoken("\r\n");
  4827. if (!content(offset_and_length.first, offset_and_length.second)) {
  4828. return false;
  4829. }
  4830. ctoken("\r\n");
  4831. }
  4832. ctoken("--");
  4833. stoken(boundary);
  4834. ctoken("--");
  4835. return true;
  4836. }
  4837. inline void make_multipart_ranges_data(const Request &req, Response &res,
  4838. const std::string &boundary,
  4839. const std::string &content_type,
  4840. size_t content_length,
  4841. std::string &data) {
  4842. process_multipart_ranges_data(
  4843. req, boundary, content_type, content_length,
  4844. [&](const std::string &token) { data += token; },
  4845. [&](const std::string &token) { data += token; },
  4846. [&](size_t offset, size_t length) {
  4847. assert(offset + length <= content_length);
  4848. data += res.body.substr(offset, length);
  4849. return true;
  4850. });
  4851. }
  4852. inline size_t get_multipart_ranges_data_length(const Request &req,
  4853. const std::string &boundary,
  4854. const std::string &content_type,
  4855. size_t content_length) {
  4856. size_t data_length = 0;
  4857. process_multipart_ranges_data(
  4858. req, boundary, content_type, content_length,
  4859. [&](const std::string &token) { data_length += token.size(); },
  4860. [&](const std::string &token) { data_length += token.size(); },
  4861. [&](size_t /*offset*/, size_t length) {
  4862. data_length += length;
  4863. return true;
  4864. });
  4865. return data_length;
  4866. }
  4867. template <typename T>
  4868. inline bool
  4869. write_multipart_ranges_data(Stream &strm, const Request &req, Response &res,
  4870. const std::string &boundary,
  4871. const std::string &content_type,
  4872. size_t content_length, const T &is_shutting_down) {
  4873. return process_multipart_ranges_data(
  4874. req, boundary, content_type, content_length,
  4875. [&](const std::string &token) { strm.write(token); },
  4876. [&](const std::string &token) { strm.write(token); },
  4877. [&](size_t offset, size_t length) {
  4878. return write_content(strm, res.content_provider_, offset, length,
  4879. is_shutting_down);
  4880. });
  4881. }
  4882. inline bool expect_content(const Request &req) {
  4883. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  4884. req.method == "DELETE") {
  4885. return true;
  4886. }
  4887. if (req.has_header("Content-Length") &&
  4888. req.get_header_value_u64("Content-Length") > 0) {
  4889. return true;
  4890. }
  4891. if (is_chunked_transfer_encoding(req.headers)) { return true; }
  4892. return false;
  4893. }
  4894. inline bool has_crlf(const std::string &s) {
  4895. auto p = s.c_str();
  4896. while (*p) {
  4897. if (*p == '\r' || *p == '\n') { return true; }
  4898. p++;
  4899. }
  4900. return false;
  4901. }
  4902. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4903. inline std::string message_digest(const std::string &s, const EVP_MD *algo) {
  4904. auto context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>(
  4905. EVP_MD_CTX_new(), EVP_MD_CTX_free);
  4906. unsigned int hash_length = 0;
  4907. unsigned char hash[EVP_MAX_MD_SIZE];
  4908. EVP_DigestInit_ex(context.get(), algo, nullptr);
  4909. EVP_DigestUpdate(context.get(), s.c_str(), s.size());
  4910. EVP_DigestFinal_ex(context.get(), hash, &hash_length);
  4911. std::stringstream ss;
  4912. for (auto i = 0u; i < hash_length; ++i) {
  4913. ss << std::hex << std::setw(2) << std::setfill('0')
  4914. << static_cast<unsigned int>(hash[i]);
  4915. }
  4916. return ss.str();
  4917. }
  4918. inline std::string MD5(const std::string &s) {
  4919. return message_digest(s, EVP_md5());
  4920. }
  4921. inline std::string SHA_256(const std::string &s) {
  4922. return message_digest(s, EVP_sha256());
  4923. }
  4924. inline std::string SHA_512(const std::string &s) {
  4925. return message_digest(s, EVP_sha512());
  4926. }
  4927. inline std::pair<std::string, std::string> make_digest_authentication_header(
  4928. const Request &req, const std::map<std::string, std::string> &auth,
  4929. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  4930. const std::string &password, bool is_proxy = false) {
  4931. std::string nc;
  4932. {
  4933. std::stringstream ss;
  4934. ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count;
  4935. nc = ss.str();
  4936. }
  4937. std::string qop;
  4938. if (auth.find("qop") != auth.end()) {
  4939. qop = auth.at("qop");
  4940. if (qop.find("auth-int") != std::string::npos) {
  4941. qop = "auth-int";
  4942. } else if (qop.find("auth") != std::string::npos) {
  4943. qop = "auth";
  4944. } else {
  4945. qop.clear();
  4946. }
  4947. }
  4948. std::string algo = "MD5";
  4949. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  4950. std::string response;
  4951. {
  4952. auto H = algo == "SHA-256" ? detail::SHA_256
  4953. : algo == "SHA-512" ? detail::SHA_512
  4954. : detail::MD5;
  4955. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  4956. auto A2 = req.method + ":" + req.path;
  4957. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  4958. if (qop.empty()) {
  4959. response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2));
  4960. } else {
  4961. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  4962. ":" + qop + ":" + H(A2));
  4963. }
  4964. }
  4965. auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : "";
  4966. auto field = "Digest username=\"" + username + "\", realm=\"" +
  4967. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  4968. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  4969. (qop.empty() ? ", response=\""
  4970. : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" +
  4971. cnonce + "\", response=\"") +
  4972. response + "\"" +
  4973. (opaque.empty() ? "" : ", opaque=\"" + opaque + "\"");
  4974. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  4975. return std::make_pair(key, field);
  4976. }
  4977. inline bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) {
  4978. detail::set_nonblocking(sock, true);
  4979. auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); });
  4980. char buf[1];
  4981. return !SSL_peek(ssl, buf, 1) &&
  4982. SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN;
  4983. }
  4984. #ifdef _WIN32
  4985. // NOTE: This code came up with the following stackoverflow post:
  4986. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  4987. inline bool load_system_certs_on_windows(X509_STORE *store) {
  4988. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  4989. if (!hStore) { return false; }
  4990. auto result = false;
  4991. PCCERT_CONTEXT pContext = NULL;
  4992. while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
  4993. nullptr) {
  4994. auto encoded_cert =
  4995. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  4996. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  4997. if (x509) {
  4998. X509_STORE_add_cert(store, x509);
  4999. X509_free(x509);
  5000. result = true;
  5001. }
  5002. }
  5003. CertFreeCertificateContext(pContext);
  5004. CertCloseStore(hStore, 0);
  5005. return result;
  5006. }
  5007. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  5008. defined(TARGET_OS_OSX)
  5009. template <typename T>
  5010. using CFObjectPtr =
  5011. std::unique_ptr<typename std::remove_pointer<T>::type, void (*)(CFTypeRef)>;
  5012. inline void cf_object_ptr_deleter(CFTypeRef obj) {
  5013. if (obj) { CFRelease(obj); }
  5014. }
  5015. inline bool retrieve_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5016. CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef};
  5017. CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll,
  5018. kCFBooleanTrue};
  5019. CFObjectPtr<CFDictionaryRef> query(
  5020. CFDictionaryCreate(nullptr, reinterpret_cast<const void **>(keys), values,
  5021. sizeof(keys) / sizeof(keys[0]),
  5022. &kCFTypeDictionaryKeyCallBacks,
  5023. &kCFTypeDictionaryValueCallBacks),
  5024. cf_object_ptr_deleter);
  5025. if (!query) { return false; }
  5026. CFTypeRef security_items = nullptr;
  5027. if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess ||
  5028. CFArrayGetTypeID() != CFGetTypeID(security_items)) {
  5029. return false;
  5030. }
  5031. certs.reset(reinterpret_cast<CFArrayRef>(security_items));
  5032. return true;
  5033. }
  5034. inline bool retrieve_root_certs_from_keychain(CFObjectPtr<CFArrayRef> &certs) {
  5035. CFArrayRef root_security_items = nullptr;
  5036. if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) {
  5037. return false;
  5038. }
  5039. certs.reset(root_security_items);
  5040. return true;
  5041. }
  5042. inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) {
  5043. auto result = false;
  5044. for (auto i = 0; i < CFArrayGetCount(certs); ++i) {
  5045. const auto cert = reinterpret_cast<const __SecCertificate *>(
  5046. CFArrayGetValueAtIndex(certs, i));
  5047. if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; }
  5048. CFDataRef cert_data = nullptr;
  5049. if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) !=
  5050. errSecSuccess) {
  5051. continue;
  5052. }
  5053. CFObjectPtr<CFDataRef> cert_data_ptr(cert_data, cf_object_ptr_deleter);
  5054. auto encoded_cert = static_cast<const unsigned char *>(
  5055. CFDataGetBytePtr(cert_data_ptr.get()));
  5056. auto x509 =
  5057. d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get()));
  5058. if (x509) {
  5059. X509_STORE_add_cert(store, x509);
  5060. X509_free(x509);
  5061. result = true;
  5062. }
  5063. }
  5064. return result;
  5065. }
  5066. inline bool load_system_certs_on_macos(X509_STORE *store) {
  5067. auto result = false;
  5068. CFObjectPtr<CFArrayRef> certs(nullptr, cf_object_ptr_deleter);
  5069. if (retrieve_certs_from_keychain(certs) && certs) {
  5070. result = add_certs_to_x509_store(certs.get(), store);
  5071. }
  5072. if (retrieve_root_certs_from_keychain(certs) && certs) {
  5073. result = add_certs_to_x509_store(certs.get(), store) || result;
  5074. }
  5075. return result;
  5076. }
  5077. #endif // _WIN32
  5078. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  5079. #ifdef _WIN32
  5080. class WSInit {
  5081. public:
  5082. WSInit() {
  5083. WSADATA wsaData;
  5084. if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true;
  5085. }
  5086. ~WSInit() {
  5087. if (is_valid_) WSACleanup();
  5088. }
  5089. bool is_valid_ = false;
  5090. };
  5091. static WSInit wsinit_;
  5092. #endif
  5093. inline bool parse_www_authenticate(const Response &res,
  5094. std::map<std::string, std::string> &auth,
  5095. bool is_proxy) {
  5096. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  5097. if (res.has_header(auth_key)) {
  5098. thread_local auto re =
  5099. std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  5100. auto s = res.get_header_value(auth_key);
  5101. auto pos = s.find(' ');
  5102. if (pos != std::string::npos) {
  5103. auto type = s.substr(0, pos);
  5104. if (type == "Basic") {
  5105. return false;
  5106. } else if (type == "Digest") {
  5107. s = s.substr(pos + 1);
  5108. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  5109. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  5110. const auto &m = *i;
  5111. auto key = s.substr(static_cast<size_t>(m.position(1)),
  5112. static_cast<size_t>(m.length(1)));
  5113. auto val = m.length(2) > 0
  5114. ? s.substr(static_cast<size_t>(m.position(2)),
  5115. static_cast<size_t>(m.length(2)))
  5116. : s.substr(static_cast<size_t>(m.position(3)),
  5117. static_cast<size_t>(m.length(3)));
  5118. auth[key] = val;
  5119. }
  5120. return true;
  5121. }
  5122. }
  5123. }
  5124. return false;
  5125. }
  5126. class ContentProviderAdapter {
  5127. public:
  5128. explicit ContentProviderAdapter(
  5129. ContentProviderWithoutLength &&content_provider)
  5130. : content_provider_(content_provider) {}
  5131. bool operator()(size_t offset, size_t, DataSink &sink) {
  5132. return content_provider_(offset, sink);
  5133. }
  5134. private:
  5135. ContentProviderWithoutLength content_provider_;
  5136. };
  5137. } // namespace detail
  5138. inline std::string hosted_at(const std::string &hostname) {
  5139. std::vector<std::string> addrs;
  5140. hosted_at(hostname, addrs);
  5141. if (addrs.empty()) { return std::string(); }
  5142. return addrs[0];
  5143. }
  5144. inline void hosted_at(const std::string &hostname,
  5145. std::vector<std::string> &addrs) {
  5146. struct addrinfo hints;
  5147. struct addrinfo *result;
  5148. memset(&hints, 0, sizeof(struct addrinfo));
  5149. hints.ai_family = AF_UNSPEC;
  5150. hints.ai_socktype = SOCK_STREAM;
  5151. hints.ai_protocol = 0;
  5152. if (detail::getaddrinfo_with_timeout(hostname.c_str(), nullptr, &hints,
  5153. &result, 0)) {
  5154. #if defined __linux__ && !defined __ANDROID__
  5155. res_init();
  5156. #endif
  5157. return;
  5158. }
  5159. auto se = detail::scope_exit([&] { freeaddrinfo(result); });
  5160. for (auto rp = result; rp; rp = rp->ai_next) {
  5161. const auto &addr =
  5162. *reinterpret_cast<struct sockaddr_storage *>(rp->ai_addr);
  5163. std::string ip;
  5164. auto dummy = -1;
  5165. if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip,
  5166. dummy)) {
  5167. addrs.push_back(ip);
  5168. }
  5169. }
  5170. }
  5171. inline std::string append_query_params(const std::string &path,
  5172. const Params &params) {
  5173. std::string path_with_query = path;
  5174. thread_local const std::regex re("[^?]+\\?.*");
  5175. auto delm = std::regex_match(path, re) ? '&' : '?';
  5176. path_with_query += delm + detail::params_to_query_str(params);
  5177. return path_with_query;
  5178. }
  5179. // Header utilities
  5180. inline std::pair<std::string, std::string>
  5181. make_range_header(const Ranges &ranges) {
  5182. std::string field = "bytes=";
  5183. auto i = 0;
  5184. for (const auto &r : ranges) {
  5185. if (i != 0) { field += ", "; }
  5186. if (r.first != -1) { field += std::to_string(r.first); }
  5187. field += '-';
  5188. if (r.second != -1) { field += std::to_string(r.second); }
  5189. i++;
  5190. }
  5191. return std::make_pair("Range", std::move(field));
  5192. }
  5193. inline std::pair<std::string, std::string>
  5194. make_basic_authentication_header(const std::string &username,
  5195. const std::string &password, bool is_proxy) {
  5196. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  5197. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5198. return std::make_pair(key, std::move(field));
  5199. }
  5200. inline std::pair<std::string, std::string>
  5201. make_bearer_token_authentication_header(const std::string &token,
  5202. bool is_proxy = false) {
  5203. auto field = "Bearer " + token;
  5204. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  5205. return std::make_pair(key, std::move(field));
  5206. }
  5207. // Request implementation
  5208. inline bool Request::has_header(const std::string &key) const {
  5209. return detail::has_header(headers, key);
  5210. }
  5211. inline std::string Request::get_header_value(const std::string &key,
  5212. const char *def, size_t id) const {
  5213. return detail::get_header_value(headers, key, def, id);
  5214. }
  5215. inline size_t Request::get_header_value_count(const std::string &key) const {
  5216. auto r = headers.equal_range(key);
  5217. return static_cast<size_t>(std::distance(r.first, r.second));
  5218. }
  5219. inline void Request::set_header(const std::string &key,
  5220. const std::string &val) {
  5221. if (detail::fields::is_field_name(key) &&
  5222. detail::fields::is_field_value(val)) {
  5223. headers.emplace(key, val);
  5224. }
  5225. }
  5226. inline bool Request::has_param(const std::string &key) const {
  5227. return params.find(key) != params.end();
  5228. }
  5229. inline std::string Request::get_param_value(const std::string &key,
  5230. size_t id) const {
  5231. auto rng = params.equal_range(key);
  5232. auto it = rng.first;
  5233. std::advance(it, static_cast<ssize_t>(id));
  5234. if (it != rng.second) { return it->second; }
  5235. return std::string();
  5236. }
  5237. inline size_t Request::get_param_value_count(const std::string &key) const {
  5238. auto r = params.equal_range(key);
  5239. return static_cast<size_t>(std::distance(r.first, r.second));
  5240. }
  5241. inline bool Request::is_multipart_form_data() const {
  5242. const auto &content_type = get_header_value("Content-Type");
  5243. return !content_type.rfind("multipart/form-data", 0);
  5244. }
  5245. inline bool Request::has_file(const std::string &key) const {
  5246. return files.find(key) != files.end();
  5247. }
  5248. inline MultipartFormData Request::get_file_value(const std::string &key) const {
  5249. auto it = files.find(key);
  5250. if (it != files.end()) { return it->second; }
  5251. return MultipartFormData();
  5252. }
  5253. inline std::vector<MultipartFormData>
  5254. Request::get_file_values(const std::string &key) const {
  5255. std::vector<MultipartFormData> values;
  5256. auto rng = files.equal_range(key);
  5257. for (auto it = rng.first; it != rng.second; it++) {
  5258. values.push_back(it->second);
  5259. }
  5260. return values;
  5261. }
  5262. // Response implementation
  5263. inline bool Response::has_header(const std::string &key) const {
  5264. return headers.find(key) != headers.end();
  5265. }
  5266. inline std::string Response::get_header_value(const std::string &key,
  5267. const char *def,
  5268. size_t id) const {
  5269. return detail::get_header_value(headers, key, def, id);
  5270. }
  5271. inline size_t Response::get_header_value_count(const std::string &key) const {
  5272. auto r = headers.equal_range(key);
  5273. return static_cast<size_t>(std::distance(r.first, r.second));
  5274. }
  5275. inline void Response::set_header(const std::string &key,
  5276. const std::string &val) {
  5277. if (detail::fields::is_field_name(key) &&
  5278. detail::fields::is_field_value(val)) {
  5279. headers.emplace(key, val);
  5280. }
  5281. }
  5282. inline void Response::set_redirect(const std::string &url, int stat) {
  5283. if (detail::fields::is_field_value(url)) {
  5284. set_header("Location", url);
  5285. if (300 <= stat && stat < 400) {
  5286. this->status = stat;
  5287. } else {
  5288. this->status = StatusCode::Found_302;
  5289. }
  5290. }
  5291. }
  5292. inline void Response::set_content(const char *s, size_t n,
  5293. const std::string &content_type) {
  5294. body.assign(s, n);
  5295. auto rng = headers.equal_range("Content-Type");
  5296. headers.erase(rng.first, rng.second);
  5297. set_header("Content-Type", content_type);
  5298. }
  5299. inline void Response::set_content(const std::string &s,
  5300. const std::string &content_type) {
  5301. set_content(s.data(), s.size(), content_type);
  5302. }
  5303. inline void Response::set_content(std::string &&s,
  5304. const std::string &content_type) {
  5305. body = std::move(s);
  5306. auto rng = headers.equal_range("Content-Type");
  5307. headers.erase(rng.first, rng.second);
  5308. set_header("Content-Type", content_type);
  5309. }
  5310. inline void Response::set_content_provider(
  5311. size_t in_length, const std::string &content_type, ContentProvider provider,
  5312. ContentProviderResourceReleaser resource_releaser) {
  5313. set_header("Content-Type", content_type);
  5314. content_length_ = in_length;
  5315. if (in_length > 0) { content_provider_ = std::move(provider); }
  5316. content_provider_resource_releaser_ = std::move(resource_releaser);
  5317. is_chunked_content_provider_ = false;
  5318. }
  5319. inline void Response::set_content_provider(
  5320. const std::string &content_type, ContentProviderWithoutLength provider,
  5321. ContentProviderResourceReleaser resource_releaser) {
  5322. set_header("Content-Type", content_type);
  5323. content_length_ = 0;
  5324. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5325. content_provider_resource_releaser_ = std::move(resource_releaser);
  5326. is_chunked_content_provider_ = false;
  5327. }
  5328. inline void Response::set_chunked_content_provider(
  5329. const std::string &content_type, ContentProviderWithoutLength provider,
  5330. ContentProviderResourceReleaser resource_releaser) {
  5331. set_header("Content-Type", content_type);
  5332. content_length_ = 0;
  5333. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  5334. content_provider_resource_releaser_ = std::move(resource_releaser);
  5335. is_chunked_content_provider_ = true;
  5336. }
  5337. inline void Response::set_file_content(const std::string &path,
  5338. const std::string &content_type) {
  5339. file_content_path_ = path;
  5340. file_content_content_type_ = content_type;
  5341. }
  5342. inline void Response::set_file_content(const std::string &path) {
  5343. file_content_path_ = path;
  5344. }
  5345. // Result implementation
  5346. inline bool Result::has_request_header(const std::string &key) const {
  5347. return request_headers_.find(key) != request_headers_.end();
  5348. }
  5349. inline std::string Result::get_request_header_value(const std::string &key,
  5350. const char *def,
  5351. size_t id) const {
  5352. return detail::get_header_value(request_headers_, key, def, id);
  5353. }
  5354. inline size_t
  5355. Result::get_request_header_value_count(const std::string &key) const {
  5356. auto r = request_headers_.equal_range(key);
  5357. return static_cast<size_t>(std::distance(r.first, r.second));
  5358. }
  5359. // Stream implementation
  5360. inline ssize_t Stream::write(const char *ptr) {
  5361. return write(ptr, strlen(ptr));
  5362. }
  5363. inline ssize_t Stream::write(const std::string &s) {
  5364. return write(s.data(), s.size());
  5365. }
  5366. namespace detail {
  5367. inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec,
  5368. time_t timeout_sec, time_t timeout_usec,
  5369. time_t &actual_timeout_sec,
  5370. time_t &actual_timeout_usec) {
  5371. auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000);
  5372. auto actual_timeout_msec =
  5373. (std::min)(max_timeout_msec - duration_msec, timeout_msec);
  5374. if (actual_timeout_msec < 0) { actual_timeout_msec = 0; }
  5375. actual_timeout_sec = actual_timeout_msec / 1000;
  5376. actual_timeout_usec = (actual_timeout_msec % 1000) * 1000;
  5377. }
  5378. // Socket stream implementation
  5379. inline SocketStream::SocketStream(
  5380. socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  5381. time_t write_timeout_sec, time_t write_timeout_usec,
  5382. time_t max_timeout_msec,
  5383. std::chrono::time_point<std::chrono::steady_clock> start_time)
  5384. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  5385. read_timeout_usec_(read_timeout_usec),
  5386. write_timeout_sec_(write_timeout_sec),
  5387. write_timeout_usec_(write_timeout_usec),
  5388. max_timeout_msec_(max_timeout_msec), start_time_(start_time),
  5389. read_buff_(read_buff_size_, 0) {}
  5390. inline SocketStream::~SocketStream() = default;
  5391. inline bool SocketStream::is_readable() const {
  5392. return read_buff_off_ < read_buff_content_size_;
  5393. }
  5394. inline bool SocketStream::wait_readable() const {
  5395. if (max_timeout_msec_ <= 0) {
  5396. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  5397. }
  5398. time_t read_timeout_sec;
  5399. time_t read_timeout_usec;
  5400. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  5401. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  5402. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  5403. }
  5404. inline bool SocketStream::wait_writable() const {
  5405. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  5406. is_socket_alive(sock_);
  5407. }
  5408. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  5409. #ifdef _WIN32
  5410. size =
  5411. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5412. #else
  5413. size = (std::min)(size,
  5414. static_cast<size_t>((std::numeric_limits<ssize_t>::max)()));
  5415. #endif
  5416. if (read_buff_off_ < read_buff_content_size_) {
  5417. auto remaining_size = read_buff_content_size_ - read_buff_off_;
  5418. if (size <= remaining_size) {
  5419. memcpy(ptr, read_buff_.data() + read_buff_off_, size);
  5420. read_buff_off_ += size;
  5421. return static_cast<ssize_t>(size);
  5422. } else {
  5423. memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size);
  5424. read_buff_off_ += remaining_size;
  5425. return static_cast<ssize_t>(remaining_size);
  5426. }
  5427. }
  5428. if (!wait_readable()) { return -1; }
  5429. read_buff_off_ = 0;
  5430. read_buff_content_size_ = 0;
  5431. if (size < read_buff_size_) {
  5432. auto n = read_socket(sock_, read_buff_.data(), read_buff_size_,
  5433. CPPHTTPLIB_RECV_FLAGS);
  5434. if (n <= 0) {
  5435. return n;
  5436. } else if (n <= static_cast<ssize_t>(size)) {
  5437. memcpy(ptr, read_buff_.data(), static_cast<size_t>(n));
  5438. return n;
  5439. } else {
  5440. memcpy(ptr, read_buff_.data(), size);
  5441. read_buff_off_ = size;
  5442. read_buff_content_size_ = static_cast<size_t>(n);
  5443. return static_cast<ssize_t>(size);
  5444. }
  5445. } else {
  5446. return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS);
  5447. }
  5448. }
  5449. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  5450. if (!wait_writable()) { return -1; }
  5451. #if defined(_WIN32) && !defined(_WIN64)
  5452. size =
  5453. (std::min)(size, static_cast<size_t>((std::numeric_limits<int>::max)()));
  5454. #endif
  5455. return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS);
  5456. }
  5457. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  5458. int &port) const {
  5459. return detail::get_remote_ip_and_port(sock_, ip, port);
  5460. }
  5461. inline void SocketStream::get_local_ip_and_port(std::string &ip,
  5462. int &port) const {
  5463. return detail::get_local_ip_and_port(sock_, ip, port);
  5464. }
  5465. inline socket_t SocketStream::socket() const { return sock_; }
  5466. inline time_t SocketStream::duration() const {
  5467. return std::chrono::duration_cast<std::chrono::milliseconds>(
  5468. std::chrono::steady_clock::now() - start_time_)
  5469. .count();
  5470. }
  5471. // Buffer stream implementation
  5472. inline bool BufferStream::is_readable() const { return true; }
  5473. inline bool BufferStream::wait_readable() const { return true; }
  5474. inline bool BufferStream::wait_writable() const { return true; }
  5475. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  5476. #if defined(_MSC_VER) && _MSC_VER < 1910
  5477. auto len_read = buffer._Copy_s(ptr, size, size, position);
  5478. #else
  5479. auto len_read = buffer.copy(ptr, size, position);
  5480. #endif
  5481. position += static_cast<size_t>(len_read);
  5482. return static_cast<ssize_t>(len_read);
  5483. }
  5484. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  5485. buffer.append(ptr, size);
  5486. return static_cast<ssize_t>(size);
  5487. }
  5488. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  5489. int & /*port*/) const {}
  5490. inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/,
  5491. int & /*port*/) const {}
  5492. inline socket_t BufferStream::socket() const { return 0; }
  5493. inline time_t BufferStream::duration() const { return 0; }
  5494. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  5495. inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern)
  5496. : MatcherBase(pattern) {
  5497. constexpr const char marker[] = "/:";
  5498. // One past the last ending position of a path param substring
  5499. std::size_t last_param_end = 0;
  5500. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5501. // Needed to ensure that parameter names are unique during matcher
  5502. // construction
  5503. // If exceptions are disabled, only last duplicate path
  5504. // parameter will be set
  5505. std::unordered_set<std::string> param_name_set;
  5506. #endif
  5507. while (true) {
  5508. const auto marker_pos = pattern.find(
  5509. marker, last_param_end == 0 ? last_param_end : last_param_end - 1);
  5510. if (marker_pos == std::string::npos) { break; }
  5511. static_fragments_.push_back(
  5512. pattern.substr(last_param_end, marker_pos - last_param_end + 1));
  5513. const auto param_name_start = marker_pos + str_len(marker);
  5514. auto sep_pos = pattern.find(separator, param_name_start);
  5515. if (sep_pos == std::string::npos) { sep_pos = pattern.length(); }
  5516. auto param_name =
  5517. pattern.substr(param_name_start, sep_pos - param_name_start);
  5518. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5519. if (param_name_set.find(param_name) != param_name_set.cend()) {
  5520. std::string msg = "Encountered path parameter '" + param_name +
  5521. "' multiple times in route pattern '" + pattern + "'.";
  5522. throw std::invalid_argument(msg);
  5523. }
  5524. #endif
  5525. param_names_.push_back(std::move(param_name));
  5526. last_param_end = sep_pos + 1;
  5527. }
  5528. if (last_param_end < pattern.length()) {
  5529. static_fragments_.push_back(pattern.substr(last_param_end));
  5530. }
  5531. }
  5532. inline bool PathParamsMatcher::match(Request &request) const {
  5533. request.matches = std::smatch();
  5534. request.path_params.clear();
  5535. request.path_params.reserve(param_names_.size());
  5536. // One past the position at which the path matched the pattern last time
  5537. std::size_t starting_pos = 0;
  5538. for (size_t i = 0; i < static_fragments_.size(); ++i) {
  5539. const auto &fragment = static_fragments_[i];
  5540. if (starting_pos + fragment.length() > request.path.length()) {
  5541. return false;
  5542. }
  5543. // Avoid unnecessary allocation by using strncmp instead of substr +
  5544. // comparison
  5545. if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(),
  5546. fragment.length()) != 0) {
  5547. return false;
  5548. }
  5549. starting_pos += fragment.length();
  5550. // Should only happen when we have a static fragment after a param
  5551. // Example: '/users/:id/subscriptions'
  5552. // The 'subscriptions' fragment here does not have a corresponding param
  5553. if (i >= param_names_.size()) { continue; }
  5554. auto sep_pos = request.path.find(separator, starting_pos);
  5555. if (sep_pos == std::string::npos) { sep_pos = request.path.length(); }
  5556. const auto &param_name = param_names_[i];
  5557. request.path_params.emplace(
  5558. param_name, request.path.substr(starting_pos, sep_pos - starting_pos));
  5559. // Mark everything up to '/' as matched
  5560. starting_pos = sep_pos + 1;
  5561. }
  5562. // Returns false if the path is longer than the pattern
  5563. return starting_pos >= request.path.length();
  5564. }
  5565. inline bool RegexMatcher::match(Request &request) const {
  5566. request.path_params.clear();
  5567. return std::regex_match(request.path, request.matches, regex_);
  5568. }
  5569. } // namespace detail
  5570. // HTTP server implementation
  5571. inline Server::Server()
  5572. : new_task_queue(
  5573. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) {
  5574. #ifndef _WIN32
  5575. signal(SIGPIPE, SIG_IGN);
  5576. #endif
  5577. }
  5578. inline Server::~Server() = default;
  5579. inline std::unique_ptr<detail::MatcherBase>
  5580. Server::make_matcher(const std::string &pattern) {
  5581. if (pattern.find("/:") != std::string::npos) {
  5582. return detail::make_unique<detail::PathParamsMatcher>(pattern);
  5583. } else {
  5584. return detail::make_unique<detail::RegexMatcher>(pattern);
  5585. }
  5586. }
  5587. inline Server &Server::Get(const std::string &pattern, Handler handler) {
  5588. get_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5589. return *this;
  5590. }
  5591. inline Server &Server::Post(const std::string &pattern, Handler handler) {
  5592. post_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5593. return *this;
  5594. }
  5595. inline Server &Server::Post(const std::string &pattern,
  5596. HandlerWithContentReader handler) {
  5597. post_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5598. std::move(handler));
  5599. return *this;
  5600. }
  5601. inline Server &Server::Put(const std::string &pattern, Handler handler) {
  5602. put_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5603. return *this;
  5604. }
  5605. inline Server &Server::Put(const std::string &pattern,
  5606. HandlerWithContentReader handler) {
  5607. put_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5608. std::move(handler));
  5609. return *this;
  5610. }
  5611. inline Server &Server::Patch(const std::string &pattern, Handler handler) {
  5612. patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5613. return *this;
  5614. }
  5615. inline Server &Server::Patch(const std::string &pattern,
  5616. HandlerWithContentReader handler) {
  5617. patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5618. std::move(handler));
  5619. return *this;
  5620. }
  5621. inline Server &Server::Delete(const std::string &pattern, Handler handler) {
  5622. delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5623. return *this;
  5624. }
  5625. inline Server &Server::Delete(const std::string &pattern,
  5626. HandlerWithContentReader handler) {
  5627. delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern),
  5628. std::move(handler));
  5629. return *this;
  5630. }
  5631. inline Server &Server::Options(const std::string &pattern, Handler handler) {
  5632. options_handlers_.emplace_back(make_matcher(pattern), std::move(handler));
  5633. return *this;
  5634. }
  5635. inline bool Server::set_base_dir(const std::string &dir,
  5636. const std::string &mount_point) {
  5637. return set_mount_point(mount_point, dir);
  5638. }
  5639. inline bool Server::set_mount_point(const std::string &mount_point,
  5640. const std::string &dir, Headers headers) {
  5641. detail::FileStat stat(dir);
  5642. if (stat.is_dir()) {
  5643. std::string mnt = !mount_point.empty() ? mount_point : "/";
  5644. if (!mnt.empty() && mnt[0] == '/') {
  5645. base_dirs_.push_back({mnt, dir, std::move(headers)});
  5646. return true;
  5647. }
  5648. }
  5649. return false;
  5650. }
  5651. inline bool Server::remove_mount_point(const std::string &mount_point) {
  5652. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  5653. if (it->mount_point == mount_point) {
  5654. base_dirs_.erase(it);
  5655. return true;
  5656. }
  5657. }
  5658. return false;
  5659. }
  5660. inline Server &
  5661. Server::set_file_extension_and_mimetype_mapping(const std::string &ext,
  5662. const std::string &mime) {
  5663. file_extension_and_mimetype_map_[ext] = mime;
  5664. return *this;
  5665. }
  5666. inline Server &Server::set_default_file_mimetype(const std::string &mime) {
  5667. default_file_mimetype_ = mime;
  5668. return *this;
  5669. }
  5670. inline Server &Server::set_file_request_handler(Handler handler) {
  5671. file_request_handler_ = std::move(handler);
  5672. return *this;
  5673. }
  5674. inline Server &Server::set_error_handler_core(HandlerWithResponse handler,
  5675. std::true_type) {
  5676. error_handler_ = std::move(handler);
  5677. return *this;
  5678. }
  5679. inline Server &Server::set_error_handler_core(Handler handler,
  5680. std::false_type) {
  5681. error_handler_ = [handler](const Request &req, Response &res) {
  5682. handler(req, res);
  5683. return HandlerResponse::Handled;
  5684. };
  5685. return *this;
  5686. }
  5687. inline Server &Server::set_exception_handler(ExceptionHandler handler) {
  5688. exception_handler_ = std::move(handler);
  5689. return *this;
  5690. }
  5691. inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
  5692. pre_routing_handler_ = std::move(handler);
  5693. return *this;
  5694. }
  5695. inline Server &Server::set_post_routing_handler(Handler handler) {
  5696. post_routing_handler_ = std::move(handler);
  5697. return *this;
  5698. }
  5699. inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) {
  5700. pre_request_handler_ = std::move(handler);
  5701. return *this;
  5702. }
  5703. inline Server &Server::set_logger(Logger logger) {
  5704. logger_ = std::move(logger);
  5705. return *this;
  5706. }
  5707. inline Server &
  5708. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  5709. expect_100_continue_handler_ = std::move(handler);
  5710. return *this;
  5711. }
  5712. inline Server &Server::set_address_family(int family) {
  5713. address_family_ = family;
  5714. return *this;
  5715. }
  5716. inline Server &Server::set_tcp_nodelay(bool on) {
  5717. tcp_nodelay_ = on;
  5718. return *this;
  5719. }
  5720. inline Server &Server::set_ipv6_v6only(bool on) {
  5721. ipv6_v6only_ = on;
  5722. return *this;
  5723. }
  5724. inline Server &Server::set_socket_options(SocketOptions socket_options) {
  5725. socket_options_ = std::move(socket_options);
  5726. return *this;
  5727. }
  5728. inline Server &Server::set_default_headers(Headers headers) {
  5729. default_headers_ = std::move(headers);
  5730. return *this;
  5731. }
  5732. inline Server &Server::set_header_writer(
  5733. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  5734. header_writer_ = writer;
  5735. return *this;
  5736. }
  5737. inline Server &Server::set_keep_alive_max_count(size_t count) {
  5738. keep_alive_max_count_ = count;
  5739. return *this;
  5740. }
  5741. inline Server &Server::set_keep_alive_timeout(time_t sec) {
  5742. keep_alive_timeout_sec_ = sec;
  5743. return *this;
  5744. }
  5745. inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
  5746. read_timeout_sec_ = sec;
  5747. read_timeout_usec_ = usec;
  5748. return *this;
  5749. }
  5750. inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
  5751. write_timeout_sec_ = sec;
  5752. write_timeout_usec_ = usec;
  5753. return *this;
  5754. }
  5755. inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
  5756. idle_interval_sec_ = sec;
  5757. idle_interval_usec_ = usec;
  5758. return *this;
  5759. }
  5760. inline Server &Server::set_payload_max_length(size_t length) {
  5761. payload_max_length_ = length;
  5762. return *this;
  5763. }
  5764. inline bool Server::bind_to_port(const std::string &host, int port,
  5765. int socket_flags) {
  5766. auto ret = bind_internal(host, port, socket_flags);
  5767. if (ret == -1) { is_decommissioned = true; }
  5768. return ret >= 0;
  5769. }
  5770. inline int Server::bind_to_any_port(const std::string &host, int socket_flags) {
  5771. auto ret = bind_internal(host, 0, socket_flags);
  5772. if (ret == -1) { is_decommissioned = true; }
  5773. return ret;
  5774. }
  5775. inline bool Server::listen_after_bind() { return listen_internal(); }
  5776. inline bool Server::listen(const std::string &host, int port,
  5777. int socket_flags) {
  5778. return bind_to_port(host, port, socket_flags) && listen_internal();
  5779. }
  5780. inline bool Server::is_running() const { return is_running_; }
  5781. inline void Server::wait_until_ready() const {
  5782. while (!is_running_ && !is_decommissioned) {
  5783. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  5784. }
  5785. }
  5786. inline void Server::stop() {
  5787. if (is_running_) {
  5788. assert(svr_sock_ != INVALID_SOCKET);
  5789. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  5790. detail::shutdown_socket(sock);
  5791. detail::close_socket(sock);
  5792. }
  5793. is_decommissioned = false;
  5794. }
  5795. inline void Server::decommission() { is_decommissioned = true; }
  5796. inline bool Server::parse_request_line(const char *s, Request &req) const {
  5797. auto len = strlen(s);
  5798. if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
  5799. len -= 2;
  5800. {
  5801. size_t count = 0;
  5802. detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
  5803. switch (count) {
  5804. case 0: req.method = std::string(b, e); break;
  5805. case 1: req.target = std::string(b, e); break;
  5806. case 2: req.version = std::string(b, e); break;
  5807. default: break;
  5808. }
  5809. count++;
  5810. });
  5811. if (count != 3) { return false; }
  5812. }
  5813. thread_local const std::set<std::string> methods{
  5814. "GET", "HEAD", "POST", "PUT", "DELETE",
  5815. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  5816. if (methods.find(req.method) == methods.end()) { return false; }
  5817. if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; }
  5818. {
  5819. // Skip URL fragment
  5820. for (size_t i = 0; i < req.target.size(); i++) {
  5821. if (req.target[i] == '#') {
  5822. req.target.erase(i);
  5823. break;
  5824. }
  5825. }
  5826. detail::divide(req.target, '?',
  5827. [&](const char *lhs_data, std::size_t lhs_size,
  5828. const char *rhs_data, std::size_t rhs_size) {
  5829. req.path = detail::decode_url(
  5830. std::string(lhs_data, lhs_size), false);
  5831. detail::parse_query_text(rhs_data, rhs_size, req.params);
  5832. });
  5833. }
  5834. return true;
  5835. }
  5836. inline bool Server::write_response(Stream &strm, bool close_connection,
  5837. Request &req, Response &res) {
  5838. // NOTE: `req.ranges` should be empty, otherwise it will be applied
  5839. // incorrectly to the error content.
  5840. req.ranges.clear();
  5841. return write_response_core(strm, close_connection, req, res, false);
  5842. }
  5843. inline bool Server::write_response_with_content(Stream &strm,
  5844. bool close_connection,
  5845. const Request &req,
  5846. Response &res) {
  5847. return write_response_core(strm, close_connection, req, res, true);
  5848. }
  5849. inline bool Server::write_response_core(Stream &strm, bool close_connection,
  5850. const Request &req, Response &res,
  5851. bool need_apply_ranges) {
  5852. assert(res.status != -1);
  5853. if (400 <= res.status && error_handler_ &&
  5854. error_handler_(req, res) == HandlerResponse::Handled) {
  5855. need_apply_ranges = true;
  5856. }
  5857. std::string content_type;
  5858. std::string boundary;
  5859. if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
  5860. // Prepare additional headers
  5861. if (close_connection || req.get_header_value("Connection") == "close") {
  5862. res.set_header("Connection", "close");
  5863. } else {
  5864. std::string s = "timeout=";
  5865. s += std::to_string(keep_alive_timeout_sec_);
  5866. s += ", max=";
  5867. s += std::to_string(keep_alive_max_count_);
  5868. res.set_header("Keep-Alive", s);
  5869. }
  5870. if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) &&
  5871. !res.has_header("Content-Type")) {
  5872. res.set_header("Content-Type", "text/plain");
  5873. }
  5874. if (res.body.empty() && !res.content_length_ && !res.content_provider_ &&
  5875. !res.has_header("Content-Length")) {
  5876. res.set_header("Content-Length", "0");
  5877. }
  5878. if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) {
  5879. res.set_header("Accept-Ranges", "bytes");
  5880. }
  5881. if (post_routing_handler_) { post_routing_handler_(req, res); }
  5882. // Response line and headers
  5883. {
  5884. detail::BufferStream bstrm;
  5885. if (!detail::write_response_line(bstrm, res.status)) { return false; }
  5886. if (!header_writer_(bstrm, res.headers)) { return false; }
  5887. // Flush buffer
  5888. auto &data = bstrm.get_buffer();
  5889. detail::write_data(strm, data.data(), data.size());
  5890. }
  5891. // Body
  5892. auto ret = true;
  5893. if (req.method != "HEAD") {
  5894. if (!res.body.empty()) {
  5895. if (!detail::write_data(strm, res.body.data(), res.body.size())) {
  5896. ret = false;
  5897. }
  5898. } else if (res.content_provider_) {
  5899. if (write_content_with_provider(strm, req, res, boundary, content_type)) {
  5900. res.content_provider_success_ = true;
  5901. } else {
  5902. ret = false;
  5903. }
  5904. }
  5905. }
  5906. // Log
  5907. if (logger_) { logger_(req, res); }
  5908. return ret;
  5909. }
  5910. inline bool
  5911. Server::write_content_with_provider(Stream &strm, const Request &req,
  5912. Response &res, const std::string &boundary,
  5913. const std::string &content_type) {
  5914. auto is_shutting_down = [this]() {
  5915. return this->svr_sock_ == INVALID_SOCKET;
  5916. };
  5917. if (res.content_length_ > 0) {
  5918. if (req.ranges.empty()) {
  5919. return detail::write_content(strm, res.content_provider_, 0,
  5920. res.content_length_, is_shutting_down);
  5921. } else if (req.ranges.size() == 1) {
  5922. auto offset_and_length = detail::get_range_offset_and_length(
  5923. req.ranges[0], res.content_length_);
  5924. return detail::write_content(strm, res.content_provider_,
  5925. offset_and_length.first,
  5926. offset_and_length.second, is_shutting_down);
  5927. } else {
  5928. return detail::write_multipart_ranges_data(
  5929. strm, req, res, boundary, content_type, res.content_length_,
  5930. is_shutting_down);
  5931. }
  5932. } else {
  5933. if (res.is_chunked_content_provider_) {
  5934. auto type = detail::encoding_type(req, res);
  5935. std::unique_ptr<detail::compressor> compressor;
  5936. if (type == detail::EncodingType::Gzip) {
  5937. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5938. compressor = detail::make_unique<detail::gzip_compressor>();
  5939. #endif
  5940. } else if (type == detail::EncodingType::Brotli) {
  5941. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5942. compressor = detail::make_unique<detail::brotli_compressor>();
  5943. #endif
  5944. } else if (type == detail::EncodingType::Zstd) {
  5945. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5946. compressor = detail::make_unique<detail::zstd_compressor>();
  5947. #endif
  5948. } else {
  5949. compressor = detail::make_unique<detail::nocompressor>();
  5950. }
  5951. assert(compressor != nullptr);
  5952. return detail::write_content_chunked(strm, res.content_provider_,
  5953. is_shutting_down, *compressor);
  5954. } else {
  5955. return detail::write_content_without_length(strm, res.content_provider_,
  5956. is_shutting_down);
  5957. }
  5958. }
  5959. }
  5960. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  5961. MultipartFormDataMap::iterator cur;
  5962. auto file_count = 0;
  5963. if (read_content_core(
  5964. strm, req, res,
  5965. // Regular
  5966. [&](const char *buf, size_t n) {
  5967. if (req.body.size() + n > req.body.max_size()) { return false; }
  5968. req.body.append(buf, n);
  5969. return true;
  5970. },
  5971. // Multipart
  5972. [&](const MultipartFormData &file) {
  5973. if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) {
  5974. return false;
  5975. }
  5976. cur = req.files.emplace(file.name, file);
  5977. return true;
  5978. },
  5979. [&](const char *buf, size_t n) {
  5980. auto &content = cur->second.content;
  5981. if (content.size() + n > content.max_size()) { return false; }
  5982. content.append(buf, n);
  5983. return true;
  5984. })) {
  5985. const auto &content_type = req.get_header_value("Content-Type");
  5986. if (!content_type.find("application/x-www-form-urlencoded")) {
  5987. if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) {
  5988. res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414?
  5989. return false;
  5990. }
  5991. detail::parse_query_text(req.body, req.params);
  5992. }
  5993. return true;
  5994. }
  5995. return false;
  5996. }
  5997. inline bool Server::read_content_with_content_receiver(
  5998. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  5999. MultipartContentHeader multipart_header,
  6000. ContentReceiver multipart_receiver) {
  6001. return read_content_core(strm, req, res, std::move(receiver),
  6002. std::move(multipart_header),
  6003. std::move(multipart_receiver));
  6004. }
  6005. inline bool
  6006. Server::read_content_core(Stream &strm, Request &req, Response &res,
  6007. ContentReceiver receiver,
  6008. MultipartContentHeader multipart_header,
  6009. ContentReceiver multipart_receiver) const {
  6010. detail::MultipartFormDataParser multipart_form_data_parser;
  6011. ContentReceiverWithProgress out;
  6012. if (req.is_multipart_form_data()) {
  6013. const auto &content_type = req.get_header_value("Content-Type");
  6014. std::string boundary;
  6015. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  6016. res.status = StatusCode::BadRequest_400;
  6017. return false;
  6018. }
  6019. multipart_form_data_parser.set_boundary(std::move(boundary));
  6020. out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) {
  6021. /* For debug
  6022. size_t pos = 0;
  6023. while (pos < n) {
  6024. auto read_size = (std::min)<size_t>(1, n - pos);
  6025. auto ret = multipart_form_data_parser.parse(
  6026. buf + pos, read_size, multipart_receiver, multipart_header);
  6027. if (!ret) { return false; }
  6028. pos += read_size;
  6029. }
  6030. return true;
  6031. */
  6032. return multipart_form_data_parser.parse(buf, n, multipart_receiver,
  6033. multipart_header);
  6034. };
  6035. } else {
  6036. out = [receiver](const char *buf, size_t n, uint64_t /*off*/,
  6037. uint64_t /*len*/) { return receiver(buf, n); };
  6038. }
  6039. if (req.method == "DELETE" && !req.has_header("Content-Length")) {
  6040. return true;
  6041. }
  6042. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  6043. out, true)) {
  6044. return false;
  6045. }
  6046. if (req.is_multipart_form_data()) {
  6047. if (!multipart_form_data_parser.is_valid()) {
  6048. res.status = StatusCode::BadRequest_400;
  6049. return false;
  6050. }
  6051. }
  6052. return true;
  6053. }
  6054. inline bool Server::handle_file_request(const Request &req, Response &res) {
  6055. for (const auto &entry : base_dirs_) {
  6056. // Prefix match
  6057. if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
  6058. std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
  6059. if (detail::is_valid_path(sub_path)) {
  6060. auto path = entry.base_dir + sub_path;
  6061. if (path.back() == '/') { path += "index.html"; }
  6062. detail::FileStat stat(path);
  6063. if (stat.is_dir()) {
  6064. res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301);
  6065. return true;
  6066. }
  6067. if (stat.is_file()) {
  6068. for (const auto &kv : entry.headers) {
  6069. res.set_header(kv.first, kv.second);
  6070. }
  6071. auto mm = std::make_shared<detail::mmap>(path.c_str());
  6072. if (!mm->is_open()) { return false; }
  6073. res.set_content_provider(
  6074. mm->size(),
  6075. detail::find_content_type(path, file_extension_and_mimetype_map_,
  6076. default_file_mimetype_),
  6077. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  6078. sink.write(mm->data() + offset, length);
  6079. return true;
  6080. });
  6081. if (req.method != "HEAD" && file_request_handler_) {
  6082. file_request_handler_(req, res);
  6083. }
  6084. return true;
  6085. }
  6086. }
  6087. }
  6088. }
  6089. return false;
  6090. }
  6091. inline socket_t
  6092. Server::create_server_socket(const std::string &host, int port,
  6093. int socket_flags,
  6094. SocketOptions socket_options) const {
  6095. return detail::create_socket(
  6096. host, std::string(), port, address_family_, socket_flags, tcp_nodelay_,
  6097. ipv6_v6only_, std::move(socket_options),
  6098. [](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool {
  6099. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  6100. return false;
  6101. }
  6102. if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; }
  6103. return true;
  6104. });
  6105. }
  6106. inline int Server::bind_internal(const std::string &host, int port,
  6107. int socket_flags) {
  6108. if (is_decommissioned) { return -1; }
  6109. if (!is_valid()) { return -1; }
  6110. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  6111. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  6112. if (port == 0) {
  6113. struct sockaddr_storage addr;
  6114. socklen_t addr_len = sizeof(addr);
  6115. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  6116. &addr_len) == -1) {
  6117. return -1;
  6118. }
  6119. if (addr.ss_family == AF_INET) {
  6120. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  6121. } else if (addr.ss_family == AF_INET6) {
  6122. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  6123. } else {
  6124. return -1;
  6125. }
  6126. } else {
  6127. return port;
  6128. }
  6129. }
  6130. inline bool Server::listen_internal() {
  6131. if (is_decommissioned) { return false; }
  6132. auto ret = true;
  6133. is_running_ = true;
  6134. auto se = detail::scope_exit([&]() { is_running_ = false; });
  6135. {
  6136. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  6137. while (svr_sock_ != INVALID_SOCKET) {
  6138. #ifndef _WIN32
  6139. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  6140. #endif
  6141. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  6142. idle_interval_usec_);
  6143. if (val == 0) { // Timeout
  6144. task_queue->on_idle();
  6145. continue;
  6146. }
  6147. #ifndef _WIN32
  6148. }
  6149. #endif
  6150. #if defined _WIN32
  6151. // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT,
  6152. // OVERLAPPED
  6153. socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0);
  6154. #elif defined SOCK_CLOEXEC
  6155. socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC);
  6156. #else
  6157. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  6158. #endif
  6159. if (sock == INVALID_SOCKET) {
  6160. if (errno == EMFILE) {
  6161. // The per-process limit of open file descriptors has been reached.
  6162. // Try to accept new connections after a short sleep.
  6163. std::this_thread::sleep_for(std::chrono::microseconds{1});
  6164. continue;
  6165. } else if (errno == EINTR || errno == EAGAIN) {
  6166. continue;
  6167. }
  6168. if (svr_sock_ != INVALID_SOCKET) {
  6169. detail::close_socket(svr_sock_);
  6170. ret = false;
  6171. } else {
  6172. ; // The server socket was closed by user.
  6173. }
  6174. break;
  6175. }
  6176. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO,
  6177. read_timeout_sec_, read_timeout_usec_);
  6178. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO,
  6179. write_timeout_sec_, write_timeout_usec_);
  6180. if (!task_queue->enqueue(
  6181. [this, sock]() { process_and_close_socket(sock); })) {
  6182. detail::shutdown_socket(sock);
  6183. detail::close_socket(sock);
  6184. }
  6185. }
  6186. task_queue->shutdown();
  6187. }
  6188. is_decommissioned = !ret;
  6189. return ret;
  6190. }
  6191. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  6192. if (pre_routing_handler_ &&
  6193. pre_routing_handler_(req, res) == HandlerResponse::Handled) {
  6194. return true;
  6195. }
  6196. // File handler
  6197. if ((req.method == "GET" || req.method == "HEAD") &&
  6198. handle_file_request(req, res)) {
  6199. return true;
  6200. }
  6201. if (detail::expect_content(req)) {
  6202. // Content reader handler
  6203. {
  6204. ContentReader reader(
  6205. [&](ContentReceiver receiver) {
  6206. return read_content_with_content_receiver(
  6207. strm, req, res, std::move(receiver), nullptr, nullptr);
  6208. },
  6209. [&](MultipartContentHeader header, ContentReceiver receiver) {
  6210. return read_content_with_content_receiver(strm, req, res, nullptr,
  6211. std::move(header),
  6212. std::move(receiver));
  6213. });
  6214. if (req.method == "POST") {
  6215. if (dispatch_request_for_content_reader(
  6216. req, res, std::move(reader),
  6217. post_handlers_for_content_reader_)) {
  6218. return true;
  6219. }
  6220. } else if (req.method == "PUT") {
  6221. if (dispatch_request_for_content_reader(
  6222. req, res, std::move(reader),
  6223. put_handlers_for_content_reader_)) {
  6224. return true;
  6225. }
  6226. } else if (req.method == "PATCH") {
  6227. if (dispatch_request_for_content_reader(
  6228. req, res, std::move(reader),
  6229. patch_handlers_for_content_reader_)) {
  6230. return true;
  6231. }
  6232. } else if (req.method == "DELETE") {
  6233. if (dispatch_request_for_content_reader(
  6234. req, res, std::move(reader),
  6235. delete_handlers_for_content_reader_)) {
  6236. return true;
  6237. }
  6238. }
  6239. }
  6240. // Read content into `req.body`
  6241. if (!read_content(strm, req, res)) { return false; }
  6242. }
  6243. // Regular handler
  6244. if (req.method == "GET" || req.method == "HEAD") {
  6245. return dispatch_request(req, res, get_handlers_);
  6246. } else if (req.method == "POST") {
  6247. return dispatch_request(req, res, post_handlers_);
  6248. } else if (req.method == "PUT") {
  6249. return dispatch_request(req, res, put_handlers_);
  6250. } else if (req.method == "DELETE") {
  6251. return dispatch_request(req, res, delete_handlers_);
  6252. } else if (req.method == "OPTIONS") {
  6253. return dispatch_request(req, res, options_handlers_);
  6254. } else if (req.method == "PATCH") {
  6255. return dispatch_request(req, res, patch_handlers_);
  6256. }
  6257. res.status = StatusCode::BadRequest_400;
  6258. return false;
  6259. }
  6260. inline bool Server::dispatch_request(Request &req, Response &res,
  6261. const Handlers &handlers) const {
  6262. for (const auto &x : handlers) {
  6263. const auto &matcher = x.first;
  6264. const auto &handler = x.second;
  6265. if (matcher->match(req)) {
  6266. req.matched_route = matcher->pattern();
  6267. if (!pre_request_handler_ ||
  6268. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  6269. handler(req, res);
  6270. }
  6271. return true;
  6272. }
  6273. }
  6274. return false;
  6275. }
  6276. inline void Server::apply_ranges(const Request &req, Response &res,
  6277. std::string &content_type,
  6278. std::string &boundary) const {
  6279. if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) {
  6280. auto it = res.headers.find("Content-Type");
  6281. if (it != res.headers.end()) {
  6282. content_type = it->second;
  6283. res.headers.erase(it);
  6284. }
  6285. boundary = detail::make_multipart_data_boundary();
  6286. res.set_header("Content-Type",
  6287. "multipart/byteranges; boundary=" + boundary);
  6288. }
  6289. auto type = detail::encoding_type(req, res);
  6290. if (res.body.empty()) {
  6291. if (res.content_length_ > 0) {
  6292. size_t length = 0;
  6293. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  6294. length = res.content_length_;
  6295. } else if (req.ranges.size() == 1) {
  6296. auto offset_and_length = detail::get_range_offset_and_length(
  6297. req.ranges[0], res.content_length_);
  6298. length = offset_and_length.second;
  6299. auto content_range = detail::make_content_range_header_field(
  6300. offset_and_length, res.content_length_);
  6301. res.set_header("Content-Range", content_range);
  6302. } else {
  6303. length = detail::get_multipart_ranges_data_length(
  6304. req, boundary, content_type, res.content_length_);
  6305. }
  6306. res.set_header("Content-Length", std::to_string(length));
  6307. } else {
  6308. if (res.content_provider_) {
  6309. if (res.is_chunked_content_provider_) {
  6310. res.set_header("Transfer-Encoding", "chunked");
  6311. if (type == detail::EncodingType::Gzip) {
  6312. res.set_header("Content-Encoding", "gzip");
  6313. } else if (type == detail::EncodingType::Brotli) {
  6314. res.set_header("Content-Encoding", "br");
  6315. } else if (type == detail::EncodingType::Zstd) {
  6316. res.set_header("Content-Encoding", "zstd");
  6317. }
  6318. }
  6319. }
  6320. }
  6321. } else {
  6322. if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) {
  6323. ;
  6324. } else if (req.ranges.size() == 1) {
  6325. auto offset_and_length =
  6326. detail::get_range_offset_and_length(req.ranges[0], res.body.size());
  6327. auto offset = offset_and_length.first;
  6328. auto length = offset_and_length.second;
  6329. auto content_range = detail::make_content_range_header_field(
  6330. offset_and_length, res.body.size());
  6331. res.set_header("Content-Range", content_range);
  6332. assert(offset + length <= res.body.size());
  6333. res.body = res.body.substr(offset, length);
  6334. } else {
  6335. std::string data;
  6336. detail::make_multipart_ranges_data(req, res, boundary, content_type,
  6337. res.body.size(), data);
  6338. res.body.swap(data);
  6339. }
  6340. if (type != detail::EncodingType::None) {
  6341. std::unique_ptr<detail::compressor> compressor;
  6342. std::string content_encoding;
  6343. if (type == detail::EncodingType::Gzip) {
  6344. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6345. compressor = detail::make_unique<detail::gzip_compressor>();
  6346. content_encoding = "gzip";
  6347. #endif
  6348. } else if (type == detail::EncodingType::Brotli) {
  6349. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6350. compressor = detail::make_unique<detail::brotli_compressor>();
  6351. content_encoding = "br";
  6352. #endif
  6353. } else if (type == detail::EncodingType::Zstd) {
  6354. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  6355. compressor = detail::make_unique<detail::zstd_compressor>();
  6356. content_encoding = "zstd";
  6357. #endif
  6358. }
  6359. if (compressor) {
  6360. std::string compressed;
  6361. if (compressor->compress(res.body.data(), res.body.size(), true,
  6362. [&](const char *data, size_t data_len) {
  6363. compressed.append(data, data_len);
  6364. return true;
  6365. })) {
  6366. res.body.swap(compressed);
  6367. res.set_header("Content-Encoding", content_encoding);
  6368. }
  6369. }
  6370. }
  6371. auto length = std::to_string(res.body.size());
  6372. res.set_header("Content-Length", length);
  6373. }
  6374. }
  6375. inline bool Server::dispatch_request_for_content_reader(
  6376. Request &req, Response &res, ContentReader content_reader,
  6377. const HandlersForContentReader &handlers) const {
  6378. for (const auto &x : handlers) {
  6379. const auto &matcher = x.first;
  6380. const auto &handler = x.second;
  6381. if (matcher->match(req)) {
  6382. req.matched_route = matcher->pattern();
  6383. if (!pre_request_handler_ ||
  6384. pre_request_handler_(req, res) != HandlerResponse::Handled) {
  6385. handler(req, res, content_reader);
  6386. }
  6387. return true;
  6388. }
  6389. }
  6390. return false;
  6391. }
  6392. inline bool
  6393. Server::process_request(Stream &strm, const std::string &remote_addr,
  6394. int remote_port, const std::string &local_addr,
  6395. int local_port, bool close_connection,
  6396. bool &connection_closed,
  6397. const std::function<void(Request &)> &setup_request) {
  6398. std::array<char, 2048> buf{};
  6399. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  6400. // Connection has been closed on client
  6401. if (!line_reader.getline()) { return false; }
  6402. Request req;
  6403. Response res;
  6404. res.version = "HTTP/1.1";
  6405. res.headers = default_headers_;
  6406. // Request line and headers
  6407. if (!parse_request_line(line_reader.ptr(), req) ||
  6408. !detail::read_headers(strm, req.headers)) {
  6409. res.status = StatusCode::BadRequest_400;
  6410. return write_response(strm, close_connection, req, res);
  6411. }
  6412. // Check if the request URI doesn't exceed the limit
  6413. if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  6414. Headers dummy;
  6415. detail::read_headers(strm, dummy);
  6416. res.status = StatusCode::UriTooLong_414;
  6417. return write_response(strm, close_connection, req, res);
  6418. }
  6419. if (req.get_header_value("Connection") == "close") {
  6420. connection_closed = true;
  6421. }
  6422. if (req.version == "HTTP/1.0" &&
  6423. req.get_header_value("Connection") != "Keep-Alive") {
  6424. connection_closed = true;
  6425. }
  6426. req.remote_addr = remote_addr;
  6427. req.remote_port = remote_port;
  6428. req.set_header("REMOTE_ADDR", req.remote_addr);
  6429. req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
  6430. req.local_addr = local_addr;
  6431. req.local_port = local_port;
  6432. req.set_header("LOCAL_ADDR", req.local_addr);
  6433. req.set_header("LOCAL_PORT", std::to_string(req.local_port));
  6434. if (req.has_header("Accept")) {
  6435. const auto &accept_header = req.get_header_value("Accept");
  6436. if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
  6437. res.status = StatusCode::BadRequest_400;
  6438. return write_response(strm, close_connection, req, res);
  6439. }
  6440. }
  6441. if (req.has_header("Range")) {
  6442. const auto &range_header_value = req.get_header_value("Range");
  6443. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  6444. res.status = StatusCode::RangeNotSatisfiable_416;
  6445. return write_response(strm, close_connection, req, res);
  6446. }
  6447. }
  6448. if (setup_request) { setup_request(req); }
  6449. if (req.get_header_value("Expect") == "100-continue") {
  6450. int status = StatusCode::Continue_100;
  6451. if (expect_100_continue_handler_) {
  6452. status = expect_100_continue_handler_(req, res);
  6453. }
  6454. switch (status) {
  6455. case StatusCode::Continue_100:
  6456. case StatusCode::ExpectationFailed_417:
  6457. detail::write_response_line(strm, status);
  6458. strm.write("\r\n");
  6459. break;
  6460. default:
  6461. connection_closed = true;
  6462. return write_response(strm, true, req, res);
  6463. }
  6464. }
  6465. // Setup `is_connection_closed` method
  6466. auto sock = strm.socket();
  6467. req.is_connection_closed = [sock]() {
  6468. return !detail::is_socket_alive(sock);
  6469. };
  6470. // Routing
  6471. auto routed = false;
  6472. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  6473. routed = routing(req, res, strm);
  6474. #else
  6475. try {
  6476. routed = routing(req, res, strm);
  6477. } catch (std::exception &e) {
  6478. if (exception_handler_) {
  6479. auto ep = std::current_exception();
  6480. exception_handler_(req, res, ep);
  6481. routed = true;
  6482. } else {
  6483. res.status = StatusCode::InternalServerError_500;
  6484. std::string val;
  6485. auto s = e.what();
  6486. for (size_t i = 0; s[i]; i++) {
  6487. switch (s[i]) {
  6488. case '\r': val += "\\r"; break;
  6489. case '\n': val += "\\n"; break;
  6490. default: val += s[i]; break;
  6491. }
  6492. }
  6493. res.set_header("EXCEPTION_WHAT", val);
  6494. }
  6495. } catch (...) {
  6496. if (exception_handler_) {
  6497. auto ep = std::current_exception();
  6498. exception_handler_(req, res, ep);
  6499. routed = true;
  6500. } else {
  6501. res.status = StatusCode::InternalServerError_500;
  6502. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  6503. }
  6504. }
  6505. #endif
  6506. if (routed) {
  6507. if (res.status == -1) {
  6508. res.status = req.ranges.empty() ? StatusCode::OK_200
  6509. : StatusCode::PartialContent_206;
  6510. }
  6511. // Serve file content by using a content provider
  6512. if (!res.file_content_path_.empty()) {
  6513. const auto &path = res.file_content_path_;
  6514. auto mm = std::make_shared<detail::mmap>(path.c_str());
  6515. if (!mm->is_open()) {
  6516. res.body.clear();
  6517. res.content_length_ = 0;
  6518. res.content_provider_ = nullptr;
  6519. res.status = StatusCode::NotFound_404;
  6520. return write_response(strm, close_connection, req, res);
  6521. }
  6522. auto content_type = res.file_content_content_type_;
  6523. if (content_type.empty()) {
  6524. content_type = detail::find_content_type(
  6525. path, file_extension_and_mimetype_map_, default_file_mimetype_);
  6526. }
  6527. res.set_content_provider(
  6528. mm->size(), content_type,
  6529. [mm](size_t offset, size_t length, DataSink &sink) -> bool {
  6530. sink.write(mm->data() + offset, length);
  6531. return true;
  6532. });
  6533. }
  6534. if (detail::range_error(req, res)) {
  6535. res.body.clear();
  6536. res.content_length_ = 0;
  6537. res.content_provider_ = nullptr;
  6538. res.status = StatusCode::RangeNotSatisfiable_416;
  6539. return write_response(strm, close_connection, req, res);
  6540. }
  6541. return write_response_with_content(strm, close_connection, req, res);
  6542. } else {
  6543. if (res.status == -1) { res.status = StatusCode::NotFound_404; }
  6544. return write_response(strm, close_connection, req, res);
  6545. }
  6546. }
  6547. inline bool Server::is_valid() const { return true; }
  6548. inline bool Server::process_and_close_socket(socket_t sock) {
  6549. std::string remote_addr;
  6550. int remote_port = 0;
  6551. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  6552. std::string local_addr;
  6553. int local_port = 0;
  6554. detail::get_local_ip_and_port(sock, local_addr, local_port);
  6555. auto ret = detail::process_server_socket(
  6556. svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  6557. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  6558. write_timeout_usec_,
  6559. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  6560. return process_request(strm, remote_addr, remote_port, local_addr,
  6561. local_port, close_connection, connection_closed,
  6562. nullptr);
  6563. });
  6564. detail::shutdown_socket(sock);
  6565. detail::close_socket(sock);
  6566. return ret;
  6567. }
  6568. // HTTP client implementation
  6569. inline ClientImpl::ClientImpl(const std::string &host)
  6570. : ClientImpl(host, 80, std::string(), std::string()) {}
  6571. inline ClientImpl::ClientImpl(const std::string &host, int port)
  6572. : ClientImpl(host, port, std::string(), std::string()) {}
  6573. inline ClientImpl::ClientImpl(const std::string &host, int port,
  6574. const std::string &client_cert_path,
  6575. const std::string &client_key_path)
  6576. : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port),
  6577. host_and_port_(adjust_host_string(host_) + ":" + std::to_string(port)),
  6578. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  6579. inline ClientImpl::~ClientImpl() {
  6580. // Wait until all the requests in flight are handled.
  6581. size_t retry_count = 10;
  6582. while (retry_count-- > 0) {
  6583. {
  6584. std::lock_guard<std::mutex> guard(socket_mutex_);
  6585. if (socket_requests_in_flight_ == 0) { break; }
  6586. }
  6587. std::this_thread::sleep_for(std::chrono::milliseconds{1});
  6588. }
  6589. std::lock_guard<std::mutex> guard(socket_mutex_);
  6590. shutdown_socket(socket_);
  6591. close_socket(socket_);
  6592. }
  6593. inline bool ClientImpl::is_valid() const { return true; }
  6594. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  6595. client_cert_path_ = rhs.client_cert_path_;
  6596. client_key_path_ = rhs.client_key_path_;
  6597. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  6598. read_timeout_sec_ = rhs.read_timeout_sec_;
  6599. read_timeout_usec_ = rhs.read_timeout_usec_;
  6600. write_timeout_sec_ = rhs.write_timeout_sec_;
  6601. write_timeout_usec_ = rhs.write_timeout_usec_;
  6602. max_timeout_msec_ = rhs.max_timeout_msec_;
  6603. basic_auth_username_ = rhs.basic_auth_username_;
  6604. basic_auth_password_ = rhs.basic_auth_password_;
  6605. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  6606. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6607. digest_auth_username_ = rhs.digest_auth_username_;
  6608. digest_auth_password_ = rhs.digest_auth_password_;
  6609. #endif
  6610. keep_alive_ = rhs.keep_alive_;
  6611. follow_location_ = rhs.follow_location_;
  6612. url_encode_ = rhs.url_encode_;
  6613. address_family_ = rhs.address_family_;
  6614. tcp_nodelay_ = rhs.tcp_nodelay_;
  6615. ipv6_v6only_ = rhs.ipv6_v6only_;
  6616. socket_options_ = rhs.socket_options_;
  6617. compress_ = rhs.compress_;
  6618. decompress_ = rhs.decompress_;
  6619. interface_ = rhs.interface_;
  6620. proxy_host_ = rhs.proxy_host_;
  6621. proxy_port_ = rhs.proxy_port_;
  6622. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  6623. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  6624. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  6625. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6626. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  6627. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  6628. #endif
  6629. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6630. ca_cert_file_path_ = rhs.ca_cert_file_path_;
  6631. ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
  6632. ca_cert_store_ = rhs.ca_cert_store_;
  6633. #endif
  6634. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6635. server_certificate_verification_ = rhs.server_certificate_verification_;
  6636. server_hostname_verification_ = rhs.server_hostname_verification_;
  6637. server_certificate_verifier_ = rhs.server_certificate_verifier_;
  6638. #endif
  6639. logger_ = rhs.logger_;
  6640. }
  6641. inline socket_t ClientImpl::create_client_socket(Error &error) const {
  6642. if (!proxy_host_.empty() && proxy_port_ != -1) {
  6643. return detail::create_client_socket(
  6644. proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_,
  6645. ipv6_v6only_, socket_options_, connection_timeout_sec_,
  6646. connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_,
  6647. write_timeout_sec_, write_timeout_usec_, interface_, error);
  6648. }
  6649. // Check is custom IP specified for host_
  6650. std::string ip;
  6651. auto it = addr_map_.find(host_);
  6652. if (it != addr_map_.end()) { ip = it->second; }
  6653. return detail::create_client_socket(
  6654. host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_,
  6655. socket_options_, connection_timeout_sec_, connection_timeout_usec_,
  6656. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  6657. write_timeout_usec_, interface_, error);
  6658. }
  6659. inline bool ClientImpl::create_and_connect_socket(Socket &socket,
  6660. Error &error) {
  6661. auto sock = create_client_socket(error);
  6662. if (sock == INVALID_SOCKET) { return false; }
  6663. socket.sock = sock;
  6664. return true;
  6665. }
  6666. inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
  6667. bool /*shutdown_gracefully*/) {
  6668. // If there are any requests in flight from threads other than us, then it's
  6669. // a thread-unsafe race because individual ssl* objects are not thread-safe.
  6670. assert(socket_requests_in_flight_ == 0 ||
  6671. socket_requests_are_from_thread_ == std::this_thread::get_id());
  6672. }
  6673. inline void ClientImpl::shutdown_socket(Socket &socket) const {
  6674. if (socket.sock == INVALID_SOCKET) { return; }
  6675. detail::shutdown_socket(socket.sock);
  6676. }
  6677. inline void ClientImpl::close_socket(Socket &socket) {
  6678. // If there are requests in flight in another thread, usually closing
  6679. // the socket will be fine and they will simply receive an error when
  6680. // using the closed socket, but it is still a bug since rarely the OS
  6681. // may reassign the socket id to be used for a new socket, and then
  6682. // suddenly they will be operating on a live socket that is different
  6683. // than the one they intended!
  6684. assert(socket_requests_in_flight_ == 0 ||
  6685. socket_requests_are_from_thread_ == std::this_thread::get_id());
  6686. // It is also a bug if this happens while SSL is still active
  6687. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6688. assert(socket.ssl == nullptr);
  6689. #endif
  6690. if (socket.sock == INVALID_SOCKET) { return; }
  6691. detail::close_socket(socket.sock);
  6692. socket.sock = INVALID_SOCKET;
  6693. }
  6694. inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
  6695. Response &res) const {
  6696. std::array<char, 2048> buf{};
  6697. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  6698. if (!line_reader.getline()) { return false; }
  6699. #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  6700. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n");
  6701. #else
  6702. thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
  6703. #endif
  6704. std::cmatch m;
  6705. if (!std::regex_match(line_reader.ptr(), m, re)) {
  6706. return req.method == "CONNECT";
  6707. }
  6708. res.version = std::string(m[1]);
  6709. res.status = std::stoi(std::string(m[2]));
  6710. res.reason = std::string(m[3]);
  6711. // Ignore '100 Continue'
  6712. while (res.status == StatusCode::Continue_100) {
  6713. if (!line_reader.getline()) { return false; } // CRLF
  6714. if (!line_reader.getline()) { return false; } // next response line
  6715. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  6716. res.version = std::string(m[1]);
  6717. res.status = std::stoi(std::string(m[2]));
  6718. res.reason = std::string(m[3]);
  6719. }
  6720. return true;
  6721. }
  6722. inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
  6723. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  6724. auto ret = send_(req, res, error);
  6725. if (error == Error::SSLPeerCouldBeClosed_) {
  6726. assert(!ret);
  6727. ret = send_(req, res, error);
  6728. }
  6729. return ret;
  6730. }
  6731. inline bool ClientImpl::send_(Request &req, Response &res, Error &error) {
  6732. {
  6733. std::lock_guard<std::mutex> guard(socket_mutex_);
  6734. // Set this to false immediately - if it ever gets set to true by the end of
  6735. // the request, we know another thread instructed us to close the socket.
  6736. socket_should_be_closed_when_request_is_done_ = false;
  6737. auto is_alive = false;
  6738. if (socket_.is_open()) {
  6739. is_alive = detail::is_socket_alive(socket_.sock);
  6740. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6741. if (is_alive && is_ssl()) {
  6742. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  6743. is_alive = false;
  6744. }
  6745. }
  6746. #endif
  6747. if (!is_alive) {
  6748. // Attempt to avoid sigpipe by shutting down non-gracefully if it seems
  6749. // like the other side has already closed the connection Also, there
  6750. // cannot be any requests in flight from other threads since we locked
  6751. // request_mutex_, so safe to close everything immediately
  6752. const bool shutdown_gracefully = false;
  6753. shutdown_ssl(socket_, shutdown_gracefully);
  6754. shutdown_socket(socket_);
  6755. close_socket(socket_);
  6756. }
  6757. }
  6758. if (!is_alive) {
  6759. if (!create_and_connect_socket(socket_, error)) { return false; }
  6760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6761. // TODO: refactoring
  6762. if (is_ssl()) {
  6763. auto &scli = static_cast<SSLClient &>(*this);
  6764. if (!proxy_host_.empty() && proxy_port_ != -1) {
  6765. auto success = false;
  6766. if (!scli.connect_with_proxy(socket_, req.start_time_, res, success,
  6767. error)) {
  6768. return success;
  6769. }
  6770. }
  6771. if (!scli.initialize_ssl(socket_, error)) { return false; }
  6772. }
  6773. #endif
  6774. }
  6775. // Mark the current socket as being in use so that it cannot be closed by
  6776. // anyone else while this request is ongoing, even though we will be
  6777. // releasing the mutex.
  6778. if (socket_requests_in_flight_ > 1) {
  6779. assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
  6780. }
  6781. socket_requests_in_flight_ += 1;
  6782. socket_requests_are_from_thread_ = std::this_thread::get_id();
  6783. }
  6784. for (const auto &header : default_headers_) {
  6785. if (req.headers.find(header.first) == req.headers.end()) {
  6786. req.headers.insert(header);
  6787. }
  6788. }
  6789. auto ret = false;
  6790. auto close_connection = !keep_alive_;
  6791. auto se = detail::scope_exit([&]() {
  6792. // Briefly lock mutex in order to mark that a request is no longer ongoing
  6793. std::lock_guard<std::mutex> guard(socket_mutex_);
  6794. socket_requests_in_flight_ -= 1;
  6795. if (socket_requests_in_flight_ <= 0) {
  6796. assert(socket_requests_in_flight_ == 0);
  6797. socket_requests_are_from_thread_ = std::thread::id();
  6798. }
  6799. if (socket_should_be_closed_when_request_is_done_ || close_connection ||
  6800. !ret) {
  6801. shutdown_ssl(socket_, true);
  6802. shutdown_socket(socket_);
  6803. close_socket(socket_);
  6804. }
  6805. });
  6806. ret = process_socket(socket_, req.start_time_, [&](Stream &strm) {
  6807. return handle_request(strm, req, res, close_connection, error);
  6808. });
  6809. if (!ret) {
  6810. if (error == Error::Success) { error = Error::Unknown; }
  6811. }
  6812. return ret;
  6813. }
  6814. inline Result ClientImpl::send(const Request &req) {
  6815. auto req2 = req;
  6816. return send_(std::move(req2));
  6817. }
  6818. inline Result ClientImpl::send_(Request &&req) {
  6819. auto res = detail::make_unique<Response>();
  6820. auto error = Error::Success;
  6821. auto ret = send(req, *res, error);
  6822. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6823. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers),
  6824. last_ssl_error_, last_openssl_error_};
  6825. #else
  6826. return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
  6827. #endif
  6828. }
  6829. inline bool ClientImpl::handle_request(Stream &strm, Request &req,
  6830. Response &res, bool close_connection,
  6831. Error &error) {
  6832. if (req.path.empty()) {
  6833. error = Error::Connection;
  6834. return false;
  6835. }
  6836. auto req_save = req;
  6837. bool ret;
  6838. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  6839. auto req2 = req;
  6840. req2.path = "http://" + host_and_port_ + req.path;
  6841. ret = process_request(strm, req2, res, close_connection, error);
  6842. req = req2;
  6843. req.path = req_save.path;
  6844. } else {
  6845. ret = process_request(strm, req, res, close_connection, error);
  6846. }
  6847. if (!ret) { return false; }
  6848. if (res.get_header_value("Connection") == "close" ||
  6849. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  6850. // TODO this requires a not-entirely-obvious chain of calls to be correct
  6851. // for this to be safe.
  6852. // This is safe to call because handle_request is only called by send_
  6853. // which locks the request mutex during the process. It would be a bug
  6854. // to call it from a different thread since it's a thread-safety issue
  6855. // to do these things to the socket if another thread is using the socket.
  6856. std::lock_guard<std::mutex> guard(socket_mutex_);
  6857. shutdown_ssl(socket_, true);
  6858. shutdown_socket(socket_);
  6859. close_socket(socket_);
  6860. }
  6861. if (300 < res.status && res.status < 400 && follow_location_) {
  6862. req = req_save;
  6863. ret = redirect(req, res, error);
  6864. }
  6865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6866. if ((res.status == StatusCode::Unauthorized_401 ||
  6867. res.status == StatusCode::ProxyAuthenticationRequired_407) &&
  6868. req.authorization_count_ < 5) {
  6869. auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407;
  6870. const auto &username =
  6871. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  6872. const auto &password =
  6873. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  6874. if (!username.empty() && !password.empty()) {
  6875. std::map<std::string, std::string> auth;
  6876. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  6877. Request new_req = req;
  6878. new_req.authorization_count_ += 1;
  6879. new_req.headers.erase(is_proxy ? "Proxy-Authorization"
  6880. : "Authorization");
  6881. new_req.headers.insert(detail::make_digest_authentication_header(
  6882. req, auth, new_req.authorization_count_, detail::random_string(10),
  6883. username, password, is_proxy));
  6884. Response new_res;
  6885. ret = send(new_req, new_res, error);
  6886. if (ret) { res = new_res; }
  6887. }
  6888. }
  6889. }
  6890. #endif
  6891. return ret;
  6892. }
  6893. inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
  6894. if (req.redirect_count_ == 0) {
  6895. error = Error::ExceedRedirectCount;
  6896. return false;
  6897. }
  6898. auto location = res.get_header_value("location");
  6899. if (location.empty()) { return false; }
  6900. thread_local const std::regex re(
  6901. R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)");
  6902. std::smatch m;
  6903. if (!std::regex_match(location, m, re)) { return false; }
  6904. auto scheme = is_ssl() ? "https" : "http";
  6905. auto next_scheme = m[1].str();
  6906. auto next_host = m[2].str();
  6907. if (next_host.empty()) { next_host = m[3].str(); }
  6908. auto port_str = m[4].str();
  6909. auto next_path = m[5].str();
  6910. auto next_query = m[6].str();
  6911. auto next_port = port_;
  6912. if (!port_str.empty()) {
  6913. next_port = std::stoi(port_str);
  6914. } else if (!next_scheme.empty()) {
  6915. next_port = next_scheme == "https" ? 443 : 80;
  6916. }
  6917. if (next_scheme.empty()) { next_scheme = scheme; }
  6918. if (next_host.empty()) { next_host = host_; }
  6919. if (next_path.empty()) { next_path = "/"; }
  6920. auto path = detail::decode_url(next_path, true) + next_query;
  6921. // Same host redirect - use current client
  6922. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  6923. return detail::redirect(*this, req, res, path, location, error);
  6924. }
  6925. // Cross-host/scheme redirect - create new client with robust setup
  6926. return create_redirect_client(next_scheme, next_host, next_port, req, res,
  6927. path, location, error);
  6928. }
  6929. // New method for robust redirect client creation
  6930. inline bool ClientImpl::create_redirect_client(
  6931. const std::string &scheme, const std::string &host, int port, Request &req,
  6932. Response &res, const std::string &path, const std::string &location,
  6933. Error &error) {
  6934. // Determine if we need SSL
  6935. auto need_ssl = (scheme == "https");
  6936. // Clean up request headers that are host/client specific
  6937. // Remove headers that should not be carried over to new host
  6938. auto headers_to_remove =
  6939. std::vector<std::string>{"Host", "Proxy-Authorization", "Authorization"};
  6940. for (const auto &header_name : headers_to_remove) {
  6941. auto it = req.headers.find(header_name);
  6942. while (it != req.headers.end()) {
  6943. it = req.headers.erase(it);
  6944. it = req.headers.find(header_name);
  6945. }
  6946. }
  6947. // Create appropriate client type and handle redirect
  6948. if (need_ssl) {
  6949. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6950. // Create SSL client for HTTPS redirect
  6951. SSLClient redirect_client(host, port);
  6952. // Setup basic client configuration first
  6953. setup_redirect_client(redirect_client);
  6954. // SSL-specific configuration for proxy environments
  6955. if (!proxy_host_.empty() && proxy_port_ != -1) {
  6956. // Critical: Disable SSL verification for proxy environments
  6957. redirect_client.enable_server_certificate_verification(false);
  6958. redirect_client.enable_server_hostname_verification(false);
  6959. } else {
  6960. // For direct SSL connections, copy SSL verification settings
  6961. redirect_client.enable_server_certificate_verification(
  6962. server_certificate_verification_);
  6963. redirect_client.enable_server_hostname_verification(
  6964. server_hostname_verification_);
  6965. }
  6966. // Handle CA certificate store and paths if available
  6967. if (ca_cert_store_) { redirect_client.set_ca_cert_store(ca_cert_store_); }
  6968. if (!ca_cert_file_path_.empty()) {
  6969. redirect_client.set_ca_cert_path(ca_cert_file_path_, ca_cert_dir_path_);
  6970. }
  6971. // Client certificates are set through constructor for SSLClient
  6972. // NOTE: SSLClient constructor already takes client_cert_path and
  6973. // client_key_path so we need to create it properly if client certs are
  6974. // needed
  6975. // Execute the redirect
  6976. return detail::redirect(redirect_client, req, res, path, location, error);
  6977. #else
  6978. // SSL not supported - set appropriate error
  6979. error = Error::SSLConnection;
  6980. return false;
  6981. #endif
  6982. } else {
  6983. // HTTP redirect
  6984. ClientImpl redirect_client(host, port);
  6985. // Setup client with robust configuration
  6986. setup_redirect_client(redirect_client);
  6987. // Execute the redirect
  6988. return detail::redirect(redirect_client, req, res, path, location, error);
  6989. }
  6990. }
  6991. // New method for robust client setup (based on basic_manual_redirect.cpp logic)
  6992. template <typename ClientType>
  6993. inline void ClientImpl::setup_redirect_client(ClientType &client) {
  6994. // Copy basic settings first
  6995. client.set_connection_timeout(connection_timeout_sec_);
  6996. client.set_read_timeout(read_timeout_sec_, read_timeout_usec_);
  6997. client.set_write_timeout(write_timeout_sec_, write_timeout_usec_);
  6998. client.set_keep_alive(keep_alive_);
  6999. client.set_follow_location(
  7000. true); // Enable redirects to handle multi-step redirects
  7001. client.set_url_encode(url_encode_);
  7002. client.set_compress(compress_);
  7003. client.set_decompress(decompress_);
  7004. // Copy authentication settings BEFORE proxy setup
  7005. if (!basic_auth_username_.empty()) {
  7006. client.set_basic_auth(basic_auth_username_, basic_auth_password_);
  7007. }
  7008. if (!bearer_token_auth_token_.empty()) {
  7009. client.set_bearer_token_auth(bearer_token_auth_token_);
  7010. }
  7011. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7012. if (!digest_auth_username_.empty()) {
  7013. client.set_digest_auth(digest_auth_username_, digest_auth_password_);
  7014. }
  7015. #endif
  7016. // Setup proxy configuration (CRITICAL ORDER - proxy must be set
  7017. // before proxy auth)
  7018. if (!proxy_host_.empty() && proxy_port_ != -1) {
  7019. // First set proxy host and port
  7020. client.set_proxy(proxy_host_, proxy_port_);
  7021. // Then set proxy authentication (order matters!)
  7022. if (!proxy_basic_auth_username_.empty()) {
  7023. client.set_proxy_basic_auth(proxy_basic_auth_username_,
  7024. proxy_basic_auth_password_);
  7025. }
  7026. if (!proxy_bearer_token_auth_token_.empty()) {
  7027. client.set_proxy_bearer_token_auth(proxy_bearer_token_auth_token_);
  7028. }
  7029. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7030. if (!proxy_digest_auth_username_.empty()) {
  7031. client.set_proxy_digest_auth(proxy_digest_auth_username_,
  7032. proxy_digest_auth_password_);
  7033. }
  7034. #endif
  7035. }
  7036. // Copy network and socket settings
  7037. client.set_address_family(address_family_);
  7038. client.set_tcp_nodelay(tcp_nodelay_);
  7039. client.set_ipv6_v6only(ipv6_v6only_);
  7040. if (socket_options_) { client.set_socket_options(socket_options_); }
  7041. if (!interface_.empty()) { client.set_interface(interface_); }
  7042. // Copy logging and headers
  7043. if (logger_) { client.set_logger(logger_); }
  7044. // NOTE: DO NOT copy default_headers_ as they may contain stale Host headers
  7045. // Each new client should generate its own headers based on its target host
  7046. }
  7047. inline bool ClientImpl::write_content_with_provider(Stream &strm,
  7048. const Request &req,
  7049. Error &error) const {
  7050. auto is_shutting_down = []() { return false; };
  7051. if (req.is_chunked_content_provider_) {
  7052. // TODO: Brotli support
  7053. std::unique_ptr<detail::compressor> compressor;
  7054. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7055. if (compress_) {
  7056. compressor = detail::make_unique<detail::gzip_compressor>();
  7057. } else
  7058. #endif
  7059. {
  7060. compressor = detail::make_unique<detail::nocompressor>();
  7061. }
  7062. return detail::write_content_chunked(strm, req.content_provider_,
  7063. is_shutting_down, *compressor, error);
  7064. } else {
  7065. return detail::write_content_with_progress(
  7066. strm, req.content_provider_, 0, req.content_length_, is_shutting_down,
  7067. req.upload_progress, error);
  7068. }
  7069. }
  7070. inline bool ClientImpl::write_request(Stream &strm, Request &req,
  7071. bool close_connection, Error &error) {
  7072. // Prepare additional headers
  7073. if (close_connection) {
  7074. if (!req.has_header("Connection")) {
  7075. req.set_header("Connection", "close");
  7076. }
  7077. }
  7078. if (!req.has_header("Host")) {
  7079. if (is_ssl()) {
  7080. if (port_ == 443) {
  7081. req.set_header("Host", host_);
  7082. } else {
  7083. req.set_header("Host", host_and_port_);
  7084. }
  7085. } else {
  7086. if (port_ == 80) {
  7087. req.set_header("Host", host_);
  7088. } else {
  7089. req.set_header("Host", host_and_port_);
  7090. }
  7091. }
  7092. }
  7093. if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); }
  7094. if (!req.content_receiver) {
  7095. if (!req.has_header("Accept-Encoding")) {
  7096. std::string accept_encoding;
  7097. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7098. accept_encoding = "br";
  7099. #endif
  7100. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7101. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  7102. accept_encoding += "gzip, deflate";
  7103. #endif
  7104. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7105. if (!accept_encoding.empty()) { accept_encoding += ", "; }
  7106. accept_encoding += "zstd";
  7107. #endif
  7108. req.set_header("Accept-Encoding", accept_encoding);
  7109. }
  7110. #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT
  7111. if (!req.has_header("User-Agent")) {
  7112. auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION;
  7113. req.set_header("User-Agent", agent);
  7114. }
  7115. #endif
  7116. };
  7117. if (req.body.empty()) {
  7118. if (req.content_provider_) {
  7119. if (!req.is_chunked_content_provider_) {
  7120. if (!req.has_header("Content-Length")) {
  7121. auto length = std::to_string(req.content_length_);
  7122. req.set_header("Content-Length", length);
  7123. }
  7124. }
  7125. } else {
  7126. if (req.method == "POST" || req.method == "PUT" ||
  7127. req.method == "PATCH") {
  7128. req.set_header("Content-Length", "0");
  7129. }
  7130. }
  7131. } else {
  7132. if (!req.has_header("Content-Type")) {
  7133. req.set_header("Content-Type", "text/plain");
  7134. }
  7135. if (!req.has_header("Content-Length")) {
  7136. auto length = std::to_string(req.body.size());
  7137. req.set_header("Content-Length", length);
  7138. }
  7139. }
  7140. if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
  7141. if (!req.has_header("Authorization")) {
  7142. req.headers.insert(make_basic_authentication_header(
  7143. basic_auth_username_, basic_auth_password_, false));
  7144. }
  7145. }
  7146. if (!proxy_basic_auth_username_.empty() &&
  7147. !proxy_basic_auth_password_.empty()) {
  7148. if (!req.has_header("Proxy-Authorization")) {
  7149. req.headers.insert(make_basic_authentication_header(
  7150. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  7151. }
  7152. }
  7153. if (!bearer_token_auth_token_.empty()) {
  7154. if (!req.has_header("Authorization")) {
  7155. req.headers.insert(make_bearer_token_authentication_header(
  7156. bearer_token_auth_token_, false));
  7157. }
  7158. }
  7159. if (!proxy_bearer_token_auth_token_.empty()) {
  7160. if (!req.has_header("Proxy-Authorization")) {
  7161. req.headers.insert(make_bearer_token_authentication_header(
  7162. proxy_bearer_token_auth_token_, true));
  7163. }
  7164. }
  7165. // Request line and headers
  7166. {
  7167. detail::BufferStream bstrm;
  7168. const auto &path_with_query =
  7169. req.params.empty() ? req.path
  7170. : append_query_params(req.path, req.params);
  7171. const auto &path =
  7172. url_encode_ ? detail::encode_url(path_with_query) : path_with_query;
  7173. detail::write_request_line(bstrm, req.method, path);
  7174. header_writer_(bstrm, req.headers);
  7175. // Flush buffer
  7176. auto &data = bstrm.get_buffer();
  7177. if (!detail::write_data(strm, data.data(), data.size())) {
  7178. error = Error::Write;
  7179. return false;
  7180. }
  7181. }
  7182. // Body
  7183. if (req.body.empty()) {
  7184. return write_content_with_provider(strm, req, error);
  7185. }
  7186. if (req.upload_progress) {
  7187. auto body_size = req.body.size();
  7188. size_t written = 0;
  7189. auto data = req.body.data();
  7190. while (written < body_size) {
  7191. size_t to_write = (std::min)(CPPHTTPLIB_SEND_BUFSIZ, body_size - written);
  7192. if (!detail::write_data(strm, data + written, to_write)) {
  7193. error = Error::Write;
  7194. return false;
  7195. }
  7196. written += to_write;
  7197. if (!req.upload_progress(written, body_size)) {
  7198. error = Error::Canceled;
  7199. return false;
  7200. }
  7201. }
  7202. } else {
  7203. if (!detail::write_data(strm, req.body.data(), req.body.size())) {
  7204. error = Error::Write;
  7205. return false;
  7206. }
  7207. }
  7208. return true;
  7209. }
  7210. inline std::unique_ptr<Response> ClientImpl::send_with_content_provider(
  7211. Request &req, const char *body, size_t content_length,
  7212. ContentProvider content_provider,
  7213. ContentProviderWithoutLength content_provider_without_length,
  7214. const std::string &content_type, Error &error) {
  7215. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7216. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7217. if (compress_) { req.set_header("Content-Encoding", "gzip"); }
  7218. #endif
  7219. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7220. if (compress_ && !content_provider_without_length) {
  7221. // TODO: Brotli support
  7222. detail::gzip_compressor compressor;
  7223. if (content_provider) {
  7224. auto ok = true;
  7225. size_t offset = 0;
  7226. DataSink data_sink;
  7227. data_sink.write = [&](const char *data, size_t data_len) -> bool {
  7228. if (ok) {
  7229. auto last = offset + data_len == content_length;
  7230. auto ret = compressor.compress(
  7231. data, data_len, last,
  7232. [&](const char *compressed_data, size_t compressed_data_len) {
  7233. req.body.append(compressed_data, compressed_data_len);
  7234. return true;
  7235. });
  7236. if (ret) {
  7237. offset += data_len;
  7238. } else {
  7239. ok = false;
  7240. }
  7241. }
  7242. return ok;
  7243. };
  7244. while (ok && offset < content_length) {
  7245. if (!content_provider(offset, content_length - offset, data_sink)) {
  7246. error = Error::Canceled;
  7247. return nullptr;
  7248. }
  7249. }
  7250. } else {
  7251. if (!compressor.compress(body, content_length, true,
  7252. [&](const char *data, size_t data_len) {
  7253. req.body.append(data, data_len);
  7254. return true;
  7255. })) {
  7256. error = Error::Compression;
  7257. return nullptr;
  7258. }
  7259. }
  7260. } else
  7261. #endif
  7262. {
  7263. if (content_provider) {
  7264. req.content_length_ = content_length;
  7265. req.content_provider_ = std::move(content_provider);
  7266. req.is_chunked_content_provider_ = false;
  7267. } else if (content_provider_without_length) {
  7268. req.content_length_ = 0;
  7269. req.content_provider_ = detail::ContentProviderAdapter(
  7270. std::move(content_provider_without_length));
  7271. req.is_chunked_content_provider_ = true;
  7272. req.set_header("Transfer-Encoding", "chunked");
  7273. } else {
  7274. req.body.assign(body, content_length);
  7275. }
  7276. }
  7277. auto res = detail::make_unique<Response>();
  7278. return send(req, *res, error) ? std::move(res) : nullptr;
  7279. }
  7280. inline Result ClientImpl::send_with_content_provider(
  7281. const std::string &method, const std::string &path, const Headers &headers,
  7282. const char *body, size_t content_length, ContentProvider content_provider,
  7283. ContentProviderWithoutLength content_provider_without_length,
  7284. const std::string &content_type, UploadProgress progress) {
  7285. Request req;
  7286. req.method = method;
  7287. req.headers = headers;
  7288. req.path = path;
  7289. req.upload_progress = std::move(progress);
  7290. if (max_timeout_msec_ > 0) {
  7291. req.start_time_ = std::chrono::steady_clock::now();
  7292. }
  7293. auto error = Error::Success;
  7294. auto res = send_with_content_provider(
  7295. req, body, content_length, std::move(content_provider),
  7296. std::move(content_provider_without_length), content_type, error);
  7297. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7298. return Result{std::move(res), error, std::move(req.headers), last_ssl_error_,
  7299. last_openssl_error_};
  7300. #else
  7301. return Result{std::move(res), error, std::move(req.headers)};
  7302. #endif
  7303. }
  7304. inline std::string
  7305. ClientImpl::adjust_host_string(const std::string &host) const {
  7306. if (host.find(':') != std::string::npos) { return "[" + host + "]"; }
  7307. return host;
  7308. }
  7309. inline bool ClientImpl::process_request(Stream &strm, Request &req,
  7310. Response &res, bool close_connection,
  7311. Error &error) {
  7312. // Send request
  7313. if (!write_request(strm, req, close_connection, error)) { return false; }
  7314. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7315. if (is_ssl()) {
  7316. auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1;
  7317. if (!is_proxy_enabled) {
  7318. if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) {
  7319. error = Error::SSLPeerCouldBeClosed_;
  7320. return false;
  7321. }
  7322. }
  7323. }
  7324. #endif
  7325. // Receive response and headers
  7326. if (!read_response_line(strm, req, res) ||
  7327. !detail::read_headers(strm, res.headers)) {
  7328. error = Error::Read;
  7329. return false;
  7330. }
  7331. // Body
  7332. if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
  7333. req.method != "CONNECT") {
  7334. auto redirect = 300 < res.status && res.status < 400 &&
  7335. res.status != StatusCode::NotModified_304 &&
  7336. follow_location_;
  7337. if (req.response_handler && !redirect) {
  7338. if (!req.response_handler(res)) {
  7339. error = Error::Canceled;
  7340. return false;
  7341. }
  7342. }
  7343. auto out =
  7344. req.content_receiver
  7345. ? static_cast<ContentReceiverWithProgress>(
  7346. [&](const char *buf, size_t n, uint64_t off, uint64_t len) {
  7347. if (redirect) { return true; }
  7348. auto ret = req.content_receiver(buf, n, off, len);
  7349. if (!ret) { error = Error::Canceled; }
  7350. return ret;
  7351. })
  7352. : static_cast<ContentReceiverWithProgress>(
  7353. [&](const char *buf, size_t n, uint64_t /*off*/,
  7354. uint64_t /*len*/) {
  7355. assert(res.body.size() + n <= res.body.max_size());
  7356. res.body.append(buf, n);
  7357. return true;
  7358. });
  7359. auto progress = [&](uint64_t current, uint64_t total) {
  7360. if (!req.download_progress || redirect) { return true; }
  7361. auto ret = req.download_progress(current, total);
  7362. if (!ret) { error = Error::Canceled; }
  7363. return ret;
  7364. };
  7365. if (res.has_header("Content-Length")) {
  7366. if (!req.content_receiver) {
  7367. auto len = res.get_header_value_u64("Content-Length");
  7368. if (len > res.body.max_size()) {
  7369. error = Error::Read;
  7370. return false;
  7371. }
  7372. res.body.reserve(static_cast<size_t>(len));
  7373. }
  7374. }
  7375. if (res.status != StatusCode::NotModified_304) {
  7376. int dummy_status;
  7377. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  7378. dummy_status, std::move(progress),
  7379. std::move(out), decompress_)) {
  7380. if (error != Error::Canceled) { error = Error::Read; }
  7381. return false;
  7382. }
  7383. }
  7384. }
  7385. // Log
  7386. if (logger_) { logger_(req, res); }
  7387. return true;
  7388. }
  7389. inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider(
  7390. const std::string &boundary,
  7391. const MultipartFormDataItemsForClientInput &items,
  7392. const MultipartFormDataProviderItems &provider_items) const {
  7393. size_t cur_item = 0;
  7394. size_t cur_start = 0;
  7395. // cur_item and cur_start are copied to within the std::function and maintain
  7396. // state between successive calls
  7397. return [&, cur_item, cur_start](size_t offset,
  7398. DataSink &sink) mutable -> bool {
  7399. if (!offset && !items.empty()) {
  7400. sink.os << detail::serialize_multipart_formdata(items, boundary, false);
  7401. return true;
  7402. } else if (cur_item < provider_items.size()) {
  7403. if (!cur_start) {
  7404. const auto &begin = detail::serialize_multipart_formdata_item_begin(
  7405. provider_items[cur_item], boundary);
  7406. offset += begin.size();
  7407. cur_start = offset;
  7408. sink.os << begin;
  7409. }
  7410. DataSink cur_sink;
  7411. auto has_data = true;
  7412. cur_sink.write = sink.write;
  7413. cur_sink.done = [&]() { has_data = false; };
  7414. if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) {
  7415. return false;
  7416. }
  7417. if (!has_data) {
  7418. sink.os << detail::serialize_multipart_formdata_item_end();
  7419. cur_item++;
  7420. cur_start = 0;
  7421. }
  7422. return true;
  7423. } else {
  7424. sink.os << detail::serialize_multipart_formdata_finish(boundary);
  7425. sink.done();
  7426. return true;
  7427. }
  7428. };
  7429. }
  7430. inline bool ClientImpl::process_socket(
  7431. const Socket &socket,
  7432. std::chrono::time_point<std::chrono::steady_clock> start_time,
  7433. std::function<bool(Stream &strm)> callback) {
  7434. return detail::process_client_socket(
  7435. socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  7436. write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback));
  7437. }
  7438. inline bool ClientImpl::is_ssl() const { return false; }
  7439. inline Result ClientImpl::Get(const std::string &path,
  7440. DownloadProgress progress) {
  7441. return Get(path, Headers(), std::move(progress));
  7442. }
  7443. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  7444. const Headers &headers,
  7445. DownloadProgress progress) {
  7446. if (params.empty()) { return Get(path, headers); }
  7447. std::string path_with_query = append_query_params(path, params);
  7448. return Get(path_with_query, headers, std::move(progress));
  7449. }
  7450. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  7451. DownloadProgress progress) {
  7452. Request req;
  7453. req.method = "GET";
  7454. req.path = path;
  7455. req.headers = headers;
  7456. req.download_progress = std::move(progress);
  7457. if (max_timeout_msec_ > 0) {
  7458. req.start_time_ = std::chrono::steady_clock::now();
  7459. }
  7460. return send_(std::move(req));
  7461. }
  7462. inline Result ClientImpl::Get(const std::string &path,
  7463. ContentReceiver content_receiver,
  7464. DownloadProgress progress) {
  7465. return Get(path, Headers(), nullptr, std::move(content_receiver),
  7466. std::move(progress));
  7467. }
  7468. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  7469. ContentReceiver content_receiver,
  7470. DownloadProgress progress) {
  7471. return Get(path, headers, nullptr, std::move(content_receiver),
  7472. std::move(progress));
  7473. }
  7474. inline Result ClientImpl::Get(const std::string &path,
  7475. ResponseHandler response_handler,
  7476. ContentReceiver content_receiver,
  7477. DownloadProgress progress) {
  7478. return Get(path, Headers(), std::move(response_handler),
  7479. std::move(content_receiver), std::move(progress));
  7480. }
  7481. inline Result ClientImpl::Get(const std::string &path, const Headers &headers,
  7482. ResponseHandler response_handler,
  7483. ContentReceiver content_receiver,
  7484. DownloadProgress progress) {
  7485. Request req;
  7486. req.method = "GET";
  7487. req.path = path;
  7488. req.headers = headers;
  7489. req.response_handler = std::move(response_handler);
  7490. req.content_receiver =
  7491. [content_receiver](const char *data, size_t data_length,
  7492. uint64_t /*offset*/, uint64_t /*total_length*/) {
  7493. return content_receiver(data, data_length);
  7494. };
  7495. req.download_progress = std::move(progress);
  7496. if (max_timeout_msec_ > 0) {
  7497. req.start_time_ = std::chrono::steady_clock::now();
  7498. }
  7499. return send_(std::move(req));
  7500. }
  7501. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  7502. const Headers &headers,
  7503. ContentReceiver content_receiver,
  7504. DownloadProgress progress) {
  7505. return Get(path, params, headers, nullptr, std::move(content_receiver),
  7506. std::move(progress));
  7507. }
  7508. inline Result ClientImpl::Get(const std::string &path, const Params &params,
  7509. const Headers &headers,
  7510. ResponseHandler response_handler,
  7511. ContentReceiver content_receiver,
  7512. DownloadProgress progress) {
  7513. if (params.empty()) {
  7514. return Get(path, headers, std::move(response_handler),
  7515. std::move(content_receiver), std::move(progress));
  7516. }
  7517. std::string path_with_query = append_query_params(path, params);
  7518. return Get(path_with_query, headers, std::move(response_handler),
  7519. std::move(content_receiver), std::move(progress));
  7520. }
  7521. inline Result ClientImpl::Head(const std::string &path) {
  7522. return Head(path, Headers());
  7523. }
  7524. inline Result ClientImpl::Head(const std::string &path,
  7525. const Headers &headers) {
  7526. Request req;
  7527. req.method = "HEAD";
  7528. req.headers = headers;
  7529. req.path = path;
  7530. if (max_timeout_msec_ > 0) {
  7531. req.start_time_ = std::chrono::steady_clock::now();
  7532. }
  7533. return send_(std::move(req));
  7534. }
  7535. inline Result ClientImpl::Post(const std::string &path) {
  7536. return Post(path, std::string(), std::string());
  7537. }
  7538. inline Result ClientImpl::Post(const std::string &path,
  7539. const Headers &headers) {
  7540. return Post(path, headers, nullptr, 0, std::string());
  7541. }
  7542. inline Result ClientImpl::Post(const std::string &path, const char *body,
  7543. size_t content_length,
  7544. const std::string &content_type,
  7545. UploadProgress progress) {
  7546. return Post(path, Headers(), body, content_length, content_type, progress);
  7547. }
  7548. inline Result ClientImpl::Post(const std::string &path, const std::string &body,
  7549. const std::string &content_type,
  7550. UploadProgress progress) {
  7551. return Post(path, Headers(), body, content_type, progress);
  7552. }
  7553. inline Result ClientImpl::Post(const std::string &path, const Params &params) {
  7554. return Post(path, Headers(), params);
  7555. }
  7556. inline Result ClientImpl::Post(const std::string &path, size_t content_length,
  7557. ContentProvider content_provider,
  7558. const std::string &content_type,
  7559. UploadProgress progress) {
  7560. return Post(path, Headers(), content_length, std::move(content_provider),
  7561. content_type, progress);
  7562. }
  7563. inline Result ClientImpl::Post(const std::string &path,
  7564. ContentProviderWithoutLength content_provider,
  7565. const std::string &content_type,
  7566. UploadProgress progress) {
  7567. return Post(path, Headers(), std::move(content_provider), content_type,
  7568. progress);
  7569. }
  7570. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7571. const Params &params) {
  7572. auto query = detail::params_to_query_str(params);
  7573. return Post(path, headers, query, "application/x-www-form-urlencoded");
  7574. }
  7575. inline Result
  7576. ClientImpl::Post(const std::string &path,
  7577. const MultipartFormDataItemsForClientInput &items,
  7578. UploadProgress progress) {
  7579. return Post(path, Headers(), items, progress);
  7580. }
  7581. inline Result
  7582. ClientImpl::Post(const std::string &path, const Headers &headers,
  7583. const MultipartFormDataItemsForClientInput &items,
  7584. UploadProgress progress) {
  7585. const auto &boundary = detail::make_multipart_data_boundary();
  7586. const auto &content_type =
  7587. detail::serialize_multipart_formdata_get_content_type(boundary);
  7588. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7589. return Post(path, headers, body, content_type, progress);
  7590. }
  7591. inline Result
  7592. ClientImpl::Post(const std::string &path, const Headers &headers,
  7593. const MultipartFormDataItemsForClientInput &items,
  7594. const std::string &boundary, UploadProgress progress) {
  7595. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  7596. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  7597. }
  7598. const auto &content_type =
  7599. detail::serialize_multipart_formdata_get_content_type(boundary);
  7600. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7601. return Post(path, headers, body, content_type, progress);
  7602. }
  7603. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7604. const char *body, size_t content_length,
  7605. const std::string &content_type,
  7606. UploadProgress progress) {
  7607. return send_with_content_provider("POST", path, headers, body, content_length,
  7608. nullptr, nullptr, content_type, progress);
  7609. }
  7610. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7611. const std::string &body,
  7612. const std::string &content_type,
  7613. UploadProgress progress) {
  7614. return send_with_content_provider("POST", path, headers, body.data(),
  7615. body.size(), nullptr, nullptr, content_type,
  7616. progress);
  7617. }
  7618. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7619. size_t content_length,
  7620. ContentProvider content_provider,
  7621. const std::string &content_type,
  7622. UploadProgress progress) {
  7623. return send_with_content_provider("POST", path, headers, nullptr,
  7624. content_length, std::move(content_provider),
  7625. nullptr, content_type, progress);
  7626. }
  7627. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7628. ContentProviderWithoutLength content_provider,
  7629. const std::string &content_type,
  7630. UploadProgress progress) {
  7631. return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr,
  7632. std::move(content_provider), content_type,
  7633. progress);
  7634. }
  7635. inline Result
  7636. ClientImpl::Post(const std::string &path, const Headers &headers,
  7637. const MultipartFormDataItemsForClientInput &items,
  7638. const MultipartFormDataProviderItems &provider_items,
  7639. UploadProgress progress) {
  7640. const auto &boundary = detail::make_multipart_data_boundary();
  7641. const auto &content_type =
  7642. detail::serialize_multipart_formdata_get_content_type(boundary);
  7643. return send_with_content_provider(
  7644. "POST", path, headers, nullptr, 0, nullptr,
  7645. get_multipart_content_provider(boundary, items, provider_items),
  7646. content_type, progress);
  7647. }
  7648. inline Result ClientImpl::Post(const std::string &path, const Headers &headers,
  7649. const std::string &body,
  7650. const std::string &content_type,
  7651. ContentReceiver content_receiver,
  7652. DownloadProgress progress) {
  7653. Request req;
  7654. req.method = "POST";
  7655. req.path = path;
  7656. req.headers = headers;
  7657. req.body = body;
  7658. req.content_receiver =
  7659. [content_receiver](const char *data, size_t data_length,
  7660. uint64_t /*offset*/, uint64_t /*total_length*/) {
  7661. return content_receiver(data, data_length);
  7662. };
  7663. req.download_progress = std::move(progress);
  7664. if (max_timeout_msec_ > 0) {
  7665. req.start_time_ = std::chrono::steady_clock::now();
  7666. }
  7667. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7668. return send_(std::move(req));
  7669. }
  7670. inline Result ClientImpl::Put(const std::string &path) {
  7671. return Put(path, std::string(), std::string());
  7672. }
  7673. inline Result ClientImpl::Put(const std::string &path, const Headers &headers) {
  7674. return Put(path, headers, nullptr, 0, std::string());
  7675. }
  7676. inline Result ClientImpl::Put(const std::string &path, const char *body,
  7677. size_t content_length,
  7678. const std::string &content_type,
  7679. UploadProgress progress) {
  7680. return Put(path, Headers(), body, content_length, content_type, progress);
  7681. }
  7682. inline Result ClientImpl::Put(const std::string &path, const std::string &body,
  7683. const std::string &content_type,
  7684. UploadProgress progress) {
  7685. return Put(path, Headers(), body, content_type, progress);
  7686. }
  7687. inline Result ClientImpl::Put(const std::string &path, const Params &params) {
  7688. return Put(path, Headers(), params);
  7689. }
  7690. inline Result ClientImpl::Put(const std::string &path, size_t content_length,
  7691. ContentProvider content_provider,
  7692. const std::string &content_type,
  7693. UploadProgress progress) {
  7694. return Put(path, Headers(), content_length, std::move(content_provider),
  7695. content_type, progress);
  7696. }
  7697. inline Result ClientImpl::Put(const std::string &path,
  7698. ContentProviderWithoutLength content_provider,
  7699. const std::string &content_type,
  7700. UploadProgress progress) {
  7701. return Put(path, Headers(), std::move(content_provider), content_type,
  7702. progress);
  7703. }
  7704. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7705. const Params &params) {
  7706. auto query = detail::params_to_query_str(params);
  7707. return Put(path, headers, query, "application/x-www-form-urlencoded");
  7708. }
  7709. inline Result ClientImpl::Put(const std::string &path,
  7710. const MultipartFormDataItemsForClientInput &items,
  7711. UploadProgress progress) {
  7712. return Put(path, Headers(), items, progress);
  7713. }
  7714. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7715. const MultipartFormDataItemsForClientInput &items,
  7716. UploadProgress progress) {
  7717. const auto &boundary = detail::make_multipart_data_boundary();
  7718. const auto &content_type =
  7719. detail::serialize_multipart_formdata_get_content_type(boundary);
  7720. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7721. return Put(path, headers, body, content_type, progress);
  7722. }
  7723. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7724. const MultipartFormDataItemsForClientInput &items,
  7725. const std::string &boundary,
  7726. UploadProgress progress) {
  7727. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  7728. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  7729. }
  7730. const auto &content_type =
  7731. detail::serialize_multipart_formdata_get_content_type(boundary);
  7732. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7733. return Put(path, headers, body, content_type, progress);
  7734. }
  7735. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7736. const char *body, size_t content_length,
  7737. const std::string &content_type,
  7738. UploadProgress progress) {
  7739. return send_with_content_provider("PUT", path, headers, body, content_length,
  7740. nullptr, nullptr, content_type, progress);
  7741. }
  7742. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7743. const std::string &body,
  7744. const std::string &content_type,
  7745. UploadProgress progress) {
  7746. return send_with_content_provider("PUT", path, headers, body.data(),
  7747. body.size(), nullptr, nullptr, content_type,
  7748. progress);
  7749. }
  7750. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7751. size_t content_length,
  7752. ContentProvider content_provider,
  7753. const std::string &content_type,
  7754. UploadProgress progress) {
  7755. return send_with_content_provider("PUT", path, headers, nullptr,
  7756. content_length, std::move(content_provider),
  7757. nullptr, content_type, progress);
  7758. }
  7759. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7760. ContentProviderWithoutLength content_provider,
  7761. const std::string &content_type,
  7762. UploadProgress progress) {
  7763. return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr,
  7764. std::move(content_provider), content_type,
  7765. progress);
  7766. }
  7767. inline Result
  7768. ClientImpl::Put(const std::string &path, const Headers &headers,
  7769. const MultipartFormDataItemsForClientInput &items,
  7770. const MultipartFormDataProviderItems &provider_items,
  7771. UploadProgress progress) {
  7772. const auto &boundary = detail::make_multipart_data_boundary();
  7773. const auto &content_type =
  7774. detail::serialize_multipart_formdata_get_content_type(boundary);
  7775. return send_with_content_provider(
  7776. "PUT", path, headers, nullptr, 0, nullptr,
  7777. get_multipart_content_provider(boundary, items, provider_items),
  7778. content_type, progress);
  7779. }
  7780. inline Result ClientImpl::Put(const std::string &path, const Headers &headers,
  7781. const std::string &body,
  7782. const std::string &content_type,
  7783. ContentReceiver content_receiver,
  7784. DownloadProgress progress) {
  7785. Request req;
  7786. req.method = "PUT";
  7787. req.path = path;
  7788. req.headers = headers;
  7789. req.body = body;
  7790. req.content_receiver =
  7791. [content_receiver](const char *data, size_t data_length,
  7792. uint64_t /*offset*/, uint64_t /*total_length*/) {
  7793. return content_receiver(data, data_length);
  7794. };
  7795. req.download_progress = std::move(progress);
  7796. if (max_timeout_msec_ > 0) {
  7797. req.start_time_ = std::chrono::steady_clock::now();
  7798. }
  7799. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7800. return send_(std::move(req));
  7801. }
  7802. inline Result ClientImpl::Patch(const std::string &path) {
  7803. return Patch(path, std::string(), std::string());
  7804. }
  7805. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7806. UploadProgress progress) {
  7807. return Patch(path, headers, nullptr, 0, std::string(), progress);
  7808. }
  7809. inline Result ClientImpl::Patch(const std::string &path, const char *body,
  7810. size_t content_length,
  7811. const std::string &content_type,
  7812. UploadProgress progress) {
  7813. return Patch(path, Headers(), body, content_length, content_type, progress);
  7814. }
  7815. inline Result ClientImpl::Patch(const std::string &path,
  7816. const std::string &body,
  7817. const std::string &content_type,
  7818. UploadProgress progress) {
  7819. return Patch(path, Headers(), body, content_type, progress);
  7820. }
  7821. inline Result ClientImpl::Patch(const std::string &path, const Params &params) {
  7822. return Patch(path, Headers(), params);
  7823. }
  7824. inline Result ClientImpl::Patch(const std::string &path, size_t content_length,
  7825. ContentProvider content_provider,
  7826. const std::string &content_type,
  7827. UploadProgress progress) {
  7828. return Patch(path, Headers(), content_length, std::move(content_provider),
  7829. content_type, progress);
  7830. }
  7831. inline Result ClientImpl::Patch(const std::string &path,
  7832. ContentProviderWithoutLength content_provider,
  7833. const std::string &content_type,
  7834. UploadProgress progress) {
  7835. return Patch(path, Headers(), std::move(content_provider), content_type,
  7836. progress);
  7837. }
  7838. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7839. const Params &params) {
  7840. auto query = detail::params_to_query_str(params);
  7841. return Patch(path, headers, query, "application/x-www-form-urlencoded");
  7842. }
  7843. inline Result
  7844. ClientImpl::Patch(const std::string &path,
  7845. const MultipartFormDataItemsForClientInput &items,
  7846. UploadProgress progress) {
  7847. return Patch(path, Headers(), items, progress);
  7848. }
  7849. inline Result
  7850. ClientImpl::Patch(const std::string &path, const Headers &headers,
  7851. const MultipartFormDataItemsForClientInput &items,
  7852. UploadProgress progress) {
  7853. const auto &boundary = detail::make_multipart_data_boundary();
  7854. const auto &content_type =
  7855. detail::serialize_multipart_formdata_get_content_type(boundary);
  7856. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7857. return Patch(path, headers, body, content_type, progress);
  7858. }
  7859. inline Result
  7860. ClientImpl::Patch(const std::string &path, const Headers &headers,
  7861. const MultipartFormDataItemsForClientInput &items,
  7862. const std::string &boundary, UploadProgress progress) {
  7863. if (!detail::is_multipart_boundary_chars_valid(boundary)) {
  7864. return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
  7865. }
  7866. const auto &content_type =
  7867. detail::serialize_multipart_formdata_get_content_type(boundary);
  7868. const auto &body = detail::serialize_multipart_formdata(items, boundary);
  7869. return Patch(path, headers, body, content_type, progress);
  7870. }
  7871. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7872. const char *body, size_t content_length,
  7873. const std::string &content_type,
  7874. UploadProgress progress) {
  7875. return send_with_content_provider("PATCH", path, headers, body,
  7876. content_length, nullptr, nullptr,
  7877. content_type, progress);
  7878. }
  7879. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7880. const std::string &body,
  7881. const std::string &content_type,
  7882. UploadProgress progress) {
  7883. return send_with_content_provider("PATCH", path, headers, body.data(),
  7884. body.size(), nullptr, nullptr, content_type,
  7885. progress);
  7886. }
  7887. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7888. size_t content_length,
  7889. ContentProvider content_provider,
  7890. const std::string &content_type,
  7891. UploadProgress progress) {
  7892. return send_with_content_provider("PATCH", path, headers, nullptr,
  7893. content_length, std::move(content_provider),
  7894. nullptr, content_type, progress);
  7895. }
  7896. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7897. ContentProviderWithoutLength content_provider,
  7898. const std::string &content_type,
  7899. UploadProgress progress) {
  7900. return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr,
  7901. std::move(content_provider), content_type,
  7902. progress);
  7903. }
  7904. inline Result
  7905. ClientImpl::Patch(const std::string &path, const Headers &headers,
  7906. const MultipartFormDataItemsForClientInput &items,
  7907. const MultipartFormDataProviderItems &provider_items,
  7908. UploadProgress progress) {
  7909. const auto &boundary = detail::make_multipart_data_boundary();
  7910. const auto &content_type =
  7911. detail::serialize_multipart_formdata_get_content_type(boundary);
  7912. return send_with_content_provider(
  7913. "PATCH", path, headers, nullptr, 0, nullptr,
  7914. get_multipart_content_provider(boundary, items, provider_items),
  7915. content_type, progress);
  7916. }
  7917. inline Result ClientImpl::Patch(const std::string &path, const Headers &headers,
  7918. const std::string &body,
  7919. const std::string &content_type,
  7920. ContentReceiver content_receiver,
  7921. DownloadProgress progress) {
  7922. Request req;
  7923. req.method = "PATCH";
  7924. req.path = path;
  7925. req.headers = headers;
  7926. req.body = body;
  7927. req.content_receiver =
  7928. [content_receiver](const char *data, size_t data_length,
  7929. uint64_t /*offset*/, uint64_t /*total_length*/) {
  7930. return content_receiver(data, data_length);
  7931. };
  7932. req.download_progress = std::move(progress);
  7933. if (max_timeout_msec_ > 0) {
  7934. req.start_time_ = std::chrono::steady_clock::now();
  7935. }
  7936. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7937. return send_(std::move(req));
  7938. }
  7939. inline Result ClientImpl::Delete(const std::string &path,
  7940. DownloadProgress progress) {
  7941. return Delete(path, Headers(), std::string(), std::string(), progress);
  7942. }
  7943. inline Result ClientImpl::Delete(const std::string &path,
  7944. const Headers &headers,
  7945. DownloadProgress progress) {
  7946. return Delete(path, headers, std::string(), std::string(), progress);
  7947. }
  7948. inline Result ClientImpl::Delete(const std::string &path, const char *body,
  7949. size_t content_length,
  7950. const std::string &content_type,
  7951. DownloadProgress progress) {
  7952. return Delete(path, Headers(), body, content_length, content_type, progress);
  7953. }
  7954. inline Result ClientImpl::Delete(const std::string &path,
  7955. const std::string &body,
  7956. const std::string &content_type,
  7957. DownloadProgress progress) {
  7958. return Delete(path, Headers(), body.data(), body.size(), content_type,
  7959. progress);
  7960. }
  7961. inline Result ClientImpl::Delete(const std::string &path,
  7962. const Headers &headers,
  7963. const std::string &body,
  7964. const std::string &content_type,
  7965. DownloadProgress progress) {
  7966. return Delete(path, headers, body.data(), body.size(), content_type,
  7967. progress);
  7968. }
  7969. inline Result ClientImpl::Delete(const std::string &path, const Params &params,
  7970. DownloadProgress progress) {
  7971. return Delete(path, Headers(), params, progress);
  7972. }
  7973. inline Result ClientImpl::Delete(const std::string &path,
  7974. const Headers &headers, const Params &params,
  7975. DownloadProgress progress) {
  7976. auto query = detail::params_to_query_str(params);
  7977. return Delete(path, headers, query, "application/x-www-form-urlencoded",
  7978. progress);
  7979. }
  7980. inline Result ClientImpl::Delete(const std::string &path,
  7981. const Headers &headers, const char *body,
  7982. size_t content_length,
  7983. const std::string &content_type,
  7984. DownloadProgress progress) {
  7985. Request req;
  7986. req.method = "DELETE";
  7987. req.headers = headers;
  7988. req.path = path;
  7989. req.download_progress = std::move(progress);
  7990. if (max_timeout_msec_ > 0) {
  7991. req.start_time_ = std::chrono::steady_clock::now();
  7992. }
  7993. if (!content_type.empty()) { req.set_header("Content-Type", content_type); }
  7994. req.body.assign(body, content_length);
  7995. return send_(std::move(req));
  7996. }
  7997. inline Result ClientImpl::Options(const std::string &path) {
  7998. return Options(path, Headers());
  7999. }
  8000. inline Result ClientImpl::Options(const std::string &path,
  8001. const Headers &headers) {
  8002. Request req;
  8003. req.method = "OPTIONS";
  8004. req.headers = headers;
  8005. req.path = path;
  8006. if (max_timeout_msec_ > 0) {
  8007. req.start_time_ = std::chrono::steady_clock::now();
  8008. }
  8009. return send_(std::move(req));
  8010. }
  8011. inline void ClientImpl::stop() {
  8012. std::lock_guard<std::mutex> guard(socket_mutex_);
  8013. // If there is anything ongoing right now, the ONLY thread-safe thing we can
  8014. // do is to shutdown_socket, so that threads using this socket suddenly
  8015. // discover they can't read/write any more and error out. Everything else
  8016. // (closing the socket, shutting ssl down) is unsafe because these actions are
  8017. // not thread-safe.
  8018. if (socket_requests_in_flight_ > 0) {
  8019. shutdown_socket(socket_);
  8020. // Aside from that, we set a flag for the socket to be closed when we're
  8021. // done.
  8022. socket_should_be_closed_when_request_is_done_ = true;
  8023. return;
  8024. }
  8025. // Otherwise, still holding the mutex, we can shut everything down ourselves
  8026. shutdown_ssl(socket_, true);
  8027. shutdown_socket(socket_);
  8028. close_socket(socket_);
  8029. }
  8030. inline std::string ClientImpl::host() const { return host_; }
  8031. inline int ClientImpl::port() const { return port_; }
  8032. inline size_t ClientImpl::is_socket_open() const {
  8033. std::lock_guard<std::mutex> guard(socket_mutex_);
  8034. return socket_.is_open();
  8035. }
  8036. inline socket_t ClientImpl::socket() const { return socket_.sock; }
  8037. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  8038. connection_timeout_sec_ = sec;
  8039. connection_timeout_usec_ = usec;
  8040. }
  8041. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  8042. read_timeout_sec_ = sec;
  8043. read_timeout_usec_ = usec;
  8044. }
  8045. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  8046. write_timeout_sec_ = sec;
  8047. write_timeout_usec_ = usec;
  8048. }
  8049. inline void ClientImpl::set_max_timeout(time_t msec) {
  8050. max_timeout_msec_ = msec;
  8051. }
  8052. inline void ClientImpl::set_basic_auth(const std::string &username,
  8053. const std::string &password) {
  8054. basic_auth_username_ = username;
  8055. basic_auth_password_ = password;
  8056. }
  8057. inline void ClientImpl::set_bearer_token_auth(const std::string &token) {
  8058. bearer_token_auth_token_ = token;
  8059. }
  8060. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8061. inline void ClientImpl::set_digest_auth(const std::string &username,
  8062. const std::string &password) {
  8063. digest_auth_username_ = username;
  8064. digest_auth_password_ = password;
  8065. }
  8066. #endif
  8067. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  8068. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  8069. inline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; }
  8070. inline void
  8071. ClientImpl::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  8072. addr_map_ = std::move(addr_map);
  8073. }
  8074. inline void ClientImpl::set_default_headers(Headers headers) {
  8075. default_headers_ = std::move(headers);
  8076. }
  8077. inline void ClientImpl::set_header_writer(
  8078. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  8079. header_writer_ = writer;
  8080. }
  8081. inline void ClientImpl::set_address_family(int family) {
  8082. address_family_ = family;
  8083. }
  8084. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  8085. inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; }
  8086. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  8087. socket_options_ = std::move(socket_options);
  8088. }
  8089. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  8090. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  8091. inline void ClientImpl::set_interface(const std::string &intf) {
  8092. interface_ = intf;
  8093. }
  8094. inline void ClientImpl::set_proxy(const std::string &host, int port) {
  8095. proxy_host_ = host;
  8096. proxy_port_ = port;
  8097. }
  8098. inline void ClientImpl::set_proxy_basic_auth(const std::string &username,
  8099. const std::string &password) {
  8100. proxy_basic_auth_username_ = username;
  8101. proxy_basic_auth_password_ = password;
  8102. }
  8103. inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) {
  8104. proxy_bearer_token_auth_token_ = token;
  8105. }
  8106. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8107. inline void ClientImpl::set_proxy_digest_auth(const std::string &username,
  8108. const std::string &password) {
  8109. proxy_digest_auth_username_ = username;
  8110. proxy_digest_auth_password_ = password;
  8111. }
  8112. inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path,
  8113. const std::string &ca_cert_dir_path) {
  8114. ca_cert_file_path_ = ca_cert_file_path;
  8115. ca_cert_dir_path_ = ca_cert_dir_path;
  8116. }
  8117. inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
  8118. if (ca_cert_store && ca_cert_store != ca_cert_store_) {
  8119. ca_cert_store_ = ca_cert_store;
  8120. }
  8121. }
  8122. inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert,
  8123. std::size_t size) const {
  8124. auto mem = BIO_new_mem_buf(ca_cert, static_cast<int>(size));
  8125. auto se = detail::scope_exit([&] { BIO_free_all(mem); });
  8126. if (!mem) { return nullptr; }
  8127. auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr);
  8128. if (!inf) { return nullptr; }
  8129. auto cts = X509_STORE_new();
  8130. if (cts) {
  8131. for (auto i = 0; i < static_cast<int>(sk_X509_INFO_num(inf)); i++) {
  8132. auto itmp = sk_X509_INFO_value(inf, i);
  8133. if (!itmp) { continue; }
  8134. if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); }
  8135. if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); }
  8136. }
  8137. }
  8138. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  8139. return cts;
  8140. }
  8141. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  8142. server_certificate_verification_ = enabled;
  8143. }
  8144. inline void ClientImpl::enable_server_hostname_verification(bool enabled) {
  8145. server_hostname_verification_ = enabled;
  8146. }
  8147. inline void ClientImpl::set_server_certificate_verifier(
  8148. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  8149. server_certificate_verifier_ = verifier;
  8150. }
  8151. #endif
  8152. inline void ClientImpl::set_logger(Logger logger) {
  8153. logger_ = std::move(logger);
  8154. }
  8155. /*
  8156. * SSL Implementation
  8157. */
  8158. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8159. namespace detail {
  8160. template <typename U, typename V>
  8161. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  8162. U SSL_connect_or_accept, V setup) {
  8163. SSL *ssl = nullptr;
  8164. {
  8165. std::lock_guard<std::mutex> guard(ctx_mutex);
  8166. ssl = SSL_new(ctx);
  8167. }
  8168. if (ssl) {
  8169. set_nonblocking(sock, true);
  8170. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  8171. BIO_set_nbio(bio, 1);
  8172. SSL_set_bio(ssl, bio, bio);
  8173. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  8174. SSL_shutdown(ssl);
  8175. {
  8176. std::lock_guard<std::mutex> guard(ctx_mutex);
  8177. SSL_free(ssl);
  8178. }
  8179. set_nonblocking(sock, false);
  8180. return nullptr;
  8181. }
  8182. BIO_set_nbio(bio, 0);
  8183. set_nonblocking(sock, false);
  8184. }
  8185. return ssl;
  8186. }
  8187. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock,
  8188. bool shutdown_gracefully) {
  8189. // sometimes we may want to skip this to try to avoid SIGPIPE if we know
  8190. // the remote has closed the network connection
  8191. // Note that it is not always possible to avoid SIGPIPE, this is merely a
  8192. // best-efforts.
  8193. if (shutdown_gracefully) {
  8194. (void)(sock);
  8195. // SSL_shutdown() returns 0 on first call (indicating close_notify alert
  8196. // sent) and 1 on subsequent call (indicating close_notify alert received)
  8197. if (SSL_shutdown(ssl) == 0) {
  8198. // Expected to return 1, but even if it doesn't, we free ssl
  8199. SSL_shutdown(ssl);
  8200. }
  8201. }
  8202. std::lock_guard<std::mutex> guard(ctx_mutex);
  8203. SSL_free(ssl);
  8204. }
  8205. template <typename U>
  8206. bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
  8207. U ssl_connect_or_accept,
  8208. time_t timeout_sec, time_t timeout_usec,
  8209. int *ssl_error) {
  8210. auto res = 0;
  8211. while ((res = ssl_connect_or_accept(ssl)) != 1) {
  8212. auto err = SSL_get_error(ssl, res);
  8213. switch (err) {
  8214. case SSL_ERROR_WANT_READ:
  8215. if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
  8216. break;
  8217. case SSL_ERROR_WANT_WRITE:
  8218. if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
  8219. break;
  8220. default: break;
  8221. }
  8222. if (ssl_error) { *ssl_error = err; }
  8223. return false;
  8224. }
  8225. return true;
  8226. }
  8227. template <typename T>
  8228. inline bool process_server_socket_ssl(
  8229. const std::atomic<socket_t> &svr_sock, SSL *ssl, socket_t sock,
  8230. size_t keep_alive_max_count, time_t keep_alive_timeout_sec,
  8231. time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec,
  8232. time_t write_timeout_usec, T callback) {
  8233. return process_server_socket_core(
  8234. svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec,
  8235. [&](bool close_connection, bool &connection_closed) {
  8236. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  8237. write_timeout_sec, write_timeout_usec);
  8238. return callback(strm, close_connection, connection_closed);
  8239. });
  8240. }
  8241. template <typename T>
  8242. inline bool process_client_socket_ssl(
  8243. SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  8244. time_t write_timeout_sec, time_t write_timeout_usec,
  8245. time_t max_timeout_msec,
  8246. std::chrono::time_point<std::chrono::steady_clock> start_time, T callback) {
  8247. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  8248. write_timeout_sec, write_timeout_usec, max_timeout_msec,
  8249. start_time);
  8250. return callback(strm);
  8251. }
  8252. // SSL socket stream implementation
  8253. inline SSLSocketStream::SSLSocketStream(
  8254. socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec,
  8255. time_t write_timeout_sec, time_t write_timeout_usec,
  8256. time_t max_timeout_msec,
  8257. std::chrono::time_point<std::chrono::steady_clock> start_time)
  8258. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  8259. read_timeout_usec_(read_timeout_usec),
  8260. write_timeout_sec_(write_timeout_sec),
  8261. write_timeout_usec_(write_timeout_usec),
  8262. max_timeout_msec_(max_timeout_msec), start_time_(start_time) {
  8263. SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
  8264. }
  8265. inline SSLSocketStream::~SSLSocketStream() = default;
  8266. inline bool SSLSocketStream::is_readable() const {
  8267. return SSL_pending(ssl_) > 0;
  8268. }
  8269. inline bool SSLSocketStream::wait_readable() const {
  8270. if (max_timeout_msec_ <= 0) {
  8271. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  8272. }
  8273. time_t read_timeout_sec;
  8274. time_t read_timeout_usec;
  8275. calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_,
  8276. read_timeout_usec_, read_timeout_sec, read_timeout_usec);
  8277. return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0;
  8278. }
  8279. inline bool SSLSocketStream::wait_writable() const {
  8280. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 &&
  8281. is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_);
  8282. }
  8283. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  8284. if (SSL_pending(ssl_) > 0) {
  8285. return SSL_read(ssl_, ptr, static_cast<int>(size));
  8286. } else if (wait_readable()) {
  8287. auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  8288. if (ret < 0) {
  8289. auto err = SSL_get_error(ssl_, ret);
  8290. auto n = 1000;
  8291. #ifdef _WIN32
  8292. while (--n >= 0 && (err == SSL_ERROR_WANT_READ ||
  8293. (err == SSL_ERROR_SYSCALL &&
  8294. WSAGetLastError() == WSAETIMEDOUT))) {
  8295. #else
  8296. while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
  8297. #endif
  8298. if (SSL_pending(ssl_) > 0) {
  8299. return SSL_read(ssl_, ptr, static_cast<int>(size));
  8300. } else if (wait_readable()) {
  8301. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8302. ret = SSL_read(ssl_, ptr, static_cast<int>(size));
  8303. if (ret >= 0) { return ret; }
  8304. err = SSL_get_error(ssl_, ret);
  8305. } else {
  8306. break;
  8307. }
  8308. }
  8309. assert(ret < 0);
  8310. }
  8311. return ret;
  8312. } else {
  8313. return -1;
  8314. }
  8315. }
  8316. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  8317. if (wait_writable()) {
  8318. auto handle_size = static_cast<int>(
  8319. std::min<size_t>(size, (std::numeric_limits<int>::max)()));
  8320. auto ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  8321. if (ret < 0) {
  8322. auto err = SSL_get_error(ssl_, ret);
  8323. auto n = 1000;
  8324. #ifdef _WIN32
  8325. while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE ||
  8326. (err == SSL_ERROR_SYSCALL &&
  8327. WSAGetLastError() == WSAETIMEDOUT))) {
  8328. #else
  8329. while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) {
  8330. #endif
  8331. if (wait_writable()) {
  8332. std::this_thread::sleep_for(std::chrono::microseconds{10});
  8333. ret = SSL_write(ssl_, ptr, static_cast<int>(handle_size));
  8334. if (ret >= 0) { return ret; }
  8335. err = SSL_get_error(ssl_, ret);
  8336. } else {
  8337. break;
  8338. }
  8339. }
  8340. assert(ret < 0);
  8341. }
  8342. return ret;
  8343. }
  8344. return -1;
  8345. }
  8346. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  8347. int &port) const {
  8348. detail::get_remote_ip_and_port(sock_, ip, port);
  8349. }
  8350. inline void SSLSocketStream::get_local_ip_and_port(std::string &ip,
  8351. int &port) const {
  8352. detail::get_local_ip_and_port(sock_, ip, port);
  8353. }
  8354. inline socket_t SSLSocketStream::socket() const { return sock_; }
  8355. inline time_t SSLSocketStream::duration() const {
  8356. return std::chrono::duration_cast<std::chrono::milliseconds>(
  8357. std::chrono::steady_clock::now() - start_time_)
  8358. .count();
  8359. }
  8360. } // namespace detail
  8361. // SSL HTTP server implementation
  8362. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  8363. const char *client_ca_cert_file_path,
  8364. const char *client_ca_cert_dir_path,
  8365. const char *private_key_password) {
  8366. ctx_ = SSL_CTX_new(TLS_server_method());
  8367. if (ctx_) {
  8368. SSL_CTX_set_options(ctx_,
  8369. SSL_OP_NO_COMPRESSION |
  8370. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  8371. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8372. if (private_key_password != nullptr && (private_key_password[0] != '\0')) {
  8373. SSL_CTX_set_default_passwd_cb_userdata(
  8374. ctx_,
  8375. reinterpret_cast<void *>(const_cast<char *>(private_key_password)));
  8376. }
  8377. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  8378. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  8379. 1 ||
  8380. SSL_CTX_check_private_key(ctx_) != 1) {
  8381. last_ssl_error_ = static_cast<int>(ERR_get_error());
  8382. SSL_CTX_free(ctx_);
  8383. ctx_ = nullptr;
  8384. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  8385. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  8386. client_ca_cert_dir_path);
  8387. SSL_CTX_set_verify(
  8388. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  8389. }
  8390. }
  8391. }
  8392. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  8393. X509_STORE *client_ca_cert_store) {
  8394. ctx_ = SSL_CTX_new(TLS_server_method());
  8395. if (ctx_) {
  8396. SSL_CTX_set_options(ctx_,
  8397. SSL_OP_NO_COMPRESSION |
  8398. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  8399. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8400. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  8401. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  8402. SSL_CTX_free(ctx_);
  8403. ctx_ = nullptr;
  8404. } else if (client_ca_cert_store) {
  8405. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  8406. SSL_CTX_set_verify(
  8407. ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);
  8408. }
  8409. }
  8410. }
  8411. inline SSLServer::SSLServer(
  8412. const std::function<bool(SSL_CTX &ssl_ctx)> &setup_ssl_ctx_callback) {
  8413. ctx_ = SSL_CTX_new(TLS_method());
  8414. if (ctx_) {
  8415. if (!setup_ssl_ctx_callback(*ctx_)) {
  8416. SSL_CTX_free(ctx_);
  8417. ctx_ = nullptr;
  8418. }
  8419. }
  8420. }
  8421. inline SSLServer::~SSLServer() {
  8422. if (ctx_) { SSL_CTX_free(ctx_); }
  8423. }
  8424. inline bool SSLServer::is_valid() const { return ctx_; }
  8425. inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; }
  8426. inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key,
  8427. X509_STORE *client_ca_cert_store) {
  8428. std::lock_guard<std::mutex> guard(ctx_mutex_);
  8429. SSL_CTX_use_certificate(ctx_, cert);
  8430. SSL_CTX_use_PrivateKey(ctx_, private_key);
  8431. if (client_ca_cert_store != nullptr) {
  8432. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  8433. }
  8434. }
  8435. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  8436. auto ssl = detail::ssl_new(
  8437. sock, ctx_, ctx_mutex_,
  8438. [&](SSL *ssl2) {
  8439. return detail::ssl_connect_or_accept_nonblocking(
  8440. sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_,
  8441. &last_ssl_error_);
  8442. },
  8443. [](SSL * /*ssl2*/) { return true; });
  8444. auto ret = false;
  8445. if (ssl) {
  8446. std::string remote_addr;
  8447. int remote_port = 0;
  8448. detail::get_remote_ip_and_port(sock, remote_addr, remote_port);
  8449. std::string local_addr;
  8450. int local_port = 0;
  8451. detail::get_local_ip_and_port(sock, local_addr, local_port);
  8452. ret = detail::process_server_socket_ssl(
  8453. svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  8454. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  8455. write_timeout_usec_,
  8456. [&](Stream &strm, bool close_connection, bool &connection_closed) {
  8457. return process_request(strm, remote_addr, remote_port, local_addr,
  8458. local_port, close_connection,
  8459. connection_closed,
  8460. [&](Request &req) { req.ssl = ssl; });
  8461. });
  8462. // Shutdown gracefully if the result seemed successful, non-gracefully if
  8463. // the connection appeared to be closed.
  8464. const bool shutdown_gracefully = ret;
  8465. detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully);
  8466. }
  8467. detail::shutdown_socket(sock);
  8468. detail::close_socket(sock);
  8469. return ret;
  8470. }
  8471. // SSL HTTP client implementation
  8472. inline SSLClient::SSLClient(const std::string &host)
  8473. : SSLClient(host, 443, std::string(), std::string()) {}
  8474. inline SSLClient::SSLClient(const std::string &host, int port)
  8475. : SSLClient(host, port, std::string(), std::string()) {}
  8476. inline SSLClient::SSLClient(const std::string &host, int port,
  8477. const std::string &client_cert_path,
  8478. const std::string &client_key_path,
  8479. const std::string &private_key_password)
  8480. : ClientImpl(host, port, client_cert_path, client_key_path) {
  8481. ctx_ = SSL_CTX_new(TLS_client_method());
  8482. SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION);
  8483. detail::split(&host_[0], &host_[host_.size()], '.',
  8484. [&](const char *b, const char *e) {
  8485. host_components_.emplace_back(b, e);
  8486. });
  8487. if (!client_cert_path.empty() && !client_key_path.empty()) {
  8488. if (!private_key_password.empty()) {
  8489. SSL_CTX_set_default_passwd_cb_userdata(
  8490. ctx_, reinterpret_cast<void *>(
  8491. const_cast<char *>(private_key_password.c_str())));
  8492. }
  8493. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  8494. SSL_FILETYPE_PEM) != 1 ||
  8495. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  8496. SSL_FILETYPE_PEM) != 1) {
  8497. last_openssl_error_ = ERR_get_error();
  8498. SSL_CTX_free(ctx_);
  8499. ctx_ = nullptr;
  8500. }
  8501. }
  8502. }
  8503. inline SSLClient::SSLClient(const std::string &host, int port,
  8504. X509 *client_cert, EVP_PKEY *client_key,
  8505. const std::string &private_key_password)
  8506. : ClientImpl(host, port) {
  8507. ctx_ = SSL_CTX_new(TLS_client_method());
  8508. detail::split(&host_[0], &host_[host_.size()], '.',
  8509. [&](const char *b, const char *e) {
  8510. host_components_.emplace_back(b, e);
  8511. });
  8512. if (client_cert != nullptr && client_key != nullptr) {
  8513. if (!private_key_password.empty()) {
  8514. SSL_CTX_set_default_passwd_cb_userdata(
  8515. ctx_, reinterpret_cast<void *>(
  8516. const_cast<char *>(private_key_password.c_str())));
  8517. }
  8518. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  8519. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  8520. last_openssl_error_ = ERR_get_error();
  8521. SSL_CTX_free(ctx_);
  8522. ctx_ = nullptr;
  8523. }
  8524. }
  8525. }
  8526. inline SSLClient::~SSLClient() {
  8527. if (ctx_) { SSL_CTX_free(ctx_); }
  8528. // Make sure to shut down SSL since shutdown_ssl will resolve to the
  8529. // base function rather than the derived function once we get to the
  8530. // base class destructor, and won't free the SSL (causing a leak).
  8531. shutdown_ssl_impl(socket_, true);
  8532. }
  8533. inline bool SSLClient::is_valid() const { return ctx_; }
  8534. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  8535. if (ca_cert_store) {
  8536. if (ctx_) {
  8537. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
  8538. // Free memory allocated for old cert and use new store `ca_cert_store`
  8539. SSL_CTX_set_cert_store(ctx_, ca_cert_store);
  8540. }
  8541. } else {
  8542. X509_STORE_free(ca_cert_store);
  8543. }
  8544. }
  8545. }
  8546. inline void SSLClient::load_ca_cert_store(const char *ca_cert,
  8547. std::size_t size) {
  8548. set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size));
  8549. }
  8550. inline long SSLClient::get_openssl_verify_result() const {
  8551. return verify_result_;
  8552. }
  8553. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  8554. inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
  8555. return is_valid() && ClientImpl::create_and_connect_socket(socket, error);
  8556. }
  8557. // Assumes that socket_mutex_ is locked and that there are no requests in flight
  8558. inline bool SSLClient::connect_with_proxy(
  8559. Socket &socket,
  8560. std::chrono::time_point<std::chrono::steady_clock> start_time,
  8561. Response &res, bool &success, Error &error) {
  8562. success = true;
  8563. Response proxy_res;
  8564. if (!detail::process_client_socket(
  8565. socket.sock, read_timeout_sec_, read_timeout_usec_,
  8566. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  8567. start_time, [&](Stream &strm) {
  8568. Request req2;
  8569. req2.method = "CONNECT";
  8570. req2.path = host_and_port_;
  8571. if (max_timeout_msec_ > 0) {
  8572. req2.start_time_ = std::chrono::steady_clock::now();
  8573. }
  8574. return process_request(strm, req2, proxy_res, false, error);
  8575. })) {
  8576. // Thread-safe to close everything because we are assuming there are no
  8577. // requests in flight
  8578. shutdown_ssl(socket, true);
  8579. shutdown_socket(socket);
  8580. close_socket(socket);
  8581. success = false;
  8582. return false;
  8583. }
  8584. if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) {
  8585. if (!proxy_digest_auth_username_.empty() &&
  8586. !proxy_digest_auth_password_.empty()) {
  8587. std::map<std::string, std::string> auth;
  8588. if (detail::parse_www_authenticate(proxy_res, auth, true)) {
  8589. // Close the current socket and create a new one for the authenticated
  8590. // request
  8591. shutdown_ssl(socket, true);
  8592. shutdown_socket(socket);
  8593. close_socket(socket);
  8594. // Create a new socket for the authenticated CONNECT request
  8595. if (!create_and_connect_socket(socket, error)) {
  8596. success = false;
  8597. return false;
  8598. }
  8599. proxy_res = Response();
  8600. if (!detail::process_client_socket(
  8601. socket.sock, read_timeout_sec_, read_timeout_usec_,
  8602. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_,
  8603. start_time, [&](Stream &strm) {
  8604. Request req3;
  8605. req3.method = "CONNECT";
  8606. req3.path = host_and_port_;
  8607. req3.headers.insert(detail::make_digest_authentication_header(
  8608. req3, auth, 1, detail::random_string(10),
  8609. proxy_digest_auth_username_, proxy_digest_auth_password_,
  8610. true));
  8611. if (max_timeout_msec_ > 0) {
  8612. req3.start_time_ = std::chrono::steady_clock::now();
  8613. }
  8614. return process_request(strm, req3, proxy_res, false, error);
  8615. })) {
  8616. // Thread-safe to close everything because we are assuming there are
  8617. // no requests in flight
  8618. shutdown_ssl(socket, true);
  8619. shutdown_socket(socket);
  8620. close_socket(socket);
  8621. success = false;
  8622. return false;
  8623. }
  8624. }
  8625. }
  8626. }
  8627. // If status code is not 200, proxy request is failed.
  8628. // Set error to ProxyConnection and return proxy response
  8629. // as the response of the request
  8630. if (proxy_res.status != StatusCode::OK_200) {
  8631. error = Error::ProxyConnection;
  8632. res = std::move(proxy_res);
  8633. // Thread-safe to close everything because we are assuming there are
  8634. // no requests in flight
  8635. shutdown_ssl(socket, true);
  8636. shutdown_socket(socket);
  8637. close_socket(socket);
  8638. return false;
  8639. }
  8640. return true;
  8641. }
  8642. inline bool SSLClient::load_certs() {
  8643. auto ret = true;
  8644. std::call_once(initialize_cert_, [&]() {
  8645. std::lock_guard<std::mutex> guard(ctx_mutex_);
  8646. if (!ca_cert_file_path_.empty()) {
  8647. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  8648. nullptr)) {
  8649. last_openssl_error_ = ERR_get_error();
  8650. ret = false;
  8651. }
  8652. } else if (!ca_cert_dir_path_.empty()) {
  8653. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  8654. ca_cert_dir_path_.c_str())) {
  8655. last_openssl_error_ = ERR_get_error();
  8656. ret = false;
  8657. }
  8658. } else {
  8659. auto loaded = false;
  8660. #ifdef _WIN32
  8661. loaded =
  8662. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  8663. #elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && \
  8664. defined(TARGET_OS_OSX)
  8665. loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_));
  8666. #endif // _WIN32
  8667. if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); }
  8668. }
  8669. });
  8670. return ret;
  8671. }
  8672. inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
  8673. auto ssl = detail::ssl_new(
  8674. socket.sock, ctx_, ctx_mutex_,
  8675. [&](SSL *ssl2) {
  8676. if (server_certificate_verification_) {
  8677. if (!load_certs()) {
  8678. error = Error::SSLLoadingCerts;
  8679. return false;
  8680. }
  8681. SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr);
  8682. }
  8683. if (!detail::ssl_connect_or_accept_nonblocking(
  8684. socket.sock, ssl2, SSL_connect, connection_timeout_sec_,
  8685. connection_timeout_usec_, &last_ssl_error_)) {
  8686. error = Error::SSLConnection;
  8687. return false;
  8688. }
  8689. if (server_certificate_verification_) {
  8690. auto verification_status = SSLVerifierResponse::NoDecisionMade;
  8691. if (server_certificate_verifier_) {
  8692. verification_status = server_certificate_verifier_(ssl2);
  8693. }
  8694. if (verification_status == SSLVerifierResponse::CertificateRejected) {
  8695. last_openssl_error_ = ERR_get_error();
  8696. error = Error::SSLServerVerification;
  8697. return false;
  8698. }
  8699. if (verification_status == SSLVerifierResponse::NoDecisionMade) {
  8700. verify_result_ = SSL_get_verify_result(ssl2);
  8701. if (verify_result_ != X509_V_OK) {
  8702. last_openssl_error_ = static_cast<unsigned long>(verify_result_);
  8703. error = Error::SSLServerVerification;
  8704. return false;
  8705. }
  8706. auto server_cert = SSL_get1_peer_certificate(ssl2);
  8707. auto se = detail::scope_exit([&] { X509_free(server_cert); });
  8708. if (server_cert == nullptr) {
  8709. last_openssl_error_ = ERR_get_error();
  8710. error = Error::SSLServerVerification;
  8711. return false;
  8712. }
  8713. if (server_hostname_verification_) {
  8714. if (!verify_host(server_cert)) {
  8715. last_openssl_error_ = X509_V_ERR_HOSTNAME_MISMATCH;
  8716. error = Error::SSLServerHostnameVerification;
  8717. return false;
  8718. }
  8719. }
  8720. }
  8721. }
  8722. return true;
  8723. },
  8724. [&](SSL *ssl2) {
  8725. #if defined(OPENSSL_IS_BORINGSSL)
  8726. SSL_set_tlsext_host_name(ssl2, host_.c_str());
  8727. #else
  8728. // NOTE: Direct call instead of using the OpenSSL macro to suppress
  8729. // -Wold-style-cast warning
  8730. SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
  8731. static_cast<void *>(const_cast<char *>(host_.c_str())));
  8732. #endif
  8733. return true;
  8734. });
  8735. if (ssl) {
  8736. socket.ssl = ssl;
  8737. return true;
  8738. }
  8739. shutdown_socket(socket);
  8740. close_socket(socket);
  8741. return false;
  8742. }
  8743. inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
  8744. shutdown_ssl_impl(socket, shutdown_gracefully);
  8745. }
  8746. inline void SSLClient::shutdown_ssl_impl(Socket &socket,
  8747. bool shutdown_gracefully) {
  8748. if (socket.sock == INVALID_SOCKET) {
  8749. assert(socket.ssl == nullptr);
  8750. return;
  8751. }
  8752. if (socket.ssl) {
  8753. detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock,
  8754. shutdown_gracefully);
  8755. socket.ssl = nullptr;
  8756. }
  8757. assert(socket.ssl == nullptr);
  8758. }
  8759. inline bool SSLClient::process_socket(
  8760. const Socket &socket,
  8761. std::chrono::time_point<std::chrono::steady_clock> start_time,
  8762. std::function<bool(Stream &strm)> callback) {
  8763. assert(socket.ssl);
  8764. return detail::process_client_socket_ssl(
  8765. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  8766. write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time,
  8767. std::move(callback));
  8768. }
  8769. inline bool SSLClient::is_ssl() const { return true; }
  8770. inline bool SSLClient::verify_host(X509 *server_cert) const {
  8771. /* Quote from RFC2818 section 3.1 "Server Identity"
  8772. If a subjectAltName extension of type dNSName is present, that MUST
  8773. be used as the identity. Otherwise, the (most specific) Common Name
  8774. field in the Subject field of the certificate MUST be used. Although
  8775. the use of the Common Name is existing practice, it is deprecated and
  8776. Certification Authorities are encouraged to use the dNSName instead.
  8777. Matching is performed using the matching rules specified by
  8778. [RFC2459]. If more than one identity of a given type is present in
  8779. the certificate (e.g., more than one dNSName name, a match in any one
  8780. of the set is considered acceptable.) Names may contain the wildcard
  8781. character * which is considered to match any single domain name
  8782. component or component fragment. E.g., *.a.com matches foo.a.com but
  8783. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  8784. In some cases, the URI is specified as an IP address rather than a
  8785. hostname. In this case, the iPAddress subjectAltName must be present
  8786. in the certificate and must exactly match the IP in the URI.
  8787. */
  8788. return verify_host_with_subject_alt_name(server_cert) ||
  8789. verify_host_with_common_name(server_cert);
  8790. }
  8791. inline bool
  8792. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  8793. auto ret = false;
  8794. auto type = GEN_DNS;
  8795. struct in6_addr addr6 = {};
  8796. struct in_addr addr = {};
  8797. size_t addr_len = 0;
  8798. #ifndef __MINGW32__
  8799. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  8800. type = GEN_IPADD;
  8801. addr_len = sizeof(struct in6_addr);
  8802. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  8803. type = GEN_IPADD;
  8804. addr_len = sizeof(struct in_addr);
  8805. }
  8806. #endif
  8807. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  8808. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  8809. if (alt_names) {
  8810. auto dsn_matched = false;
  8811. auto ip_matched = false;
  8812. auto count = sk_GENERAL_NAME_num(alt_names);
  8813. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  8814. auto val = sk_GENERAL_NAME_value(alt_names, i);
  8815. if (val->type == type) {
  8816. auto name =
  8817. reinterpret_cast<const char *>(ASN1_STRING_get0_data(val->d.ia5));
  8818. auto name_len = static_cast<size_t>(ASN1_STRING_length(val->d.ia5));
  8819. switch (type) {
  8820. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  8821. case GEN_IPADD:
  8822. if (!memcmp(&addr6, name, addr_len) ||
  8823. !memcmp(&addr, name, addr_len)) {
  8824. ip_matched = true;
  8825. }
  8826. break;
  8827. }
  8828. }
  8829. }
  8830. if (dsn_matched || ip_matched) { ret = true; }
  8831. }
  8832. GENERAL_NAMES_free(const_cast<STACK_OF(GENERAL_NAME) *>(
  8833. reinterpret_cast<const STACK_OF(GENERAL_NAME) *>(alt_names)));
  8834. return ret;
  8835. }
  8836. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  8837. const auto subject_name = X509_get_subject_name(server_cert);
  8838. if (subject_name != nullptr) {
  8839. char name[BUFSIZ];
  8840. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  8841. name, sizeof(name));
  8842. if (name_len != -1) {
  8843. return check_host_name(name, static_cast<size_t>(name_len));
  8844. }
  8845. }
  8846. return false;
  8847. }
  8848. inline bool SSLClient::check_host_name(const char *pattern,
  8849. size_t pattern_len) const {
  8850. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  8851. // Wildcard match
  8852. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  8853. std::vector<std::string> pattern_components;
  8854. detail::split(&pattern[0], &pattern[pattern_len], '.',
  8855. [&](const char *b, const char *e) {
  8856. pattern_components.emplace_back(b, e);
  8857. });
  8858. if (host_components_.size() != pattern_components.size()) { return false; }
  8859. auto itr = pattern_components.begin();
  8860. for (const auto &h : host_components_) {
  8861. auto &p = *itr;
  8862. if (p != h && p != "*") {
  8863. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  8864. !p.compare(0, p.size() - 1, h));
  8865. if (!partial_match) { return false; }
  8866. }
  8867. ++itr;
  8868. }
  8869. return true;
  8870. }
  8871. #endif
  8872. // Universal client implementation
  8873. inline Client::Client(const std::string &scheme_host_port)
  8874. : Client(scheme_host_port, std::string(), std::string()) {}
  8875. inline Client::Client(const std::string &scheme_host_port,
  8876. const std::string &client_cert_path,
  8877. const std::string &client_key_path) {
  8878. const static std::regex re(
  8879. R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
  8880. std::smatch m;
  8881. if (std::regex_match(scheme_host_port, m, re)) {
  8882. auto scheme = m[1].str();
  8883. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8884. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  8885. #else
  8886. if (!scheme.empty() && scheme != "http") {
  8887. #endif
  8888. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8889. std::string msg = "'" + scheme + "' scheme is not supported.";
  8890. throw std::invalid_argument(msg);
  8891. #endif
  8892. return;
  8893. }
  8894. auto is_ssl = scheme == "https";
  8895. auto host = m[2].str();
  8896. if (host.empty()) { host = m[3].str(); }
  8897. auto port_str = m[4].str();
  8898. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  8899. if (is_ssl) {
  8900. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8901. cli_ = detail::make_unique<SSLClient>(host, port, client_cert_path,
  8902. client_key_path);
  8903. is_ssl_ = is_ssl;
  8904. #endif
  8905. } else {
  8906. cli_ = detail::make_unique<ClientImpl>(host, port, client_cert_path,
  8907. client_key_path);
  8908. }
  8909. } else {
  8910. // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress)
  8911. // if port param below changes.
  8912. cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
  8913. client_cert_path, client_key_path);
  8914. }
  8915. } // namespace detail
  8916. inline Client::Client(const std::string &host, int port)
  8917. : cli_(detail::make_unique<ClientImpl>(host, port)) {}
  8918. inline Client::Client(const std::string &host, int port,
  8919. const std::string &client_cert_path,
  8920. const std::string &client_key_path)
  8921. : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
  8922. client_key_path)) {}
  8923. inline Client::~Client() = default;
  8924. inline bool Client::is_valid() const {
  8925. return cli_ != nullptr && cli_->is_valid();
  8926. }
  8927. inline Result Client::Get(const std::string &path, DownloadProgress progress) {
  8928. return cli_->Get(path, std::move(progress));
  8929. }
  8930. inline Result Client::Get(const std::string &path, const Headers &headers,
  8931. DownloadProgress progress) {
  8932. return cli_->Get(path, headers, std::move(progress));
  8933. }
  8934. inline Result Client::Get(const std::string &path,
  8935. ContentReceiver content_receiver,
  8936. DownloadProgress progress) {
  8937. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  8938. }
  8939. inline Result Client::Get(const std::string &path, const Headers &headers,
  8940. ContentReceiver content_receiver,
  8941. DownloadProgress progress) {
  8942. return cli_->Get(path, headers, std::move(content_receiver),
  8943. std::move(progress));
  8944. }
  8945. inline Result Client::Get(const std::string &path,
  8946. ResponseHandler response_handler,
  8947. ContentReceiver content_receiver,
  8948. DownloadProgress progress) {
  8949. return cli_->Get(path, std::move(response_handler),
  8950. std::move(content_receiver), std::move(progress));
  8951. }
  8952. inline Result Client::Get(const std::string &path, const Headers &headers,
  8953. ResponseHandler response_handler,
  8954. ContentReceiver content_receiver,
  8955. DownloadProgress progress) {
  8956. return cli_->Get(path, headers, std::move(response_handler),
  8957. std::move(content_receiver), std::move(progress));
  8958. }
  8959. inline Result Client::Get(const std::string &path, const Params &params,
  8960. const Headers &headers, DownloadProgress progress) {
  8961. return cli_->Get(path, params, headers, std::move(progress));
  8962. }
  8963. inline Result Client::Get(const std::string &path, const Params &params,
  8964. const Headers &headers,
  8965. ContentReceiver content_receiver,
  8966. DownloadProgress progress) {
  8967. return cli_->Get(path, params, headers, std::move(content_receiver),
  8968. std::move(progress));
  8969. }
  8970. inline Result Client::Get(const std::string &path, const Params &params,
  8971. const Headers &headers,
  8972. ResponseHandler response_handler,
  8973. ContentReceiver content_receiver,
  8974. DownloadProgress progress) {
  8975. return cli_->Get(path, params, headers, std::move(response_handler),
  8976. std::move(content_receiver), std::move(progress));
  8977. }
  8978. inline Result Client::Head(const std::string &path) { return cli_->Head(path); }
  8979. inline Result Client::Head(const std::string &path, const Headers &headers) {
  8980. return cli_->Head(path, headers);
  8981. }
  8982. inline Result Client::Post(const std::string &path) { return cli_->Post(path); }
  8983. inline Result Client::Post(const std::string &path, const Headers &headers) {
  8984. return cli_->Post(path, headers);
  8985. }
  8986. inline Result Client::Post(const std::string &path, const char *body,
  8987. size_t content_length,
  8988. const std::string &content_type,
  8989. UploadProgress progress) {
  8990. return cli_->Post(path, body, content_length, content_type, progress);
  8991. }
  8992. inline Result Client::Post(const std::string &path, const Headers &headers,
  8993. const char *body, size_t content_length,
  8994. const std::string &content_type,
  8995. UploadProgress progress) {
  8996. return cli_->Post(path, headers, body, content_length, content_type,
  8997. progress);
  8998. }
  8999. inline Result Client::Post(const std::string &path, const std::string &body,
  9000. const std::string &content_type,
  9001. UploadProgress progress) {
  9002. return cli_->Post(path, body, content_type, progress);
  9003. }
  9004. inline Result Client::Post(const std::string &path, const Headers &headers,
  9005. const std::string &body,
  9006. const std::string &content_type,
  9007. UploadProgress progress) {
  9008. return cli_->Post(path, headers, body, content_type, progress);
  9009. }
  9010. inline Result Client::Post(const std::string &path, size_t content_length,
  9011. ContentProvider content_provider,
  9012. const std::string &content_type,
  9013. UploadProgress progress) {
  9014. return cli_->Post(path, content_length, std::move(content_provider),
  9015. content_type, progress);
  9016. }
  9017. inline Result Client::Post(const std::string &path,
  9018. ContentProviderWithoutLength content_provider,
  9019. const std::string &content_type,
  9020. UploadProgress progress) {
  9021. return cli_->Post(path, std::move(content_provider), content_type, progress);
  9022. }
  9023. inline Result Client::Post(const std::string &path, const Headers &headers,
  9024. size_t content_length,
  9025. ContentProvider content_provider,
  9026. const std::string &content_type,
  9027. UploadProgress progress) {
  9028. return cli_->Post(path, headers, content_length, std::move(content_provider),
  9029. content_type, progress);
  9030. }
  9031. inline Result Client::Post(const std::string &path, const Headers &headers,
  9032. ContentProviderWithoutLength content_provider,
  9033. const std::string &content_type,
  9034. UploadProgress progress) {
  9035. return cli_->Post(path, headers, std::move(content_provider), content_type,
  9036. progress);
  9037. }
  9038. inline Result Client::Post(const std::string &path, const Params &params) {
  9039. return cli_->Post(path, params);
  9040. }
  9041. inline Result Client::Post(const std::string &path, const Headers &headers,
  9042. const Params &params) {
  9043. return cli_->Post(path, headers, params);
  9044. }
  9045. inline Result Client::Post(const std::string &path,
  9046. const MultipartFormDataItemsForClientInput &items,
  9047. UploadProgress progress) {
  9048. return cli_->Post(path, items, progress);
  9049. }
  9050. inline Result Client::Post(const std::string &path, const Headers &headers,
  9051. const MultipartFormDataItemsForClientInput &items,
  9052. UploadProgress progress) {
  9053. return cli_->Post(path, headers, items, progress);
  9054. }
  9055. inline Result Client::Post(const std::string &path, const Headers &headers,
  9056. const MultipartFormDataItemsForClientInput &items,
  9057. const std::string &boundary,
  9058. UploadProgress progress) {
  9059. return cli_->Post(path, headers, items, boundary, progress);
  9060. }
  9061. inline Result Client::Post(const std::string &path, const Headers &headers,
  9062. const MultipartFormDataItemsForClientInput &items,
  9063. const MultipartFormDataProviderItems &provider_items,
  9064. UploadProgress progress) {
  9065. return cli_->Post(path, headers, items, provider_items, progress);
  9066. }
  9067. inline Result Client::Post(const std::string &path, const Headers &headers,
  9068. const std::string &body,
  9069. const std::string &content_type,
  9070. ContentReceiver content_receiver,
  9071. DownloadProgress progress) {
  9072. return cli_->Post(path, headers, body, content_type, content_receiver,
  9073. progress);
  9074. }
  9075. inline Result Client::Put(const std::string &path) { return cli_->Put(path); }
  9076. inline Result Client::Put(const std::string &path, const Headers &headers) {
  9077. return cli_->Put(path, headers);
  9078. }
  9079. inline Result Client::Put(const std::string &path, const char *body,
  9080. size_t content_length,
  9081. const std::string &content_type,
  9082. UploadProgress progress) {
  9083. return cli_->Put(path, body, content_length, content_type, progress);
  9084. }
  9085. inline Result Client::Put(const std::string &path, const Headers &headers,
  9086. const char *body, size_t content_length,
  9087. const std::string &content_type,
  9088. UploadProgress progress) {
  9089. return cli_->Put(path, headers, body, content_length, content_type, progress);
  9090. }
  9091. inline Result Client::Put(const std::string &path, const std::string &body,
  9092. const std::string &content_type,
  9093. UploadProgress progress) {
  9094. return cli_->Put(path, body, content_type, progress);
  9095. }
  9096. inline Result Client::Put(const std::string &path, const Headers &headers,
  9097. const std::string &body,
  9098. const std::string &content_type,
  9099. UploadProgress progress) {
  9100. return cli_->Put(path, headers, body, content_type, progress);
  9101. }
  9102. inline Result Client::Put(const std::string &path, size_t content_length,
  9103. ContentProvider content_provider,
  9104. const std::string &content_type,
  9105. UploadProgress progress) {
  9106. return cli_->Put(path, content_length, std::move(content_provider),
  9107. content_type, progress);
  9108. }
  9109. inline Result Client::Put(const std::string &path,
  9110. ContentProviderWithoutLength content_provider,
  9111. const std::string &content_type,
  9112. UploadProgress progress) {
  9113. return cli_->Put(path, std::move(content_provider), content_type, progress);
  9114. }
  9115. inline Result Client::Put(const std::string &path, const Headers &headers,
  9116. size_t content_length,
  9117. ContentProvider content_provider,
  9118. const std::string &content_type,
  9119. UploadProgress progress) {
  9120. return cli_->Put(path, headers, content_length, std::move(content_provider),
  9121. content_type, progress);
  9122. }
  9123. inline Result Client::Put(const std::string &path, const Headers &headers,
  9124. ContentProviderWithoutLength content_provider,
  9125. const std::string &content_type,
  9126. UploadProgress progress) {
  9127. return cli_->Put(path, headers, std::move(content_provider), content_type,
  9128. progress);
  9129. }
  9130. inline Result Client::Put(const std::string &path, const Params &params) {
  9131. return cli_->Put(path, params);
  9132. }
  9133. inline Result Client::Put(const std::string &path, const Headers &headers,
  9134. const Params &params) {
  9135. return cli_->Put(path, headers, params);
  9136. }
  9137. inline Result Client::Put(const std::string &path,
  9138. const MultipartFormDataItemsForClientInput &items,
  9139. UploadProgress progress) {
  9140. return cli_->Put(path, items, progress);
  9141. }
  9142. inline Result Client::Put(const std::string &path, const Headers &headers,
  9143. const MultipartFormDataItemsForClientInput &items,
  9144. UploadProgress progress) {
  9145. return cli_->Put(path, headers, items, progress);
  9146. }
  9147. inline Result Client::Put(const std::string &path, const Headers &headers,
  9148. const MultipartFormDataItemsForClientInput &items,
  9149. const std::string &boundary,
  9150. UploadProgress progress) {
  9151. return cli_->Put(path, headers, items, boundary, progress);
  9152. }
  9153. inline Result Client::Put(const std::string &path, const Headers &headers,
  9154. const MultipartFormDataItemsForClientInput &items,
  9155. const MultipartFormDataProviderItems &provider_items,
  9156. UploadProgress progress) {
  9157. return cli_->Put(path, headers, items, provider_items, progress);
  9158. }
  9159. inline Result Client::Put(const std::string &path, const Headers &headers,
  9160. const std::string &body,
  9161. const std::string &content_type,
  9162. ContentReceiver content_receiver,
  9163. DownloadProgress progress) {
  9164. return cli_->Put(path, headers, body, content_type, content_receiver,
  9165. progress);
  9166. }
  9167. inline Result Client::Patch(const std::string &path) {
  9168. return cli_->Patch(path);
  9169. }
  9170. inline Result Client::Patch(const std::string &path, const Headers &headers) {
  9171. return cli_->Patch(path, headers);
  9172. }
  9173. inline Result Client::Patch(const std::string &path, const char *body,
  9174. size_t content_length,
  9175. const std::string &content_type,
  9176. UploadProgress progress) {
  9177. return cli_->Patch(path, body, content_length, content_type, progress);
  9178. }
  9179. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9180. const char *body, size_t content_length,
  9181. const std::string &content_type,
  9182. UploadProgress progress) {
  9183. return cli_->Patch(path, headers, body, content_length, content_type,
  9184. progress);
  9185. }
  9186. inline Result Client::Patch(const std::string &path, const std::string &body,
  9187. const std::string &content_type,
  9188. UploadProgress progress) {
  9189. return cli_->Patch(path, body, content_type, progress);
  9190. }
  9191. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9192. const std::string &body,
  9193. const std::string &content_type,
  9194. UploadProgress progress) {
  9195. return cli_->Patch(path, headers, body, content_type, progress);
  9196. }
  9197. inline Result Client::Patch(const std::string &path, size_t content_length,
  9198. ContentProvider content_provider,
  9199. const std::string &content_type,
  9200. UploadProgress progress) {
  9201. return cli_->Patch(path, content_length, std::move(content_provider),
  9202. content_type, progress);
  9203. }
  9204. inline Result Client::Patch(const std::string &path,
  9205. ContentProviderWithoutLength content_provider,
  9206. const std::string &content_type,
  9207. UploadProgress progress) {
  9208. return cli_->Patch(path, std::move(content_provider), content_type, progress);
  9209. }
  9210. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9211. size_t content_length,
  9212. ContentProvider content_provider,
  9213. const std::string &content_type,
  9214. UploadProgress progress) {
  9215. return cli_->Patch(path, headers, content_length, std::move(content_provider),
  9216. content_type, progress);
  9217. }
  9218. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9219. ContentProviderWithoutLength content_provider,
  9220. const std::string &content_type,
  9221. UploadProgress progress) {
  9222. return cli_->Patch(path, headers, std::move(content_provider), content_type,
  9223. progress);
  9224. }
  9225. inline Result Client::Patch(const std::string &path, const Params &params) {
  9226. return cli_->Patch(path, params);
  9227. }
  9228. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9229. const Params &params) {
  9230. return cli_->Patch(path, headers, params);
  9231. }
  9232. inline Result Client::Patch(const std::string &path,
  9233. const MultipartFormDataItemsForClientInput &items,
  9234. UploadProgress progress) {
  9235. return cli_->Patch(path, items, progress);
  9236. }
  9237. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9238. const MultipartFormDataItemsForClientInput &items,
  9239. UploadProgress progress) {
  9240. return cli_->Patch(path, headers, items, progress);
  9241. }
  9242. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9243. const MultipartFormDataItemsForClientInput &items,
  9244. const std::string &boundary,
  9245. UploadProgress progress) {
  9246. return cli_->Patch(path, headers, items, boundary, progress);
  9247. }
  9248. inline Result
  9249. Client::Patch(const std::string &path, const Headers &headers,
  9250. const MultipartFormDataItemsForClientInput &items,
  9251. const MultipartFormDataProviderItems &provider_items,
  9252. UploadProgress progress) {
  9253. return cli_->Patch(path, headers, items, provider_items, progress);
  9254. }
  9255. inline Result Client::Patch(const std::string &path, const Headers &headers,
  9256. const std::string &body,
  9257. const std::string &content_type,
  9258. ContentReceiver content_receiver,
  9259. DownloadProgress progress) {
  9260. return cli_->Patch(path, headers, body, content_type, content_receiver,
  9261. progress);
  9262. }
  9263. inline Result Client::Delete(const std::string &path,
  9264. DownloadProgress progress) {
  9265. return cli_->Delete(path, progress);
  9266. }
  9267. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9268. DownloadProgress progress) {
  9269. return cli_->Delete(path, headers, progress);
  9270. }
  9271. inline Result Client::Delete(const std::string &path, const char *body,
  9272. size_t content_length,
  9273. const std::string &content_type,
  9274. DownloadProgress progress) {
  9275. return cli_->Delete(path, body, content_length, content_type, progress);
  9276. }
  9277. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9278. const char *body, size_t content_length,
  9279. const std::string &content_type,
  9280. DownloadProgress progress) {
  9281. return cli_->Delete(path, headers, body, content_length, content_type,
  9282. progress);
  9283. }
  9284. inline Result Client::Delete(const std::string &path, const std::string &body,
  9285. const std::string &content_type,
  9286. DownloadProgress progress) {
  9287. return cli_->Delete(path, body, content_type, progress);
  9288. }
  9289. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9290. const std::string &body,
  9291. const std::string &content_type,
  9292. DownloadProgress progress) {
  9293. return cli_->Delete(path, headers, body, content_type, progress);
  9294. }
  9295. inline Result Client::Delete(const std::string &path, const Params &params,
  9296. DownloadProgress progress) {
  9297. return cli_->Delete(path, params, progress);
  9298. }
  9299. inline Result Client::Delete(const std::string &path, const Headers &headers,
  9300. const Params &params, DownloadProgress progress) {
  9301. return cli_->Delete(path, headers, params, progress);
  9302. }
  9303. inline Result Client::Options(const std::string &path) {
  9304. return cli_->Options(path);
  9305. }
  9306. inline Result Client::Options(const std::string &path, const Headers &headers) {
  9307. return cli_->Options(path, headers);
  9308. }
  9309. inline bool Client::send(Request &req, Response &res, Error &error) {
  9310. return cli_->send(req, res, error);
  9311. }
  9312. inline Result Client::send(const Request &req) { return cli_->send(req); }
  9313. inline void Client::stop() { cli_->stop(); }
  9314. inline std::string Client::host() const { return cli_->host(); }
  9315. inline int Client::port() const { return cli_->port(); }
  9316. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  9317. inline socket_t Client::socket() const { return cli_->socket(); }
  9318. inline void
  9319. Client::set_hostname_addr_map(std::map<std::string, std::string> addr_map) {
  9320. cli_->set_hostname_addr_map(std::move(addr_map));
  9321. }
  9322. inline void Client::set_default_headers(Headers headers) {
  9323. cli_->set_default_headers(std::move(headers));
  9324. }
  9325. inline void Client::set_header_writer(
  9326. std::function<ssize_t(Stream &, Headers &)> const &writer) {
  9327. cli_->set_header_writer(writer);
  9328. }
  9329. inline void Client::set_address_family(int family) {
  9330. cli_->set_address_family(family);
  9331. }
  9332. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  9333. inline void Client::set_socket_options(SocketOptions socket_options) {
  9334. cli_->set_socket_options(std::move(socket_options));
  9335. }
  9336. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  9337. cli_->set_connection_timeout(sec, usec);
  9338. }
  9339. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  9340. cli_->set_read_timeout(sec, usec);
  9341. }
  9342. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  9343. cli_->set_write_timeout(sec, usec);
  9344. }
  9345. inline void Client::set_basic_auth(const std::string &username,
  9346. const std::string &password) {
  9347. cli_->set_basic_auth(username, password);
  9348. }
  9349. inline void Client::set_bearer_token_auth(const std::string &token) {
  9350. cli_->set_bearer_token_auth(token);
  9351. }
  9352. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9353. inline void Client::set_digest_auth(const std::string &username,
  9354. const std::string &password) {
  9355. cli_->set_digest_auth(username, password);
  9356. }
  9357. #endif
  9358. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  9359. inline void Client::set_follow_location(bool on) {
  9360. cli_->set_follow_location(on);
  9361. }
  9362. inline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); }
  9363. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  9364. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  9365. inline void Client::set_interface(const std::string &intf) {
  9366. cli_->set_interface(intf);
  9367. }
  9368. inline void Client::set_proxy(const std::string &host, int port) {
  9369. cli_->set_proxy(host, port);
  9370. }
  9371. inline void Client::set_proxy_basic_auth(const std::string &username,
  9372. const std::string &password) {
  9373. cli_->set_proxy_basic_auth(username, password);
  9374. }
  9375. inline void Client::set_proxy_bearer_token_auth(const std::string &token) {
  9376. cli_->set_proxy_bearer_token_auth(token);
  9377. }
  9378. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9379. inline void Client::set_proxy_digest_auth(const std::string &username,
  9380. const std::string &password) {
  9381. cli_->set_proxy_digest_auth(username, password);
  9382. }
  9383. #endif
  9384. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9385. inline void Client::enable_server_certificate_verification(bool enabled) {
  9386. cli_->enable_server_certificate_verification(enabled);
  9387. }
  9388. inline void Client::enable_server_hostname_verification(bool enabled) {
  9389. cli_->enable_server_hostname_verification(enabled);
  9390. }
  9391. inline void Client::set_server_certificate_verifier(
  9392. std::function<SSLVerifierResponse(SSL *ssl)> verifier) {
  9393. cli_->set_server_certificate_verifier(verifier);
  9394. }
  9395. #endif
  9396. inline void Client::set_logger(Logger logger) {
  9397. cli_->set_logger(std::move(logger));
  9398. }
  9399. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9400. inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path,
  9401. const std::string &ca_cert_dir_path) {
  9402. cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
  9403. }
  9404. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  9405. if (is_ssl_) {
  9406. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  9407. } else {
  9408. cli_->set_ca_cert_store(ca_cert_store);
  9409. }
  9410. }
  9411. inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) {
  9412. set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size));
  9413. }
  9414. inline long Client::get_openssl_verify_result() const {
  9415. if (is_ssl_) {
  9416. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  9417. }
  9418. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  9419. }
  9420. inline SSL_CTX *Client::ssl_context() const {
  9421. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  9422. return nullptr;
  9423. }
  9424. #endif
  9425. // ----------------------------------------------------------------------------
  9426. } // namespace httplib
  9427. #endif // CPPHTTPLIB_HTTPLIB_H