httplib.h 344 KB

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