2
0

httplib.h 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2020 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. /*
  10. * Configuration
  11. */
  12. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  13. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  14. #endif
  15. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  16. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  17. #endif
  18. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
  19. #define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
  20. #endif
  21. #ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
  22. #define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
  23. #endif
  24. #ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND
  25. #define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
  26. #endif
  27. #ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND
  28. #define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
  29. #endif
  30. #ifndef CPPHTTPLIB_WRITE_TIMEOUT_SECOND
  31. #define CPPHTTPLIB_WRITE_TIMEOUT_SECOND 5
  32. #endif
  33. #ifndef CPPHTTPLIB_WRITE_TIMEOUT_USECOND
  34. #define CPPHTTPLIB_WRITE_TIMEOUT_USECOND 0
  35. #endif
  36. #ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
  37. #define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
  38. #endif
  39. #ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
  40. #ifdef _WIN32
  41. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000
  42. #else
  43. #define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
  44. #endif
  45. #endif
  46. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  47. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  48. #endif
  49. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  50. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  51. #endif
  52. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  53. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
  54. #endif
  55. #ifndef CPPHTTPLIB_TCP_NODELAY
  56. #define CPPHTTPLIB_TCP_NODELAY false
  57. #endif
  58. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  59. #define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
  60. #endif
  61. #ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
  62. #define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
  63. #endif
  64. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  65. #define CPPHTTPLIB_THREAD_POOL_COUNT \
  66. ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
  67. ? std::thread::hardware_concurrency() - 1 \
  68. : 0))
  69. #endif
  70. /*
  71. * Headers
  72. */
  73. #ifdef _WIN32
  74. #ifndef _CRT_SECURE_NO_WARNINGS
  75. #define _CRT_SECURE_NO_WARNINGS
  76. #endif //_CRT_SECURE_NO_WARNINGS
  77. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  78. #define _CRT_NONSTDC_NO_DEPRECATE
  79. #endif //_CRT_NONSTDC_NO_DEPRECATE
  80. #if defined(_MSC_VER)
  81. #ifdef _WIN64
  82. using ssize_t = __int64;
  83. #else
  84. using ssize_t = int;
  85. #endif
  86. #if _MSC_VER < 1900
  87. #define snprintf _snprintf_s
  88. #endif
  89. #endif // _MSC_VER
  90. #ifndef S_ISREG
  91. #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
  92. #endif // S_ISREG
  93. #ifndef S_ISDIR
  94. #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
  95. #endif // S_ISDIR
  96. #ifndef NOMINMAX
  97. #define NOMINMAX
  98. #endif // NOMINMAX
  99. #include <io.h>
  100. #include <winsock2.h>
  101. #include <wincrypt.h>
  102. #include <ws2tcpip.h>
  103. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  104. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  105. #endif
  106. #ifdef _MSC_VER
  107. #pragma comment(lib, "ws2_32.lib")
  108. #pragma comment(lib, "crypt32.lib")
  109. #pragma comment(lib, "cryptui.lib")
  110. #endif
  111. #ifndef strcasecmp
  112. #define strcasecmp _stricmp
  113. #endif // strcasecmp
  114. using socket_t = SOCKET;
  115. #ifdef CPPHTTPLIB_USE_POLL
  116. #define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
  117. #endif
  118. #else // not _WIN32
  119. #include <arpa/inet.h>
  120. #include <cstring>
  121. #include <ifaddrs.h>
  122. #include <netdb.h>
  123. #include <netinet/in.h>
  124. #ifdef __linux__
  125. #include <resolv.h>
  126. #endif
  127. #include <netinet/tcp.h>
  128. #ifdef CPPHTTPLIB_USE_POLL
  129. #include <poll.h>
  130. #endif
  131. #include <csignal>
  132. #include <pthread.h>
  133. #include <sys/select.h>
  134. #include <sys/socket.h>
  135. #include <unistd.h>
  136. using socket_t = int;
  137. #define INVALID_SOCKET (-1)
  138. #endif //_WIN32
  139. #include <array>
  140. #include <atomic>
  141. #include <cassert>
  142. #include <cctype>
  143. #include <climits>
  144. #include <condition_variable>
  145. #include <errno.h>
  146. #include <fcntl.h>
  147. #include <fstream>
  148. #include <functional>
  149. #include <iostream>
  150. #include <list>
  151. #include <map>
  152. #include <memory>
  153. #include <mutex>
  154. #include <random>
  155. #include <regex>
  156. #include <sstream>
  157. #include <string>
  158. #include <sys/stat.h>
  159. #include <thread>
  160. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  161. #include <openssl/err.h>
  162. #include <openssl/md5.h>
  163. #include <openssl/ssl.h>
  164. #include <openssl/x509v3.h>
  165. #if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
  166. #include <openssl/applink.c>
  167. #endif
  168. #include <iomanip>
  169. #include <iostream>
  170. #include <sstream>
  171. #if OPENSSL_VERSION_NUMBER < 0x1010100fL
  172. #error Sorry, OpenSSL versions prior to 1.1.1 are not supported
  173. #endif
  174. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  175. #include <openssl/crypto.h>
  176. inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
  177. return M_ASN1_STRING_data(asn1);
  178. }
  179. #endif
  180. #endif
  181. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  182. #include <zlib.h>
  183. #endif
  184. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  185. #include <brotli/decode.h>
  186. #include <brotli/encode.h>
  187. #endif
  188. /*
  189. * Declaration
  190. */
  191. namespace httplib {
  192. namespace detail {
  193. struct ci {
  194. bool operator()(const std::string &s1, const std::string &s2) const {
  195. return std::lexicographical_compare(
  196. s1.begin(), s1.end(), s2.begin(), s2.end(),
  197. [](char c1, char c2) { return ::tolower(c1) < ::tolower(c2); });
  198. }
  199. };
  200. } // namespace detail
  201. using Headers = std::multimap<std::string, std::string, detail::ci>;
  202. using Params = std::multimap<std::string, std::string>;
  203. using Match = std::smatch;
  204. using Progress = std::function<bool(uint64_t current, uint64_t total)>;
  205. struct Response;
  206. using ResponseHandler = std::function<bool(const Response &response)>;
  207. struct MultipartFormData {
  208. std::string name;
  209. std::string content;
  210. std::string filename;
  211. std::string content_type;
  212. };
  213. using MultipartFormDataItems = std::vector<MultipartFormData>;
  214. using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
  215. class DataSink {
  216. public:
  217. DataSink() : os(&sb_), sb_(*this) {}
  218. DataSink(const DataSink &) = delete;
  219. DataSink &operator=(const DataSink &) = delete;
  220. DataSink(DataSink &&) = delete;
  221. DataSink &operator=(DataSink &&) = delete;
  222. std::function<void(const char *data, size_t data_len)> write;
  223. std::function<void()> done;
  224. std::function<bool()> is_writable;
  225. std::ostream os;
  226. private:
  227. class data_sink_streambuf : public std::streambuf {
  228. public:
  229. explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
  230. protected:
  231. std::streamsize xsputn(const char *s, std::streamsize n) {
  232. sink_.write(s, static_cast<size_t>(n));
  233. return n;
  234. }
  235. private:
  236. DataSink &sink_;
  237. };
  238. data_sink_streambuf sb_;
  239. };
  240. using ContentProvider =
  241. std::function<bool(size_t offset, size_t length, DataSink &sink)>;
  242. using ContentProviderWithoutLength =
  243. std::function<bool(size_t offset, DataSink &sink)>;
  244. using ContentReceiver =
  245. std::function<bool(const char *data, size_t data_length)>;
  246. using MultipartContentHeader =
  247. std::function<bool(const MultipartFormData &file)>;
  248. class ContentReader {
  249. public:
  250. using Reader = std::function<bool(ContentReceiver receiver)>;
  251. using MultipartReader = std::function<bool(MultipartContentHeader header,
  252. ContentReceiver receiver)>;
  253. ContentReader(Reader reader, MultipartReader multipart_reader)
  254. : reader_(reader), multipart_reader_(multipart_reader) {}
  255. bool operator()(MultipartContentHeader header,
  256. ContentReceiver receiver) const {
  257. return multipart_reader_(header, receiver);
  258. }
  259. bool operator()(ContentReceiver receiver) const { return reader_(receiver); }
  260. Reader reader_;
  261. MultipartReader multipart_reader_;
  262. };
  263. using Range = std::pair<ssize_t, ssize_t>;
  264. using Ranges = std::vector<Range>;
  265. struct Request {
  266. std::string method;
  267. std::string path;
  268. Headers headers;
  269. std::string body;
  270. std::string remote_addr;
  271. int remote_port = -1;
  272. // for server
  273. std::string version;
  274. std::string target;
  275. Params params;
  276. MultipartFormDataMap files;
  277. Ranges ranges;
  278. Match matches;
  279. // for client
  280. size_t redirect_count = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  281. ResponseHandler response_handler;
  282. ContentReceiver content_receiver;
  283. size_t content_length = 0;
  284. ContentProvider content_provider;
  285. Progress progress;
  286. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  287. const SSL *ssl;
  288. #endif
  289. bool has_header(const char *key) const;
  290. std::string get_header_value(const char *key, size_t id = 0) const;
  291. template <typename T>
  292. T get_header_value(const char *key, size_t id = 0) const;
  293. size_t get_header_value_count(const char *key) const;
  294. void set_header(const char *key, const char *val);
  295. void set_header(const char *key, const std::string &val);
  296. bool has_param(const char *key) const;
  297. std::string get_param_value(const char *key, size_t id = 0) const;
  298. size_t get_param_value_count(const char *key) const;
  299. bool is_multipart_form_data() const;
  300. bool has_file(const char *key) const;
  301. MultipartFormData get_file_value(const char *key) const;
  302. // private members...
  303. size_t authorization_count_ = 0;
  304. };
  305. struct Response {
  306. std::string version;
  307. int status = -1;
  308. std::string reason;
  309. Headers headers;
  310. std::string body;
  311. bool has_header(const char *key) const;
  312. std::string get_header_value(const char *key, size_t id = 0) const;
  313. template <typename T>
  314. T get_header_value(const char *key, size_t id = 0) const;
  315. size_t get_header_value_count(const char *key) const;
  316. void set_header(const char *key, const char *val);
  317. void set_header(const char *key, const std::string &val);
  318. void set_redirect(const char *url, int status = 302);
  319. void set_redirect(const std::string &url, int status = 302);
  320. void set_content(const char *s, size_t n, const char *content_type);
  321. void set_content(std::string s, const char *content_type);
  322. void set_content_provider(
  323. size_t length, const char *content_type, ContentProvider provider,
  324. const std::function<void()> &resource_releaser = nullptr);
  325. void set_content_provider(
  326. const char *content_type, ContentProviderWithoutLength provider,
  327. const std::function<void()> &resource_releaser = nullptr);
  328. void set_chunked_content_provider(
  329. const char *content_type, ContentProviderWithoutLength provider,
  330. const std::function<void()> &resource_releaser = nullptr);
  331. Response() = default;
  332. Response(const Response &) = default;
  333. Response &operator=(const Response &) = default;
  334. Response(Response &&) = default;
  335. Response &operator=(Response &&) = default;
  336. ~Response() {
  337. if (content_provider_resource_releaser_) {
  338. content_provider_resource_releaser_();
  339. }
  340. }
  341. // private members...
  342. size_t content_length_ = 0;
  343. ContentProvider content_provider_;
  344. std::function<void()> content_provider_resource_releaser_;
  345. bool is_chunked_content_provider = false;
  346. };
  347. class Stream {
  348. public:
  349. virtual ~Stream() = default;
  350. virtual bool is_readable() const = 0;
  351. virtual bool is_writable() const = 0;
  352. virtual ssize_t read(char *ptr, size_t size) = 0;
  353. virtual ssize_t write(const char *ptr, size_t size) = 0;
  354. virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
  355. template <typename... Args>
  356. ssize_t write_format(const char *fmt, const Args &... args);
  357. ssize_t write(const char *ptr);
  358. ssize_t write(const std::string &s);
  359. };
  360. class TaskQueue {
  361. public:
  362. TaskQueue() = default;
  363. virtual ~TaskQueue() = default;
  364. virtual void enqueue(std::function<void()> fn) = 0;
  365. virtual void shutdown() = 0;
  366. virtual void on_idle(){};
  367. };
  368. class ThreadPool : public TaskQueue {
  369. public:
  370. explicit ThreadPool(size_t n) : shutdown_(false) {
  371. while (n) {
  372. threads_.emplace_back(worker(*this));
  373. n--;
  374. }
  375. }
  376. ThreadPool(const ThreadPool &) = delete;
  377. ~ThreadPool() override = default;
  378. void enqueue(std::function<void()> fn) override {
  379. std::unique_lock<std::mutex> lock(mutex_);
  380. jobs_.push_back(fn);
  381. cond_.notify_one();
  382. }
  383. void shutdown() override {
  384. // Stop all worker threads...
  385. {
  386. std::unique_lock<std::mutex> lock(mutex_);
  387. shutdown_ = true;
  388. }
  389. cond_.notify_all();
  390. // Join...
  391. for (auto &t : threads_) {
  392. t.join();
  393. }
  394. }
  395. private:
  396. struct worker {
  397. explicit worker(ThreadPool &pool) : pool_(pool) {}
  398. void operator()() {
  399. for (;;) {
  400. std::function<void()> fn;
  401. {
  402. std::unique_lock<std::mutex> lock(pool_.mutex_);
  403. pool_.cond_.wait(
  404. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  405. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  406. fn = pool_.jobs_.front();
  407. pool_.jobs_.pop_front();
  408. }
  409. assert(true == static_cast<bool>(fn));
  410. fn();
  411. }
  412. }
  413. ThreadPool &pool_;
  414. };
  415. friend struct worker;
  416. std::vector<std::thread> threads_;
  417. std::list<std::function<void()>> jobs_;
  418. bool shutdown_;
  419. std::condition_variable cond_;
  420. std::mutex mutex_;
  421. };
  422. using Logger = std::function<void(const Request &, const Response &)>;
  423. using SocketOptions = std::function<void(socket_t sock)>;
  424. inline void default_socket_options(socket_t sock) {
  425. int yes = 1;
  426. #ifdef _WIN32
  427. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
  428. sizeof(yes));
  429. setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
  430. reinterpret_cast<char *>(&yes), sizeof(yes));
  431. #else
  432. #ifdef SO_REUSEPORT
  433. setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<void *>(&yes),
  434. sizeof(yes));
  435. #else
  436. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<void *>(&yes),
  437. sizeof(yes));
  438. #endif
  439. #endif
  440. }
  441. class Server {
  442. public:
  443. using Handler = std::function<void(const Request &, Response &)>;
  444. using HandlerWithContentReader = std::function<void(
  445. const Request &, Response &, const ContentReader &content_reader)>;
  446. using Expect100ContinueHandler =
  447. std::function<int(const Request &, Response &)>;
  448. Server();
  449. virtual ~Server();
  450. virtual bool is_valid() const;
  451. Server &Get(const char *pattern, Handler handler);
  452. Server &Post(const char *pattern, Handler handler);
  453. Server &Post(const char *pattern, HandlerWithContentReader handler);
  454. Server &Put(const char *pattern, Handler handler);
  455. Server &Put(const char *pattern, HandlerWithContentReader handler);
  456. Server &Patch(const char *pattern, Handler handler);
  457. Server &Patch(const char *pattern, HandlerWithContentReader handler);
  458. Server &Delete(const char *pattern, Handler handler);
  459. Server &Delete(const char *pattern, HandlerWithContentReader handler);
  460. Server &Options(const char *pattern, Handler handler);
  461. bool set_base_dir(const char *dir, const char *mount_point = nullptr);
  462. bool set_mount_point(const char *mount_point, const char *dir);
  463. bool remove_mount_point(const char *mount_point);
  464. void set_file_extension_and_mimetype_mapping(const char *ext,
  465. const char *mime);
  466. void set_file_request_handler(Handler handler);
  467. void set_error_handler(Handler handler);
  468. void set_expect_100_continue_handler(Expect100ContinueHandler handler);
  469. void set_logger(Logger logger);
  470. void set_tcp_nodelay(bool on);
  471. void set_socket_options(SocketOptions socket_options);
  472. void set_keep_alive_max_count(size_t count);
  473. void set_keep_alive_timeout(time_t sec);
  474. void set_read_timeout(time_t sec, time_t usec = 0);
  475. void set_write_timeout(time_t sec, time_t usec = 0);
  476. void set_idle_interval(time_t sec, time_t usec = 0);
  477. void set_payload_max_length(size_t length);
  478. bool bind_to_port(const char *host, int port, int socket_flags = 0);
  479. int bind_to_any_port(const char *host, int socket_flags = 0);
  480. bool listen_after_bind();
  481. bool listen(const char *host, int port, int socket_flags = 0);
  482. bool is_running() const;
  483. void stop();
  484. std::function<TaskQueue *(void)> new_task_queue;
  485. protected:
  486. bool process_request(Stream &strm, bool close_connection,
  487. bool &connection_closed,
  488. const std::function<void(Request &)> &setup_request);
  489. std::atomic<socket_t> svr_sock_;
  490. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  491. time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
  492. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  493. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  494. time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
  495. time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
  496. time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
  497. time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
  498. size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
  499. private:
  500. using Handlers = std::vector<std::pair<std::regex, Handler>>;
  501. using HandlersForContentReader =
  502. std::vector<std::pair<std::regex, HandlerWithContentReader>>;
  503. socket_t create_server_socket(const char *host, int port, int socket_flags,
  504. SocketOptions socket_options) const;
  505. int bind_internal(const char *host, int port, int socket_flags);
  506. bool listen_internal();
  507. bool routing(Request &req, Response &res, Stream &strm);
  508. bool handle_file_request(Request &req, Response &res, bool head = false);
  509. bool dispatch_request(Request &req, Response &res, const Handlers &handlers);
  510. bool
  511. dispatch_request_for_content_reader(Request &req, Response &res,
  512. ContentReader content_reader,
  513. const HandlersForContentReader &handlers);
  514. bool parse_request_line(const char *s, Request &req);
  515. bool write_response(Stream &strm, bool close_connection, const Request &req,
  516. Response &res);
  517. bool write_content_with_provider(Stream &strm, const Request &req,
  518. Response &res, const std::string &boundary,
  519. const std::string &content_type);
  520. bool read_content(Stream &strm, Request &req, Response &res);
  521. bool
  522. read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
  523. ContentReceiver receiver,
  524. MultipartContentHeader multipart_header,
  525. ContentReceiver multipart_receiver);
  526. bool read_content_core(Stream &strm, Request &req, Response &res,
  527. ContentReceiver receiver,
  528. MultipartContentHeader mulitpart_header,
  529. ContentReceiver multipart_receiver);
  530. virtual bool process_and_close_socket(socket_t sock);
  531. std::atomic<bool> is_running_;
  532. std::vector<std::pair<std::string, std::string>> base_dirs_;
  533. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  534. Handler file_request_handler_;
  535. Handlers get_handlers_;
  536. Handlers post_handlers_;
  537. HandlersForContentReader post_handlers_for_content_reader_;
  538. Handlers put_handlers_;
  539. HandlersForContentReader put_handlers_for_content_reader_;
  540. Handlers patch_handlers_;
  541. HandlersForContentReader patch_handlers_for_content_reader_;
  542. Handlers delete_handlers_;
  543. HandlersForContentReader delete_handlers_for_content_reader_;
  544. Handlers options_handlers_;
  545. Handler error_handler_;
  546. Logger logger_;
  547. Expect100ContinueHandler expect_100_continue_handler_;
  548. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  549. SocketOptions socket_options_ = default_socket_options;
  550. };
  551. enum Error {
  552. Success = 0,
  553. Unknown,
  554. Connection,
  555. BindIPAddress,
  556. Read,
  557. Write,
  558. ExceedRedirectCount,
  559. Canceled,
  560. SSLConnection,
  561. SSLLoadingCerts,
  562. SSLServerVerification
  563. };
  564. class Result {
  565. public:
  566. Result(const std::shared_ptr<Response> &res, Error err)
  567. : res_(res), err_(err) {}
  568. operator bool() const { return res_ != nullptr; }
  569. bool operator==(std::nullptr_t) const { return res_ == nullptr; }
  570. bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
  571. const Response &value() const { return *res_; }
  572. const Response &operator*() const { return *res_; }
  573. const Response *operator->() const { return res_.get(); }
  574. Error error() const { return err_; }
  575. private:
  576. std::shared_ptr<Response> res_;
  577. Error err_;
  578. };
  579. class ClientImpl {
  580. public:
  581. explicit ClientImpl(const std::string &host);
  582. explicit ClientImpl(const std::string &host, int port);
  583. explicit ClientImpl(const std::string &host, int port,
  584. const std::string &client_cert_path,
  585. const std::string &client_key_path);
  586. virtual ~ClientImpl();
  587. virtual bool is_valid() const;
  588. Result Get(const char *path);
  589. Result Get(const char *path, const Headers &headers);
  590. Result Get(const char *path, Progress progress);
  591. Result Get(const char *path, const Headers &headers, Progress progress);
  592. Result Get(const char *path, ContentReceiver content_receiver);
  593. Result Get(const char *path, const Headers &headers,
  594. ContentReceiver content_receiver);
  595. Result Get(const char *path, ContentReceiver content_receiver,
  596. Progress progress);
  597. Result Get(const char *path, const Headers &headers,
  598. ContentReceiver content_receiver, Progress progress);
  599. Result Get(const char *path, ResponseHandler response_handler,
  600. ContentReceiver content_receiver);
  601. Result Get(const char *path, const Headers &headers,
  602. ResponseHandler response_handler,
  603. ContentReceiver content_receiver);
  604. Result Get(const char *path, ResponseHandler response_handler,
  605. ContentReceiver content_receiver, Progress progress);
  606. Result Get(const char *path, const Headers &headers,
  607. ResponseHandler response_handler, ContentReceiver content_receiver,
  608. Progress progress);
  609. Result Head(const char *path);
  610. Result Head(const char *path, const Headers &headers);
  611. Result Post(const char *path);
  612. Result Post(const char *path, const std::string &body,
  613. const char *content_type);
  614. Result Post(const char *path, const Headers &headers, const std::string &body,
  615. const char *content_type);
  616. Result Post(const char *path, size_t content_length,
  617. ContentProvider content_provider, const char *content_type);
  618. Result Post(const char *path, const Headers &headers, size_t content_length,
  619. ContentProvider content_provider, const char *content_type);
  620. Result Post(const char *path, const Params &params);
  621. Result Post(const char *path, const Headers &headers, const Params &params);
  622. Result Post(const char *path, const MultipartFormDataItems &items);
  623. Result Post(const char *path, const Headers &headers,
  624. const MultipartFormDataItems &items);
  625. Result Put(const char *path);
  626. Result Put(const char *path, const std::string &body,
  627. const char *content_type);
  628. Result Put(const char *path, const Headers &headers, const std::string &body,
  629. const char *content_type);
  630. Result Put(const char *path, size_t content_length,
  631. ContentProvider content_provider, const char *content_type);
  632. Result Put(const char *path, const Headers &headers, size_t content_length,
  633. ContentProvider content_provider, const char *content_type);
  634. Result Put(const char *path, const Params &params);
  635. Result Put(const char *path, const Headers &headers, const Params &params);
  636. Result Patch(const char *path, const std::string &body,
  637. const char *content_type);
  638. Result Patch(const char *path, const Headers &headers,
  639. const std::string &body, const char *content_type);
  640. Result Patch(const char *path, size_t content_length,
  641. ContentProvider content_provider, const char *content_type);
  642. Result Patch(const char *path, const Headers &headers, size_t content_length,
  643. ContentProvider content_provider, const char *content_type);
  644. Result Delete(const char *path);
  645. Result Delete(const char *path, const std::string &body,
  646. const char *content_type);
  647. Result Delete(const char *path, const Headers &headers);
  648. Result Delete(const char *path, const Headers &headers,
  649. const std::string &body, const char *content_type);
  650. Result Options(const char *path);
  651. Result Options(const char *path, const Headers &headers);
  652. bool send(const Request &req, Response &res);
  653. size_t is_socket_open() const;
  654. void stop();
  655. void set_default_headers(Headers headers);
  656. void set_tcp_nodelay(bool on);
  657. void set_socket_options(SocketOptions socket_options);
  658. void set_connection_timeout(time_t sec, time_t usec = 0);
  659. void set_read_timeout(time_t sec, time_t usec = 0);
  660. void set_write_timeout(time_t sec, time_t usec = 0);
  661. void set_basic_auth(const char *username, const char *password);
  662. void set_bearer_token_auth(const char *token);
  663. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  664. void set_digest_auth(const char *username, const char *password);
  665. #endif
  666. void set_keep_alive(bool on);
  667. void set_follow_location(bool on);
  668. void set_compress(bool on);
  669. void set_decompress(bool on);
  670. void set_interface(const char *intf);
  671. void set_proxy(const char *host, int port);
  672. void set_proxy_basic_auth(const char *username, const char *password);
  673. void set_proxy_bearer_token_auth(const char *token);
  674. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  675. void set_proxy_digest_auth(const char *username, const char *password);
  676. #endif
  677. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  678. void enable_server_certificate_verification(bool enabled);
  679. #endif
  680. void set_logger(Logger logger);
  681. protected:
  682. struct Socket {
  683. socket_t sock = INVALID_SOCKET;
  684. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  685. SSL *ssl = nullptr;
  686. #endif
  687. bool is_open() const { return sock != INVALID_SOCKET; }
  688. };
  689. virtual bool create_and_connect_socket(Socket &socket);
  690. virtual void close_socket(Socket &socket, bool process_socket_ret);
  691. bool process_request(Stream &strm, const Request &req, Response &res,
  692. bool close_connection);
  693. Error get_last_error() const;
  694. void copy_settings(const ClientImpl &rhs);
  695. // Error state
  696. mutable Error error_ = Error::Success;
  697. // Socket endoint information
  698. const std::string host_;
  699. const int port_;
  700. const std::string host_and_port_;
  701. // Current open socket
  702. Socket socket_;
  703. mutable std::mutex socket_mutex_;
  704. std::recursive_mutex request_mutex_;
  705. // Default headers
  706. Headers default_headers_;
  707. // Settings
  708. std::string client_cert_path_;
  709. std::string client_key_path_;
  710. time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
  711. time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
  712. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  713. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  714. time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
  715. time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
  716. std::string basic_auth_username_;
  717. std::string basic_auth_password_;
  718. std::string bearer_token_auth_token_;
  719. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  720. std::string digest_auth_username_;
  721. std::string digest_auth_password_;
  722. #endif
  723. bool keep_alive_ = false;
  724. bool follow_location_ = false;
  725. bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
  726. SocketOptions socket_options_ = nullptr;
  727. bool compress_ = false;
  728. bool decompress_ = true;
  729. std::string interface_;
  730. std::string proxy_host_;
  731. int proxy_port_ = -1;
  732. std::string proxy_basic_auth_username_;
  733. std::string proxy_basic_auth_password_;
  734. std::string proxy_bearer_token_auth_token_;
  735. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  736. std::string proxy_digest_auth_username_;
  737. std::string proxy_digest_auth_password_;
  738. #endif
  739. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  740. bool server_certificate_verification_ = true;
  741. #endif
  742. Logger logger_;
  743. private:
  744. socket_t create_client_socket() const;
  745. bool read_response_line(Stream &strm, Response &res);
  746. bool write_request(Stream &strm, const Request &req, bool close_connection);
  747. bool redirect(const Request &req, Response &res);
  748. bool handle_request(Stream &strm, const Request &req, Response &res,
  749. bool close_connection);
  750. void stop_core();
  751. std::shared_ptr<Response> send_with_content_provider(
  752. const char *method, const char *path, const Headers &headers,
  753. const std::string &body, size_t content_length,
  754. ContentProvider content_provider, const char *content_type);
  755. virtual bool process_socket(Socket &socket,
  756. std::function<bool(Stream &strm)> callback);
  757. virtual bool is_ssl() const;
  758. };
  759. class Client {
  760. public:
  761. // Universal interface
  762. explicit Client(const char *scheme_host_port);
  763. explicit Client(const char *scheme_host_port,
  764. const std::string &client_cert_path,
  765. const std::string &client_key_path);
  766. // HTTP only interface
  767. explicit Client(const std::string &host, int port);
  768. explicit Client(const std::string &host, int port,
  769. const std::string &client_cert_path,
  770. const std::string &client_key_path);
  771. ~Client();
  772. bool is_valid() const;
  773. Result Get(const char *path);
  774. Result Get(const char *path, const Headers &headers);
  775. Result Get(const char *path, Progress progress);
  776. Result Get(const char *path, const Headers &headers, Progress progress);
  777. Result Get(const char *path, ContentReceiver content_receiver);
  778. Result Get(const char *path, const Headers &headers,
  779. ContentReceiver content_receiver);
  780. Result Get(const char *path, ContentReceiver content_receiver,
  781. Progress progress);
  782. Result Get(const char *path, const Headers &headers,
  783. ContentReceiver content_receiver, Progress progress);
  784. Result Get(const char *path, ResponseHandler response_handler,
  785. ContentReceiver content_receiver);
  786. Result Get(const char *path, const Headers &headers,
  787. ResponseHandler response_handler,
  788. ContentReceiver content_receiver);
  789. Result Get(const char *path, const Headers &headers,
  790. ResponseHandler response_handler, ContentReceiver content_receiver,
  791. Progress progress);
  792. Result Get(const char *path, ResponseHandler response_handler,
  793. ContentReceiver content_receiver, Progress progress);
  794. Result Head(const char *path);
  795. Result Head(const char *path, const Headers &headers);
  796. Result Post(const char *path);
  797. Result Post(const char *path, const std::string &body,
  798. const char *content_type);
  799. Result Post(const char *path, const Headers &headers, const std::string &body,
  800. const char *content_type);
  801. Result Post(const char *path, size_t content_length,
  802. ContentProvider content_provider, const char *content_type);
  803. Result Post(const char *path, const Headers &headers, size_t content_length,
  804. ContentProvider content_provider, const char *content_type);
  805. Result Post(const char *path, const Params &params);
  806. Result Post(const char *path, const Headers &headers, const Params &params);
  807. Result Post(const char *path, const MultipartFormDataItems &items);
  808. Result Post(const char *path, const Headers &headers,
  809. const MultipartFormDataItems &items);
  810. Result Put(const char *path);
  811. Result Put(const char *path, const std::string &body,
  812. const char *content_type);
  813. Result Put(const char *path, const Headers &headers, const std::string &body,
  814. const char *content_type);
  815. Result Put(const char *path, size_t content_length,
  816. ContentProvider content_provider, const char *content_type);
  817. Result Put(const char *path, const Headers &headers, size_t content_length,
  818. ContentProvider content_provider, const char *content_type);
  819. Result Put(const char *path, const Params &params);
  820. Result Put(const char *path, const Headers &headers, const Params &params);
  821. Result Patch(const char *path, const std::string &body,
  822. const char *content_type);
  823. Result Patch(const char *path, const Headers &headers,
  824. const std::string &body, const char *content_type);
  825. Result Patch(const char *path, size_t content_length,
  826. ContentProvider content_provider, const char *content_type);
  827. Result Patch(const char *path, const Headers &headers, size_t content_length,
  828. ContentProvider content_provider, const char *content_type);
  829. Result Delete(const char *path);
  830. Result Delete(const char *path, const std::string &body,
  831. const char *content_type);
  832. Result Delete(const char *path, const Headers &headers);
  833. Result Delete(const char *path, const Headers &headers,
  834. const std::string &body, const char *content_type);
  835. Result Options(const char *path);
  836. Result Options(const char *path, const Headers &headers);
  837. bool send(const Request &req, Response &res);
  838. size_t is_socket_open() const;
  839. void stop();
  840. void set_default_headers(Headers headers);
  841. void set_tcp_nodelay(bool on);
  842. void set_socket_options(SocketOptions socket_options);
  843. void set_connection_timeout(time_t sec, time_t usec = 0);
  844. void set_read_timeout(time_t sec, time_t usec = 0);
  845. void set_write_timeout(time_t sec, time_t usec = 0);
  846. void set_basic_auth(const char *username, const char *password);
  847. void set_bearer_token_auth(const char *token);
  848. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  849. void set_digest_auth(const char *username, const char *password);
  850. #endif
  851. void set_keep_alive(bool on);
  852. void set_follow_location(bool on);
  853. void set_compress(bool on);
  854. void set_decompress(bool on);
  855. void set_interface(const char *intf);
  856. void set_proxy(const char *host, int port);
  857. void set_proxy_basic_auth(const char *username, const char *password);
  858. void set_proxy_bearer_token_auth(const char *token);
  859. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  860. void set_proxy_digest_auth(const char *username, const char *password);
  861. #endif
  862. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  863. void enable_server_certificate_verification(bool enabled);
  864. #endif
  865. void set_logger(Logger logger);
  866. // SSL
  867. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  868. void set_ca_cert_path(const char *ca_cert_file_path,
  869. const char *ca_cert_dir_path = nullptr);
  870. void set_ca_cert_store(X509_STORE *ca_cert_store);
  871. long get_openssl_verify_result() const;
  872. SSL_CTX *ssl_context() const;
  873. #endif
  874. private:
  875. std::shared_ptr<ClientImpl> cli_;
  876. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  877. bool is_ssl_ = false;
  878. #endif
  879. }; // namespace httplib
  880. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  881. class SSLServer : public Server {
  882. public:
  883. SSLServer(const char *cert_path, const char *private_key_path,
  884. const char *client_ca_cert_file_path = nullptr,
  885. const char *client_ca_cert_dir_path = nullptr);
  886. SSLServer(X509 *cert, EVP_PKEY *private_key,
  887. X509_STORE *client_ca_cert_store = nullptr);
  888. ~SSLServer() override;
  889. bool is_valid() const override;
  890. private:
  891. bool process_and_close_socket(socket_t sock) override;
  892. SSL_CTX *ctx_;
  893. std::mutex ctx_mutex_;
  894. };
  895. class SSLClient : public ClientImpl {
  896. public:
  897. explicit SSLClient(const std::string &host);
  898. explicit SSLClient(const std::string &host, int port);
  899. explicit SSLClient(const std::string &host, int port,
  900. const std::string &client_cert_path,
  901. const std::string &client_key_path);
  902. explicit SSLClient(const std::string &host, int port, X509 *client_cert,
  903. EVP_PKEY *client_key);
  904. ~SSLClient() override;
  905. bool is_valid() const override;
  906. void set_ca_cert_path(const char *ca_cert_file_path,
  907. const char *ca_cert_dir_path = nullptr);
  908. void set_ca_cert_store(X509_STORE *ca_cert_store);
  909. long get_openssl_verify_result() const;
  910. SSL_CTX *ssl_context() const;
  911. private:
  912. bool create_and_connect_socket(Socket &socket) override;
  913. void close_socket(Socket &socket, bool process_socket_ret) override;
  914. bool process_socket(Socket &socket,
  915. std::function<bool(Stream &strm)> callback) override;
  916. bool is_ssl() const override;
  917. bool connect_with_proxy(Socket &sock, Response &res, bool &success);
  918. bool initialize_ssl(Socket &socket);
  919. bool load_certs();
  920. bool verify_host(X509 *server_cert) const;
  921. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  922. bool verify_host_with_common_name(X509 *server_cert) const;
  923. bool check_host_name(const char *pattern, size_t pattern_len) const;
  924. SSL_CTX *ctx_;
  925. std::mutex ctx_mutex_;
  926. std::once_flag initialize_cert_;
  927. std::vector<std::string> host_components_;
  928. std::string ca_cert_file_path_;
  929. std::string ca_cert_dir_path_;
  930. X509_STORE *ca_cert_store_ = nullptr;
  931. long verify_result_ = 0;
  932. friend class ClientImpl;
  933. };
  934. #endif
  935. // ----------------------------------------------------------------------------
  936. /*
  937. * Implementation
  938. */
  939. namespace detail {
  940. inline bool is_hex(char c, int &v) {
  941. if (0x20 <= c && isdigit(c)) {
  942. v = c - '0';
  943. return true;
  944. } else if ('A' <= c && c <= 'F') {
  945. v = c - 'A' + 10;
  946. return true;
  947. } else if ('a' <= c && c <= 'f') {
  948. v = c - 'a' + 10;
  949. return true;
  950. }
  951. return false;
  952. }
  953. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  954. int &val) {
  955. if (i >= s.size()) { return false; }
  956. val = 0;
  957. for (; cnt; i++, cnt--) {
  958. if (!s[i]) { return false; }
  959. int v = 0;
  960. if (is_hex(s[i], v)) {
  961. val = val * 16 + v;
  962. } else {
  963. return false;
  964. }
  965. }
  966. return true;
  967. }
  968. inline std::string from_i_to_hex(size_t n) {
  969. const char *charset = "0123456789abcdef";
  970. std::string ret;
  971. do {
  972. ret = charset[n & 15] + ret;
  973. n >>= 4;
  974. } while (n > 0);
  975. return ret;
  976. }
  977. inline bool start_with(const std::string &a, const std::string &b) {
  978. if (a.size() < b.size()) { return false; }
  979. for (size_t i = 0; i < b.size(); i++) {
  980. if (std::tolower(a[i]) != std::tolower(b[i])) { return false; }
  981. }
  982. return true;
  983. }
  984. inline size_t to_utf8(int code, char *buff) {
  985. if (code < 0x0080) {
  986. buff[0] = (code & 0x7F);
  987. return 1;
  988. } else if (code < 0x0800) {
  989. buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
  990. buff[1] = static_cast<char>(0x80 | (code & 0x3F));
  991. return 2;
  992. } else if (code < 0xD800) {
  993. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  994. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  995. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  996. return 3;
  997. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  998. return 0;
  999. } else if (code < 0x10000) {
  1000. buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
  1001. buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1002. buff[2] = static_cast<char>(0x80 | (code & 0x3F));
  1003. return 3;
  1004. } else if (code < 0x110000) {
  1005. buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
  1006. buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
  1007. buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
  1008. buff[3] = static_cast<char>(0x80 | (code & 0x3F));
  1009. return 4;
  1010. }
  1011. // NOTREACHED
  1012. return 0;
  1013. }
  1014. // NOTE: This code came up with the following stackoverflow post:
  1015. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  1016. inline std::string base64_encode(const std::string &in) {
  1017. static const auto lookup =
  1018. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  1019. std::string out;
  1020. out.reserve(in.size());
  1021. int val = 0;
  1022. int valb = -6;
  1023. for (auto c : in) {
  1024. val = (val << 8) + static_cast<uint8_t>(c);
  1025. valb += 8;
  1026. while (valb >= 0) {
  1027. out.push_back(lookup[(val >> valb) & 0x3F]);
  1028. valb -= 6;
  1029. }
  1030. }
  1031. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  1032. while (out.size() % 4) {
  1033. out.push_back('=');
  1034. }
  1035. return out;
  1036. }
  1037. inline bool is_file(const std::string &path) {
  1038. struct stat st;
  1039. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  1040. }
  1041. inline bool is_dir(const std::string &path) {
  1042. struct stat st;
  1043. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  1044. }
  1045. inline bool is_valid_path(const std::string &path) {
  1046. size_t level = 0;
  1047. size_t i = 0;
  1048. // Skip slash
  1049. while (i < path.size() && path[i] == '/') {
  1050. i++;
  1051. }
  1052. while (i < path.size()) {
  1053. // Read component
  1054. auto beg = i;
  1055. while (i < path.size() && path[i] != '/') {
  1056. i++;
  1057. }
  1058. auto len = i - beg;
  1059. assert(len > 0);
  1060. if (!path.compare(beg, len, ".")) {
  1061. ;
  1062. } else if (!path.compare(beg, len, "..")) {
  1063. if (level == 0) { return false; }
  1064. level--;
  1065. } else {
  1066. level++;
  1067. }
  1068. // Skip slash
  1069. while (i < path.size() && path[i] == '/') {
  1070. i++;
  1071. }
  1072. }
  1073. return true;
  1074. }
  1075. inline std::string encode_url(const std::string &s) {
  1076. std::string result;
  1077. for (size_t i = 0; s[i]; i++) {
  1078. switch (s[i]) {
  1079. case ' ': result += "%20"; break;
  1080. case '+': result += "%2B"; break;
  1081. case '\r': result += "%0D"; break;
  1082. case '\n': result += "%0A"; break;
  1083. case '\'': result += "%27"; break;
  1084. case ',': result += "%2C"; break;
  1085. // case ':': result += "%3A"; break; // ok? probably...
  1086. case ';': result += "%3B"; break;
  1087. default:
  1088. auto c = static_cast<uint8_t>(s[i]);
  1089. if (c >= 0x80) {
  1090. result += '%';
  1091. char hex[4];
  1092. auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  1093. assert(len == 2);
  1094. result.append(hex, static_cast<size_t>(len));
  1095. } else {
  1096. result += s[i];
  1097. }
  1098. break;
  1099. }
  1100. }
  1101. return result;
  1102. }
  1103. inline std::string decode_url(const std::string &s,
  1104. bool convert_plus_to_space) {
  1105. std::string result;
  1106. for (size_t i = 0; i < s.size(); i++) {
  1107. if (s[i] == '%' && i + 1 < s.size()) {
  1108. if (s[i + 1] == 'u') {
  1109. int val = 0;
  1110. if (from_hex_to_i(s, i + 2, 4, val)) {
  1111. // 4 digits Unicode codes
  1112. char buff[4];
  1113. size_t len = to_utf8(val, buff);
  1114. if (len > 0) { result.append(buff, len); }
  1115. i += 5; // 'u0000'
  1116. } else {
  1117. result += s[i];
  1118. }
  1119. } else {
  1120. int val = 0;
  1121. if (from_hex_to_i(s, i + 1, 2, val)) {
  1122. // 2 digits hex codes
  1123. result += static_cast<char>(val);
  1124. i += 2; // '00'
  1125. } else {
  1126. result += s[i];
  1127. }
  1128. }
  1129. } else if (convert_plus_to_space && s[i] == '+') {
  1130. result += ' ';
  1131. } else {
  1132. result += s[i];
  1133. }
  1134. }
  1135. return result;
  1136. }
  1137. inline void read_file(const std::string &path, std::string &out) {
  1138. std::ifstream fs(path, std::ios_base::binary);
  1139. fs.seekg(0, std::ios_base::end);
  1140. auto size = fs.tellg();
  1141. fs.seekg(0);
  1142. out.resize(static_cast<size_t>(size));
  1143. fs.read(&out[0], static_cast<std::streamsize>(size));
  1144. }
  1145. inline std::string file_extension(const std::string &path) {
  1146. std::smatch m;
  1147. static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  1148. if (std::regex_search(path, m, re)) { return m[1].str(); }
  1149. return std::string();
  1150. }
  1151. inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
  1152. inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
  1153. size_t right) {
  1154. while (b + left < e && is_space_or_tab(b[left])) {
  1155. left++;
  1156. }
  1157. while (right > 0 && is_space_or_tab(b[right - 1])) {
  1158. right--;
  1159. }
  1160. return std::make_pair(left, right);
  1161. }
  1162. inline std::string trim_copy(const std::string &s) {
  1163. auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
  1164. return s.substr(r.first, r.second - r.first);
  1165. }
  1166. template <class Fn> void split(const char *b, const char *e, char d, Fn fn) {
  1167. size_t i = 0;
  1168. size_t beg = 0;
  1169. while (e ? (b + i < e) : (b[i] != '\0')) {
  1170. if (b[i] == d) {
  1171. auto r = trim(b, e, beg, i);
  1172. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  1173. beg = i + 1;
  1174. }
  1175. i++;
  1176. }
  1177. if (i) {
  1178. auto r = trim(b, e, beg, i);
  1179. if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
  1180. }
  1181. }
  1182. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  1183. // to store data. The call can set memory on stack for performance.
  1184. class stream_line_reader {
  1185. public:
  1186. stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size)
  1187. : strm_(strm), fixed_buffer_(fixed_buffer),
  1188. fixed_buffer_size_(fixed_buffer_size) {}
  1189. const char *ptr() const {
  1190. if (glowable_buffer_.empty()) {
  1191. return fixed_buffer_;
  1192. } else {
  1193. return glowable_buffer_.data();
  1194. }
  1195. }
  1196. size_t size() const {
  1197. if (glowable_buffer_.empty()) {
  1198. return fixed_buffer_used_size_;
  1199. } else {
  1200. return glowable_buffer_.size();
  1201. }
  1202. }
  1203. bool end_with_crlf() const {
  1204. auto end = ptr() + size();
  1205. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  1206. }
  1207. bool getline() {
  1208. fixed_buffer_used_size_ = 0;
  1209. glowable_buffer_.clear();
  1210. for (size_t i = 0;; i++) {
  1211. char byte;
  1212. auto n = strm_.read(&byte, 1);
  1213. if (n < 0) {
  1214. return false;
  1215. } else if (n == 0) {
  1216. if (i == 0) {
  1217. return false;
  1218. } else {
  1219. break;
  1220. }
  1221. }
  1222. append(byte);
  1223. if (byte == '\n') { break; }
  1224. }
  1225. return true;
  1226. }
  1227. private:
  1228. void append(char c) {
  1229. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  1230. fixed_buffer_[fixed_buffer_used_size_++] = c;
  1231. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  1232. } else {
  1233. if (glowable_buffer_.empty()) {
  1234. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  1235. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  1236. }
  1237. glowable_buffer_ += c;
  1238. }
  1239. }
  1240. Stream &strm_;
  1241. char *fixed_buffer_;
  1242. const size_t fixed_buffer_size_;
  1243. size_t fixed_buffer_used_size_ = 0;
  1244. std::string glowable_buffer_;
  1245. };
  1246. inline int close_socket(socket_t sock) {
  1247. #ifdef _WIN32
  1248. return closesocket(sock);
  1249. #else
  1250. return close(sock);
  1251. #endif
  1252. }
  1253. template <typename T> inline ssize_t handle_EINTR(T fn) {
  1254. ssize_t res = false;
  1255. while (true) {
  1256. res = fn();
  1257. if (res < 0 && errno == EINTR) { continue; }
  1258. break;
  1259. }
  1260. return res;
  1261. }
  1262. inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
  1263. #ifdef CPPHTTPLIB_USE_POLL
  1264. struct pollfd pfd_read;
  1265. pfd_read.fd = sock;
  1266. pfd_read.events = POLLIN;
  1267. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1268. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1269. #else
  1270. fd_set fds;
  1271. FD_ZERO(&fds);
  1272. FD_SET(sock, &fds);
  1273. timeval tv;
  1274. tv.tv_sec = static_cast<long>(sec);
  1275. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1276. return handle_EINTR([&]() {
  1277. return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
  1278. });
  1279. #endif
  1280. }
  1281. inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
  1282. #ifdef CPPHTTPLIB_USE_POLL
  1283. struct pollfd pfd_read;
  1284. pfd_read.fd = sock;
  1285. pfd_read.events = POLLOUT;
  1286. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1287. return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1288. #else
  1289. fd_set fds;
  1290. FD_ZERO(&fds);
  1291. FD_SET(sock, &fds);
  1292. timeval tv;
  1293. tv.tv_sec = static_cast<long>(sec);
  1294. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1295. return handle_EINTR([&]() {
  1296. return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);
  1297. });
  1298. #endif
  1299. }
  1300. inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
  1301. #ifdef CPPHTTPLIB_USE_POLL
  1302. struct pollfd pfd_read;
  1303. pfd_read.fd = sock;
  1304. pfd_read.events = POLLIN | POLLOUT;
  1305. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  1306. auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
  1307. if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
  1308. int error = 0;
  1309. socklen_t len = sizeof(error);
  1310. auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
  1311. reinterpret_cast<char *>(&error), &len);
  1312. return res >= 0 && !error;
  1313. }
  1314. return false;
  1315. #else
  1316. fd_set fdsr;
  1317. FD_ZERO(&fdsr);
  1318. FD_SET(sock, &fdsr);
  1319. auto fdsw = fdsr;
  1320. auto fdse = fdsr;
  1321. timeval tv;
  1322. tv.tv_sec = static_cast<long>(sec);
  1323. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
  1324. auto ret = handle_EINTR([&]() {
  1325. return select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv);
  1326. });
  1327. if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  1328. int error = 0;
  1329. socklen_t len = sizeof(error);
  1330. return getsockopt(sock, SOL_SOCKET, SO_ERROR,
  1331. reinterpret_cast<char *>(&error), &len) >= 0 &&
  1332. !error;
  1333. }
  1334. return false;
  1335. #endif
  1336. }
  1337. class SocketStream : public Stream {
  1338. public:
  1339. SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
  1340. time_t write_timeout_sec, time_t write_timeout_usec);
  1341. ~SocketStream() override;
  1342. bool is_readable() const override;
  1343. bool is_writable() const override;
  1344. ssize_t read(char *ptr, size_t size) override;
  1345. ssize_t write(const char *ptr, size_t size) override;
  1346. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1347. private:
  1348. socket_t sock_;
  1349. time_t read_timeout_sec_;
  1350. time_t read_timeout_usec_;
  1351. time_t write_timeout_sec_;
  1352. time_t write_timeout_usec_;
  1353. };
  1354. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1355. class SSLSocketStream : public Stream {
  1356. public:
  1357. SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
  1358. time_t read_timeout_usec, time_t write_timeout_sec,
  1359. time_t write_timeout_usec);
  1360. ~SSLSocketStream() override;
  1361. bool is_readable() const override;
  1362. bool is_writable() const override;
  1363. ssize_t read(char *ptr, size_t size) override;
  1364. ssize_t write(const char *ptr, size_t size) override;
  1365. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1366. private:
  1367. socket_t sock_;
  1368. SSL *ssl_;
  1369. time_t read_timeout_sec_;
  1370. time_t read_timeout_usec_;
  1371. time_t write_timeout_sec_;
  1372. time_t write_timeout_usec_;
  1373. };
  1374. #endif
  1375. class BufferStream : public Stream {
  1376. public:
  1377. BufferStream() = default;
  1378. ~BufferStream() override = default;
  1379. bool is_readable() const override;
  1380. bool is_writable() const override;
  1381. ssize_t read(char *ptr, size_t size) override;
  1382. ssize_t write(const char *ptr, size_t size) override;
  1383. void get_remote_ip_and_port(std::string &ip, int &port) const override;
  1384. const std::string &get_buffer() const;
  1385. private:
  1386. std::string buffer;
  1387. size_t position = 0;
  1388. };
  1389. inline bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) {
  1390. using namespace std::chrono;
  1391. auto start = steady_clock::now();
  1392. while (true) {
  1393. auto val = select_read(sock, 0, 10000);
  1394. if (val < 0) {
  1395. return false;
  1396. } else if (val == 0) {
  1397. auto current = steady_clock::now();
  1398. auto duration = duration_cast<milliseconds>(current - start);
  1399. auto timeout = keep_alive_timeout_sec * 1000;
  1400. if (duration.count() > timeout) { return false; }
  1401. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1402. } else {
  1403. return true;
  1404. }
  1405. }
  1406. }
  1407. template <typename T>
  1408. inline bool
  1409. process_server_socket_core(socket_t sock, size_t keep_alive_max_count,
  1410. time_t keep_alive_timeout_sec, T callback) {
  1411. assert(keep_alive_max_count > 0);
  1412. auto ret = false;
  1413. auto count = keep_alive_max_count;
  1414. while (count > 0 && keep_alive(sock, keep_alive_timeout_sec)) {
  1415. auto close_connection = count == 1;
  1416. auto connection_closed = false;
  1417. ret = callback(close_connection, connection_closed);
  1418. if (!ret || connection_closed) { break; }
  1419. count--;
  1420. }
  1421. return ret;
  1422. }
  1423. template <typename T>
  1424. inline bool
  1425. process_server_socket(socket_t sock, size_t keep_alive_max_count,
  1426. time_t keep_alive_timeout_sec, time_t read_timeout_sec,
  1427. time_t read_timeout_usec, time_t write_timeout_sec,
  1428. time_t write_timeout_usec, T callback) {
  1429. return process_server_socket_core(
  1430. sock, keep_alive_max_count, keep_alive_timeout_sec,
  1431. [&](bool close_connection, bool &connection_closed) {
  1432. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  1433. write_timeout_sec, write_timeout_usec);
  1434. return callback(strm, close_connection, connection_closed);
  1435. });
  1436. }
  1437. template <typename T>
  1438. inline bool process_client_socket(socket_t sock, time_t read_timeout_sec,
  1439. time_t read_timeout_usec,
  1440. time_t write_timeout_sec,
  1441. time_t write_timeout_usec, T callback) {
  1442. SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
  1443. write_timeout_sec, write_timeout_usec);
  1444. return callback(strm);
  1445. }
  1446. inline int shutdown_socket(socket_t sock) {
  1447. #ifdef _WIN32
  1448. return shutdown(sock, SD_BOTH);
  1449. #else
  1450. return shutdown(sock, SHUT_RDWR);
  1451. #endif
  1452. }
  1453. template <typename BindOrConnect>
  1454. socket_t create_socket(const char *host, int port, int socket_flags,
  1455. bool tcp_nodelay, SocketOptions socket_options,
  1456. BindOrConnect bind_or_connect) {
  1457. // Get address info
  1458. struct addrinfo hints;
  1459. struct addrinfo *result;
  1460. memset(&hints, 0, sizeof(struct addrinfo));
  1461. hints.ai_family = AF_UNSPEC;
  1462. hints.ai_socktype = SOCK_STREAM;
  1463. hints.ai_flags = socket_flags;
  1464. hints.ai_protocol = 0;
  1465. auto service = std::to_string(port);
  1466. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  1467. #ifdef __linux__
  1468. res_init();
  1469. #endif
  1470. return INVALID_SOCKET;
  1471. }
  1472. for (auto rp = result; rp; rp = rp->ai_next) {
  1473. // Create a socket
  1474. #ifdef _WIN32
  1475. auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
  1476. nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT);
  1477. /**
  1478. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  1479. * and above the socket creation fails on older Windows Systems.
  1480. *
  1481. * Let's try to create a socket the old way in this case.
  1482. *
  1483. * Reference:
  1484. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  1485. *
  1486. * WSA_FLAG_NO_HANDLE_INHERIT:
  1487. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  1488. * SP1, and later
  1489. *
  1490. */
  1491. if (sock == INVALID_SOCKET) {
  1492. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1493. }
  1494. #else
  1495. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1496. #endif
  1497. if (sock == INVALID_SOCKET) { continue; }
  1498. #ifndef _WIN32
  1499. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; }
  1500. #endif
  1501. if (tcp_nodelay) {
  1502. int yes = 1;
  1503. setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&yes),
  1504. sizeof(yes));
  1505. }
  1506. if (socket_options) { socket_options(sock); }
  1507. if (rp->ai_family == AF_INET6) {
  1508. int no = 0;
  1509. setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<char *>(&no),
  1510. sizeof(no));
  1511. }
  1512. // bind or connect
  1513. if (bind_or_connect(sock, *rp)) {
  1514. freeaddrinfo(result);
  1515. return sock;
  1516. }
  1517. close_socket(sock);
  1518. }
  1519. freeaddrinfo(result);
  1520. return INVALID_SOCKET;
  1521. }
  1522. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  1523. #ifdef _WIN32
  1524. auto flags = nonblocking ? 1UL : 0UL;
  1525. ioctlsocket(sock, FIONBIO, &flags);
  1526. #else
  1527. auto flags = fcntl(sock, F_GETFL, 0);
  1528. fcntl(sock, F_SETFL,
  1529. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  1530. #endif
  1531. }
  1532. inline bool is_connection_error() {
  1533. #ifdef _WIN32
  1534. return WSAGetLastError() != WSAEWOULDBLOCK;
  1535. #else
  1536. return errno != EINPROGRESS;
  1537. #endif
  1538. }
  1539. inline bool bind_ip_address(socket_t sock, const char *host) {
  1540. struct addrinfo hints;
  1541. struct addrinfo *result;
  1542. memset(&hints, 0, sizeof(struct addrinfo));
  1543. hints.ai_family = AF_UNSPEC;
  1544. hints.ai_socktype = SOCK_STREAM;
  1545. hints.ai_protocol = 0;
  1546. if (getaddrinfo(host, "0", &hints, &result)) { return false; }
  1547. auto ret = false;
  1548. for (auto rp = result; rp; rp = rp->ai_next) {
  1549. const auto &ai = *rp;
  1550. if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  1551. ret = true;
  1552. break;
  1553. }
  1554. }
  1555. freeaddrinfo(result);
  1556. return ret;
  1557. }
  1558. #if !defined _WIN32 && !defined ANDROID
  1559. #define USE_IF2IP
  1560. #endif
  1561. #ifdef USE_IF2IP
  1562. inline std::string if2ip(const std::string &ifn) {
  1563. struct ifaddrs *ifap;
  1564. getifaddrs(&ifap);
  1565. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  1566. if (ifa->ifa_addr && ifn == ifa->ifa_name) {
  1567. if (ifa->ifa_addr->sa_family == AF_INET) {
  1568. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  1569. char buf[INET_ADDRSTRLEN];
  1570. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  1571. freeifaddrs(ifap);
  1572. return std::string(buf, INET_ADDRSTRLEN);
  1573. }
  1574. }
  1575. }
  1576. }
  1577. freeifaddrs(ifap);
  1578. return std::string();
  1579. }
  1580. #endif
  1581. inline socket_t create_client_socket(const char *host, int port,
  1582. bool tcp_nodelay,
  1583. SocketOptions socket_options,
  1584. time_t timeout_sec, time_t timeout_usec,
  1585. const std::string &intf, Error &error) {
  1586. auto sock = create_socket(
  1587. host, port, 0, tcp_nodelay, socket_options,
  1588. [&](socket_t sock, struct addrinfo &ai) -> bool {
  1589. if (!intf.empty()) {
  1590. #ifdef USE_IF2IP
  1591. auto ip = if2ip(intf);
  1592. if (ip.empty()) { ip = intf; }
  1593. if (!bind_ip_address(sock, ip.c_str())) {
  1594. error = Error::BindIPAddress;
  1595. return false;
  1596. }
  1597. #endif
  1598. }
  1599. set_nonblocking(sock, true);
  1600. auto ret =
  1601. ::connect(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
  1602. if (ret < 0) {
  1603. if (is_connection_error() ||
  1604. !wait_until_socket_is_ready(sock, timeout_sec, timeout_usec)) {
  1605. close_socket(sock);
  1606. error = Error::Connection;
  1607. return false;
  1608. }
  1609. }
  1610. set_nonblocking(sock, false);
  1611. error = Error::Success;
  1612. return true;
  1613. });
  1614. if (sock != INVALID_SOCKET) {
  1615. error = Error::Success;
  1616. } else {
  1617. if (error == Error::Success) { error = Error::Connection; }
  1618. }
  1619. return sock;
  1620. }
  1621. inline void get_remote_ip_and_port(const struct sockaddr_storage &addr,
  1622. socklen_t addr_len, std::string &ip,
  1623. int &port) {
  1624. if (addr.ss_family == AF_INET) {
  1625. port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
  1626. } else if (addr.ss_family == AF_INET6) {
  1627. port =
  1628. ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
  1629. }
  1630. std::array<char, NI_MAXHOST> ipstr{};
  1631. if (!getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
  1632. ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
  1633. 0, NI_NUMERICHOST)) {
  1634. ip = ipstr.data();
  1635. }
  1636. }
  1637. inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
  1638. struct sockaddr_storage addr;
  1639. socklen_t addr_len = sizeof(addr);
  1640. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
  1641. &addr_len)) {
  1642. get_remote_ip_and_port(addr, addr_len, ip, port);
  1643. }
  1644. }
  1645. inline const char *
  1646. find_content_type(const std::string &path,
  1647. const std::map<std::string, std::string> &user_data) {
  1648. auto ext = file_extension(path);
  1649. auto it = user_data.find(ext);
  1650. if (it != user_data.end()) { return it->second.c_str(); }
  1651. if (ext == "txt") {
  1652. return "text/plain";
  1653. } else if (ext == "html" || ext == "htm") {
  1654. return "text/html";
  1655. } else if (ext == "css") {
  1656. return "text/css";
  1657. } else if (ext == "jpeg" || ext == "jpg") {
  1658. return "image/jpg";
  1659. } else if (ext == "png") {
  1660. return "image/png";
  1661. } else if (ext == "gif") {
  1662. return "image/gif";
  1663. } else if (ext == "svg") {
  1664. return "image/svg+xml";
  1665. } else if (ext == "ico") {
  1666. return "image/x-icon";
  1667. } else if (ext == "json") {
  1668. return "application/json";
  1669. } else if (ext == "pdf") {
  1670. return "application/pdf";
  1671. } else if (ext == "js") {
  1672. return "application/javascript";
  1673. } else if (ext == "wasm") {
  1674. return "application/wasm";
  1675. } else if (ext == "xml") {
  1676. return "application/xml";
  1677. } else if (ext == "xhtml") {
  1678. return "application/xhtml+xml";
  1679. }
  1680. return nullptr;
  1681. }
  1682. inline const char *status_message(int status) {
  1683. switch (status) {
  1684. case 100: return "Continue";
  1685. case 101: return "Switching Protocol";
  1686. case 102: return "Processing";
  1687. case 103: return "Early Hints";
  1688. case 200: return "OK";
  1689. case 201: return "Created";
  1690. case 202: return "Accepted";
  1691. case 203: return "Non-Authoritative Information";
  1692. case 204: return "No Content";
  1693. case 205: return "Reset Content";
  1694. case 206: return "Partial Content";
  1695. case 207: return "Multi-Status";
  1696. case 208: return "Already Reported";
  1697. case 226: return "IM Used";
  1698. case 300: return "Multiple Choice";
  1699. case 301: return "Moved Permanently";
  1700. case 302: return "Found";
  1701. case 303: return "See Other";
  1702. case 304: return "Not Modified";
  1703. case 305: return "Use Proxy";
  1704. case 306: return "unused";
  1705. case 307: return "Temporary Redirect";
  1706. case 308: return "Permanent Redirect";
  1707. case 400: return "Bad Request";
  1708. case 401: return "Unauthorized";
  1709. case 402: return "Payment Required";
  1710. case 403: return "Forbidden";
  1711. case 404: return "Not Found";
  1712. case 405: return "Method Not Allowed";
  1713. case 406: return "Not Acceptable";
  1714. case 407: return "Proxy Authentication Required";
  1715. case 408: return "Request Timeout";
  1716. case 409: return "Conflict";
  1717. case 410: return "Gone";
  1718. case 411: return "Length Required";
  1719. case 412: return "Precondition Failed";
  1720. case 413: return "Payload Too Large";
  1721. case 414: return "URI Too Long";
  1722. case 415: return "Unsupported Media Type";
  1723. case 416: return "Range Not Satisfiable";
  1724. case 417: return "Expectation Failed";
  1725. case 418: return "I'm a teapot";
  1726. case 421: return "Misdirected Request";
  1727. case 422: return "Unprocessable Entity";
  1728. case 423: return "Locked";
  1729. case 424: return "Failed Dependency";
  1730. case 425: return "Too Early";
  1731. case 426: return "Upgrade Required";
  1732. case 428: return "Precondition Required";
  1733. case 429: return "Too Many Requests";
  1734. case 431: return "Request Header Fields Too Large";
  1735. case 451: return "Unavailable For Legal Reasons";
  1736. case 501: return "Not Implemented";
  1737. case 502: return "Bad Gateway";
  1738. case 503: return "Service Unavailable";
  1739. case 504: return "Gateway Timeout";
  1740. case 505: return "HTTP Version Not Supported";
  1741. case 506: return "Variant Also Negotiates";
  1742. case 507: return "Insufficient Storage";
  1743. case 508: return "Loop Detected";
  1744. case 510: return "Not Extended";
  1745. case 511: return "Network Authentication Required";
  1746. default:
  1747. case 500: return "Internal Server Error";
  1748. }
  1749. }
  1750. inline bool can_compress_content_type(const std::string &content_type) {
  1751. return (!content_type.find("text/") && content_type != "text/event-stream") ||
  1752. content_type == "image/svg+xml" ||
  1753. content_type == "application/javascript" ||
  1754. content_type == "application/json" ||
  1755. content_type == "application/xml" ||
  1756. content_type == "application/xhtml+xml";
  1757. }
  1758. enum class EncodingType { None = 0, Gzip, Brotli };
  1759. inline EncodingType encoding_type(const Request &req, const Response &res) {
  1760. auto ret =
  1761. detail::can_compress_content_type(res.get_header_value("Content-Type"));
  1762. if (!ret) { return EncodingType::None; }
  1763. const auto &s = req.get_header_value("Accept-Encoding");
  1764. (void)(s);
  1765. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1766. // TODO: 'Accept-Encoding' has br, not br;q=0
  1767. ret = s.find("br") != std::string::npos;
  1768. if (ret) { return EncodingType::Brotli; }
  1769. #endif
  1770. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1771. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  1772. ret = s.find("gzip") != std::string::npos;
  1773. if (ret) { return EncodingType::Gzip; }
  1774. #endif
  1775. return EncodingType::None;
  1776. }
  1777. class compressor {
  1778. public:
  1779. virtual ~compressor(){};
  1780. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1781. virtual bool compress(const char *data, size_t data_length, bool last,
  1782. Callback callback) = 0;
  1783. };
  1784. class decompressor {
  1785. public:
  1786. virtual ~decompressor() {}
  1787. virtual bool is_valid() const = 0;
  1788. typedef std::function<bool(const char *data, size_t data_len)> Callback;
  1789. virtual bool decompress(const char *data, size_t data_length,
  1790. Callback callback) = 0;
  1791. };
  1792. class nocompressor : public compressor {
  1793. public:
  1794. ~nocompressor(){};
  1795. bool compress(const char *data, size_t data_length, bool /*last*/,
  1796. Callback callback) override {
  1797. if (!data_length) { return true; }
  1798. return callback(data, data_length);
  1799. }
  1800. };
  1801. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1802. class gzip_compressor : public compressor {
  1803. public:
  1804. gzip_compressor() {
  1805. std::memset(&strm_, 0, sizeof(strm_));
  1806. strm_.zalloc = Z_NULL;
  1807. strm_.zfree = Z_NULL;
  1808. strm_.opaque = Z_NULL;
  1809. is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  1810. Z_DEFAULT_STRATEGY) == Z_OK;
  1811. }
  1812. ~gzip_compressor() { deflateEnd(&strm_); }
  1813. bool compress(const char *data, size_t data_length, bool last,
  1814. Callback callback) override {
  1815. assert(is_valid_);
  1816. auto flush = last ? Z_FINISH : Z_NO_FLUSH;
  1817. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(data_length);
  1818. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  1819. int ret = Z_OK;
  1820. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1821. do {
  1822. strm_.avail_out = buff.size();
  1823. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  1824. ret = deflate(&strm_, flush);
  1825. assert(ret != Z_STREAM_ERROR);
  1826. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  1827. return false;
  1828. }
  1829. } while (strm_.avail_out == 0);
  1830. assert((last && ret == Z_STREAM_END) || (!last && ret == Z_OK));
  1831. assert(strm_.avail_in == 0);
  1832. return true;
  1833. }
  1834. private:
  1835. bool is_valid_ = false;
  1836. z_stream strm_;
  1837. };
  1838. class gzip_decompressor : public decompressor {
  1839. public:
  1840. gzip_decompressor() {
  1841. std::memset(&strm_, 0, sizeof(strm_));
  1842. strm_.zalloc = Z_NULL;
  1843. strm_.zfree = Z_NULL;
  1844. strm_.opaque = Z_NULL;
  1845. // 15 is the value of wbits, which should be at the maximum possible value
  1846. // to ensure that any gzip stream can be decoded. The offset of 32 specifies
  1847. // that the stream type should be automatically detected either gzip or
  1848. // deflate.
  1849. is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
  1850. }
  1851. ~gzip_decompressor() { inflateEnd(&strm_); }
  1852. bool is_valid() const override { return is_valid_; }
  1853. bool decompress(const char *data, size_t data_length,
  1854. Callback callback) override {
  1855. assert(is_valid_);
  1856. int ret = Z_OK;
  1857. strm_.avail_in = static_cast<decltype(strm_.avail_in)>(data_length);
  1858. strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  1859. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1860. while (strm_.avail_in > 0) {
  1861. strm_.avail_out = buff.size();
  1862. strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
  1863. ret = inflate(&strm_, Z_NO_FLUSH);
  1864. assert(ret != Z_STREAM_ERROR);
  1865. switch (ret) {
  1866. case Z_NEED_DICT:
  1867. case Z_DATA_ERROR:
  1868. case Z_MEM_ERROR: inflateEnd(&strm_); return false;
  1869. }
  1870. if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
  1871. return false;
  1872. }
  1873. }
  1874. return ret == Z_OK || ret == Z_STREAM_END;
  1875. }
  1876. private:
  1877. bool is_valid_ = false;
  1878. z_stream strm_;
  1879. };
  1880. #endif
  1881. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1882. class brotli_compressor : public compressor {
  1883. public:
  1884. brotli_compressor() {
  1885. state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
  1886. }
  1887. ~brotli_compressor() { BrotliEncoderDestroyInstance(state_); }
  1888. bool compress(const char *data, size_t data_length, bool last,
  1889. Callback callback) override {
  1890. std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1891. auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
  1892. auto available_in = data_length;
  1893. auto next_in = reinterpret_cast<const uint8_t *>(data);
  1894. for (;;) {
  1895. if (last) {
  1896. if (BrotliEncoderIsFinished(state_)) { break; }
  1897. } else {
  1898. if (!available_in) { break; }
  1899. }
  1900. auto available_out = buff.size();
  1901. auto next_out = buff.data();
  1902. if (!BrotliEncoderCompressStream(state_, operation, &available_in,
  1903. &next_in, &available_out, &next_out,
  1904. nullptr)) {
  1905. return false;
  1906. }
  1907. auto output_bytes = buff.size() - available_out;
  1908. if (output_bytes) {
  1909. callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
  1910. }
  1911. }
  1912. return true;
  1913. }
  1914. private:
  1915. BrotliEncoderState *state_ = nullptr;
  1916. };
  1917. class brotli_decompressor : public decompressor {
  1918. public:
  1919. brotli_decompressor() {
  1920. decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
  1921. decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
  1922. : BROTLI_DECODER_RESULT_ERROR;
  1923. }
  1924. ~brotli_decompressor() {
  1925. if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
  1926. }
  1927. bool is_valid() const override { return decoder_s; }
  1928. bool decompress(const char *data, size_t data_length,
  1929. Callback callback) override {
  1930. if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  1931. decoder_r == BROTLI_DECODER_RESULT_ERROR) {
  1932. return 0;
  1933. }
  1934. const uint8_t *next_in = (const uint8_t *)data;
  1935. size_t avail_in = data_length;
  1936. size_t total_out;
  1937. decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
  1938. std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
  1939. while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
  1940. char *next_out = buff.data();
  1941. size_t avail_out = buff.size();
  1942. decoder_r = BrotliDecoderDecompressStream(
  1943. decoder_s, &avail_in, &next_in, &avail_out,
  1944. reinterpret_cast<uint8_t **>(&next_out), &total_out);
  1945. if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
  1946. if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
  1947. }
  1948. return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
  1949. decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
  1950. }
  1951. private:
  1952. BrotliDecoderResult decoder_r;
  1953. BrotliDecoderState *decoder_s = nullptr;
  1954. };
  1955. #endif
  1956. inline bool has_header(const Headers &headers, const char *key) {
  1957. return headers.find(key) != headers.end();
  1958. }
  1959. inline const char *get_header_value(const Headers &headers, const char *key,
  1960. size_t id = 0, const char *def = nullptr) {
  1961. auto rng = headers.equal_range(key);
  1962. auto it = rng.first;
  1963. std::advance(it, static_cast<ssize_t>(id));
  1964. if (it != rng.second) { return it->second.c_str(); }
  1965. return def;
  1966. }
  1967. template <typename T>
  1968. inline T get_header_value(const Headers & /*headers*/, const char * /*key*/,
  1969. size_t /*id*/ = 0, uint64_t /*def*/ = 0) {}
  1970. template <>
  1971. inline uint64_t get_header_value<uint64_t>(const Headers &headers,
  1972. const char *key, size_t id,
  1973. uint64_t def) {
  1974. auto rng = headers.equal_range(key);
  1975. auto it = rng.first;
  1976. std::advance(it, static_cast<ssize_t>(id));
  1977. if (it != rng.second) {
  1978. return std::strtoull(it->second.data(), nullptr, 10);
  1979. }
  1980. return def;
  1981. }
  1982. template <typename T>
  1983. inline bool parse_header(const char *beg, const char *end, T fn) {
  1984. // Skip trailing spaces and tabs.
  1985. while (beg < end && is_space_or_tab(end[-1])) {
  1986. end--;
  1987. }
  1988. auto p = beg;
  1989. while (p < end && *p != ':') {
  1990. p++;
  1991. }
  1992. if (p == end) { return false; }
  1993. auto key_end = p;
  1994. if (*p++ != ':') { return false; }
  1995. while (p < end && is_space_or_tab(*p)) {
  1996. p++;
  1997. }
  1998. if (p < end) {
  1999. fn(std::string(beg, key_end), decode_url(std::string(p, end), false));
  2000. return true;
  2001. }
  2002. return false;
  2003. }
  2004. inline bool read_headers(Stream &strm, Headers &headers) {
  2005. const auto bufsiz = 2048;
  2006. char buf[bufsiz];
  2007. stream_line_reader line_reader(strm, buf, bufsiz);
  2008. for (;;) {
  2009. if (!line_reader.getline()) { return false; }
  2010. // Check if the line ends with CRLF.
  2011. if (line_reader.end_with_crlf()) {
  2012. // Blank line indicates end of headers.
  2013. if (line_reader.size() == 2) { break; }
  2014. } else {
  2015. continue; // Skip invalid line.
  2016. }
  2017. // Exclude CRLF
  2018. auto end = line_reader.ptr() + line_reader.size() - 2;
  2019. parse_header(line_reader.ptr(), end,
  2020. [&](std::string &&key, std::string &&val) {
  2021. headers.emplace(std::move(key), std::move(val));
  2022. });
  2023. }
  2024. return true;
  2025. }
  2026. inline bool read_content_with_length(Stream &strm, uint64_t len,
  2027. Progress progress, ContentReceiver out) {
  2028. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  2029. uint64_t r = 0;
  2030. while (r < len) {
  2031. auto read_len = static_cast<size_t>(len - r);
  2032. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  2033. if (n <= 0) { return false; }
  2034. if (!out(buf, static_cast<size_t>(n))) { return false; }
  2035. r += static_cast<uint64_t>(n);
  2036. if (progress) {
  2037. if (!progress(r, len)) { return false; }
  2038. }
  2039. }
  2040. return true;
  2041. }
  2042. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  2043. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  2044. uint64_t r = 0;
  2045. while (r < len) {
  2046. auto read_len = static_cast<size_t>(len - r);
  2047. auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  2048. if (n <= 0) { return; }
  2049. r += static_cast<uint64_t>(n);
  2050. }
  2051. }
  2052. inline bool read_content_without_length(Stream &strm, ContentReceiver out) {
  2053. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  2054. for (;;) {
  2055. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  2056. if (n < 0) {
  2057. return false;
  2058. } else if (n == 0) {
  2059. return true;
  2060. }
  2061. if (!out(buf, static_cast<size_t>(n))) { return false; }
  2062. }
  2063. return true;
  2064. }
  2065. inline bool read_content_chunked(Stream &strm, ContentReceiver out) {
  2066. const auto bufsiz = 16;
  2067. char buf[bufsiz];
  2068. stream_line_reader line_reader(strm, buf, bufsiz);
  2069. if (!line_reader.getline()) { return false; }
  2070. unsigned long chunk_len;
  2071. while (true) {
  2072. char *end_ptr;
  2073. chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
  2074. if (end_ptr == line_reader.ptr()) { return false; }
  2075. if (chunk_len == ULONG_MAX) { return false; }
  2076. if (chunk_len == 0) { break; }
  2077. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  2078. return false;
  2079. }
  2080. if (!line_reader.getline()) { return false; }
  2081. if (strcmp(line_reader.ptr(), "\r\n")) { break; }
  2082. if (!line_reader.getline()) { return false; }
  2083. }
  2084. if (chunk_len == 0) {
  2085. // Reader terminator after chunks
  2086. if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n"))
  2087. return false;
  2088. }
  2089. return true;
  2090. }
  2091. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  2092. return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""),
  2093. "chunked");
  2094. }
  2095. template <typename T, typename U>
  2096. bool prepare_content_receiver(T &x, int &status, ContentReceiver receiver,
  2097. bool decompress, U callback) {
  2098. if (decompress) {
  2099. std::string encoding = x.get_header_value("Content-Encoding");
  2100. std::shared_ptr<decompressor> decompressor;
  2101. if (encoding.find("gzip") != std::string::npos ||
  2102. encoding.find("deflate") != std::string::npos) {
  2103. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2104. decompressor = std::make_shared<gzip_decompressor>();
  2105. #else
  2106. status = 415;
  2107. return false;
  2108. #endif
  2109. } else if (encoding.find("br") != std::string::npos) {
  2110. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2111. decompressor = std::make_shared<brotli_decompressor>();
  2112. #else
  2113. status = 415;
  2114. return false;
  2115. #endif
  2116. }
  2117. if (decompressor) {
  2118. if (decompressor->is_valid()) {
  2119. ContentReceiver out = [&](const char *buf, size_t n) {
  2120. return decompressor->decompress(
  2121. buf, n,
  2122. [&](const char *buf, size_t n) { return receiver(buf, n); });
  2123. };
  2124. return callback(out);
  2125. } else {
  2126. status = 500;
  2127. return false;
  2128. }
  2129. }
  2130. }
  2131. ContentReceiver out = [&](const char *buf, size_t n) {
  2132. return receiver(buf, n);
  2133. };
  2134. return callback(out);
  2135. }
  2136. template <typename T>
  2137. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  2138. Progress progress, ContentReceiver receiver,
  2139. bool decompress) {
  2140. return prepare_content_receiver(
  2141. x, status, receiver, decompress, [&](const ContentReceiver &out) {
  2142. auto ret = true;
  2143. auto exceed_payload_max_length = false;
  2144. if (is_chunked_transfer_encoding(x.headers)) {
  2145. ret = read_content_chunked(strm, out);
  2146. } else if (!has_header(x.headers, "Content-Length")) {
  2147. ret = read_content_without_length(strm, out);
  2148. } else {
  2149. auto len = get_header_value<uint64_t>(x.headers, "Content-Length");
  2150. if (len > payload_max_length) {
  2151. exceed_payload_max_length = true;
  2152. skip_content_with_length(strm, len);
  2153. ret = false;
  2154. } else if (len > 0) {
  2155. ret = read_content_with_length(strm, len, progress, out);
  2156. }
  2157. }
  2158. if (!ret) { status = exceed_payload_max_length ? 413 : 400; }
  2159. return ret;
  2160. });
  2161. }
  2162. template <typename T>
  2163. inline ssize_t write_headers(Stream &strm, const T &info,
  2164. const Headers &headers) {
  2165. ssize_t write_len = 0;
  2166. for (const auto &x : info.headers) {
  2167. if (x.first == "EXCEPTION_WHAT") { continue; }
  2168. auto len =
  2169. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  2170. if (len < 0) { return len; }
  2171. write_len += len;
  2172. }
  2173. for (const auto &x : headers) {
  2174. auto len =
  2175. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  2176. if (len < 0) { return len; }
  2177. write_len += len;
  2178. }
  2179. auto len = strm.write("\r\n");
  2180. if (len < 0) { return len; }
  2181. write_len += len;
  2182. return write_len;
  2183. }
  2184. inline bool write_data(Stream &strm, const char *d, size_t l) {
  2185. size_t offset = 0;
  2186. while (offset < l) {
  2187. auto length = strm.write(d + offset, l - offset);
  2188. if (length < 0) { return false; }
  2189. offset += static_cast<size_t>(length);
  2190. }
  2191. return true;
  2192. }
  2193. template <typename T>
  2194. inline ssize_t write_content(Stream &strm, ContentProvider content_provider,
  2195. size_t offset, size_t length, T is_shutting_down) {
  2196. size_t begin_offset = offset;
  2197. size_t end_offset = offset + length;
  2198. auto ok = true;
  2199. DataSink data_sink;
  2200. data_sink.write = [&](const char *d, size_t l) {
  2201. if (ok) {
  2202. offset += l;
  2203. if (!write_data(strm, d, l)) { ok = false; }
  2204. }
  2205. };
  2206. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  2207. while (offset < end_offset && !is_shutting_down()) {
  2208. if (!content_provider(offset, end_offset - offset, data_sink)) {
  2209. return -1;
  2210. }
  2211. if (!ok) { return -1; }
  2212. }
  2213. return static_cast<ssize_t>(offset - begin_offset);
  2214. }
  2215. template <typename T>
  2216. inline ssize_t write_content_without_length(Stream &strm,
  2217. ContentProvider content_provider,
  2218. T is_shutting_down) {
  2219. size_t offset = 0;
  2220. auto data_available = true;
  2221. auto ok = true;
  2222. DataSink data_sink;
  2223. data_sink.write = [&](const char *d, size_t l) {
  2224. if (ok) {
  2225. offset += l;
  2226. if (!write_data(strm, d, l)) { ok = false; }
  2227. }
  2228. };
  2229. data_sink.done = [&](void) { data_available = false; };
  2230. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  2231. while (data_available && !is_shutting_down()) {
  2232. if (!content_provider(offset, 0, data_sink)) { return -1; }
  2233. if (!ok) { return -1; }
  2234. }
  2235. return static_cast<ssize_t>(offset);
  2236. }
  2237. template <typename T, typename U>
  2238. inline ssize_t write_content_chunked(Stream &strm,
  2239. ContentProvider content_provider,
  2240. T is_shutting_down, U &compressor) {
  2241. size_t offset = 0;
  2242. auto data_available = true;
  2243. ssize_t total_written_length = 0;
  2244. auto ok = true;
  2245. DataSink data_sink;
  2246. data_sink.write = [&](const char *d, size_t l) {
  2247. if (!ok) { return; }
  2248. data_available = l > 0;
  2249. offset += l;
  2250. std::string payload;
  2251. if (!compressor.compress(d, l, false,
  2252. [&](const char *data, size_t data_len) {
  2253. payload.append(data, data_len);
  2254. return true;
  2255. })) {
  2256. ok = false;
  2257. return;
  2258. }
  2259. if (!payload.empty()) {
  2260. // Emit chunked response header and footer for each chunk
  2261. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  2262. if (write_data(strm, chunk.data(), chunk.size())) {
  2263. total_written_length += chunk.size();
  2264. } else {
  2265. ok = false;
  2266. return;
  2267. }
  2268. }
  2269. };
  2270. data_sink.done = [&](void) {
  2271. if (!ok) { return; }
  2272. data_available = false;
  2273. std::string payload;
  2274. if (!compressor.compress(nullptr, 0, true,
  2275. [&](const char *data, size_t data_len) {
  2276. payload.append(data, data_len);
  2277. return true;
  2278. })) {
  2279. ok = false;
  2280. return;
  2281. }
  2282. if (!payload.empty()) {
  2283. // Emit chunked response header and footer for each chunk
  2284. auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
  2285. if (write_data(strm, chunk.data(), chunk.size())) {
  2286. total_written_length += chunk.size();
  2287. } else {
  2288. ok = false;
  2289. return;
  2290. }
  2291. }
  2292. static const std::string done_marker("0\r\n\r\n");
  2293. if (write_data(strm, done_marker.data(), done_marker.size())) {
  2294. total_written_length += done_marker.size();
  2295. } else {
  2296. ok = false;
  2297. }
  2298. };
  2299. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  2300. while (data_available && !is_shutting_down()) {
  2301. if (!content_provider(offset, 0, data_sink)) { return -1; }
  2302. if (!ok) { return -1; }
  2303. }
  2304. return total_written_length;
  2305. }
  2306. template <typename T>
  2307. inline bool redirect(T &cli, const Request &req, Response &res,
  2308. const std::string &path) {
  2309. Request new_req = req;
  2310. new_req.path = path;
  2311. new_req.redirect_count -= 1;
  2312. if (res.status == 303 && (req.method != "GET" && req.method != "HEAD")) {
  2313. new_req.method = "GET";
  2314. new_req.body.clear();
  2315. new_req.headers.clear();
  2316. }
  2317. Response new_res;
  2318. auto ret = cli.send(new_req, new_res);
  2319. if (ret) { res = new_res; }
  2320. return ret;
  2321. }
  2322. inline std::string params_to_query_str(const Params &params) {
  2323. std::string query;
  2324. for (auto it = params.begin(); it != params.end(); ++it) {
  2325. if (it != params.begin()) { query += "&"; }
  2326. query += it->first;
  2327. query += "=";
  2328. query += encode_url(it->second);
  2329. }
  2330. return query;
  2331. }
  2332. inline void parse_query_text(const std::string &s, Params &params) {
  2333. split(s.data(), s.data() + s.size(), '&', [&](const char *b, const char *e) {
  2334. std::string key;
  2335. std::string val;
  2336. split(b, e, '=', [&](const char *b2, const char *e2) {
  2337. if (key.empty()) {
  2338. key.assign(b2, e2);
  2339. } else {
  2340. val.assign(b2, e2);
  2341. }
  2342. });
  2343. if (!key.empty()) {
  2344. params.emplace(decode_url(key, true), decode_url(val, true));
  2345. }
  2346. });
  2347. }
  2348. inline bool parse_multipart_boundary(const std::string &content_type,
  2349. std::string &boundary) {
  2350. auto pos = content_type.find("boundary=");
  2351. if (pos == std::string::npos) { return false; }
  2352. boundary = content_type.substr(pos + 9);
  2353. if (boundary.length() >= 2 && boundary.front() == '"' &&
  2354. boundary.back() == '"') {
  2355. boundary = boundary.substr(1, boundary.size() - 2);
  2356. }
  2357. return !boundary.empty();
  2358. }
  2359. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  2360. static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
  2361. std::smatch m;
  2362. if (std::regex_match(s, m, re_first_range)) {
  2363. auto pos = static_cast<size_t>(m.position(1));
  2364. auto len = static_cast<size_t>(m.length(1));
  2365. bool all_valid_ranges = true;
  2366. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  2367. if (!all_valid_ranges) return;
  2368. static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
  2369. std::cmatch cm;
  2370. if (std::regex_match(b, e, cm, re_another_range)) {
  2371. ssize_t first = -1;
  2372. if (!cm.str(1).empty()) {
  2373. first = static_cast<ssize_t>(std::stoll(cm.str(1)));
  2374. }
  2375. ssize_t last = -1;
  2376. if (!cm.str(2).empty()) {
  2377. last = static_cast<ssize_t>(std::stoll(cm.str(2)));
  2378. }
  2379. if (first != -1 && last != -1 && first > last) {
  2380. all_valid_ranges = false;
  2381. return;
  2382. }
  2383. ranges.emplace_back(std::make_pair(first, last));
  2384. }
  2385. });
  2386. return all_valid_ranges;
  2387. }
  2388. return false;
  2389. }
  2390. class MultipartFormDataParser {
  2391. public:
  2392. MultipartFormDataParser() = default;
  2393. void set_boundary(std::string &&boundary) { boundary_ = boundary; }
  2394. bool is_valid() const { return is_valid_; }
  2395. template <typename T, typename U>
  2396. bool parse(const char *buf, size_t n, T content_callback, U header_callback) {
  2397. static const std::regex re_content_disposition(
  2398. "^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename="
  2399. "\"(.*?)\")?\\s*$",
  2400. std::regex_constants::icase);
  2401. static const std::string dash_ = "--";
  2402. static const std::string crlf_ = "\r\n";
  2403. buf_.append(buf, n); // TODO: performance improvement
  2404. while (!buf_.empty()) {
  2405. switch (state_) {
  2406. case 0: { // Initial boundary
  2407. auto pattern = dash_ + boundary_ + crlf_;
  2408. if (pattern.size() > buf_.size()) { return true; }
  2409. auto pos = buf_.find(pattern);
  2410. if (pos != 0) { return false; }
  2411. buf_.erase(0, pattern.size());
  2412. off_ += pattern.size();
  2413. state_ = 1;
  2414. break;
  2415. }
  2416. case 1: { // New entry
  2417. clear_file_info();
  2418. state_ = 2;
  2419. break;
  2420. }
  2421. case 2: { // Headers
  2422. auto pos = buf_.find(crlf_);
  2423. while (pos != std::string::npos) {
  2424. // Empty line
  2425. if (pos == 0) {
  2426. if (!header_callback(file_)) {
  2427. is_valid_ = false;
  2428. return false;
  2429. }
  2430. buf_.erase(0, crlf_.size());
  2431. off_ += crlf_.size();
  2432. state_ = 3;
  2433. break;
  2434. }
  2435. static const std::string header_name = "content-type:";
  2436. const auto header = buf_.substr(0, pos);
  2437. if (start_with(header, header_name)) {
  2438. file_.content_type = trim_copy(header.substr(header_name.size()));
  2439. } else {
  2440. std::smatch m;
  2441. if (std::regex_match(header, m, re_content_disposition)) {
  2442. file_.name = m[1];
  2443. file_.filename = m[2];
  2444. }
  2445. }
  2446. buf_.erase(0, pos + crlf_.size());
  2447. off_ += pos + crlf_.size();
  2448. pos = buf_.find(crlf_);
  2449. }
  2450. if (state_ != 3) { return true; }
  2451. break;
  2452. }
  2453. case 3: { // Body
  2454. {
  2455. auto pattern = crlf_ + dash_;
  2456. if (pattern.size() > buf_.size()) { return true; }
  2457. auto pos = buf_.find(pattern);
  2458. if (pos == std::string::npos) {
  2459. pos = buf_.size();
  2460. while (pos > 0) {
  2461. auto c = buf_[pos - 1];
  2462. if (c != '\r' && c != '\n' && c != '-') { break; }
  2463. pos--;
  2464. }
  2465. }
  2466. if (!content_callback(buf_.data(), pos)) {
  2467. is_valid_ = false;
  2468. return false;
  2469. }
  2470. off_ += pos;
  2471. buf_.erase(0, pos);
  2472. }
  2473. {
  2474. auto pattern = crlf_ + dash_ + boundary_;
  2475. if (pattern.size() > buf_.size()) { return true; }
  2476. auto pos = buf_.find(pattern);
  2477. if (pos != std::string::npos) {
  2478. if (!content_callback(buf_.data(), pos)) {
  2479. is_valid_ = false;
  2480. return false;
  2481. }
  2482. off_ += pos + pattern.size();
  2483. buf_.erase(0, pos + pattern.size());
  2484. state_ = 4;
  2485. } else {
  2486. if (!content_callback(buf_.data(), pattern.size())) {
  2487. is_valid_ = false;
  2488. return false;
  2489. }
  2490. off_ += pattern.size();
  2491. buf_.erase(0, pattern.size());
  2492. }
  2493. }
  2494. break;
  2495. }
  2496. case 4: { // Boundary
  2497. if (crlf_.size() > buf_.size()) { return true; }
  2498. if (buf_.compare(0, crlf_.size(), crlf_) == 0) {
  2499. buf_.erase(0, crlf_.size());
  2500. off_ += crlf_.size();
  2501. state_ = 1;
  2502. } else {
  2503. auto pattern = dash_ + crlf_;
  2504. if (pattern.size() > buf_.size()) { return true; }
  2505. if (buf_.compare(0, pattern.size(), pattern) == 0) {
  2506. buf_.erase(0, pattern.size());
  2507. off_ += pattern.size();
  2508. is_valid_ = true;
  2509. state_ = 5;
  2510. } else {
  2511. return true;
  2512. }
  2513. }
  2514. break;
  2515. }
  2516. case 5: { // Done
  2517. is_valid_ = false;
  2518. return false;
  2519. }
  2520. }
  2521. }
  2522. return true;
  2523. }
  2524. private:
  2525. void clear_file_info() {
  2526. file_.name.clear();
  2527. file_.filename.clear();
  2528. file_.content_type.clear();
  2529. }
  2530. std::string boundary_;
  2531. std::string buf_;
  2532. size_t state_ = 0;
  2533. bool is_valid_ = false;
  2534. size_t off_ = 0;
  2535. MultipartFormData file_;
  2536. };
  2537. inline std::string to_lower(const char *beg, const char *end) {
  2538. std::string out;
  2539. auto it = beg;
  2540. while (it != end) {
  2541. out += static_cast<char>(::tolower(*it));
  2542. it++;
  2543. }
  2544. return out;
  2545. }
  2546. inline std::string make_multipart_data_boundary() {
  2547. static const char data[] =
  2548. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2549. std::random_device seed_gen;
  2550. std::mt19937 engine(seed_gen());
  2551. std::string result = "--cpp-httplib-multipart-data-";
  2552. for (auto i = 0; i < 16; i++) {
  2553. result += data[engine() % (sizeof(data) - 1)];
  2554. }
  2555. return result;
  2556. }
  2557. inline std::pair<size_t, size_t>
  2558. get_range_offset_and_length(const Request &req, size_t content_length,
  2559. size_t index) {
  2560. auto r = req.ranges[index];
  2561. if (r.first == -1 && r.second == -1) {
  2562. return std::make_pair(0, content_length);
  2563. }
  2564. auto slen = static_cast<ssize_t>(content_length);
  2565. if (r.first == -1) {
  2566. r.first = slen - r.second;
  2567. r.second = slen - 1;
  2568. }
  2569. if (r.second == -1) { r.second = slen - 1; }
  2570. return std::make_pair(r.first, r.second - r.first + 1);
  2571. }
  2572. inline std::string make_content_range_header_field(size_t offset, size_t length,
  2573. size_t content_length) {
  2574. std::string field = "bytes ";
  2575. field += std::to_string(offset);
  2576. field += "-";
  2577. field += std::to_string(offset + length - 1);
  2578. field += "/";
  2579. field += std::to_string(content_length);
  2580. return field;
  2581. }
  2582. template <typename SToken, typename CToken, typename Content>
  2583. bool process_multipart_ranges_data(const Request &req, Response &res,
  2584. const std::string &boundary,
  2585. const std::string &content_type,
  2586. SToken stoken, CToken ctoken,
  2587. Content content) {
  2588. for (size_t i = 0; i < req.ranges.size(); i++) {
  2589. ctoken("--");
  2590. stoken(boundary);
  2591. ctoken("\r\n");
  2592. if (!content_type.empty()) {
  2593. ctoken("Content-Type: ");
  2594. stoken(content_type);
  2595. ctoken("\r\n");
  2596. }
  2597. auto offsets = get_range_offset_and_length(req, res.body.size(), i);
  2598. auto offset = offsets.first;
  2599. auto length = offsets.second;
  2600. ctoken("Content-Range: ");
  2601. stoken(make_content_range_header_field(offset, length, res.body.size()));
  2602. ctoken("\r\n");
  2603. ctoken("\r\n");
  2604. if (!content(offset, length)) { return false; }
  2605. ctoken("\r\n");
  2606. }
  2607. ctoken("--");
  2608. stoken(boundary);
  2609. ctoken("--\r\n");
  2610. return true;
  2611. }
  2612. inline std::string make_multipart_ranges_data(const Request &req, Response &res,
  2613. const std::string &boundary,
  2614. const std::string &content_type) {
  2615. std::string data;
  2616. process_multipart_ranges_data(
  2617. req, res, boundary, content_type,
  2618. [&](const std::string &token) { data += token; },
  2619. [&](const char *token) { data += token; },
  2620. [&](size_t offset, size_t length) {
  2621. data += res.body.substr(offset, length);
  2622. return true;
  2623. });
  2624. return data;
  2625. }
  2626. inline size_t
  2627. get_multipart_ranges_data_length(const Request &req, Response &res,
  2628. const std::string &boundary,
  2629. const std::string &content_type) {
  2630. size_t data_length = 0;
  2631. process_multipart_ranges_data(
  2632. req, res, boundary, content_type,
  2633. [&](const std::string &token) { data_length += token.size(); },
  2634. [&](const char *token) { data_length += strlen(token); },
  2635. [&](size_t /*offset*/, size_t length) {
  2636. data_length += length;
  2637. return true;
  2638. });
  2639. return data_length;
  2640. }
  2641. template <typename T>
  2642. inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
  2643. Response &res,
  2644. const std::string &boundary,
  2645. const std::string &content_type,
  2646. T is_shutting_down) {
  2647. return process_multipart_ranges_data(
  2648. req, res, boundary, content_type,
  2649. [&](const std::string &token) { strm.write(token); },
  2650. [&](const char *token) { strm.write(token); },
  2651. [&](size_t offset, size_t length) {
  2652. return write_content(strm, res.content_provider_, offset, length,
  2653. is_shutting_down) >= 0;
  2654. });
  2655. }
  2656. inline std::pair<size_t, size_t>
  2657. get_range_offset_and_length(const Request &req, const Response &res,
  2658. size_t index) {
  2659. auto r = req.ranges[index];
  2660. if (r.second == -1) {
  2661. r.second = static_cast<ssize_t>(res.content_length_) - 1;
  2662. }
  2663. return std::make_pair(r.first, r.second - r.first + 1);
  2664. }
  2665. inline bool expect_content(const Request &req) {
  2666. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  2667. req.method == "PRI" || req.method == "DELETE") {
  2668. return true;
  2669. }
  2670. // TODO: check if Content-Length is set
  2671. return false;
  2672. }
  2673. inline bool has_crlf(const char *s) {
  2674. auto p = s;
  2675. while (*p) {
  2676. if (*p == '\r' || *p == '\n') { return true; }
  2677. p++;
  2678. }
  2679. return false;
  2680. }
  2681. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2682. template <typename CTX, typename Init, typename Update, typename Final>
  2683. inline std::string message_digest(const std::string &s, Init init,
  2684. Update update, Final final,
  2685. size_t digest_length) {
  2686. using namespace std;
  2687. std::vector<unsigned char> md(digest_length, 0);
  2688. CTX ctx;
  2689. init(&ctx);
  2690. update(&ctx, s.data(), s.size());
  2691. final(md.data(), &ctx);
  2692. stringstream ss;
  2693. for (auto c : md) {
  2694. ss << setfill('0') << setw(2) << hex << (unsigned int)c;
  2695. }
  2696. return ss.str();
  2697. }
  2698. inline std::string MD5(const std::string &s) {
  2699. return message_digest<MD5_CTX>(s, MD5_Init, MD5_Update, MD5_Final,
  2700. MD5_DIGEST_LENGTH);
  2701. }
  2702. inline std::string SHA_256(const std::string &s) {
  2703. return message_digest<SHA256_CTX>(s, SHA256_Init, SHA256_Update, SHA256_Final,
  2704. SHA256_DIGEST_LENGTH);
  2705. }
  2706. inline std::string SHA_512(const std::string &s) {
  2707. return message_digest<SHA512_CTX>(s, SHA512_Init, SHA512_Update, SHA512_Final,
  2708. SHA512_DIGEST_LENGTH);
  2709. }
  2710. #endif
  2711. #ifdef _WIN32
  2712. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2713. // NOTE: This code came up with the following stackoverflow post:
  2714. // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
  2715. inline bool load_system_certs_on_windows(X509_STORE *store) {
  2716. auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
  2717. if (!hStore) { return false; }
  2718. PCCERT_CONTEXT pContext = NULL;
  2719. while (pContext = CertEnumCertificatesInStore(hStore, pContext)) {
  2720. auto encoded_cert =
  2721. static_cast<const unsigned char *>(pContext->pbCertEncoded);
  2722. auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
  2723. if (x509) {
  2724. X509_STORE_add_cert(store, x509);
  2725. X509_free(x509);
  2726. }
  2727. }
  2728. CertFreeCertificateContext(pContext);
  2729. CertCloseStore(hStore, 0);
  2730. return true;
  2731. }
  2732. #endif
  2733. class WSInit {
  2734. public:
  2735. WSInit() {
  2736. WSADATA wsaData;
  2737. WSAStartup(0x0002, &wsaData);
  2738. }
  2739. ~WSInit() { WSACleanup(); }
  2740. };
  2741. static WSInit wsinit_;
  2742. #endif
  2743. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2744. inline std::pair<std::string, std::string> make_digest_authentication_header(
  2745. const Request &req, const std::map<std::string, std::string> &auth,
  2746. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  2747. const std::string &password, bool is_proxy = false) {
  2748. using namespace std;
  2749. string nc;
  2750. {
  2751. stringstream ss;
  2752. ss << setfill('0') << setw(8) << hex << cnonce_count;
  2753. nc = ss.str();
  2754. }
  2755. auto qop = auth.at("qop");
  2756. if (qop.find("auth-int") != std::string::npos) {
  2757. qop = "auth-int";
  2758. } else {
  2759. qop = "auth";
  2760. }
  2761. std::string algo = "MD5";
  2762. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  2763. string response;
  2764. {
  2765. auto H = algo == "SHA-256"
  2766. ? detail::SHA_256
  2767. : algo == "SHA-512" ? detail::SHA_512 : detail::MD5;
  2768. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  2769. auto A2 = req.method + ":" + req.path;
  2770. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  2771. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  2772. ":" + qop + ":" + H(A2));
  2773. }
  2774. auto field = "Digest username=\"" + username + "\", realm=\"" +
  2775. auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
  2776. "\", uri=\"" + req.path + "\", algorithm=" + algo +
  2777. ", qop=" + qop + ", nc=\"" + nc + "\", cnonce=\"" + cnonce +
  2778. "\", response=\"" + response + "\"";
  2779. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2780. return std::make_pair(key, field);
  2781. }
  2782. #endif
  2783. inline bool parse_www_authenticate(const Response &res,
  2784. std::map<std::string, std::string> &auth,
  2785. bool is_proxy) {
  2786. auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  2787. if (res.has_header(auth_key)) {
  2788. static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  2789. auto s = res.get_header_value(auth_key);
  2790. auto pos = s.find(' ');
  2791. if (pos != std::string::npos) {
  2792. auto type = s.substr(0, pos);
  2793. if (type == "Basic") {
  2794. return false;
  2795. } else if (type == "Digest") {
  2796. s = s.substr(pos + 1);
  2797. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  2798. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  2799. auto m = *i;
  2800. auto key = s.substr(static_cast<size_t>(m.position(1)),
  2801. static_cast<size_t>(m.length(1)));
  2802. auto val = m.length(2) > 0
  2803. ? s.substr(static_cast<size_t>(m.position(2)),
  2804. static_cast<size_t>(m.length(2)))
  2805. : s.substr(static_cast<size_t>(m.position(3)),
  2806. static_cast<size_t>(m.length(3)));
  2807. auth[key] = val;
  2808. }
  2809. return true;
  2810. }
  2811. }
  2812. }
  2813. return false;
  2814. }
  2815. // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240
  2816. inline std::string random_string(size_t length) {
  2817. auto randchar = []() -> char {
  2818. const char charset[] = "0123456789"
  2819. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2820. "abcdefghijklmnopqrstuvwxyz";
  2821. const size_t max_index = (sizeof(charset) - 1);
  2822. return charset[static_cast<size_t>(rand()) % max_index];
  2823. };
  2824. std::string str(length, 0);
  2825. std::generate_n(str.begin(), length, randchar);
  2826. return str;
  2827. }
  2828. class ContentProviderAdapter {
  2829. public:
  2830. explicit ContentProviderAdapter(
  2831. ContentProviderWithoutLength &&content_provider)
  2832. : content_provider_(content_provider) {}
  2833. bool operator()(size_t offset, size_t, DataSink &sink) {
  2834. return content_provider_(offset, sink);
  2835. }
  2836. private:
  2837. ContentProviderWithoutLength content_provider_;
  2838. };
  2839. } // namespace detail
  2840. // Header utilities
  2841. inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
  2842. std::string field = "bytes=";
  2843. auto i = 0;
  2844. for (auto r : ranges) {
  2845. if (i != 0) { field += ", "; }
  2846. if (r.first != -1) { field += std::to_string(r.first); }
  2847. field += '-';
  2848. if (r.second != -1) { field += std::to_string(r.second); }
  2849. i++;
  2850. }
  2851. return std::make_pair("Range", field);
  2852. }
  2853. inline std::pair<std::string, std::string>
  2854. make_basic_authentication_header(const std::string &username,
  2855. const std::string &password,
  2856. bool is_proxy = false) {
  2857. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  2858. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2859. return std::make_pair(key, field);
  2860. }
  2861. inline std::pair<std::string, std::string>
  2862. make_bearer_token_authentication_header(const std::string &token,
  2863. bool is_proxy = false) {
  2864. auto field = "Bearer " + token;
  2865. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2866. return std::make_pair(key, field);
  2867. }
  2868. // Request implementation
  2869. inline bool Request::has_header(const char *key) const {
  2870. return detail::has_header(headers, key);
  2871. }
  2872. inline std::string Request::get_header_value(const char *key, size_t id) const {
  2873. return detail::get_header_value(headers, key, id, "");
  2874. }
  2875. template <typename T>
  2876. inline T Request::get_header_value(const char *key, size_t id) const {
  2877. return detail::get_header_value<T>(headers, key, id, 0);
  2878. }
  2879. inline size_t Request::get_header_value_count(const char *key) const {
  2880. auto r = headers.equal_range(key);
  2881. return static_cast<size_t>(std::distance(r.first, r.second));
  2882. }
  2883. inline void Request::set_header(const char *key, const char *val) {
  2884. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  2885. headers.emplace(key, val);
  2886. }
  2887. }
  2888. inline void Request::set_header(const char *key, const std::string &val) {
  2889. if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
  2890. headers.emplace(key, val);
  2891. }
  2892. }
  2893. inline bool Request::has_param(const char *key) const {
  2894. return params.find(key) != params.end();
  2895. }
  2896. inline std::string Request::get_param_value(const char *key, size_t id) const {
  2897. auto rng = params.equal_range(key);
  2898. auto it = rng.first;
  2899. std::advance(it, static_cast<ssize_t>(id));
  2900. if (it != rng.second) { return it->second; }
  2901. return std::string();
  2902. }
  2903. inline size_t Request::get_param_value_count(const char *key) const {
  2904. auto r = params.equal_range(key);
  2905. return static_cast<size_t>(std::distance(r.first, r.second));
  2906. }
  2907. inline bool Request::is_multipart_form_data() const {
  2908. const auto &content_type = get_header_value("Content-Type");
  2909. return !content_type.find("multipart/form-data");
  2910. }
  2911. inline bool Request::has_file(const char *key) const {
  2912. return files.find(key) != files.end();
  2913. }
  2914. inline MultipartFormData Request::get_file_value(const char *key) const {
  2915. auto it = files.find(key);
  2916. if (it != files.end()) { return it->second; }
  2917. return MultipartFormData();
  2918. }
  2919. // Response implementation
  2920. inline bool Response::has_header(const char *key) const {
  2921. return headers.find(key) != headers.end();
  2922. }
  2923. inline std::string Response::get_header_value(const char *key,
  2924. size_t id) const {
  2925. return detail::get_header_value(headers, key, id, "");
  2926. }
  2927. template <typename T>
  2928. inline T Response::get_header_value(const char *key, size_t id) const {
  2929. return detail::get_header_value<T>(headers, key, id, 0);
  2930. }
  2931. inline size_t Response::get_header_value_count(const char *key) const {
  2932. auto r = headers.equal_range(key);
  2933. return static_cast<size_t>(std::distance(r.first, r.second));
  2934. }
  2935. inline void Response::set_header(const char *key, const char *val) {
  2936. if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
  2937. headers.emplace(key, val);
  2938. }
  2939. }
  2940. inline void Response::set_header(const char *key, const std::string &val) {
  2941. if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
  2942. headers.emplace(key, val);
  2943. }
  2944. }
  2945. inline void Response::set_redirect(const char *url, int stat) {
  2946. if (!detail::has_crlf(url)) {
  2947. set_header("Location", url);
  2948. if (300 <= stat && stat < 400) {
  2949. this->status = stat;
  2950. } else {
  2951. this->status = 302;
  2952. }
  2953. }
  2954. }
  2955. inline void Response::set_redirect(const std::string &url, int stat) {
  2956. set_redirect(url.c_str(), stat);
  2957. }
  2958. inline void Response::set_content(const char *s, size_t n,
  2959. const char *content_type) {
  2960. body.assign(s, n);
  2961. set_header("Content-Type", content_type);
  2962. }
  2963. inline void Response::set_content(std::string s, const char *content_type) {
  2964. body = std::move(s);
  2965. set_header("Content-Type", content_type);
  2966. }
  2967. inline void
  2968. Response::set_content_provider(size_t in_length, const char *content_type,
  2969. ContentProvider provider,
  2970. const std::function<void()> &resource_releaser) {
  2971. assert(in_length > 0);
  2972. set_header("Content-Type", content_type);
  2973. content_length_ = in_length;
  2974. content_provider_ = std::move(provider);
  2975. content_provider_resource_releaser_ = resource_releaser;
  2976. is_chunked_content_provider = false;
  2977. }
  2978. inline void
  2979. Response::set_content_provider(const char *content_type,
  2980. ContentProviderWithoutLength provider,
  2981. const std::function<void()> &resource_releaser) {
  2982. set_header("Content-Type", content_type);
  2983. content_length_ = 0;
  2984. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  2985. content_provider_resource_releaser_ = resource_releaser;
  2986. is_chunked_content_provider = false;
  2987. }
  2988. inline void Response::set_chunked_content_provider(
  2989. const char *content_type, ContentProviderWithoutLength provider,
  2990. const std::function<void()> &resource_releaser) {
  2991. set_header("Content-Type", content_type);
  2992. content_length_ = 0;
  2993. content_provider_ = detail::ContentProviderAdapter(std::move(provider));
  2994. content_provider_resource_releaser_ = resource_releaser;
  2995. is_chunked_content_provider = true;
  2996. }
  2997. // Rstream implementation
  2998. inline ssize_t Stream::write(const char *ptr) {
  2999. return write(ptr, strlen(ptr));
  3000. }
  3001. inline ssize_t Stream::write(const std::string &s) {
  3002. return write(s.data(), s.size());
  3003. }
  3004. template <typename... Args>
  3005. inline ssize_t Stream::write_format(const char *fmt, const Args &... args) {
  3006. const auto bufsiz = 2048;
  3007. std::array<char, bufsiz> buf;
  3008. #if defined(_MSC_VER) && _MSC_VER < 1900
  3009. auto sn = _snprintf_s(buf.data(), bufsiz - 1, buf.size() - 1, fmt, args...);
  3010. #else
  3011. auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...);
  3012. #endif
  3013. if (sn <= 0) { return sn; }
  3014. auto n = static_cast<size_t>(sn);
  3015. if (n >= buf.size() - 1) {
  3016. std::vector<char> glowable_buf(buf.size());
  3017. while (n >= glowable_buf.size() - 1) {
  3018. glowable_buf.resize(glowable_buf.size() * 2);
  3019. #if defined(_MSC_VER) && _MSC_VER < 1900
  3020. n = static_cast<size_t>(_snprintf_s(&glowable_buf[0], glowable_buf.size(),
  3021. glowable_buf.size() - 1, fmt,
  3022. args...));
  3023. #else
  3024. n = static_cast<size_t>(
  3025. snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...));
  3026. #endif
  3027. }
  3028. return write(&glowable_buf[0], n);
  3029. } else {
  3030. return write(buf.data(), n);
  3031. }
  3032. }
  3033. namespace detail {
  3034. // Socket stream implementation
  3035. inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
  3036. time_t read_timeout_usec,
  3037. time_t write_timeout_sec,
  3038. time_t write_timeout_usec)
  3039. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  3040. read_timeout_usec_(read_timeout_usec),
  3041. write_timeout_sec_(write_timeout_sec),
  3042. write_timeout_usec_(write_timeout_usec) {}
  3043. inline SocketStream::~SocketStream() {}
  3044. inline bool SocketStream::is_readable() const {
  3045. return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  3046. }
  3047. inline bool SocketStream::is_writable() const {
  3048. return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
  3049. }
  3050. inline ssize_t SocketStream::read(char *ptr, size_t size) {
  3051. if (!is_readable()) { return -1; }
  3052. #ifdef _WIN32
  3053. if (size > static_cast<size_t>((std::numeric_limits<int>::max)())) {
  3054. return -1;
  3055. }
  3056. return recv(sock_, ptr, static_cast<int>(size), 0);
  3057. #else
  3058. return handle_EINTR([&]() { return recv(sock_, ptr, size, 0); });
  3059. #endif
  3060. }
  3061. inline ssize_t SocketStream::write(const char *ptr, size_t size) {
  3062. if (!is_writable()) { return -1; }
  3063. #ifdef _WIN32
  3064. if (size > static_cast<size_t>((std::numeric_limits<int>::max)())) {
  3065. return -1;
  3066. }
  3067. return send(sock_, ptr, static_cast<int>(size), 0);
  3068. #else
  3069. return handle_EINTR([&]() { return send(sock_, ptr, size, 0); });
  3070. #endif
  3071. }
  3072. inline void SocketStream::get_remote_ip_and_port(std::string &ip,
  3073. int &port) const {
  3074. return detail::get_remote_ip_and_port(sock_, ip, port);
  3075. }
  3076. // Buffer stream implementation
  3077. inline bool BufferStream::is_readable() const { return true; }
  3078. inline bool BufferStream::is_writable() const { return true; }
  3079. inline ssize_t BufferStream::read(char *ptr, size_t size) {
  3080. #if defined(_MSC_VER) && _MSC_VER <= 1900
  3081. auto len_read = buffer._Copy_s(ptr, size, size, position);
  3082. #else
  3083. auto len_read = buffer.copy(ptr, size, position);
  3084. #endif
  3085. position += static_cast<size_t>(len_read);
  3086. return static_cast<ssize_t>(len_read);
  3087. }
  3088. inline ssize_t BufferStream::write(const char *ptr, size_t size) {
  3089. buffer.append(ptr, size);
  3090. return static_cast<ssize_t>(size);
  3091. }
  3092. inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
  3093. int & /*port*/) const {}
  3094. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  3095. } // namespace detail
  3096. // HTTP server implementation
  3097. inline Server::Server()
  3098. : new_task_queue(
  3099. [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }),
  3100. svr_sock_(INVALID_SOCKET), is_running_(false) {
  3101. #ifndef _WIN32
  3102. signal(SIGPIPE, SIG_IGN);
  3103. #endif
  3104. }
  3105. inline Server::~Server() {}
  3106. inline Server &Server::Get(const char *pattern, Handler handler) {
  3107. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3108. return *this;
  3109. }
  3110. inline Server &Server::Post(const char *pattern, Handler handler) {
  3111. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3112. return *this;
  3113. }
  3114. inline Server &Server::Post(const char *pattern,
  3115. HandlerWithContentReader handler) {
  3116. post_handlers_for_content_reader_.push_back(
  3117. std::make_pair(std::regex(pattern), handler));
  3118. return *this;
  3119. }
  3120. inline Server &Server::Put(const char *pattern, Handler handler) {
  3121. put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3122. return *this;
  3123. }
  3124. inline Server &Server::Put(const char *pattern,
  3125. HandlerWithContentReader handler) {
  3126. put_handlers_for_content_reader_.push_back(
  3127. std::make_pair(std::regex(pattern), handler));
  3128. return *this;
  3129. }
  3130. inline Server &Server::Patch(const char *pattern, Handler handler) {
  3131. patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3132. return *this;
  3133. }
  3134. inline Server &Server::Patch(const char *pattern,
  3135. HandlerWithContentReader handler) {
  3136. patch_handlers_for_content_reader_.push_back(
  3137. std::make_pair(std::regex(pattern), handler));
  3138. return *this;
  3139. }
  3140. inline Server &Server::Delete(const char *pattern, Handler handler) {
  3141. delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3142. return *this;
  3143. }
  3144. inline Server &Server::Delete(const char *pattern,
  3145. HandlerWithContentReader handler) {
  3146. delete_handlers_for_content_reader_.push_back(
  3147. std::make_pair(std::regex(pattern), handler));
  3148. return *this;
  3149. }
  3150. inline Server &Server::Options(const char *pattern, Handler handler) {
  3151. options_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  3152. return *this;
  3153. }
  3154. inline bool Server::set_base_dir(const char *dir, const char *mount_point) {
  3155. return set_mount_point(mount_point, dir);
  3156. }
  3157. inline bool Server::set_mount_point(const char *mount_point, const char *dir) {
  3158. if (detail::is_dir(dir)) {
  3159. std::string mnt = mount_point ? mount_point : "/";
  3160. if (!mnt.empty() && mnt[0] == '/') {
  3161. base_dirs_.emplace_back(mnt, dir);
  3162. return true;
  3163. }
  3164. }
  3165. return false;
  3166. }
  3167. inline bool Server::remove_mount_point(const char *mount_point) {
  3168. for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
  3169. if (it->first == mount_point) {
  3170. base_dirs_.erase(it);
  3171. return true;
  3172. }
  3173. }
  3174. return false;
  3175. }
  3176. inline void Server::set_file_extension_and_mimetype_mapping(const char *ext,
  3177. const char *mime) {
  3178. file_extension_and_mimetype_map_[ext] = mime;
  3179. }
  3180. inline void Server::set_file_request_handler(Handler handler) {
  3181. file_request_handler_ = std::move(handler);
  3182. }
  3183. inline void Server::set_error_handler(Handler handler) {
  3184. error_handler_ = std::move(handler);
  3185. }
  3186. inline void Server::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  3187. inline void Server::set_socket_options(SocketOptions socket_options) {
  3188. socket_options_ = socket_options;
  3189. }
  3190. inline void Server::set_logger(Logger logger) { logger_ = std::move(logger); }
  3191. inline void
  3192. Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
  3193. expect_100_continue_handler_ = std::move(handler);
  3194. }
  3195. inline void Server::set_keep_alive_max_count(size_t count) {
  3196. keep_alive_max_count_ = count;
  3197. }
  3198. inline void Server::set_keep_alive_timeout(time_t sec) {
  3199. keep_alive_timeout_sec_ = sec;
  3200. }
  3201. inline void Server::set_read_timeout(time_t sec, time_t usec) {
  3202. read_timeout_sec_ = sec;
  3203. read_timeout_usec_ = usec;
  3204. }
  3205. inline void Server::set_write_timeout(time_t sec, time_t usec) {
  3206. write_timeout_sec_ = sec;
  3207. write_timeout_usec_ = usec;
  3208. }
  3209. inline void Server::set_idle_interval(time_t sec, time_t usec) {
  3210. idle_interval_sec_ = sec;
  3211. idle_interval_usec_ = usec;
  3212. }
  3213. inline void Server::set_payload_max_length(size_t length) {
  3214. payload_max_length_ = length;
  3215. }
  3216. inline bool Server::bind_to_port(const char *host, int port, int socket_flags) {
  3217. if (bind_internal(host, port, socket_flags) < 0) return false;
  3218. return true;
  3219. }
  3220. inline int Server::bind_to_any_port(const char *host, int socket_flags) {
  3221. return bind_internal(host, 0, socket_flags);
  3222. }
  3223. inline bool Server::listen_after_bind() { return listen_internal(); }
  3224. inline bool Server::listen(const char *host, int port, int socket_flags) {
  3225. return bind_to_port(host, port, socket_flags) && listen_internal();
  3226. }
  3227. inline bool Server::is_running() const { return is_running_; }
  3228. inline void Server::stop() {
  3229. if (is_running_) {
  3230. assert(svr_sock_ != INVALID_SOCKET);
  3231. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  3232. detail::shutdown_socket(sock);
  3233. detail::close_socket(sock);
  3234. }
  3235. }
  3236. inline bool Server::parse_request_line(const char *s, Request &req) {
  3237. const static std::regex re(
  3238. "(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI) "
  3239. "(([^?]+)(?:\\?(.*?))?) (HTTP/1\\.[01])\r\n");
  3240. std::cmatch m;
  3241. if (std::regex_match(s, m, re)) {
  3242. req.version = std::string(m[5]);
  3243. req.method = std::string(m[1]);
  3244. req.target = std::string(m[2]);
  3245. req.path = detail::decode_url(m[3], false);
  3246. // Parse query text
  3247. auto len = std::distance(m[4].first, m[4].second);
  3248. if (len > 0) { detail::parse_query_text(m[4], req.params); }
  3249. return true;
  3250. }
  3251. return false;
  3252. }
  3253. inline bool Server::write_response(Stream &strm, bool close_connection,
  3254. const Request &req, Response &res) {
  3255. assert(res.status != -1);
  3256. if (400 <= res.status && error_handler_) { error_handler_(req, res); }
  3257. detail::BufferStream bstrm;
  3258. // Response line
  3259. if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status,
  3260. detail::status_message(res.status))) {
  3261. return false;
  3262. }
  3263. // Headers
  3264. if (close_connection || req.get_header_value("Connection") == "close") {
  3265. res.set_header("Connection", "close");
  3266. } else {
  3267. std::stringstream ss;
  3268. ss << "timeout=" << keep_alive_timeout_sec_
  3269. << ", max=" << keep_alive_max_count_;
  3270. res.set_header("Keep-Alive", ss.str());
  3271. }
  3272. if (!res.has_header("Content-Type") &&
  3273. (!res.body.empty() || res.content_length_ > 0 || res.content_provider_)) {
  3274. res.set_header("Content-Type", "text/plain");
  3275. }
  3276. if (!res.has_header("Accept-Ranges") && req.method == "HEAD") {
  3277. res.set_header("Accept-Ranges", "bytes");
  3278. }
  3279. std::string content_type;
  3280. std::string boundary;
  3281. if (req.ranges.size() > 1) {
  3282. boundary = detail::make_multipart_data_boundary();
  3283. auto it = res.headers.find("Content-Type");
  3284. if (it != res.headers.end()) {
  3285. content_type = it->second;
  3286. res.headers.erase(it);
  3287. }
  3288. res.headers.emplace("Content-Type",
  3289. "multipart/byteranges; boundary=" + boundary);
  3290. }
  3291. auto type = detail::encoding_type(req, res);
  3292. if (res.body.empty()) {
  3293. if (res.content_length_ > 0) {
  3294. size_t length = 0;
  3295. if (req.ranges.empty()) {
  3296. length = res.content_length_;
  3297. } else if (req.ranges.size() == 1) {
  3298. auto offsets =
  3299. detail::get_range_offset_and_length(req, res.content_length_, 0);
  3300. auto offset = offsets.first;
  3301. length = offsets.second;
  3302. auto content_range = detail::make_content_range_header_field(
  3303. offset, length, res.content_length_);
  3304. res.set_header("Content-Range", content_range);
  3305. } else {
  3306. length = detail::get_multipart_ranges_data_length(req, res, boundary,
  3307. content_type);
  3308. }
  3309. res.set_header("Content-Length", std::to_string(length));
  3310. } else {
  3311. if (res.content_provider_) {
  3312. if (res.is_chunked_content_provider) {
  3313. res.set_header("Transfer-Encoding", "chunked");
  3314. if (type == detail::EncodingType::Gzip) {
  3315. res.set_header("Content-Encoding", "gzip");
  3316. } else if (type == detail::EncodingType::Brotli) {
  3317. res.set_header("Content-Encoding", "br");
  3318. }
  3319. }
  3320. } else {
  3321. res.set_header("Content-Length", "0");
  3322. }
  3323. }
  3324. } else {
  3325. if (req.ranges.empty()) {
  3326. ;
  3327. } else if (req.ranges.size() == 1) {
  3328. auto offsets =
  3329. detail::get_range_offset_and_length(req, res.body.size(), 0);
  3330. auto offset = offsets.first;
  3331. auto length = offsets.second;
  3332. auto content_range = detail::make_content_range_header_field(
  3333. offset, length, res.body.size());
  3334. res.set_header("Content-Range", content_range);
  3335. res.body = res.body.substr(offset, length);
  3336. } else {
  3337. res.body =
  3338. detail::make_multipart_ranges_data(req, res, boundary, content_type);
  3339. }
  3340. if (type != detail::EncodingType::None) {
  3341. std::shared_ptr<detail::compressor> compressor;
  3342. if (type == detail::EncodingType::Gzip) {
  3343. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3344. compressor = std::make_shared<detail::gzip_compressor>();
  3345. res.set_header("Content-Encoding", "gzip");
  3346. #endif
  3347. } else if (type == detail::EncodingType::Brotli) {
  3348. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3349. compressor = std::make_shared<detail::brotli_compressor>();
  3350. res.set_header("Content-Encoding", "brotli");
  3351. #endif
  3352. }
  3353. if (compressor) {
  3354. std::string compressed;
  3355. if (!compressor->compress(res.body.data(), res.body.size(), true,
  3356. [&](const char *data, size_t data_len) {
  3357. compressed.append(data, data_len);
  3358. return true;
  3359. })) {
  3360. return false;
  3361. }
  3362. res.body.swap(compressed);
  3363. }
  3364. }
  3365. auto length = std::to_string(res.body.size());
  3366. res.set_header("Content-Length", length);
  3367. }
  3368. if (!detail::write_headers(bstrm, res, Headers())) { return false; }
  3369. // Flush buffer
  3370. auto &data = bstrm.get_buffer();
  3371. strm.write(data.data(), data.size());
  3372. // Body
  3373. auto ret = true;
  3374. if (req.method != "HEAD") {
  3375. if (!res.body.empty()) {
  3376. if (!strm.write(res.body)) { ret = false; }
  3377. } else if (res.content_provider_) {
  3378. if (!write_content_with_provider(strm, req, res, boundary,
  3379. content_type)) {
  3380. ret = false;
  3381. }
  3382. }
  3383. }
  3384. // Log
  3385. if (logger_) { logger_(req, res); }
  3386. return ret;
  3387. }
  3388. inline bool
  3389. Server::write_content_with_provider(Stream &strm, const Request &req,
  3390. Response &res, const std::string &boundary,
  3391. const std::string &content_type) {
  3392. auto is_shutting_down = [this]() {
  3393. return this->svr_sock_ == INVALID_SOCKET;
  3394. };
  3395. if (res.content_length_ > 0) {
  3396. if (req.ranges.empty()) {
  3397. if (detail::write_content(strm, res.content_provider_, 0,
  3398. res.content_length_, is_shutting_down) < 0) {
  3399. return false;
  3400. }
  3401. } else if (req.ranges.size() == 1) {
  3402. auto offsets =
  3403. detail::get_range_offset_and_length(req, res.content_length_, 0);
  3404. auto offset = offsets.first;
  3405. auto length = offsets.second;
  3406. if (detail::write_content(strm, res.content_provider_, offset, length,
  3407. is_shutting_down) < 0) {
  3408. return false;
  3409. }
  3410. } else {
  3411. if (!detail::write_multipart_ranges_data(
  3412. strm, req, res, boundary, content_type, is_shutting_down)) {
  3413. return false;
  3414. }
  3415. }
  3416. } else {
  3417. if (res.is_chunked_content_provider) {
  3418. auto type = detail::encoding_type(req, res);
  3419. std::shared_ptr<detail::compressor> compressor;
  3420. if (type == detail::EncodingType::Gzip) {
  3421. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3422. compressor = std::make_shared<detail::gzip_compressor>();
  3423. #endif
  3424. } else if (type == detail::EncodingType::Brotli) {
  3425. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3426. compressor = std::make_shared<detail::brotli_compressor>();
  3427. #endif
  3428. } else {
  3429. compressor = std::make_shared<detail::nocompressor>();
  3430. }
  3431. assert(compressor != nullptr);
  3432. if (detail::write_content_chunked(strm, res.content_provider_,
  3433. is_shutting_down, *compressor) < 0) {
  3434. return false;
  3435. }
  3436. } else {
  3437. if (detail::write_content_without_length(strm, res.content_provider_,
  3438. is_shutting_down) < 0) {
  3439. return false;
  3440. }
  3441. }
  3442. }
  3443. return true;
  3444. }
  3445. inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
  3446. MultipartFormDataMap::iterator cur;
  3447. if (read_content_core(
  3448. strm, req, res,
  3449. // Regular
  3450. [&](const char *buf, size_t n) {
  3451. if (req.body.size() + n > req.body.max_size()) { return false; }
  3452. req.body.append(buf, n);
  3453. return true;
  3454. },
  3455. // Multipart
  3456. [&](const MultipartFormData &file) {
  3457. cur = req.files.emplace(file.name, file);
  3458. return true;
  3459. },
  3460. [&](const char *buf, size_t n) {
  3461. auto &content = cur->second.content;
  3462. if (content.size() + n > content.max_size()) { return false; }
  3463. content.append(buf, n);
  3464. return true;
  3465. })) {
  3466. const auto &content_type = req.get_header_value("Content-Type");
  3467. if (!content_type.find("application/x-www-form-urlencoded")) {
  3468. detail::parse_query_text(req.body, req.params);
  3469. }
  3470. return true;
  3471. }
  3472. return false;
  3473. }
  3474. inline bool Server::read_content_with_content_receiver(
  3475. Stream &strm, Request &req, Response &res, ContentReceiver receiver,
  3476. MultipartContentHeader multipart_header,
  3477. ContentReceiver multipart_receiver) {
  3478. return read_content_core(strm, req, res, receiver, multipart_header,
  3479. multipart_receiver);
  3480. }
  3481. inline bool Server::read_content_core(Stream &strm, Request &req, Response &res,
  3482. ContentReceiver receiver,
  3483. MultipartContentHeader mulitpart_header,
  3484. ContentReceiver multipart_receiver) {
  3485. detail::MultipartFormDataParser multipart_form_data_parser;
  3486. ContentReceiver out;
  3487. if (req.is_multipart_form_data()) {
  3488. const auto &content_type = req.get_header_value("Content-Type");
  3489. std::string boundary;
  3490. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  3491. res.status = 400;
  3492. return false;
  3493. }
  3494. multipart_form_data_parser.set_boundary(std::move(boundary));
  3495. out = [&](const char *buf, size_t n) {
  3496. /* For debug
  3497. size_t pos = 0;
  3498. while (pos < n) {
  3499. auto read_size = std::min<size_t>(1, n - pos);
  3500. auto ret = multipart_form_data_parser.parse(
  3501. buf + pos, read_size, multipart_receiver, mulitpart_header);
  3502. if (!ret) { return false; }
  3503. pos += read_size;
  3504. }
  3505. return true;
  3506. */
  3507. return multipart_form_data_parser.parse(buf, n, multipart_receiver,
  3508. mulitpart_header);
  3509. };
  3510. } else {
  3511. out = receiver;
  3512. }
  3513. if (req.method == "DELETE" && !req.has_header("Content-Length")) {
  3514. return true;
  3515. }
  3516. if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
  3517. out, true)) {
  3518. return false;
  3519. }
  3520. if (req.is_multipart_form_data()) {
  3521. if (!multipart_form_data_parser.is_valid()) {
  3522. res.status = 400;
  3523. return false;
  3524. }
  3525. }
  3526. return true;
  3527. }
  3528. inline bool Server::handle_file_request(Request &req, Response &res,
  3529. bool head) {
  3530. for (const auto &kv : base_dirs_) {
  3531. const auto &mount_point = kv.first;
  3532. const auto &base_dir = kv.second;
  3533. // Prefix match
  3534. if (!req.path.compare(0, mount_point.size(), mount_point)) {
  3535. std::string sub_path = "/" + req.path.substr(mount_point.size());
  3536. if (detail::is_valid_path(sub_path)) {
  3537. auto path = base_dir + sub_path;
  3538. if (path.back() == '/') { path += "index.html"; }
  3539. if (detail::is_file(path)) {
  3540. detail::read_file(path, res.body);
  3541. auto type =
  3542. detail::find_content_type(path, file_extension_and_mimetype_map_);
  3543. if (type) { res.set_header("Content-Type", type); }
  3544. res.status = 200;
  3545. if (!head && file_request_handler_) {
  3546. file_request_handler_(req, res);
  3547. }
  3548. return true;
  3549. }
  3550. }
  3551. }
  3552. }
  3553. return false;
  3554. }
  3555. inline socket_t
  3556. Server::create_server_socket(const char *host, int port, int socket_flags,
  3557. SocketOptions socket_options) const {
  3558. return detail::create_socket(
  3559. host, port, socket_flags, tcp_nodelay_, socket_options,
  3560. [](socket_t sock, struct addrinfo &ai) -> bool {
  3561. if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
  3562. return false;
  3563. }
  3564. if (::listen(sock, 5)) { // Listen through 5 channels
  3565. return false;
  3566. }
  3567. return true;
  3568. });
  3569. }
  3570. inline int Server::bind_internal(const char *host, int port, int socket_flags) {
  3571. if (!is_valid()) { return -1; }
  3572. svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
  3573. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  3574. if (port == 0) {
  3575. struct sockaddr_storage addr;
  3576. socklen_t addr_len = sizeof(addr);
  3577. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
  3578. &addr_len) == -1) {
  3579. return -1;
  3580. }
  3581. if (addr.ss_family == AF_INET) {
  3582. return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
  3583. } else if (addr.ss_family == AF_INET6) {
  3584. return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
  3585. } else {
  3586. return -1;
  3587. }
  3588. } else {
  3589. return port;
  3590. }
  3591. }
  3592. inline bool Server::listen_internal() {
  3593. auto ret = true;
  3594. is_running_ = true;
  3595. {
  3596. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  3597. while (svr_sock_ != INVALID_SOCKET) {
  3598. #ifndef _WIN32
  3599. if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
  3600. #endif
  3601. auto val = detail::select_read(svr_sock_, idle_interval_sec_,
  3602. idle_interval_usec_);
  3603. if (val == 0) { // Timeout
  3604. task_queue->on_idle();
  3605. continue;
  3606. }
  3607. #ifndef _WIN32
  3608. }
  3609. #endif
  3610. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  3611. if (sock == INVALID_SOCKET) {
  3612. if (errno == EMFILE) {
  3613. // The per-process limit of open file descriptors has been reached.
  3614. // Try to accept new connections after a short sleep.
  3615. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3616. continue;
  3617. }
  3618. if (svr_sock_ != INVALID_SOCKET) {
  3619. detail::close_socket(svr_sock_);
  3620. ret = false;
  3621. } else {
  3622. ; // The server socket was closed by user.
  3623. }
  3624. break;
  3625. }
  3626. #if __cplusplus > 201703L
  3627. task_queue->enqueue([=, this]() { process_and_close_socket(sock); });
  3628. #else
  3629. task_queue->enqueue([=]() { process_and_close_socket(sock); });
  3630. #endif
  3631. }
  3632. task_queue->shutdown();
  3633. }
  3634. is_running_ = false;
  3635. return ret;
  3636. }
  3637. inline bool Server::routing(Request &req, Response &res, Stream &strm) {
  3638. // File handler
  3639. bool is_head_request = req.method == "HEAD";
  3640. if ((req.method == "GET" || is_head_request) &&
  3641. handle_file_request(req, res, is_head_request)) {
  3642. return true;
  3643. }
  3644. if (detail::expect_content(req)) {
  3645. // Content reader handler
  3646. {
  3647. ContentReader reader(
  3648. [&](ContentReceiver receiver) {
  3649. return read_content_with_content_receiver(strm, req, res, receiver,
  3650. nullptr, nullptr);
  3651. },
  3652. [&](MultipartContentHeader header, ContentReceiver receiver) {
  3653. return read_content_with_content_receiver(strm, req, res, nullptr,
  3654. header, receiver);
  3655. });
  3656. if (req.method == "POST") {
  3657. if (dispatch_request_for_content_reader(
  3658. req, res, reader, post_handlers_for_content_reader_)) {
  3659. return true;
  3660. }
  3661. } else if (req.method == "PUT") {
  3662. if (dispatch_request_for_content_reader(
  3663. req, res, reader, put_handlers_for_content_reader_)) {
  3664. return true;
  3665. }
  3666. } else if (req.method == "PATCH") {
  3667. if (dispatch_request_for_content_reader(
  3668. req, res, reader, patch_handlers_for_content_reader_)) {
  3669. return true;
  3670. }
  3671. } else if (req.method == "DELETE") {
  3672. if (dispatch_request_for_content_reader(
  3673. req, res, reader, delete_handlers_for_content_reader_)) {
  3674. return true;
  3675. }
  3676. }
  3677. }
  3678. // Read content into `req.body`
  3679. if (!read_content(strm, req, res)) { return false; }
  3680. }
  3681. // Regular handler
  3682. if (req.method == "GET" || req.method == "HEAD") {
  3683. return dispatch_request(req, res, get_handlers_);
  3684. } else if (req.method == "POST") {
  3685. return dispatch_request(req, res, post_handlers_);
  3686. } else if (req.method == "PUT") {
  3687. return dispatch_request(req, res, put_handlers_);
  3688. } else if (req.method == "DELETE") {
  3689. return dispatch_request(req, res, delete_handlers_);
  3690. } else if (req.method == "OPTIONS") {
  3691. return dispatch_request(req, res, options_handlers_);
  3692. } else if (req.method == "PATCH") {
  3693. return dispatch_request(req, res, patch_handlers_);
  3694. }
  3695. res.status = 400;
  3696. return false;
  3697. }
  3698. inline bool Server::dispatch_request(Request &req, Response &res,
  3699. const Handlers &handlers) {
  3700. try {
  3701. for (const auto &x : handlers) {
  3702. const auto &pattern = x.first;
  3703. const auto &handler = x.second;
  3704. if (std::regex_match(req.path, req.matches, pattern)) {
  3705. handler(req, res);
  3706. return true;
  3707. }
  3708. }
  3709. } catch (const std::exception &ex) {
  3710. res.status = 500;
  3711. res.set_header("EXCEPTION_WHAT", ex.what());
  3712. } catch (...) {
  3713. res.status = 500;
  3714. res.set_header("EXCEPTION_WHAT", "UNKNOWN");
  3715. }
  3716. return false;
  3717. }
  3718. inline bool Server::dispatch_request_for_content_reader(
  3719. Request &req, Response &res, ContentReader content_reader,
  3720. const HandlersForContentReader &handlers) {
  3721. for (const auto &x : handlers) {
  3722. const auto &pattern = x.first;
  3723. const auto &handler = x.second;
  3724. if (std::regex_match(req.path, req.matches, pattern)) {
  3725. handler(req, res, content_reader);
  3726. return true;
  3727. }
  3728. }
  3729. return false;
  3730. }
  3731. inline bool
  3732. Server::process_request(Stream &strm, bool close_connection,
  3733. bool &connection_closed,
  3734. const std::function<void(Request &)> &setup_request) {
  3735. std::array<char, 2048> buf{};
  3736. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  3737. // Connection has been closed on client
  3738. if (!line_reader.getline()) { return false; }
  3739. Request req;
  3740. Response res;
  3741. res.version = "HTTP/1.1";
  3742. // Check if the request URI doesn't exceed the limit
  3743. if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  3744. Headers dummy;
  3745. detail::read_headers(strm, dummy);
  3746. res.status = 414;
  3747. return write_response(strm, close_connection, req, res);
  3748. }
  3749. // Request line and headers
  3750. if (!parse_request_line(line_reader.ptr(), req) ||
  3751. !detail::read_headers(strm, req.headers)) {
  3752. res.status = 400;
  3753. return write_response(strm, close_connection, req, res);
  3754. }
  3755. if (req.get_header_value("Connection") == "close") {
  3756. connection_closed = true;
  3757. }
  3758. if (req.version == "HTTP/1.0" &&
  3759. req.get_header_value("Connection") != "Keep-Alive") {
  3760. connection_closed = true;
  3761. }
  3762. strm.get_remote_ip_and_port(req.remote_addr, req.remote_port);
  3763. req.set_header("REMOTE_ADDR", req.remote_addr);
  3764. req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
  3765. if (req.has_header("Range")) {
  3766. const auto &range_header_value = req.get_header_value("Range");
  3767. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  3768. // TODO: error
  3769. }
  3770. }
  3771. if (setup_request) { setup_request(req); }
  3772. if (req.get_header_value("Expect") == "100-continue") {
  3773. auto status = 100;
  3774. if (expect_100_continue_handler_) {
  3775. status = expect_100_continue_handler_(req, res);
  3776. }
  3777. switch (status) {
  3778. case 100:
  3779. case 417:
  3780. strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status,
  3781. detail::status_message(status));
  3782. break;
  3783. default: return write_response(strm, close_connection, req, res);
  3784. }
  3785. }
  3786. // Rounting
  3787. if (routing(req, res, strm)) {
  3788. if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
  3789. } else {
  3790. if (res.status == -1) { res.status = 404; }
  3791. }
  3792. return write_response(strm, close_connection, req, res);
  3793. }
  3794. inline bool Server::is_valid() const { return true; }
  3795. inline bool Server::process_and_close_socket(socket_t sock) {
  3796. auto ret = detail::process_server_socket(
  3797. sock, keep_alive_max_count_, keep_alive_timeout_sec_, read_timeout_sec_,
  3798. read_timeout_usec_, write_timeout_sec_, write_timeout_usec_,
  3799. [this](Stream &strm, bool close_connection, bool &connection_closed) {
  3800. return process_request(strm, close_connection, connection_closed,
  3801. nullptr);
  3802. });
  3803. detail::shutdown_socket(sock);
  3804. detail::close_socket(sock);
  3805. return ret;
  3806. }
  3807. // HTTP client implementation
  3808. inline ClientImpl::ClientImpl(const std::string &host)
  3809. : ClientImpl(host, 80, std::string(), std::string()) {}
  3810. inline ClientImpl::ClientImpl(const std::string &host, int port)
  3811. : ClientImpl(host, port, std::string(), std::string()) {}
  3812. inline ClientImpl::ClientImpl(const std::string &host, int port,
  3813. const std::string &client_cert_path,
  3814. const std::string &client_key_path)
  3815. : host_(host), port_(port),
  3816. host_and_port_(host_ + ":" + std::to_string(port_)),
  3817. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  3818. inline ClientImpl::~ClientImpl() { stop_core(); }
  3819. inline bool ClientImpl::is_valid() const { return true; }
  3820. inline Error ClientImpl::get_last_error() const { return error_; }
  3821. inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
  3822. client_cert_path_ = rhs.client_cert_path_;
  3823. client_key_path_ = rhs.client_key_path_;
  3824. connection_timeout_sec_ = rhs.connection_timeout_sec_;
  3825. read_timeout_sec_ = rhs.read_timeout_sec_;
  3826. read_timeout_usec_ = rhs.read_timeout_usec_;
  3827. write_timeout_sec_ = rhs.write_timeout_sec_;
  3828. write_timeout_usec_ = rhs.write_timeout_usec_;
  3829. basic_auth_username_ = rhs.basic_auth_username_;
  3830. basic_auth_password_ = rhs.basic_auth_password_;
  3831. bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
  3832. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3833. digest_auth_username_ = rhs.digest_auth_username_;
  3834. digest_auth_password_ = rhs.digest_auth_password_;
  3835. #endif
  3836. keep_alive_ = rhs.keep_alive_;
  3837. follow_location_ = rhs.follow_location_;
  3838. tcp_nodelay_ = rhs.tcp_nodelay_;
  3839. socket_options_ = rhs.socket_options_;
  3840. compress_ = rhs.compress_;
  3841. decompress_ = rhs.decompress_;
  3842. interface_ = rhs.interface_;
  3843. proxy_host_ = rhs.proxy_host_;
  3844. proxy_port_ = rhs.proxy_port_;
  3845. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  3846. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  3847. proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
  3848. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3849. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  3850. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  3851. #endif
  3852. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3853. server_certificate_verification_ = rhs.server_certificate_verification_;
  3854. #endif
  3855. logger_ = rhs.logger_;
  3856. }
  3857. inline socket_t ClientImpl::create_client_socket() const {
  3858. if (!proxy_host_.empty() && proxy_port_ != -1) {
  3859. return detail::create_client_socket(
  3860. proxy_host_.c_str(), proxy_port_, tcp_nodelay_, socket_options_,
  3861. connection_timeout_sec_, connection_timeout_usec_, interface_, error_);
  3862. }
  3863. return detail::create_client_socket(
  3864. host_.c_str(), port_, tcp_nodelay_, socket_options_,
  3865. connection_timeout_sec_, connection_timeout_usec_, interface_, error_);
  3866. }
  3867. inline bool ClientImpl::create_and_connect_socket(Socket &socket) {
  3868. auto sock = create_client_socket();
  3869. if (sock == INVALID_SOCKET) { return false; }
  3870. socket.sock = sock;
  3871. return true;
  3872. }
  3873. inline void ClientImpl::close_socket(Socket &socket,
  3874. bool /*process_socket_ret*/) {
  3875. detail::close_socket(socket.sock);
  3876. socket_.sock = INVALID_SOCKET;
  3877. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3878. socket_.ssl = nullptr;
  3879. #endif
  3880. }
  3881. inline bool ClientImpl::read_response_line(Stream &strm, Response &res) {
  3882. std::array<char, 2048> buf;
  3883. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  3884. if (!line_reader.getline()) { return false; }
  3885. const static std::regex re("(HTTP/1\\.[01]) (\\d+) (.*?)\r\n");
  3886. std::cmatch m;
  3887. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  3888. res.version = std::string(m[1]);
  3889. res.status = std::stoi(std::string(m[2]));
  3890. res.reason = std::string(m[3]);
  3891. // Ignore '100 Continue'
  3892. while (res.status == 100) {
  3893. if (!line_reader.getline()) { return false; } // CRLF
  3894. if (!line_reader.getline()) { return false; } // next response line
  3895. if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
  3896. res.version = std::string(m[1]);
  3897. res.status = std::stoi(std::string(m[2]));
  3898. res.reason = std::string(m[3]);
  3899. }
  3900. return true;
  3901. }
  3902. inline bool ClientImpl::send(const Request &req, Response &res) {
  3903. std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
  3904. {
  3905. std::lock_guard<std::mutex> guard(socket_mutex_);
  3906. auto is_alive = false;
  3907. if (socket_.is_open()) {
  3908. is_alive = detail::select_write(socket_.sock, 0, 0) > 0;
  3909. if (!is_alive) { close_socket(socket_, false); }
  3910. }
  3911. if (!is_alive) {
  3912. if (!create_and_connect_socket(socket_)) { return false; }
  3913. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3914. // TODO: refactoring
  3915. if (is_ssl()) {
  3916. auto &scli = static_cast<SSLClient &>(*this);
  3917. if (!proxy_host_.empty() && proxy_port_ != -1) {
  3918. bool success = false;
  3919. if (!scli.connect_with_proxy(socket_, res, success)) {
  3920. return success;
  3921. }
  3922. }
  3923. if (!scli.initialize_ssl(socket_)) { return false; }
  3924. }
  3925. #endif
  3926. }
  3927. }
  3928. auto close_connection = !keep_alive_;
  3929. auto ret = process_socket(socket_, [&](Stream &strm) {
  3930. return handle_request(strm, req, res, close_connection);
  3931. });
  3932. if (close_connection || !ret) { stop_core(); }
  3933. if (!ret) {
  3934. if (error_ == Error::Success) { error_ = Error::Unknown; }
  3935. }
  3936. return ret;
  3937. }
  3938. inline bool ClientImpl::handle_request(Stream &strm, const Request &req,
  3939. Response &res, bool close_connection) {
  3940. if (req.path.empty()) {
  3941. error_ = Error::Connection;
  3942. return false;
  3943. }
  3944. bool ret;
  3945. if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
  3946. auto req2 = req;
  3947. req2.path = "http://" + host_and_port_ + req.path;
  3948. ret = process_request(strm, req2, res, close_connection);
  3949. } else {
  3950. ret = process_request(strm, req, res, close_connection);
  3951. }
  3952. if (!ret) { return false; }
  3953. if (300 < res.status && res.status < 400 && follow_location_) {
  3954. ret = redirect(req, res);
  3955. }
  3956. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3957. if ((res.status == 401 || res.status == 407) &&
  3958. req.authorization_count_ < 5) {
  3959. auto is_proxy = res.status == 407;
  3960. const auto &username =
  3961. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  3962. const auto &password =
  3963. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  3964. if (!username.empty() && !password.empty()) {
  3965. std::map<std::string, std::string> auth;
  3966. if (detail::parse_www_authenticate(res, auth, is_proxy)) {
  3967. Request new_req = req;
  3968. new_req.authorization_count_ += 1;
  3969. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  3970. new_req.headers.erase(key);
  3971. new_req.headers.insert(detail::make_digest_authentication_header(
  3972. req, auth, new_req.authorization_count_, detail::random_string(10),
  3973. username, password, is_proxy));
  3974. Response new_res;
  3975. ret = send(new_req, new_res);
  3976. if (ret) { res = new_res; }
  3977. }
  3978. }
  3979. }
  3980. #endif
  3981. return ret;
  3982. }
  3983. inline bool ClientImpl::redirect(const Request &req, Response &res) {
  3984. if (req.redirect_count == 0) {
  3985. error_ = Error::ExceedRedirectCount;
  3986. return false;
  3987. }
  3988. auto location = detail::decode_url(res.get_header_value("location"), true);
  3989. if (location.empty()) { return false; }
  3990. const static std::regex re(
  3991. R"(^(?:(https?):)?(?://([^:/?#]*)(?::(\d+))?)?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
  3992. std::smatch m;
  3993. if (!std::regex_match(location, m, re)) { return false; }
  3994. auto scheme = is_ssl() ? "https" : "http";
  3995. auto next_scheme = m[1].str();
  3996. auto next_host = m[2].str();
  3997. auto port_str = m[3].str();
  3998. auto next_path = m[4].str();
  3999. auto next_port = port_;
  4000. if (!port_str.empty()) {
  4001. next_port = std::stoi(port_str);
  4002. } else if (!next_scheme.empty()) {
  4003. next_port = next_scheme == "https" ? 443 : 80;
  4004. }
  4005. if (next_scheme.empty()) { next_scheme = scheme; }
  4006. if (next_host.empty()) { next_host = host_; }
  4007. if (next_path.empty()) { next_path = "/"; }
  4008. if (next_scheme == scheme && next_host == host_ && next_port == port_) {
  4009. return detail::redirect(*this, req, res, next_path);
  4010. } else {
  4011. if (next_scheme == "https") {
  4012. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4013. SSLClient cli(next_host.c_str(), next_port);
  4014. cli.copy_settings(*this);
  4015. auto ret = detail::redirect(cli, req, res, next_path);
  4016. if (!ret) { error_ = cli.get_last_error(); }
  4017. return ret;
  4018. #else
  4019. return false;
  4020. #endif
  4021. } else {
  4022. ClientImpl cli(next_host.c_str(), next_port);
  4023. cli.copy_settings(*this);
  4024. auto ret = detail::redirect(cli, req, res, next_path);
  4025. if (!ret) { error_ = cli.get_last_error(); }
  4026. return ret;
  4027. }
  4028. }
  4029. }
  4030. inline bool ClientImpl::write_request(Stream &strm, const Request &req,
  4031. bool close_connection) {
  4032. detail::BufferStream bstrm;
  4033. // Request line
  4034. const auto &path = detail::encode_url(req.path);
  4035. bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
  4036. // Additonal headers
  4037. Headers headers;
  4038. if (close_connection) { headers.emplace("Connection", "close"); }
  4039. if (!req.has_header("Host")) {
  4040. if (is_ssl()) {
  4041. if (port_ == 443) {
  4042. headers.emplace("Host", host_);
  4043. } else {
  4044. headers.emplace("Host", host_and_port_);
  4045. }
  4046. } else {
  4047. if (port_ == 80) {
  4048. headers.emplace("Host", host_);
  4049. } else {
  4050. headers.emplace("Host", host_and_port_);
  4051. }
  4052. }
  4053. }
  4054. if (!req.has_header("Accept")) { headers.emplace("Accept", "*/*"); }
  4055. if (!req.has_header("User-Agent")) {
  4056. headers.emplace("User-Agent", "cpp-httplib/0.7");
  4057. }
  4058. if (req.body.empty()) {
  4059. if (req.content_provider) {
  4060. auto length = std::to_string(req.content_length);
  4061. headers.emplace("Content-Length", length);
  4062. } else {
  4063. headers.emplace("Content-Length", "0");
  4064. }
  4065. } else {
  4066. if (!req.has_header("Content-Type")) {
  4067. headers.emplace("Content-Type", "text/plain");
  4068. }
  4069. if (!req.has_header("Content-Length")) {
  4070. auto length = std::to_string(req.body.size());
  4071. headers.emplace("Content-Length", length);
  4072. }
  4073. }
  4074. if (!basic_auth_password_.empty()) {
  4075. headers.insert(make_basic_authentication_header(
  4076. basic_auth_username_, basic_auth_password_, false));
  4077. }
  4078. if (!proxy_basic_auth_username_.empty() &&
  4079. !proxy_basic_auth_password_.empty()) {
  4080. headers.insert(make_basic_authentication_header(
  4081. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  4082. }
  4083. if (!bearer_token_auth_token_.empty()) {
  4084. headers.insert(make_bearer_token_authentication_header(
  4085. bearer_token_auth_token_, false));
  4086. }
  4087. if (!proxy_bearer_token_auth_token_.empty()) {
  4088. headers.insert(make_bearer_token_authentication_header(
  4089. proxy_bearer_token_auth_token_, true));
  4090. }
  4091. detail::write_headers(bstrm, req, headers);
  4092. // Flush buffer
  4093. auto &data = bstrm.get_buffer();
  4094. if (!detail::write_data(strm, data.data(), data.size())) {
  4095. error_ = Error::Write;
  4096. return false;
  4097. }
  4098. // Body
  4099. if (req.body.empty()) {
  4100. if (req.content_provider) {
  4101. size_t offset = 0;
  4102. size_t end_offset = req.content_length;
  4103. bool ok = true;
  4104. DataSink data_sink;
  4105. data_sink.write = [&](const char *d, size_t l) {
  4106. if (ok) {
  4107. if (detail::write_data(strm, d, l)) {
  4108. offset += l;
  4109. } else {
  4110. ok = false;
  4111. }
  4112. }
  4113. };
  4114. data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
  4115. while (offset < end_offset) {
  4116. if (!req.content_provider(offset, end_offset - offset, data_sink)) {
  4117. error_ = Error::Canceled;
  4118. return false;
  4119. }
  4120. if (!ok) {
  4121. error_ = Error::Write;
  4122. return false;
  4123. }
  4124. }
  4125. }
  4126. } else {
  4127. return detail::write_data(strm, req.body.data(), req.body.size());
  4128. }
  4129. return true;
  4130. }
  4131. inline std::shared_ptr<Response> ClientImpl::send_with_content_provider(
  4132. const char *method, const char *path, const Headers &headers,
  4133. const std::string &body, size_t content_length,
  4134. ContentProvider content_provider, const char *content_type) {
  4135. Request req;
  4136. req.method = method;
  4137. req.headers = default_headers_;
  4138. req.headers.insert(headers.begin(), headers.end());
  4139. req.path = path;
  4140. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  4141. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4142. if (compress_) {
  4143. detail::gzip_compressor compressor;
  4144. if (content_provider) {
  4145. auto ok = true;
  4146. size_t offset = 0;
  4147. DataSink data_sink;
  4148. data_sink.write = [&](const char *data, size_t data_len) {
  4149. if (ok) {
  4150. auto last = offset + data_len == content_length;
  4151. auto ret = compressor.compress(
  4152. data, data_len, last, [&](const char *data, size_t data_len) {
  4153. req.body.append(data, data_len);
  4154. return true;
  4155. });
  4156. if (ret) {
  4157. offset += data_len;
  4158. } else {
  4159. ok = false;
  4160. }
  4161. }
  4162. };
  4163. data_sink.is_writable = [&](void) { return ok && true; };
  4164. while (ok && offset < content_length) {
  4165. if (!content_provider(offset, content_length - offset, data_sink)) {
  4166. error_ = Error::Canceled;
  4167. return nullptr;
  4168. }
  4169. }
  4170. } else {
  4171. if (!compressor.compress(body.data(), body.size(), true,
  4172. [&](const char *data, size_t data_len) {
  4173. req.body.append(data, data_len);
  4174. return true;
  4175. })) {
  4176. return nullptr;
  4177. }
  4178. }
  4179. req.headers.emplace("Content-Encoding", "gzip");
  4180. } else
  4181. #endif
  4182. {
  4183. if (content_provider) {
  4184. req.content_length = content_length;
  4185. req.content_provider = content_provider;
  4186. } else {
  4187. req.body = body;
  4188. }
  4189. }
  4190. auto res = std::make_shared<Response>();
  4191. return send(req, *res) ? res : nullptr;
  4192. }
  4193. inline bool ClientImpl::process_request(Stream &strm, const Request &req,
  4194. Response &res, bool close_connection) {
  4195. // Send request
  4196. if (!write_request(strm, req, close_connection)) { return false; }
  4197. // Receive response and headers
  4198. if (!read_response_line(strm, res) ||
  4199. !detail::read_headers(strm, res.headers)) {
  4200. error_ = Error::Read;
  4201. return false;
  4202. }
  4203. if (req.response_handler) {
  4204. if (!req.response_handler(res)) {
  4205. error_ = Error::Canceled;
  4206. return false;
  4207. }
  4208. }
  4209. // Body
  4210. if (req.method != "HEAD" && req.method != "CONNECT") {
  4211. auto out =
  4212. req.content_receiver
  4213. ? static_cast<ContentReceiver>([&](const char *buf, size_t n) {
  4214. auto ret = req.content_receiver(buf, n);
  4215. if (!ret) { error_ = Error::Canceled; }
  4216. return ret;
  4217. })
  4218. : static_cast<ContentReceiver>([&](const char *buf, size_t n) {
  4219. if (res.body.size() + n > res.body.max_size()) { return false; }
  4220. res.body.append(buf, n);
  4221. return true;
  4222. });
  4223. auto progress = [&](uint64_t current, uint64_t total) {
  4224. if (!req.progress) { return true; }
  4225. auto ret = req.progress(current, total);
  4226. if (!ret) { error_ = Error::Canceled; }
  4227. return ret;
  4228. };
  4229. int dummy_status;
  4230. if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
  4231. dummy_status, progress, out, decompress_)) {
  4232. if (error_ != Error::Canceled) { error_ = Error::Read; }
  4233. return false;
  4234. }
  4235. }
  4236. if (res.get_header_value("Connection") == "close" ||
  4237. (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
  4238. stop_core();
  4239. }
  4240. // Log
  4241. if (logger_) { logger_(req, res); }
  4242. return true;
  4243. }
  4244. inline bool
  4245. ClientImpl::process_socket(Socket &socket,
  4246. std::function<bool(Stream &strm)> callback) {
  4247. return detail::process_client_socket(socket.sock, read_timeout_sec_,
  4248. read_timeout_usec_, write_timeout_sec_,
  4249. write_timeout_usec_, callback);
  4250. }
  4251. inline bool ClientImpl::is_ssl() const { return false; }
  4252. inline Result ClientImpl::Get(const char *path) {
  4253. return Get(path, Headers(), Progress());
  4254. }
  4255. inline Result ClientImpl::Get(const char *path, Progress progress) {
  4256. return Get(path, Headers(), std::move(progress));
  4257. }
  4258. inline Result ClientImpl::Get(const char *path, const Headers &headers) {
  4259. return Get(path, headers, Progress());
  4260. }
  4261. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4262. Progress progress) {
  4263. Request req;
  4264. req.method = "GET";
  4265. req.path = path;
  4266. req.headers = default_headers_;
  4267. req.headers.insert(headers.begin(), headers.end());
  4268. req.progress = std::move(progress);
  4269. auto res = std::make_shared<Response>();
  4270. auto ret = send(req, *res);
  4271. return Result{ret ? res : nullptr, get_last_error()};
  4272. }
  4273. inline Result ClientImpl::Get(const char *path,
  4274. ContentReceiver content_receiver) {
  4275. return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr);
  4276. }
  4277. inline Result ClientImpl::Get(const char *path,
  4278. ContentReceiver content_receiver,
  4279. Progress progress) {
  4280. return Get(path, Headers(), nullptr, std::move(content_receiver),
  4281. std::move(progress));
  4282. }
  4283. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4284. ContentReceiver content_receiver) {
  4285. return Get(path, headers, nullptr, std::move(content_receiver), nullptr);
  4286. }
  4287. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4288. ContentReceiver content_receiver,
  4289. Progress progress) {
  4290. return Get(path, headers, nullptr, std::move(content_receiver),
  4291. std::move(progress));
  4292. }
  4293. inline Result ClientImpl::Get(const char *path,
  4294. ResponseHandler response_handler,
  4295. ContentReceiver content_receiver) {
  4296. return Get(path, Headers(), std::move(response_handler), content_receiver,
  4297. nullptr);
  4298. }
  4299. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4300. ResponseHandler response_handler,
  4301. ContentReceiver content_receiver) {
  4302. return Get(path, headers, std::move(response_handler), content_receiver,
  4303. nullptr);
  4304. }
  4305. inline Result ClientImpl::Get(const char *path,
  4306. ResponseHandler response_handler,
  4307. ContentReceiver content_receiver,
  4308. Progress progress) {
  4309. return Get(path, Headers(), std::move(response_handler), content_receiver,
  4310. progress);
  4311. }
  4312. inline Result ClientImpl::Get(const char *path, const Headers &headers,
  4313. ResponseHandler response_handler,
  4314. ContentReceiver content_receiver,
  4315. Progress progress) {
  4316. Request req;
  4317. req.method = "GET";
  4318. req.path = path;
  4319. req.headers = default_headers_;
  4320. req.headers.insert(headers.begin(), headers.end());
  4321. req.response_handler = std::move(response_handler);
  4322. req.content_receiver = std::move(content_receiver);
  4323. req.progress = std::move(progress);
  4324. auto res = std::make_shared<Response>();
  4325. auto ret = send(req, *res);
  4326. return Result{ret ? res : nullptr, get_last_error()};
  4327. }
  4328. inline Result ClientImpl::Head(const char *path) {
  4329. return Head(path, Headers());
  4330. }
  4331. inline Result ClientImpl::Head(const char *path, const Headers &headers) {
  4332. Request req;
  4333. req.method = "HEAD";
  4334. req.headers = default_headers_;
  4335. req.headers.insert(headers.begin(), headers.end());
  4336. req.path = path;
  4337. auto res = std::make_shared<Response>();
  4338. auto ret = send(req, *res);
  4339. return Result{ret ? res : nullptr, get_last_error()};
  4340. }
  4341. inline Result ClientImpl::Post(const char *path) {
  4342. return Post(path, std::string(), nullptr);
  4343. }
  4344. inline Result ClientImpl::Post(const char *path, const std::string &body,
  4345. const char *content_type) {
  4346. return Post(path, Headers(), body, content_type);
  4347. }
  4348. inline Result ClientImpl::Post(const char *path, const Headers &headers,
  4349. const std::string &body,
  4350. const char *content_type) {
  4351. auto ret = send_with_content_provider("POST", path, headers, body, 0, nullptr,
  4352. content_type);
  4353. return Result{ret, get_last_error()};
  4354. }
  4355. inline Result ClientImpl::Post(const char *path, const Params &params) {
  4356. return Post(path, Headers(), params);
  4357. }
  4358. inline Result ClientImpl::Post(const char *path, size_t content_length,
  4359. ContentProvider content_provider,
  4360. const char *content_type) {
  4361. return Post(path, Headers(), content_length, content_provider, content_type);
  4362. }
  4363. inline Result ClientImpl::Post(const char *path, const Headers &headers,
  4364. size_t content_length,
  4365. ContentProvider content_provider,
  4366. const char *content_type) {
  4367. auto ret = send_with_content_provider("POST", path, headers, std::string(),
  4368. content_length, content_provider,
  4369. content_type);
  4370. return Result{ret, get_last_error()};
  4371. }
  4372. inline Result ClientImpl::Post(const char *path, const Headers &headers,
  4373. const Params &params) {
  4374. auto query = detail::params_to_query_str(params);
  4375. return Post(path, headers, query, "application/x-www-form-urlencoded");
  4376. }
  4377. inline Result ClientImpl::Post(const char *path,
  4378. const MultipartFormDataItems &items) {
  4379. return Post(path, Headers(), items);
  4380. }
  4381. inline Result ClientImpl::Post(const char *path, const Headers &headers,
  4382. const MultipartFormDataItems &items) {
  4383. auto boundary = detail::make_multipart_data_boundary();
  4384. std::string body;
  4385. for (const auto &item : items) {
  4386. body += "--" + boundary + "\r\n";
  4387. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4388. if (!item.filename.empty()) {
  4389. body += "; filename=\"" + item.filename + "\"";
  4390. }
  4391. body += "\r\n";
  4392. if (!item.content_type.empty()) {
  4393. body += "Content-Type: " + item.content_type + "\r\n";
  4394. }
  4395. body += "\r\n";
  4396. body += item.content + "\r\n";
  4397. }
  4398. body += "--" + boundary + "--\r\n";
  4399. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4400. return Post(path, headers, body, content_type.c_str());
  4401. }
  4402. inline Result ClientImpl::Put(const char *path) {
  4403. return Put(path, std::string(), nullptr);
  4404. }
  4405. inline Result ClientImpl::Put(const char *path, const std::string &body,
  4406. const char *content_type) {
  4407. return Put(path, Headers(), body, content_type);
  4408. }
  4409. inline Result ClientImpl::Put(const char *path, const Headers &headers,
  4410. const std::string &body,
  4411. const char *content_type) {
  4412. auto ret = send_with_content_provider("PUT", path, headers, body, 0, nullptr,
  4413. content_type);
  4414. return Result{ret, get_last_error()};
  4415. }
  4416. inline Result ClientImpl::Put(const char *path, size_t content_length,
  4417. ContentProvider content_provider,
  4418. const char *content_type) {
  4419. return Put(path, Headers(), content_length, content_provider, content_type);
  4420. }
  4421. inline Result ClientImpl::Put(const char *path, const Headers &headers,
  4422. size_t content_length,
  4423. ContentProvider content_provider,
  4424. const char *content_type) {
  4425. auto ret = send_with_content_provider("PUT", path, headers, std::string(),
  4426. content_length, content_provider,
  4427. content_type);
  4428. return Result{ret, get_last_error()};
  4429. }
  4430. inline Result ClientImpl::Put(const char *path, const Params &params) {
  4431. return Put(path, Headers(), params);
  4432. }
  4433. inline Result ClientImpl::Put(const char *path, const Headers &headers,
  4434. const Params &params) {
  4435. auto query = detail::params_to_query_str(params);
  4436. return Put(path, headers, query, "application/x-www-form-urlencoded");
  4437. }
  4438. inline Result ClientImpl::Patch(const char *path, const std::string &body,
  4439. const char *content_type) {
  4440. return Patch(path, Headers(), body, content_type);
  4441. }
  4442. inline Result ClientImpl::Patch(const char *path, const Headers &headers,
  4443. const std::string &body,
  4444. const char *content_type) {
  4445. auto ret = send_with_content_provider("PATCH", path, headers, body, 0,
  4446. nullptr, content_type);
  4447. return Result{ret, get_last_error()};
  4448. }
  4449. inline Result ClientImpl::Patch(const char *path, size_t content_length,
  4450. ContentProvider content_provider,
  4451. const char *content_type) {
  4452. return Patch(path, Headers(), content_length, content_provider, content_type);
  4453. }
  4454. inline Result ClientImpl::Patch(const char *path, const Headers &headers,
  4455. size_t content_length,
  4456. ContentProvider content_provider,
  4457. const char *content_type) {
  4458. auto ret = send_with_content_provider("PATCH", path, headers, std::string(),
  4459. content_length, content_provider,
  4460. content_type);
  4461. return Result{ret, get_last_error()};
  4462. }
  4463. inline Result ClientImpl::Delete(const char *path) {
  4464. return Delete(path, Headers(), std::string(), nullptr);
  4465. }
  4466. inline Result ClientImpl::Delete(const char *path, const std::string &body,
  4467. const char *content_type) {
  4468. return Delete(path, Headers(), body, content_type);
  4469. }
  4470. inline Result ClientImpl::Delete(const char *path, const Headers &headers) {
  4471. return Delete(path, headers, std::string(), nullptr);
  4472. }
  4473. inline Result ClientImpl::Delete(const char *path, const Headers &headers,
  4474. const std::string &body,
  4475. const char *content_type) {
  4476. Request req;
  4477. req.method = "DELETE";
  4478. req.headers = default_headers_;
  4479. req.headers.insert(headers.begin(), headers.end());
  4480. req.path = path;
  4481. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  4482. req.body = body;
  4483. auto res = std::make_shared<Response>();
  4484. auto ret = send(req, *res);
  4485. return Result{ret ? res : nullptr, get_last_error()};
  4486. }
  4487. inline Result ClientImpl::Options(const char *path) {
  4488. return Options(path, Headers());
  4489. }
  4490. inline Result ClientImpl::Options(const char *path, const Headers &headers) {
  4491. Request req;
  4492. req.method = "OPTIONS";
  4493. req.headers = default_headers_;
  4494. req.headers.insert(headers.begin(), headers.end());
  4495. req.path = path;
  4496. auto res = std::make_shared<Response>();
  4497. auto ret = send(req, *res);
  4498. return Result{ret ? res : nullptr, get_last_error()};
  4499. }
  4500. inline size_t ClientImpl::is_socket_open() const {
  4501. std::lock_guard<std::mutex> guard(socket_mutex_);
  4502. return socket_.is_open();
  4503. }
  4504. inline void ClientImpl::stop() {
  4505. stop_core();
  4506. error_ = Error::Canceled;
  4507. }
  4508. inline void ClientImpl::stop_core() {
  4509. std::lock_guard<std::mutex> guard(socket_mutex_);
  4510. if (socket_.is_open()) {
  4511. detail::shutdown_socket(socket_.sock);
  4512. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4513. close_socket(socket_, true);
  4514. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4515. }
  4516. }
  4517. inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
  4518. connection_timeout_sec_ = sec;
  4519. connection_timeout_usec_ = usec;
  4520. }
  4521. inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
  4522. read_timeout_sec_ = sec;
  4523. read_timeout_usec_ = usec;
  4524. }
  4525. inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
  4526. write_timeout_sec_ = sec;
  4527. write_timeout_usec_ = usec;
  4528. }
  4529. inline void ClientImpl::set_basic_auth(const char *username,
  4530. const char *password) {
  4531. basic_auth_username_ = username;
  4532. basic_auth_password_ = password;
  4533. }
  4534. inline void ClientImpl::set_bearer_token_auth(const char *token) {
  4535. bearer_token_auth_token_ = token;
  4536. }
  4537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4538. inline void ClientImpl::set_digest_auth(const char *username,
  4539. const char *password) {
  4540. digest_auth_username_ = username;
  4541. digest_auth_password_ = password;
  4542. }
  4543. #endif
  4544. inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
  4545. inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
  4546. inline void ClientImpl::set_default_headers(Headers headers) {
  4547. default_headers_ = std::move(headers);
  4548. }
  4549. inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
  4550. inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
  4551. socket_options_ = socket_options;
  4552. }
  4553. inline void ClientImpl::set_compress(bool on) { compress_ = on; }
  4554. inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
  4555. inline void ClientImpl::set_interface(const char *intf) { interface_ = intf; }
  4556. inline void ClientImpl::set_proxy(const char *host, int port) {
  4557. proxy_host_ = host;
  4558. proxy_port_ = port;
  4559. }
  4560. inline void ClientImpl::set_proxy_basic_auth(const char *username,
  4561. const char *password) {
  4562. proxy_basic_auth_username_ = username;
  4563. proxy_basic_auth_password_ = password;
  4564. }
  4565. inline void ClientImpl::set_proxy_bearer_token_auth(const char *token) {
  4566. proxy_bearer_token_auth_token_ = token;
  4567. }
  4568. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4569. inline void ClientImpl::set_proxy_digest_auth(const char *username,
  4570. const char *password) {
  4571. proxy_digest_auth_username_ = username;
  4572. proxy_digest_auth_password_ = password;
  4573. }
  4574. #endif
  4575. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4576. inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
  4577. server_certificate_verification_ = enabled;
  4578. }
  4579. #endif
  4580. inline void ClientImpl::set_logger(Logger logger) {
  4581. logger_ = std::move(logger);
  4582. }
  4583. /*
  4584. * SSL Implementation
  4585. */
  4586. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4587. namespace detail {
  4588. template <typename U, typename V>
  4589. inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
  4590. U SSL_connect_or_accept, V setup) {
  4591. SSL *ssl = nullptr;
  4592. {
  4593. std::lock_guard<std::mutex> guard(ctx_mutex);
  4594. ssl = SSL_new(ctx);
  4595. }
  4596. if (ssl) {
  4597. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  4598. SSL_set_bio(ssl, bio, bio);
  4599. if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
  4600. SSL_shutdown(ssl);
  4601. {
  4602. std::lock_guard<std::mutex> guard(ctx_mutex);
  4603. SSL_free(ssl);
  4604. }
  4605. return nullptr;
  4606. }
  4607. }
  4608. return ssl;
  4609. }
  4610. inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl,
  4611. bool process_socket_ret) {
  4612. if (process_socket_ret) {
  4613. SSL_shutdown(ssl); // shutdown only if not already closed by remote
  4614. }
  4615. std::lock_guard<std::mutex> guard(ctx_mutex);
  4616. SSL_free(ssl);
  4617. }
  4618. template <typename T>
  4619. inline bool
  4620. process_server_socket_ssl(SSL *ssl, socket_t sock, size_t keep_alive_max_count,
  4621. time_t keep_alive_timeout_sec,
  4622. time_t read_timeout_sec, time_t read_timeout_usec,
  4623. time_t write_timeout_sec, time_t write_timeout_usec,
  4624. T callback) {
  4625. return process_server_socket_core(
  4626. sock, keep_alive_max_count, keep_alive_timeout_sec,
  4627. [&](bool close_connection, bool &connection_closed) {
  4628. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  4629. write_timeout_sec, write_timeout_usec);
  4630. return callback(strm, close_connection, connection_closed);
  4631. });
  4632. }
  4633. template <typename T>
  4634. inline bool
  4635. process_client_socket_ssl(SSL *ssl, socket_t sock, time_t read_timeout_sec,
  4636. time_t read_timeout_usec, time_t write_timeout_sec,
  4637. time_t write_timeout_usec, T callback) {
  4638. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
  4639. write_timeout_sec, write_timeout_usec);
  4640. return callback(strm);
  4641. }
  4642. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  4643. static std::shared_ptr<std::vector<std::mutex>> openSSL_locks_;
  4644. class SSLThreadLocks {
  4645. public:
  4646. SSLThreadLocks() {
  4647. openSSL_locks_ =
  4648. std::make_shared<std::vector<std::mutex>>(CRYPTO_num_locks());
  4649. CRYPTO_set_locking_callback(locking_callback);
  4650. }
  4651. ~SSLThreadLocks() { CRYPTO_set_locking_callback(nullptr); }
  4652. private:
  4653. static void locking_callback(int mode, int type, const char * /*file*/,
  4654. int /*line*/) {
  4655. auto &lk = (*openSSL_locks_)[static_cast<size_t>(type)];
  4656. if (mode & CRYPTO_LOCK) {
  4657. lk.lock();
  4658. } else {
  4659. lk.unlock();
  4660. }
  4661. }
  4662. };
  4663. #endif
  4664. class SSLInit {
  4665. public:
  4666. SSLInit() {
  4667. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  4668. SSL_load_error_strings();
  4669. SSL_library_init();
  4670. #else
  4671. OPENSSL_init_ssl(
  4672. OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
  4673. #endif
  4674. }
  4675. ~SSLInit() {
  4676. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  4677. ERR_free_strings();
  4678. #endif
  4679. }
  4680. private:
  4681. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  4682. SSLThreadLocks thread_init_;
  4683. #endif
  4684. };
  4685. // SSL socket stream implementation
  4686. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
  4687. time_t read_timeout_sec,
  4688. time_t read_timeout_usec,
  4689. time_t write_timeout_sec,
  4690. time_t write_timeout_usec)
  4691. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  4692. read_timeout_usec_(read_timeout_usec),
  4693. write_timeout_sec_(write_timeout_sec),
  4694. write_timeout_usec_(write_timeout_usec) {
  4695. {
  4696. timeval tv;
  4697. tv.tv_sec = static_cast<long>(read_timeout_sec);
  4698. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec);
  4699. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<char *>(&tv),
  4700. sizeof(tv));
  4701. }
  4702. {
  4703. timeval tv;
  4704. tv.tv_sec = static_cast<long>(write_timeout_sec);
  4705. tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec);
  4706. setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<char *>(&tv),
  4707. sizeof(tv));
  4708. }
  4709. }
  4710. inline SSLSocketStream::~SSLSocketStream() {}
  4711. inline bool SSLSocketStream::is_readable() const {
  4712. return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
  4713. }
  4714. inline bool SSLSocketStream::is_writable() const {
  4715. return detail::select_write(sock_, write_timeout_sec_, write_timeout_usec_) >
  4716. 0;
  4717. }
  4718. inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
  4719. if (SSL_pending(ssl_) > 0 || is_readable()) {
  4720. return SSL_read(ssl_, ptr, static_cast<int>(size));
  4721. }
  4722. return -1;
  4723. }
  4724. inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
  4725. if (is_writable()) { return SSL_write(ssl_, ptr, static_cast<int>(size)); }
  4726. return -1;
  4727. }
  4728. inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
  4729. int &port) const {
  4730. detail::get_remote_ip_and_port(sock_, ip, port);
  4731. }
  4732. static SSLInit sslinit_;
  4733. } // namespace detail
  4734. // SSL HTTP server implementation
  4735. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  4736. const char *client_ca_cert_file_path,
  4737. const char *client_ca_cert_dir_path) {
  4738. ctx_ = SSL_CTX_new(SSLv23_server_method());
  4739. if (ctx_) {
  4740. SSL_CTX_set_options(ctx_,
  4741. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  4742. SSL_OP_NO_COMPRESSION |
  4743. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4744. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  4745. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  4746. // EC_KEY_free(ecdh);
  4747. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  4748. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  4749. 1) {
  4750. SSL_CTX_free(ctx_);
  4751. ctx_ = nullptr;
  4752. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  4753. // if (client_ca_cert_file_path) {
  4754. // auto list = SSL_load_client_CA_file(client_ca_cert_file_path);
  4755. // SSL_CTX_set_client_CA_list(ctx_, list);
  4756. // }
  4757. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  4758. client_ca_cert_dir_path);
  4759. SSL_CTX_set_verify(
  4760. ctx_,
  4761. SSL_VERIFY_PEER |
  4762. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4763. nullptr);
  4764. }
  4765. }
  4766. }
  4767. inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
  4768. X509_STORE *client_ca_cert_store) {
  4769. ctx_ = SSL_CTX_new(SSLv23_server_method());
  4770. if (ctx_) {
  4771. SSL_CTX_set_options(ctx_,
  4772. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  4773. SSL_OP_NO_COMPRESSION |
  4774. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4775. if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
  4776. SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
  4777. SSL_CTX_free(ctx_);
  4778. ctx_ = nullptr;
  4779. } else if (client_ca_cert_store) {
  4780. SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
  4781. SSL_CTX_set_verify(
  4782. ctx_,
  4783. SSL_VERIFY_PEER |
  4784. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4785. nullptr);
  4786. }
  4787. }
  4788. }
  4789. inline SSLServer::~SSLServer() {
  4790. if (ctx_) { SSL_CTX_free(ctx_); }
  4791. }
  4792. inline bool SSLServer::is_valid() const { return ctx_; }
  4793. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  4794. auto ssl = detail::ssl_new(sock, ctx_, ctx_mutex_, SSL_accept,
  4795. [](SSL * /*ssl*/) { return true; });
  4796. if (ssl) {
  4797. auto ret = detail::process_server_socket_ssl(
  4798. ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
  4799. read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
  4800. write_timeout_usec_,
  4801. [this, ssl](Stream &strm, bool close_connection,
  4802. bool &connection_closed) {
  4803. return process_request(strm, close_connection, connection_closed,
  4804. [&](Request &req) { req.ssl = ssl; });
  4805. });
  4806. detail::ssl_delete(ctx_mutex_, ssl, ret);
  4807. return ret;
  4808. }
  4809. detail::close_socket(sock);
  4810. return false;
  4811. }
  4812. // SSL HTTP client implementation
  4813. inline SSLClient::SSLClient(const std::string &host)
  4814. : SSLClient(host, 443, std::string(), std::string()) {}
  4815. inline SSLClient::SSLClient(const std::string &host, int port)
  4816. : SSLClient(host, port, std::string(), std::string()) {}
  4817. inline SSLClient::SSLClient(const std::string &host, int port,
  4818. const std::string &client_cert_path,
  4819. const std::string &client_key_path)
  4820. : ClientImpl(host, port, client_cert_path, client_key_path) {
  4821. ctx_ = SSL_CTX_new(SSLv23_client_method());
  4822. detail::split(&host_[0], &host_[host_.size()], '.',
  4823. [&](const char *b, const char *e) {
  4824. host_components_.emplace_back(std::string(b, e));
  4825. });
  4826. if (!client_cert_path.empty() && !client_key_path.empty()) {
  4827. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  4828. SSL_FILETYPE_PEM) != 1 ||
  4829. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  4830. SSL_FILETYPE_PEM) != 1) {
  4831. SSL_CTX_free(ctx_);
  4832. ctx_ = nullptr;
  4833. }
  4834. }
  4835. }
  4836. inline SSLClient::SSLClient(const std::string &host, int port,
  4837. X509 *client_cert, EVP_PKEY *client_key)
  4838. : ClientImpl(host, port) {
  4839. ctx_ = SSL_CTX_new(SSLv23_client_method());
  4840. detail::split(&host_[0], &host_[host_.size()], '.',
  4841. [&](const char *b, const char *e) {
  4842. host_components_.emplace_back(std::string(b, e));
  4843. });
  4844. if (client_cert != nullptr && client_key != nullptr) {
  4845. if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
  4846. SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
  4847. SSL_CTX_free(ctx_);
  4848. ctx_ = nullptr;
  4849. }
  4850. }
  4851. }
  4852. inline SSLClient::~SSLClient() {
  4853. if (ctx_) { SSL_CTX_free(ctx_); }
  4854. }
  4855. inline bool SSLClient::is_valid() const { return ctx_; }
  4856. inline void SSLClient::set_ca_cert_path(const char *ca_cert_file_path,
  4857. const char *ca_cert_dir_path) {
  4858. if (ca_cert_file_path) { ca_cert_file_path_ = ca_cert_file_path; }
  4859. if (ca_cert_dir_path) { ca_cert_dir_path_ = ca_cert_dir_path; }
  4860. }
  4861. inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
  4862. if (ca_cert_store) { ca_cert_store_ = ca_cert_store; }
  4863. }
  4864. inline long SSLClient::get_openssl_verify_result() const {
  4865. return verify_result_;
  4866. }
  4867. inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
  4868. inline bool SSLClient::create_and_connect_socket(Socket &socket) {
  4869. return is_valid() && ClientImpl::create_and_connect_socket(socket);
  4870. }
  4871. inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res,
  4872. bool &success) {
  4873. success = true;
  4874. Response res2;
  4875. if (!detail::process_client_socket(
  4876. socket.sock, read_timeout_sec_, read_timeout_usec_,
  4877. write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
  4878. Request req2;
  4879. req2.method = "CONNECT";
  4880. req2.path = host_and_port_;
  4881. return process_request(strm, req2, res2, false);
  4882. })) {
  4883. close_socket(socket, true);
  4884. success = false;
  4885. return false;
  4886. }
  4887. if (res2.status == 407) {
  4888. if (!proxy_digest_auth_username_.empty() &&
  4889. !proxy_digest_auth_password_.empty()) {
  4890. std::map<std::string, std::string> auth;
  4891. if (detail::parse_www_authenticate(res2, auth, true)) {
  4892. Response res3;
  4893. if (!detail::process_client_socket(
  4894. socket.sock, read_timeout_sec_, read_timeout_usec_,
  4895. write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
  4896. Request req3;
  4897. req3.method = "CONNECT";
  4898. req3.path = host_and_port_;
  4899. req3.headers.insert(detail::make_digest_authentication_header(
  4900. req3, auth, 1, detail::random_string(10),
  4901. proxy_digest_auth_username_, proxy_digest_auth_password_,
  4902. true));
  4903. return process_request(strm, req3, res3, false);
  4904. })) {
  4905. close_socket(socket, true);
  4906. success = false;
  4907. return false;
  4908. }
  4909. }
  4910. } else {
  4911. res = res2;
  4912. return false;
  4913. }
  4914. }
  4915. return true;
  4916. }
  4917. inline bool SSLClient::load_certs() {
  4918. bool ret = true;
  4919. std::call_once(initialize_cert_, [&]() {
  4920. std::lock_guard<std::mutex> guard(ctx_mutex_);
  4921. if (!ca_cert_file_path_.empty()) {
  4922. if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
  4923. nullptr)) {
  4924. ret = false;
  4925. }
  4926. } else if (!ca_cert_dir_path_.empty()) {
  4927. if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
  4928. ca_cert_dir_path_.c_str())) {
  4929. ret = false;
  4930. }
  4931. } else if (ca_cert_store_ != nullptr) {
  4932. if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store_) {
  4933. SSL_CTX_set_cert_store(ctx_, ca_cert_store_);
  4934. }
  4935. } else {
  4936. #ifdef _WIN32
  4937. detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
  4938. #else
  4939. SSL_CTX_set_default_verify_paths(ctx_);
  4940. #endif
  4941. }
  4942. });
  4943. return ret;
  4944. }
  4945. inline bool SSLClient::initialize_ssl(Socket &socket) {
  4946. auto ssl = detail::ssl_new(
  4947. socket.sock, ctx_, ctx_mutex_,
  4948. [&](SSL *ssl) {
  4949. if (server_certificate_verification_) {
  4950. if (!load_certs()) {
  4951. error_ = Error::SSLLoadingCerts;
  4952. return false;
  4953. }
  4954. SSL_set_verify(ssl, SSL_VERIFY_NONE, nullptr);
  4955. }
  4956. if (SSL_connect(ssl) != 1) {
  4957. error_ = Error::SSLConnection;
  4958. return false;
  4959. }
  4960. if (server_certificate_verification_) {
  4961. verify_result_ = SSL_get_verify_result(ssl);
  4962. if (verify_result_ != X509_V_OK) {
  4963. error_ = Error::SSLServerVerification;
  4964. return false;
  4965. }
  4966. auto server_cert = SSL_get_peer_certificate(ssl);
  4967. if (server_cert == nullptr) {
  4968. error_ = Error::SSLServerVerification;
  4969. return false;
  4970. }
  4971. if (!verify_host(server_cert)) {
  4972. X509_free(server_cert);
  4973. error_ = Error::SSLServerVerification;
  4974. return false;
  4975. }
  4976. X509_free(server_cert);
  4977. }
  4978. return true;
  4979. },
  4980. [&](SSL *ssl) {
  4981. SSL_set_tlsext_host_name(ssl, host_.c_str());
  4982. return true;
  4983. });
  4984. if (ssl) {
  4985. socket.ssl = ssl;
  4986. return true;
  4987. }
  4988. close_socket(socket, false);
  4989. return false;
  4990. }
  4991. inline void SSLClient::close_socket(Socket &socket, bool process_socket_ret) {
  4992. detail::close_socket(socket.sock);
  4993. socket_.sock = INVALID_SOCKET;
  4994. if (socket.ssl) {
  4995. detail::ssl_delete(ctx_mutex_, socket.ssl, process_socket_ret);
  4996. socket_.ssl = nullptr;
  4997. }
  4998. }
  4999. inline bool
  5000. SSLClient::process_socket(Socket &socket,
  5001. std::function<bool(Stream &strm)> callback) {
  5002. assert(socket.ssl);
  5003. return detail::process_client_socket_ssl(
  5004. socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
  5005. write_timeout_sec_, write_timeout_usec_, callback);
  5006. }
  5007. inline bool SSLClient::is_ssl() const { return true; }
  5008. inline bool SSLClient::verify_host(X509 *server_cert) const {
  5009. /* Quote from RFC2818 section 3.1 "Server Identity"
  5010. If a subjectAltName extension of type dNSName is present, that MUST
  5011. be used as the identity. Otherwise, the (most specific) Common Name
  5012. field in the Subject field of the certificate MUST be used. Although
  5013. the use of the Common Name is existing practice, it is deprecated and
  5014. Certification Authorities are encouraged to use the dNSName instead.
  5015. Matching is performed using the matching rules specified by
  5016. [RFC2459]. If more than one identity of a given type is present in
  5017. the certificate (e.g., more than one dNSName name, a match in any one
  5018. of the set is considered acceptable.) Names may contain the wildcard
  5019. character * which is considered to match any single domain name
  5020. component or component fragment. E.g., *.a.com matches foo.a.com but
  5021. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  5022. In some cases, the URI is specified as an IP address rather than a
  5023. hostname. In this case, the iPAddress subjectAltName must be present
  5024. in the certificate and must exactly match the IP in the URI.
  5025. */
  5026. return verify_host_with_subject_alt_name(server_cert) ||
  5027. verify_host_with_common_name(server_cert);
  5028. }
  5029. inline bool
  5030. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  5031. auto ret = false;
  5032. auto type = GEN_DNS;
  5033. struct in6_addr addr6;
  5034. struct in_addr addr;
  5035. size_t addr_len = 0;
  5036. #ifndef __MINGW32__
  5037. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  5038. type = GEN_IPADD;
  5039. addr_len = sizeof(struct in6_addr);
  5040. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  5041. type = GEN_IPADD;
  5042. addr_len = sizeof(struct in_addr);
  5043. }
  5044. #endif
  5045. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  5046. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  5047. if (alt_names) {
  5048. auto dsn_matched = false;
  5049. auto ip_mached = false;
  5050. auto count = sk_GENERAL_NAME_num(alt_names);
  5051. for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
  5052. auto val = sk_GENERAL_NAME_value(alt_names, i);
  5053. if (val->type == type) {
  5054. auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);
  5055. auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);
  5056. if (strlen(name) == name_len) {
  5057. switch (type) {
  5058. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  5059. case GEN_IPADD:
  5060. if (!memcmp(&addr6, name, addr_len) ||
  5061. !memcmp(&addr, name, addr_len)) {
  5062. ip_mached = true;
  5063. }
  5064. break;
  5065. }
  5066. }
  5067. }
  5068. }
  5069. if (dsn_matched || ip_mached) { ret = true; }
  5070. }
  5071. GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);
  5072. return ret;
  5073. }
  5074. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  5075. const auto subject_name = X509_get_subject_name(server_cert);
  5076. if (subject_name != nullptr) {
  5077. char name[BUFSIZ];
  5078. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5079. name, sizeof(name));
  5080. if (name_len != -1) {
  5081. return check_host_name(name, static_cast<size_t>(name_len));
  5082. }
  5083. }
  5084. return false;
  5085. }
  5086. inline bool SSLClient::check_host_name(const char *pattern,
  5087. size_t pattern_len) const {
  5088. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  5089. // Wildcard match
  5090. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  5091. std::vector<std::string> pattern_components;
  5092. detail::split(&pattern[0], &pattern[pattern_len], '.',
  5093. [&](const char *b, const char *e) {
  5094. pattern_components.emplace_back(std::string(b, e));
  5095. });
  5096. if (host_components_.size() != pattern_components.size()) { return false; }
  5097. auto itr = pattern_components.begin();
  5098. for (const auto &h : host_components_) {
  5099. auto &p = *itr;
  5100. if (p != h && p != "*") {
  5101. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  5102. !p.compare(0, p.size() - 1, h));
  5103. if (!partial_match) { return false; }
  5104. }
  5105. ++itr;
  5106. }
  5107. return true;
  5108. }
  5109. #endif
  5110. // Universal client implementation
  5111. inline Client::Client(const char *scheme_host_port)
  5112. : Client(scheme_host_port, std::string(), std::string()) {}
  5113. inline Client::Client(const char *scheme_host_port,
  5114. const std::string &client_cert_path,
  5115. const std::string &client_key_path) {
  5116. const static std::regex re(R"(^(?:([a-z]+)://)?([^:/?#]+)(?::(\d+))?)");
  5117. std::cmatch m;
  5118. if (std::regex_match(scheme_host_port, m, re)) {
  5119. auto scheme = m[1].str();
  5120. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5121. if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
  5122. #else
  5123. if (!scheme.empty() && scheme != "http") {
  5124. #endif
  5125. return;
  5126. }
  5127. auto is_ssl = scheme == "https";
  5128. auto host = m[2].str();
  5129. auto port_str = m[3].str();
  5130. auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
  5131. if (is_ssl) {
  5132. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5133. cli_ = std::make_shared<SSLClient>(host.c_str(), port, client_cert_path,
  5134. client_key_path);
  5135. is_ssl_ = is_ssl;
  5136. #endif
  5137. } else {
  5138. cli_ = std::make_shared<ClientImpl>(host.c_str(), port, client_cert_path,
  5139. client_key_path);
  5140. }
  5141. } else {
  5142. cli_ = std::make_shared<ClientImpl>(scheme_host_port, 80, client_cert_path,
  5143. client_key_path);
  5144. }
  5145. }
  5146. inline Client::Client(const std::string &host, int port)
  5147. : cli_(std::make_shared<ClientImpl>(host, port)) {}
  5148. inline Client::Client(const std::string &host, int port,
  5149. const std::string &client_cert_path,
  5150. const std::string &client_key_path)
  5151. : cli_(std::make_shared<ClientImpl>(host, port, client_cert_path,
  5152. client_key_path)) {}
  5153. inline Client::~Client() {}
  5154. inline bool Client::is_valid() const {
  5155. return cli_ != nullptr && cli_->is_valid();
  5156. }
  5157. inline Result Client::Get(const char *path) { return cli_->Get(path); }
  5158. inline Result Client::Get(const char *path, const Headers &headers) {
  5159. return cli_->Get(path, headers);
  5160. }
  5161. inline Result Client::Get(const char *path, Progress progress) {
  5162. return cli_->Get(path, progress);
  5163. }
  5164. inline Result Client::Get(const char *path, const Headers &headers,
  5165. Progress progress) {
  5166. return cli_->Get(path, headers, progress);
  5167. }
  5168. inline Result Client::Get(const char *path, ContentReceiver content_receiver) {
  5169. return cli_->Get(path, std::move(content_receiver));
  5170. }
  5171. inline Result Client::Get(const char *path, const Headers &headers,
  5172. ContentReceiver content_receiver) {
  5173. return cli_->Get(path, headers, std::move(content_receiver));
  5174. }
  5175. inline Result Client::Get(const char *path, ContentReceiver content_receiver,
  5176. Progress progress) {
  5177. return cli_->Get(path, std::move(content_receiver), std::move(progress));
  5178. }
  5179. inline Result Client::Get(const char *path, const Headers &headers,
  5180. ContentReceiver content_receiver, Progress progress) {
  5181. return cli_->Get(path, headers, std::move(content_receiver),
  5182. std::move(progress));
  5183. }
  5184. inline Result Client::Get(const char *path, ResponseHandler response_handler,
  5185. ContentReceiver content_receiver) {
  5186. return cli_->Get(path, std::move(response_handler),
  5187. std::move(content_receiver));
  5188. }
  5189. inline Result Client::Get(const char *path, const Headers &headers,
  5190. ResponseHandler response_handler,
  5191. ContentReceiver content_receiver) {
  5192. return cli_->Get(path, headers, std::move(response_handler),
  5193. std::move(content_receiver));
  5194. }
  5195. inline Result Client::Get(const char *path, ResponseHandler response_handler,
  5196. ContentReceiver content_receiver, Progress progress) {
  5197. return cli_->Get(path, std::move(response_handler),
  5198. std::move(content_receiver), std::move(progress));
  5199. }
  5200. inline Result Client::Get(const char *path, const Headers &headers,
  5201. ResponseHandler response_handler,
  5202. ContentReceiver content_receiver, Progress progress) {
  5203. return cli_->Get(path, headers, response_handler, content_receiver, progress);
  5204. }
  5205. inline Result Client::Head(const char *path) { return cli_->Head(path); }
  5206. inline Result Client::Head(const char *path, const Headers &headers) {
  5207. return cli_->Head(path, headers);
  5208. }
  5209. inline Result Client::Post(const char *path) { return cli_->Post(path); }
  5210. inline Result Client::Post(const char *path, const std::string &body,
  5211. const char *content_type) {
  5212. return cli_->Post(path, body, content_type);
  5213. }
  5214. inline Result Client::Post(const char *path, const Headers &headers,
  5215. const std::string &body, const char *content_type) {
  5216. return cli_->Post(path, headers, body, content_type);
  5217. }
  5218. inline Result Client::Post(const char *path, size_t content_length,
  5219. ContentProvider content_provider,
  5220. const char *content_type) {
  5221. return cli_->Post(path, content_length, content_provider, content_type);
  5222. }
  5223. inline Result Client::Post(const char *path, const Headers &headers,
  5224. size_t content_length,
  5225. ContentProvider content_provider,
  5226. const char *content_type) {
  5227. return cli_->Post(path, headers, content_length, content_provider,
  5228. content_type);
  5229. }
  5230. inline Result Client::Post(const char *path, const Params &params) {
  5231. return cli_->Post(path, params);
  5232. }
  5233. inline Result Client::Post(const char *path, const Headers &headers,
  5234. const Params &params) {
  5235. return cli_->Post(path, headers, params);
  5236. }
  5237. inline Result Client::Post(const char *path,
  5238. const MultipartFormDataItems &items) {
  5239. return cli_->Post(path, items);
  5240. }
  5241. inline Result Client::Post(const char *path, const Headers &headers,
  5242. const MultipartFormDataItems &items) {
  5243. return cli_->Post(path, headers, items);
  5244. }
  5245. inline Result Client::Put(const char *path) { return cli_->Put(path); }
  5246. inline Result Client::Put(const char *path, const std::string &body,
  5247. const char *content_type) {
  5248. return cli_->Put(path, body, content_type);
  5249. }
  5250. inline Result Client::Put(const char *path, const Headers &headers,
  5251. const std::string &body, const char *content_type) {
  5252. return cli_->Put(path, headers, body, content_type);
  5253. }
  5254. inline Result Client::Put(const char *path, size_t content_length,
  5255. ContentProvider content_provider,
  5256. const char *content_type) {
  5257. return cli_->Put(path, content_length, content_provider, content_type);
  5258. }
  5259. inline Result Client::Put(const char *path, const Headers &headers,
  5260. size_t content_length,
  5261. ContentProvider content_provider,
  5262. const char *content_type) {
  5263. return cli_->Put(path, headers, content_length, content_provider,
  5264. content_type);
  5265. }
  5266. inline Result Client::Put(const char *path, const Params &params) {
  5267. return cli_->Put(path, params);
  5268. }
  5269. inline Result Client::Put(const char *path, const Headers &headers,
  5270. const Params &params) {
  5271. return cli_->Put(path, headers, params);
  5272. }
  5273. inline Result Client::Patch(const char *path, const std::string &body,
  5274. const char *content_type) {
  5275. return cli_->Patch(path, body, content_type);
  5276. }
  5277. inline Result Client::Patch(const char *path, const Headers &headers,
  5278. const std::string &body, const char *content_type) {
  5279. return cli_->Patch(path, headers, body, content_type);
  5280. }
  5281. inline Result Client::Patch(const char *path, size_t content_length,
  5282. ContentProvider content_provider,
  5283. const char *content_type) {
  5284. return cli_->Patch(path, content_length, content_provider, content_type);
  5285. }
  5286. inline Result Client::Patch(const char *path, const Headers &headers,
  5287. size_t content_length,
  5288. ContentProvider content_provider,
  5289. const char *content_type) {
  5290. return cli_->Patch(path, headers, content_length, content_provider,
  5291. content_type);
  5292. }
  5293. inline Result Client::Delete(const char *path) { return cli_->Delete(path); }
  5294. inline Result Client::Delete(const char *path, const std::string &body,
  5295. const char *content_type) {
  5296. return cli_->Delete(path, body, content_type);
  5297. }
  5298. inline Result Client::Delete(const char *path, const Headers &headers) {
  5299. return cli_->Delete(path, headers);
  5300. }
  5301. inline Result Client::Delete(const char *path, const Headers &headers,
  5302. const std::string &body,
  5303. const char *content_type) {
  5304. return cli_->Delete(path, headers, body, content_type);
  5305. }
  5306. inline Result Client::Options(const char *path) { return cli_->Options(path); }
  5307. inline Result Client::Options(const char *path, const Headers &headers) {
  5308. return cli_->Options(path, headers);
  5309. }
  5310. inline bool Client::send(const Request &req, Response &res) {
  5311. return cli_->send(req, res);
  5312. }
  5313. inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
  5314. inline void Client::stop() { cli_->stop(); }
  5315. inline void Client::set_default_headers(Headers headers) {
  5316. cli_->set_default_headers(std::move(headers));
  5317. }
  5318. inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
  5319. inline void Client::set_socket_options(SocketOptions socket_options) {
  5320. cli_->set_socket_options(socket_options);
  5321. }
  5322. inline void Client::set_connection_timeout(time_t sec, time_t usec) {
  5323. cli_->set_connection_timeout(sec, usec);
  5324. }
  5325. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  5326. cli_->set_read_timeout(sec, usec);
  5327. }
  5328. inline void Client::set_write_timeout(time_t sec, time_t usec) {
  5329. cli_->set_write_timeout(sec, usec);
  5330. }
  5331. inline void Client::set_basic_auth(const char *username, const char *password) {
  5332. cli_->set_basic_auth(username, password);
  5333. }
  5334. inline void Client::set_bearer_token_auth(const char *token) {
  5335. cli_->set_bearer_token_auth(token);
  5336. }
  5337. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5338. inline void Client::set_digest_auth(const char *username,
  5339. const char *password) {
  5340. cli_->set_digest_auth(username, password);
  5341. }
  5342. #endif
  5343. inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
  5344. inline void Client::set_follow_location(bool on) {
  5345. cli_->set_follow_location(on);
  5346. }
  5347. inline void Client::set_compress(bool on) { cli_->set_compress(on); }
  5348. inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
  5349. inline void Client::set_interface(const char *intf) {
  5350. cli_->set_interface(intf);
  5351. }
  5352. inline void Client::set_proxy(const char *host, int port) {
  5353. cli_->set_proxy(host, port);
  5354. }
  5355. inline void Client::set_proxy_basic_auth(const char *username,
  5356. const char *password) {
  5357. cli_->set_proxy_basic_auth(username, password);
  5358. }
  5359. inline void Client::set_proxy_bearer_token_auth(const char *token) {
  5360. cli_->set_proxy_bearer_token_auth(token);
  5361. }
  5362. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5363. inline void Client::set_proxy_digest_auth(const char *username,
  5364. const char *password) {
  5365. cli_->set_proxy_digest_auth(username, password);
  5366. }
  5367. #endif
  5368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5369. inline void Client::enable_server_certificate_verification(bool enabled) {
  5370. cli_->enable_server_certificate_verification(enabled);
  5371. }
  5372. #endif
  5373. inline void Client::set_logger(Logger logger) { cli_->set_logger(logger); }
  5374. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5375. inline void Client::set_ca_cert_path(const char *ca_cert_file_path,
  5376. const char *ca_cert_dir_path) {
  5377. if (is_ssl_) {
  5378. static_cast<SSLClient &>(*cli_).set_ca_cert_path(ca_cert_file_path,
  5379. ca_cert_dir_path);
  5380. }
  5381. }
  5382. inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
  5383. if (is_ssl_) {
  5384. static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
  5385. }
  5386. }
  5387. inline long Client::get_openssl_verify_result() const {
  5388. if (is_ssl_) {
  5389. return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
  5390. }
  5391. return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
  5392. }
  5393. inline SSL_CTX *Client::ssl_context() const {
  5394. if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
  5395. return nullptr;
  5396. }
  5397. #endif
  5398. // ----------------------------------------------------------------------------
  5399. } // namespace httplib
  5400. #endif // CPPHTTPLIB_HTTPLIB_H