httplib.h 201 KB

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