httplib.h 324 KB

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