httplib.h 339 KB

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