httplib.h 267 KB

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