httplib.cc 202 KB

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