httplib.h 303 KB

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