httplib.h 211 KB

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