httplib.h 259 KB

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