httplib.h 253 KB

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