test.cc 1004 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. // ".//x.sock", which is not taken for a URL
  153. client_GET("./" + pathname_.substr(1));
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_TRUE(s0.is_peer_alive());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.is_peer_alive());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. // PORT + 1 is shared with the SSL redirect tests and with
  263. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  264. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  265. // because that happens on a worker thread the ASSERT does not stop the
  266. // test: it runs on and fails at the disconnected_svr_sock check instead.
  267. default_socket_options(s);
  268. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  269. ASSERT_EQ(0, listen(s, 1));
  270. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. std::thread cli{[&] {
  275. const int s = socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_LE(0, s);
  277. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. cli.join();
  281. svr.join();
  282. ASSERT_NE(disconnected_svr_sock, -1);
  283. const auto asSocketStream = [&](socket_t fd,
  284. std::function<bool(Stream &)> func) {
  285. return detail::process_client_socket(
  286. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  287. };
  288. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  289. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  290. // wait_writable() returns true because select_write() only checks if the
  291. // send buffer has space. Peer disconnection is detected later by send().
  292. EXPECT_TRUE(ss.wait_writable());
  293. return true;
  294. });
  295. ASSERT_EQ(0, close(disconnected_svr_sock));
  296. }
  297. #endif // #ifndef _WIN32
  298. TEST(SetSocketOptTest, TcpNoDelay) {
  299. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  300. ASSERT_NE(sock, INVALID_SOCKET);
  301. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  302. int val = 0;
  303. socklen_t len = sizeof(val);
  304. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  305. reinterpret_cast<char *>(&val), &len));
  306. EXPECT_NE(val, 0);
  307. detail::close_socket(sock);
  308. }
  309. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  310. // accept() reports failures through WSAGetLastError() on Windows and through
  311. // errno everywhere else. Asking the wrong one is what made the accept loop
  312. // treat every recoverable failure as fatal on Windows.
  313. struct Classification {
  314. bool resource;
  315. bool transient;
  316. };
  317. auto classify = [](int err) {
  318. #ifdef _WIN32
  319. WSASetLastError(err);
  320. #else
  321. errno = err;
  322. #endif
  323. // Read both before asserting: an assertion may clobber the error slot.
  324. Classification c;
  325. c.resource = detail::is_accept_resource_error();
  326. c.transient = detail::is_accept_transient_error();
  327. return c;
  328. };
  329. #ifdef _WIN32
  330. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  331. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  332. WSAECONNRESET, WSAECONNABORTED};
  333. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  334. #else
  335. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  336. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  337. ECONNABORTED};
  338. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  339. #endif
  340. for (auto err : resource_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.resource) << "error " << err;
  343. EXPECT_FALSE(c.transient) << "error " << err;
  344. }
  345. for (auto err : transient_errors) {
  346. const auto c = classify(err);
  347. EXPECT_TRUE(c.transient) << "error " << err;
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. }
  350. for (auto err : fatal_errors) {
  351. const auto c = classify(err);
  352. EXPECT_FALSE(c.resource) << "error " << err;
  353. EXPECT_FALSE(c.transient) << "error " << err;
  354. }
  355. #ifdef _WIN32
  356. WSASetLastError(0);
  357. #else
  358. errno = 0;
  359. #endif
  360. }
  361. TEST(ClientTest, MoveConstructible) {
  362. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  364. }
  365. TEST(ClientTest, MoveAssignable) {
  366. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  367. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  368. }
  369. #ifdef _WIN32
  370. TEST(StartupTest, WSAStartup) {
  371. WSADATA wsaData;
  372. int ret = WSAStartup(0x0002, &wsaData);
  373. ASSERT_EQ(0, ret);
  374. }
  375. #endif
  376. TEST(DecodePathTest, PercentCharacter) {
  377. EXPECT_EQ(
  378. decode_path_component(
  379. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  380. U8("descrip=Gastos áéíóúñÑ 6"));
  381. }
  382. TEST(DecodePathTest, PercentCharacterNUL) {
  383. string expected;
  384. expected.push_back('x');
  385. expected.push_back('\0');
  386. expected.push_back('x');
  387. EXPECT_EQ(decode_path_component("x%00x"), expected);
  388. }
  389. TEST(DecodePathTest, UnicodeEncoding) {
  390. // %u0041 = 'A' (1-byte UTF-8)
  391. EXPECT_EQ("A", decode_path_component("%u0041"));
  392. // %u00E9 = 'é' (2-byte UTF-8)
  393. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  394. // %u3042 = 'あ' (3-byte UTF-8)
  395. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  396. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  397. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  398. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  399. // neighbours)
  400. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  401. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  402. }
  403. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  404. // A sign or whitespace inside the two-character escape window must not be
  405. // accepted as a valid percent-encoding; the sequence is passed through
  406. // literally, matching decode_uri_component / decode_path_component.
  407. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  408. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  409. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  410. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  411. // Well-formed escapes still decode.
  412. EXPECT_EQ("-", decode_query_component("%2D", false));
  413. EXPECT_EQ("A", decode_query_component("%41", false));
  414. }
  415. TEST(SanitizeFilenameTest, VariousPatterns) {
  416. // Path traversal
  417. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  419. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  420. // Normal and edge cases
  421. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  422. EXPECT_EQ("filename.txt",
  423. httplib::sanitize_filename("/path/to/filename.txt"));
  424. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  425. EXPECT_EQ("", httplib::sanitize_filename(".."));
  426. EXPECT_EQ("", httplib::sanitize_filename(""));
  427. // Null bytes stripped
  428. EXPECT_EQ("safe.txt",
  429. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  430. // Whitespace-only rejected
  431. EXPECT_EQ("", httplib::sanitize_filename(" "));
  432. }
  433. // Forward declaration (see the base64_encode note below): split builds move the
  434. // definition into httplib.cc, so re-declaring it here lets the test link.
  435. namespace httplib {
  436. namespace detail {
  437. bool is_chunked_transfer_encoding(const Headers &headers);
  438. } // namespace detail
  439. } // namespace httplib
  440. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  441. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  442. auto make = [](std::initializer_list<const char *> lines) {
  443. Headers h;
  444. for (auto te : lines) {
  445. if (te) { h.emplace("Transfer-Encoding", te); }
  446. }
  447. return h;
  448. };
  449. // Sole coding, matched case-insensitively.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  453. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  457. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  462. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  463. // were received, into one list. Headers preserves that order, so the answer
  464. // is decided by the last coding of the last line and the order the lines
  465. // arrived in is significant.
  466. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  469. // The split can fall anywhere in the list.
  470. EXPECT_TRUE(
  471. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  472. EXPECT_FALSE(
  473. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  474. // A trailing line naming no coding leaves the list ending in nothing, so it
  475. // must not inherit the chunked from the line before it.
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  477. }
  478. // Forward declarations (see the base64_encode note below).
  479. namespace httplib {
  480. namespace detail {
  481. bool parse_status_line(const char *line, std::string &version, int &status,
  482. std::string &reason);
  483. std::string file_extension(const std::string &path);
  484. std::string
  485. find_content_type(const std::string &path,
  486. const std::map<std::string, std::string> &user_data,
  487. const std::string &default_content_type);
  488. bool can_compress_content_type(const std::string &content_type);
  489. bool is_prohibited_header_name(const std::string &name);
  490. #ifdef CPPHTTPLIB_SSL_ENABLED
  491. bool match_hostname(const std::string &pattern, const std::string &hostname);
  492. #endif
  493. } // namespace detail
  494. } // namespace httplib
  495. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  496. struct {
  497. const char *line;
  498. const char *version;
  499. int status;
  500. const char *reason;
  501. } cases[] = {
  502. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  503. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  504. // The reason phrase may be empty, or left out along with its space.
  505. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  506. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  507. };
  508. for (const auto &c : cases) {
  509. std::string version;
  510. int status = 0;
  511. std::string reason = "unset";
  512. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  513. << c.line;
  514. EXPECT_EQ(c.version, version);
  515. EXPECT_EQ(c.status, status);
  516. EXPECT_EQ(c.reason, reason);
  517. }
  518. }
  519. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  520. const char *lines[] = {
  521. "HTTP/2 200 OK\r\n",
  522. "HTTP/1.2 200 OK\r\n",
  523. "HTTP/1.1 20 OK\r\n",
  524. "HTTP/1.1 2000 OK\r\n",
  525. "HTTP/1.1 2x0 OK\r\n",
  526. "HTTP/1.1 200 OK\r\n",
  527. "HTTP/1.1 200OK\r\n",
  528. "HTTP/1.1 200 O\rK\r\n",
  529. "HTTP/1.1 200 OK",
  530. "HTTP/1.1 200 OK\r\nX",
  531. "",
  532. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  533. "HTTP/1.1 200 OK\n",
  534. #endif
  535. };
  536. for (auto line : lines) {
  537. std::string version;
  538. int status = 0;
  539. std::string reason;
  540. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  541. << line;
  542. }
  543. }
  544. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  545. // Long enough to overflow the stack when matched with std::regex.
  546. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  547. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  548. std::string version;
  549. int status = 0;
  550. std::string reason;
  551. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  552. EXPECT_EQ(200, status);
  553. EXPECT_EQ(long_reason, reason);
  554. }
  555. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  556. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  557. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  558. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  559. EXPECT_EQ("", detail::file_extension("noext"));
  560. EXPECT_EQ("", detail::file_extension("a."));
  561. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  562. EXPECT_EQ("", detail::file_extension("a.b-c"));
  563. // Long enough to overflow the stack when matched with std::regex.
  564. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  565. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  566. }
  567. #ifdef CPPHTTPLIB_SSL_ENABLED
  568. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  569. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  570. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  572. // A wildcard needs two labels after it, in the leftmost label only
  573. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  574. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  575. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  576. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  577. EXPECT_FALSE(
  578. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  579. // No name may have an empty label
  580. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  581. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  582. }
  583. #endif
  584. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  585. detail::case_ignore::hash hash;
  586. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  587. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  588. // Long enough to overflow the stack if hashed one call per character.
  589. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  590. }
  591. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  592. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  593. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  594. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  595. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  596. // Same 26-bit hash as html, svg and js.
  597. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  598. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  600. }
  601. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  602. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  603. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  604. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  605. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  606. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  607. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  608. // Same 26-bit hash as application/json.
  609. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  610. }
  611. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  612. Request req;
  613. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  614. EXPECT_TRUE(req.is_multipart_form_data());
  615. std::string boundary;
  616. EXPECT_TRUE(detail::parse_multipart_boundary(
  617. req.get_header_value("Content-Type"), boundary));
  618. EXPECT_EQ("x", boundary);
  619. }
  620. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  621. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  623. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  624. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  625. // Same 26-bit hash as REMOTE_ADDR.
  626. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  627. }
  628. // Forward declaration: in split builds split.py strips `inline` and moves the
  629. // definition into httplib.cc, so detail::base64_encode is not visible from the
  630. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  631. // in both header-only and split builds.
  632. namespace httplib {
  633. namespace detail {
  634. std::string base64_encode(const std::string &in);
  635. } // namespace detail
  636. } // namespace httplib
  637. TEST(Base64EncodeTest, KnownAnswers) {
  638. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  639. // where the accumulator's top bit is already set before the next shift.
  640. EXPECT_EQ("", detail::base64_encode(""));
  641. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  642. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  643. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  644. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  645. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  646. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  647. // High bytes keep the top bit set across several rounds.
  648. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  649. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  650. }
  651. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(ClientQueryOrder, PreserveOrder) {
  661. // This test reproduces Issue #2259: client may reorder query parameters
  662. // when sending a GET request. The expected behavior is that the client
  663. // preserves the original query string order when the caller supplied it
  664. // as part of the path.
  665. Server svr;
  666. svr.Get("/", [&](const Request &req, Response &res) {
  667. // Echo back the raw target so the test can assert ordering
  668. res.set_content(req.target, "text/plain");
  669. });
  670. std::thread t{[&] { svr.listen(HOST, PORT); }};
  671. auto se = detail::scope_exit([&] {
  672. svr.stop();
  673. t.join();
  674. ASSERT_FALSE(svr.is_running());
  675. });
  676. svr.wait_until_ready();
  677. Client cli(HOST, PORT);
  678. ASSERT_TRUE(cli.is_valid());
  679. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  680. auto res = cli.Get(original);
  681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  682. // Expect the echoed target to exactly match the original path (order
  683. // preserved)
  684. EXPECT_EQ(res->body, original);
  685. }
  686. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  687. string chineseCharacters = U8("中国語");
  688. string russianCharacters = U8("дом");
  689. string brazilianCharacters = U8("óculos");
  690. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  691. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  692. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  693. "%D0%B4%D0%BE%D0%BC");
  694. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  695. }
  696. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  697. string unescapedCharacters = "-_.!~*'()";
  698. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  699. }
  700. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  701. string reservedCharacters = ";,/?:@&=+$";
  702. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  703. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  704. }
  705. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  706. string chineseCharacters = U8("中国語");
  707. string russianCharacters = U8("дом");
  708. string brazilianCharacters = U8("óculos");
  709. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  710. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  711. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  712. "%D0%B4%D0%BE%D0%BC");
  713. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  714. }
  715. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  716. // Issue #2082 use case: encoding path component with ampersand
  717. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  718. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  719. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  720. }
  721. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$#";
  727. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  728. }
  729. TEST(EncodeUriTest, TestUTF8Characters) {
  730. string chineseCharacters = U8("中国語");
  731. string russianCharacters = U8("дом");
  732. string brazilianCharacters = U8("óculos");
  733. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  734. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  735. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  736. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  737. }
  738. TEST(EncodeUriTest, TestCompleteUri) {
  739. string uri =
  740. "https://example.com/path/to/resource?query=value&param=test#fragment";
  741. EXPECT_EQ(
  742. httplib::encode_uri(uri),
  743. "https://example.com/path/to/resource?query=value&param=test#fragment");
  744. }
  745. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  746. string uri =
  747. "https://example.com/path with spaces/file name.html?q=hello world";
  748. EXPECT_EQ(httplib::encode_uri(uri),
  749. "https://example.com/path%20with%20spaces/"
  750. "file%20name.html?q=hello%20world");
  751. }
  752. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  753. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  755. }
  756. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  757. string unescapedCharacters = "-_.!~*'()";
  758. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  759. }
  760. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  761. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  762. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  763. string encodedBrazilian = "%C3%B3culos";
  764. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  765. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  767. }
  768. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  769. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  770. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  771. "Piri Tommy Villiers - on & on");
  772. }
  773. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  774. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  775. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  776. }
  777. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  778. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  779. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  780. }
  781. TEST(DecodeUriTest, TestUTF8Characters) {
  782. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  783. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  784. string encodedBrazilian = "%C3%B3culos";
  785. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  786. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  787. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  788. }
  789. TEST(DecodeUriTest, TestCompleteUri) {
  790. string encodedUri = "https://example.com/path%20with%20spaces/"
  791. "file%20name.html?q=hello%20world";
  792. EXPECT_EQ(
  793. httplib::decode_uri(encodedUri),
  794. "https://example.com/path with spaces/file name.html?q=hello world");
  795. }
  796. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  797. string original =
  798. "https://example.com/path with spaces/file name.html?q=hello world";
  799. string encoded = httplib::encode_uri(original);
  800. string decoded = httplib::decode_uri(encoded);
  801. EXPECT_EQ(decoded, original);
  802. }
  803. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  804. // decode_uri is the inverse of encode_uri: an escaped reserved character
  805. // stays encoded so it is not promoted into a real delimiter, while
  806. // non-reserved escapes still decode (like JS decodeURI).
  807. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  808. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  809. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  810. "%3F%3A%40%26%3D%2B%24%2C%3B");
  811. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  812. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  813. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  814. "http://example.com/a%2Fb");
  815. // decode_uri_component still decodes the reserved character.
  816. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  817. }
  818. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  819. string original = "Piri Tommy Villiers - on & on";
  820. string encoded = httplib::encode_uri_component(original);
  821. string decoded = httplib::decode_uri_component(encoded);
  822. EXPECT_EQ(decoded, original);
  823. }
  824. TEST(TrimTests, TrimStringTests) {
  825. EXPECT_EQ("abc", detail::trim_copy("abc"));
  826. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  827. EXPECT_TRUE(detail::trim_copy("").empty());
  828. }
  829. TEST(AsciiTest, LocaleIndependentClassification) {
  830. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  831. // which consult the global C locale: std::isalnum(0xC5) can return true
  832. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  833. // helpers must classify every byte by the ASCII grammar alone.
  834. for (int i = 0; i < 256; i++) {
  835. auto c = static_cast<char>(i);
  836. auto is_digit = i >= '0' && i <= '9';
  837. auto is_upper = i >= 'A' && i <= 'Z';
  838. auto is_lower = i >= 'a' && i <= 'z';
  839. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  840. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  841. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  842. << "byte " << i;
  843. }
  844. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  845. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  846. // Non-ASCII bytes must be percent-encoded, never passed through as
  847. // alphanumeric.
  848. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  849. }
  850. TEST(FromCharsTest, Double) {
  851. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  852. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  853. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  854. auto parse = [](const std::string &s, double &v) {
  855. return detail::from_chars(s.data(), s.data() + s.size(), v);
  856. };
  857. double v = -1.0;
  858. // Representative quality values.
  859. EXPECT_EQ(parse("0", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 0.0);
  861. EXPECT_EQ(parse("1", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 1.0);
  863. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.8);
  865. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.001);
  867. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 1.0);
  869. // A missing integer or fractional part is tolerated.
  870. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.5);
  872. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 5.0);
  874. // Values outside [0, 1] still parse; the caller range-checks them.
  875. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 123.456);
  877. // Stops at the first byte that is not part of the number and reports where.
  878. std::string trailing = "0.9, text/html";
  879. auto r = parse(trailing, v);
  880. EXPECT_EQ(r.ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 0.9);
  882. EXPECT_EQ(*r.ptr, ',');
  883. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  884. // outright, and an 'e'/'E' simply ends the number.
  885. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  886. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  887. std::string exp_input = "1.5e3";
  888. r = parse(exp_input, v);
  889. EXPECT_EQ(r.ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 1.5);
  891. EXPECT_EQ(*r.ptr, 'e');
  892. // Invalid inputs.
  893. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  898. // Pathological but well-formed inputs must stay bounded (no overflow, no
  899. // out-of-bounds table access) and stay within [0, 1] for the caller.
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  901. std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.0);
  903. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  904. std::errc{});
  905. EXPECT_GE(v, 0.0);
  906. EXPECT_LE(v, 1.0);
  907. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  908. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  909. }
  910. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  911. // Simple case without quality values
  912. std::vector<std::string> result1;
  913. EXPECT_TRUE(detail::parse_accept_header(
  914. "text/html,application/json,text/plain", result1));
  915. EXPECT_EQ(result1.size(), 3U);
  916. EXPECT_EQ(result1[0], "text/html");
  917. EXPECT_EQ(result1[1], "application/json");
  918. EXPECT_EQ(result1[2], "text/plain");
  919. // With quality values
  920. std::vector<std::string> result2;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  923. EXPECT_EQ(result2.size(), 3U);
  924. EXPECT_EQ(result2[0], "application/json"); // highest q value
  925. EXPECT_EQ(result2[1], "text/html");
  926. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  927. }
  928. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  929. // Mixed with and without quality values
  930. std::vector<std::string> result;
  931. EXPECT_TRUE(detail::parse_accept_header(
  932. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  933. EXPECT_EQ(result.size(), 3U);
  934. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  935. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  936. EXPECT_EQ(result[2], "application/json"); // q=0.5
  937. }
  938. TEST(ParseAcceptHeaderTest, EdgeCases) {
  939. // Empty header
  940. std::vector<std::string> empty_result;
  941. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  942. EXPECT_TRUE(empty_result.empty());
  943. // Single type
  944. std::vector<std::string> single_result;
  945. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  946. EXPECT_EQ(single_result.size(), 1U);
  947. EXPECT_EQ(single_result[0], "application/json");
  948. // Wildcard types
  949. std::vector<std::string> wildcard_result;
  950. EXPECT_TRUE(detail::parse_accept_header(
  951. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  952. EXPECT_EQ(wildcard_result.size(), 3U);
  953. EXPECT_EQ(wildcard_result[0], "application/json");
  954. EXPECT_EQ(wildcard_result[1], "text/*");
  955. EXPECT_EQ(wildcard_result[2], "*/*");
  956. }
  957. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  958. // Common browser Accept header
  959. std::vector<std::string> browser_result;
  960. EXPECT_TRUE(
  961. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  962. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  963. browser_result));
  964. EXPECT_EQ(browser_result.size(), 6U);
  965. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  970. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  971. // API client header
  972. std::vector<std::string> api_result;
  973. EXPECT_TRUE(detail::parse_accept_header(
  974. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  975. api_result));
  976. EXPECT_EQ(api_result.size(), 3U);
  977. EXPECT_EQ(api_result[0], "application/json");
  978. EXPECT_EQ(api_result[1], "application/xml");
  979. EXPECT_EQ(api_result[2], "text/plain");
  980. }
  981. TEST(ParseAcceptHeaderTest, SpecialCases) {
  982. // Quality value with 3 decimal places
  983. std::vector<std::string> decimal_result;
  984. EXPECT_TRUE(detail::parse_accept_header(
  985. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  986. EXPECT_EQ(decimal_result.size(), 2U);
  987. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  988. EXPECT_EQ(decimal_result[1], "text/html");
  989. // Zero quality (should still be included but with lowest priority)
  990. std::vector<std::string> zero_q_result;
  991. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  992. zero_q_result));
  993. EXPECT_EQ(zero_q_result.size(), 2U);
  994. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  995. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  996. // No spaces around commas
  997. std::vector<std::string> no_space_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1000. no_space_result));
  1001. EXPECT_EQ(no_space_result.size(), 3U);
  1002. EXPECT_EQ(no_space_result[0], "text/html");
  1003. EXPECT_EQ(no_space_result[1], "application/json");
  1004. EXPECT_EQ(no_space_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1007. // Quality values always use '.' as the decimal separator, so parsing must
  1008. // not depend on the process locale. An embedding application may have
  1009. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1010. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1011. std::string saved = cur ? cur : "C";
  1012. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1013. "fr_FR.UTF-8"};
  1014. bool switched = false;
  1015. for (const auto loc : comma_locales) {
  1016. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1017. std::localeconv()->decimal_point[0] == ',') {
  1018. switched = true;
  1019. break;
  1020. }
  1021. }
  1022. if (!switched) {
  1023. std::setlocale(LC_NUMERIC, saved.c_str());
  1024. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1025. }
  1026. // The higher-weighted type appears later in the list, so a correct parse
  1027. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1028. // sensitive parse reads both weights as 0 and leaves the original order.
  1029. std::vector<std::string> result;
  1030. EXPECT_TRUE(detail::parse_accept_header(
  1031. "application/json;q=0.1,text/html;q=0.9", result));
  1032. ASSERT_EQ(result.size(), 2U);
  1033. EXPECT_EQ(result[0], "text/html");
  1034. EXPECT_EQ(result[1], "application/json");
  1035. std::setlocale(LC_NUMERIC, saved.c_str());
  1036. }
  1037. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1038. std::vector<std::string> result;
  1039. // Invalid quality value (> 1.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1042. // Invalid quality value (< 0.0)
  1043. EXPECT_FALSE(
  1044. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1045. // Invalid quality value (not a number)
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=invalid,application/json", result));
  1048. // A valid numeric prefix does not make the entire quality value valid.
  1049. EXPECT_FALSE(detail::parse_accept_header(
  1050. "text/html;q=0.5junk,application/json", result));
  1051. // Empty quality value
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("text/html;q=,application/json", result));
  1054. // Invalid media type format (no slash and not wildcard)
  1055. EXPECT_FALSE(
  1056. detail::parse_accept_header("invalidtype,application/json", result));
  1057. // Valid cases should still work
  1058. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*/*");
  1061. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "*");
  1064. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1065. EXPECT_EQ(result.size(), 1U);
  1066. EXPECT_EQ(result[0], "text/*");
  1067. }
  1068. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1069. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1070. // and must not be answered with 400 Bad Request.
  1071. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1072. struct {
  1073. const char *value;
  1074. std::vector<std::string> expected;
  1075. } cases[] = {
  1076. {",application/json", {"application/json"}},
  1077. {"text/html,", {"text/html"}},
  1078. {"text/html,,*/*", {"text/html", "*/*"}},
  1079. // An empty element may be spelled with whitespace in it
  1080. {"text/html, , application/json", {"text/html", "application/json"}},
  1081. // Nothing but empty elements is an empty list, which means the same
  1082. // thing as no Accept header at all
  1083. {",,,", {}},
  1084. // Quality values still apply across ignored empty elements
  1085. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1086. };
  1087. for (const auto &c : cases) {
  1088. std::vector<std::string> result;
  1089. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1090. << "value: " << c.value;
  1091. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1092. }
  1093. // An invalid entry is still rejected when empty elements surround it
  1094. std::vector<std::string> result;
  1095. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1096. }
  1097. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1098. // or ';' inside one does not end the list element or the parameter. Section
  1099. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1100. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1101. struct {
  1102. const char *value;
  1103. std::vector<std::string> expected;
  1104. } cases[] = {
  1105. {"text/html;profile=\"a,b\",application/json",
  1106. {"text/html", "application/json"}},
  1107. // A "q=" inside a quoted value is not the weight
  1108. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1109. {"text/html", "application/json"}},
  1110. // The weight after a quoted value still applies
  1111. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1114. {"application/json", "text/html"}},
  1115. {"text/html;profile=\"a\\\"b\",application/json",
  1116. {"text/html", "application/json"}},
  1117. // An escaped backslash does not escape the '"' after it
  1118. {"text/html;profile=\"a\\\\\",application/json",
  1119. {"text/html", "application/json"}},
  1120. };
  1121. for (const auto &c : cases) {
  1122. std::vector<std::string> result;
  1123. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1124. << "value: " << c.value;
  1125. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1126. }
  1127. }
  1128. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1129. Server svr;
  1130. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1132. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1133. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1134. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1135. res.set_content("ok", "text/plain");
  1136. });
  1137. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1138. EXPECT_TRUE(false);
  1139. res.set_content("bad request", "text/plain");
  1140. });
  1141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1142. auto se = detail::scope_exit([&] {
  1143. svr.stop();
  1144. listen_thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. });
  1147. svr.wait_until_ready();
  1148. Client cli("localhost", PORT);
  1149. {
  1150. auto res = cli.Get(
  1151. "/accept_ok",
  1152. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. auto res = cli.Get("/accept_bad_request",
  1158. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1161. }
  1162. }
  1163. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1164. Server svr;
  1165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1166. res.set_content("ok", "text/plain");
  1167. });
  1168. std::atomic<int> start_count{0};
  1169. std::atomic<bool> running_when_called{false};
  1170. svr.set_start_handler([&]() {
  1171. running_when_called = svr.is_running();
  1172. start_count++;
  1173. });
  1174. auto port = svr.bind_to_any_port(HOST);
  1175. std::thread t([&]() { svr.listen_after_bind(); });
  1176. auto se = detail::scope_exit([&] {
  1177. svr.stop();
  1178. t.join();
  1179. ASSERT_FALSE(svr.is_running());
  1180. });
  1181. svr.wait_until_ready();
  1182. // A successful request proves the accept loop is running, which the start
  1183. // handler precedes; so by now the handler must have run exactly once.
  1184. Client cli(HOST, port);
  1185. cli.set_connection_timeout(std::chrono::seconds(5));
  1186. auto res = cli.Get("/");
  1187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1188. EXPECT_EQ(StatusCode::OK_200, res->status);
  1189. EXPECT_EQ(1, start_count.load());
  1190. EXPECT_TRUE(running_when_called.load());
  1191. }
  1192. TEST(DivideTest, DivideStringTests) {
  1193. auto divide = [](const std::string &str, char d) {
  1194. std::string lhs;
  1195. std::string rhs;
  1196. detail::divide(str, d,
  1197. [&](const char *lhs_data, std::size_t lhs_size,
  1198. const char *rhs_data, std::size_t rhs_size) {
  1199. lhs.assign(lhs_data, lhs_size);
  1200. rhs.assign(rhs_data, rhs_size);
  1201. });
  1202. return std::make_pair(std::move(lhs), std::move(rhs));
  1203. };
  1204. {
  1205. const auto res = divide("", '=');
  1206. EXPECT_EQ(res.first, "");
  1207. EXPECT_EQ(res.second, "");
  1208. }
  1209. {
  1210. const auto res = divide("=", '=');
  1211. EXPECT_EQ(res.first, "");
  1212. EXPECT_EQ(res.second, "");
  1213. }
  1214. {
  1215. const auto res = divide(" ", '=');
  1216. EXPECT_EQ(res.first, " ");
  1217. EXPECT_EQ(res.second, "");
  1218. }
  1219. {
  1220. const auto res = divide("a", '=');
  1221. EXPECT_EQ(res.first, "a");
  1222. EXPECT_EQ(res.second, "");
  1223. }
  1224. {
  1225. const auto res = divide("a=", '=');
  1226. EXPECT_EQ(res.first, "a");
  1227. EXPECT_EQ(res.second, "");
  1228. }
  1229. {
  1230. const auto res = divide("=b", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "b");
  1233. }
  1234. {
  1235. const auto res = divide("a=b", '=');
  1236. EXPECT_EQ(res.first, "a");
  1237. EXPECT_EQ(res.second, "b");
  1238. }
  1239. {
  1240. const auto res = divide("a=b=", '=');
  1241. EXPECT_EQ(res.first, "a");
  1242. EXPECT_EQ(res.second, "b=");
  1243. }
  1244. {
  1245. const auto res = divide("a=b=c", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "b=c");
  1248. }
  1249. }
  1250. TEST(SplitTest, ParseQueryString) {
  1251. string s = "key1=val1&key2=val2&key3=val3";
  1252. Params dic;
  1253. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1254. [&](const char *b, const char *e) {
  1255. string key, val;
  1256. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1257. if (key.empty()) {
  1258. key.assign(b2, e2);
  1259. } else {
  1260. val.assign(b2, e2);
  1261. }
  1262. });
  1263. dic.emplace(key, val);
  1264. });
  1265. EXPECT_EQ("val1", dic.find("key1")->second);
  1266. EXPECT_EQ("val2", dic.find("key2")->second);
  1267. EXPECT_EQ("val3", dic.find("key3")->second);
  1268. }
  1269. TEST(SplitTest, ParseInvalidQueryTests) {
  1270. {
  1271. string s = " ";
  1272. Params dict;
  1273. detail::parse_query_text(s, dict);
  1274. EXPECT_TRUE(dict.empty());
  1275. }
  1276. {
  1277. string s = " = =";
  1278. Params dict;
  1279. detail::parse_query_text(s, dict);
  1280. EXPECT_TRUE(dict.empty());
  1281. }
  1282. }
  1283. TEST(ParseQueryTest, ParseQueryString) {
  1284. {
  1285. std::string s = "key1=val1&key2=val2&key3=val3";
  1286. Params dic;
  1287. detail::parse_query_text(s, dic);
  1288. EXPECT_EQ("val1", dic.find("key1")->second);
  1289. EXPECT_EQ("val2", dic.find("key2")->second);
  1290. EXPECT_EQ("val3", dic.find("key3")->second);
  1291. }
  1292. {
  1293. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("", dic.find("key1")->second);
  1297. EXPECT_EQ("val1", dic.find("key2")->second);
  1298. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1299. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1300. }
  1301. }
  1302. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1303. Params dic;
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1305. dic.emplace("key1", "val1");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1307. dic.emplace("key2", "val2");
  1308. dic.emplace("key3", "val3");
  1309. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1310. }
  1311. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1312. Params params;
  1313. params.emplace("a", "1");
  1314. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1315. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1316. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1317. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1318. // Long enough to overflow the stack when matched with std::regex.
  1319. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1320. EXPECT_EQ("/p?" + long_query + "&a=1",
  1321. append_query_params("/p?" + long_query, params));
  1322. }
  1323. // Joins every entry of a Headers or Params into "key=value " so a whole
  1324. // traversal can be compared in one assertion. Both are instantiations of the
  1325. // same insertion-ordered container, so one helper serves both.
  1326. template <typename Map> static std::string entries_to_string(const Map &m) {
  1327. std::string s;
  1328. for (const auto &entry : m) {
  1329. s += entry.first + "=" + entry.second + " ";
  1330. }
  1331. return s;
  1332. }
  1333. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1334. // Params used to be a std::multimap, which sorted by name and handed the
  1335. // caller's query back alphabetised. A client signing its query string could
  1336. // not reproduce the order it asked for.
  1337. Params dic;
  1338. dic.emplace("zulu", "1");
  1339. dic.emplace("alpha", "2");
  1340. dic.emplace("mike", "3");
  1341. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1342. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1343. }
  1344. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1345. Params dic;
  1346. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1347. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1348. }
  1349. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1350. Request req;
  1351. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1352. req.params);
  1353. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1354. EXPECT_EQ("first", req.get_param_value("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1356. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1357. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1358. EXPECT_EQ("", req.get_param_value("tag", 3));
  1359. }
  1360. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1361. // Params shares its container with Headers, which matches field names
  1362. // case-insensitively. Parameter names must not pick that up.
  1363. Params dic;
  1364. dic.emplace("Key", "upper");
  1365. dic.emplace("key", "lower");
  1366. EXPECT_EQ(2U, dic.size());
  1367. EXPECT_EQ(1U, dic.count("Key"));
  1368. EXPECT_EQ(1U, dic.count("key"));
  1369. EXPECT_EQ("upper", dic.find("Key")->second);
  1370. EXPECT_EQ("lower", dic.find("key")->second);
  1371. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1372. }
  1373. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1374. Server svr;
  1375. std::string order;
  1376. svr.Get("/order", [&](const Request &req, Response &res) {
  1377. order = entries_to_string(req.params);
  1378. res.set_content("ok", "text/plain");
  1379. });
  1380. auto port = svr.bind_to_any_port(HOST);
  1381. thread t = thread([&] { svr.listen_after_bind(); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. t.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, port);
  1389. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1390. ASSERT_TRUE(res);
  1391. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1392. }
  1393. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1394. Server svr;
  1395. std::string field_order, file_order;
  1396. svr.Post("/order", [&](const Request &req, Response &res) {
  1397. for (const auto &field : req.form.fields) {
  1398. field_order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. for (const auto &file : req.form.files) {
  1401. file_order += file.first + "=" + file.second.filename + " ";
  1402. }
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. UploadFormDataItems items = {
  1414. {"zulu", "1", "", ""},
  1415. {"alpha", "2", "", ""},
  1416. {"mike", "3", "", ""},
  1417. {"zebra", "z", "z.txt", "text/plain"},
  1418. {"apple", "a", "a.txt", "text/plain"},
  1419. };
  1420. Client cli(HOST, port);
  1421. auto res = cli.Post("/order", items);
  1422. ASSERT_TRUE(res);
  1423. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1424. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1425. }
  1426. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1427. Server svr;
  1428. std::vector<std::string> values;
  1429. std::string first, second, out_of_range, order;
  1430. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1431. values = req.form.get_fields("tag");
  1432. first = req.form.get_field("tag", 0);
  1433. second = req.form.get_field("tag", 1);
  1434. out_of_range = req.form.get_field("tag", 2);
  1435. for (const auto &field : req.form.fields) {
  1436. order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. res.set_content("ok", "text/plain");
  1439. });
  1440. auto port = svr.bind_to_any_port(HOST);
  1441. thread t = thread([&] { svr.listen_after_bind(); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. t.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1449. // not adjacent in the container.
  1450. UploadFormDataItems items = {
  1451. {"tag", "first", "", ""},
  1452. {"other", "x", "", ""},
  1453. {"tag", "second", "", ""},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/repeated", items);
  1457. ASSERT_TRUE(res);
  1458. ASSERT_EQ(2U, values.size());
  1459. EXPECT_EQ("first", values[0]);
  1460. EXPECT_EQ("second", values[1]);
  1461. EXPECT_EQ("first", first);
  1462. EXPECT_EQ("second", second);
  1463. // std::multimap already kept entries sharing a name in insertion order, so
  1464. // everything above passes without this change too. The whole traversal is
  1465. // what tells the two apart: sorting by name would hoist "other" to the front
  1466. // and the two "tag" parts would end up adjacent.
  1467. EXPECT_EQ("tag=first other=x tag=second ", order);
  1468. // Advancing past the last entry of a name used to run off the container;
  1469. // the container's saturating increment makes it return the default instead.
  1470. EXPECT_EQ("", out_of_range);
  1471. }
  1472. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1473. Server svr;
  1474. std::string file_names;
  1475. svr.Post("/upload", [&](const Request &req, Response &res) {
  1476. for (const auto &file : req.form.files) {
  1477. file_names += file.first + "|" + file.second.filename + " ";
  1478. }
  1479. res.set_content("ok", "text/plain");
  1480. });
  1481. auto port = svr.bind_to_any_port(HOST);
  1482. thread t = thread([&] { svr.listen_after_bind(); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. t.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. svr.wait_until_ready();
  1489. // A trailing backslash would otherwise escape the closing quote.
  1490. UploadFormDataItems items = {
  1491. {"dir\\", "x", "a.txt", "text/plain"},
  1492. {"b", "y", "a\\\\b.txt", "text/plain"},
  1493. };
  1494. Client cli(HOST, port);
  1495. auto res = cli.Post("/upload", items);
  1496. ASSERT_TRUE(res);
  1497. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1498. }
  1499. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1500. // Server::read_content() keeps a FormFields::iterator alive across the
  1501. // content callbacks that fill the part it points at. The container is
  1502. // vector-backed, so a later emplace can reallocate and invalidate an older
  1503. // iterator; 64 parts grow the vector through seven reallocations, which
  1504. // checks that every part's content still lands in its own entry.
  1505. const size_t part_count = 64;
  1506. // One formula for both the parts sent and the values expected back, so the
  1507. // two cannot drift apart.
  1508. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1509. auto content_of = [](size_t i) {
  1510. return std::string(64, static_cast<char>('a' + (i % 26)));
  1511. };
  1512. Server svr;
  1513. std::vector<std::pair<std::string, std::string>> received;
  1514. svr.Post("/many", [&](const Request &req, Response &res) {
  1515. for (const auto &field : req.form.fields) {
  1516. received.emplace_back(field.first, field.second.content);
  1517. }
  1518. res.set_content("ok", "text/plain");
  1519. });
  1520. auto port = svr.bind_to_any_port(HOST);
  1521. thread t = thread([&] { svr.listen_after_bind(); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. t.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. UploadFormDataItems items;
  1529. for (size_t i = 0; i < part_count; i++) {
  1530. items.push_back({name_of(i), content_of(i), "", ""});
  1531. }
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/many", items);
  1534. ASSERT_TRUE(res);
  1535. ASSERT_EQ(part_count, received.size());
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1538. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1539. }
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1542. string content_type = "multipart/form-data; boundary=something";
  1543. string boundary;
  1544. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1545. EXPECT_TRUE(ret);
  1546. EXPECT_EQ(boundary, "something");
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1549. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1556. string content_type =
  1557. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1572. const string boundary(70, 'a');
  1573. string content_type = "multipart/form-data; boundary=" + boundary;
  1574. string parsed;
  1575. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(parsed, boundary);
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1580. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1581. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_FALSE(ret);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1587. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1588. // is 72 characters on the wire and still valid.
  1589. const string boundary(70, 'a');
  1590. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1591. string parsed;
  1592. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1593. EXPECT_EQ(parsed, boundary);
  1594. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1595. parsed.clear();
  1596. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1597. }
  1598. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1599. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1600. // The parameter parser must not treat that '=' as the key/value separator.
  1601. string content_type =
  1602. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1603. "charset=UTF-8";
  1604. string parsed;
  1605. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1606. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1607. }
  1608. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1609. // A ';' inside the quoted-string is part of the value, not a parameter
  1610. // separator, so it must not truncate the boundary.
  1611. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "a;b");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1617. string parsed;
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1620. EXPECT_EQ("a\\b", parsed);
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(
  1622. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1623. EXPECT_EQ("a\"b", parsed);
  1624. }
  1625. TEST(ParseDispositionParamsTest, QuotedValues) {
  1626. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1627. // ';' and '=' are ordinary characters inside one.
  1628. struct {
  1629. const char *value;
  1630. std::vector<std::pair<const char *, const char *>> expected;
  1631. } cases[] = {
  1632. {"name=\"file1\"; filename=\"a.txt\"",
  1633. {{"name", "file1"}, {"filename", "a.txt"}}},
  1634. // Whitespace around '=' and ';' is still trimmed
  1635. {"name=\"file2\" ;filename = \"a.html\"",
  1636. {{"name", "file2"}, {"filename", "a.html"}}},
  1637. // '=' inside the value used to leave only the text after the last one
  1638. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1639. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1640. {"name=\"x=y\"", {{"name", "x=y"}}},
  1641. // ';' inside the value used to truncate the pair and leave a bogus one
  1642. {"name=\"file3\"; filename=\"a;b.txt\"",
  1643. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1644. // An unquoted value keeps working, and so does filename*
  1645. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1646. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1647. // A parameter with no key is dropped rather than turned into one whose
  1648. // key is the value
  1649. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1650. // An escaped quote does not end the value
  1651. {"name=\"a\\\"; filename=evil.php\"",
  1652. {{"name", "a\"; filename=evil.php"}}},
  1653. // Other backslashes, as in a Windows path, are kept
  1654. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1655. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1656. };
  1657. for (const auto &c : cases) {
  1658. Params params;
  1659. detail::parse_disposition_params(c.value, params);
  1660. for (const auto &kv : c.expected) {
  1661. auto it = params.find(kv.first);
  1662. ASSERT_NE(it, params.end())
  1663. << "value: " << c.value << ", key: " << kv.first;
  1664. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1665. }
  1666. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1667. }
  1668. }
  1669. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1670. Server svr;
  1671. std::string filename;
  1672. std::string content;
  1673. svr.Post("/upload", [&](const Request &req, Response &) {
  1674. const auto &file = req.form.get_file("file");
  1675. filename = file.filename;
  1676. content = file.content;
  1677. });
  1678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1679. auto se = detail::scope_exit([&] {
  1680. svr.stop();
  1681. thread.join();
  1682. ASSERT_FALSE(svr.is_running());
  1683. });
  1684. svr.wait_until_ready();
  1685. std::string body = "--B\r\n"
  1686. "Content-Disposition: form-data; name=\"file\"; "
  1687. "filename=\"a.txt\"\r\n"
  1688. "Content-Type: text/plain\r\n"
  1689. "\r\n"
  1690. "hello\r\n"
  1691. "--B--\r\n";
  1692. Client cli(HOST, PORT);
  1693. auto res = cli.Post(
  1694. "/upload",
  1695. [&](size_t offset, DataSink &sink) {
  1696. if (offset < body.size()) {
  1697. sink.write(&body[offset], 1);
  1698. } else {
  1699. sink.done();
  1700. }
  1701. return true;
  1702. },
  1703. "multipart/form-data; boundary=B");
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. EXPECT_EQ(StatusCode::OK_200, res->status);
  1706. EXPECT_EQ("a.txt", filename);
  1707. EXPECT_EQ("hello", content);
  1708. }
  1709. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1710. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1711. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1712. Server svr;
  1713. std::string field_value, file_name, file_filename;
  1714. bool has_field = false, has_file = false;
  1715. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1716. has_field = req.form.has_field("x=y");
  1717. field_value = req.form.get_field("x=y");
  1718. has_file = req.form.has_file("file1");
  1719. const auto &file = req.form.get_file("file1");
  1720. file_name = file.name;
  1721. file_filename = file.filename;
  1722. res.set_content("ok", "text/plain");
  1723. });
  1724. auto port = svr.bind_to_any_port(HOST);
  1725. thread t = thread([&] { svr.listen_after_bind(); });
  1726. auto se = detail::scope_exit([&] {
  1727. svr.stop();
  1728. t.join();
  1729. ASSERT_FALSE(svr.is_running());
  1730. });
  1731. svr.wait_until_ready();
  1732. UploadFormDataItems items = {
  1733. {"x=y", "field-value", "", ""},
  1734. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1735. };
  1736. Client cli(HOST, port);
  1737. auto res = cli.Post("/quoted", items);
  1738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1739. ASSERT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_TRUE(has_field);
  1741. EXPECT_EQ("field-value", field_value);
  1742. EXPECT_TRUE(has_file);
  1743. EXPECT_EQ("file1", file_name);
  1744. EXPECT_EQ("a;b=report.pdf", file_filename);
  1745. }
  1746. TEST(GetHeaderValueTest, DefaultValue) {
  1747. Headers headers = {{"Dummy", "Dummy"}};
  1748. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1749. EXPECT_STREQ("text/plain", val);
  1750. }
  1751. TEST(GetHeaderValueTest, DefaultValueInt) {
  1752. Headers headers = {{"Dummy", "Dummy"}};
  1753. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1754. EXPECT_EQ(100ull, val);
  1755. }
  1756. TEST(GetHeaderValueTest, RegularValue) {
  1757. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1758. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1759. EXPECT_STREQ("text/html", val);
  1760. }
  1761. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1762. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1763. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1764. EXPECT_STREQ("text/html", val);
  1765. }
  1766. TEST(GetHeaderValueTest, SetContent) {
  1767. Response res;
  1768. res.set_content("html", "text/html");
  1769. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1770. res.set_content("text", "text/plain");
  1771. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1772. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1773. }
  1774. TEST(GetHeaderValueTest, RegularValueInt) {
  1775. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1776. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1777. EXPECT_EQ(100ull, val);
  1778. }
  1779. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1780. Headers headers = {{"Content-Length", "x"}};
  1781. auto is_invalid_value = false;
  1782. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1783. is_invalid_value);
  1784. EXPECT_EQ(0ull, val);
  1785. EXPECT_TRUE(is_invalid_value);
  1786. }
  1787. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1788. // An all-digit value that overflows size_t must be reported as invalid, not
  1789. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1790. // a large length to a small one on 32-bit builds, leaving the framing length
  1791. // wrong while is_invalid_value stayed false.
  1792. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1793. auto is_invalid_value = false;
  1794. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1795. is_invalid_value);
  1796. EXPECT_TRUE(is_invalid_value);
  1797. // A well-formed length is unaffected.
  1798. Headers ok = {{"Content-Length", "1234"}};
  1799. is_invalid_value = false;
  1800. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1801. is_invalid_value);
  1802. EXPECT_EQ(1234ull, val);
  1803. EXPECT_FALSE(is_invalid_value);
  1804. }
  1805. TEST(GetHeaderValueTest, Range) {
  1806. {
  1807. Headers headers = {make_range_header({{1, -1}})};
  1808. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1809. EXPECT_STREQ("bytes=1-", val);
  1810. }
  1811. {
  1812. Headers headers = {make_range_header({{-1, 1}})};
  1813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1814. EXPECT_STREQ("bytes=-1", val);
  1815. }
  1816. {
  1817. Headers headers = {make_range_header({{1, 10}})};
  1818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1819. EXPECT_STREQ("bytes=1-10", val);
  1820. }
  1821. {
  1822. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1824. EXPECT_STREQ("bytes=1-10, 100-", val);
  1825. }
  1826. {
  1827. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1829. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1830. }
  1831. {
  1832. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=0-0, -1", val);
  1835. }
  1836. }
  1837. TEST(BearerTokenAuthTest, SchemeValidation) {
  1838. // A value shorter than "Bearer " must not throw from the fixed-length
  1839. // substr, and a non-Bearer scheme must not be reported as a token.
  1840. struct {
  1841. const char *value;
  1842. const char *expected;
  1843. } cases[] = {
  1844. {"x", ""},
  1845. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1846. {"Bearer abc123", "abc123"},
  1847. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1848. };
  1849. for (const auto &c : cases) {
  1850. Request req;
  1851. req.set_header("Authorization", c.value);
  1852. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1853. }
  1854. }
  1855. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1856. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1857. // to depend on the standard library (libstdc++ handed back duplicates in
  1858. // reverse insertion order, libc++ in insertion order).
  1859. Request req;
  1860. req.set_header("Accept-Encoding", "gzip");
  1861. req.set_header("Accept-Encoding", "deflate");
  1862. req.set_header("Accept-Encoding", "br");
  1863. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1864. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1866. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1867. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1868. }
  1869. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1870. Request req;
  1871. req.set_header("X-Test", "only");
  1872. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1873. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1875. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1876. }
  1877. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-First", "1");
  1880. req.set_header("X-Test", "2");
  1881. req.params.emplace("first", "1");
  1882. req.params.emplace("test", "2");
  1883. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1884. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1885. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1886. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1887. // The second one is negative when read as a signed value
  1888. const auto max_id = (std::numeric_limits<size_t>::max)();
  1889. for (auto id : {max_id / 2, max_id}) {
  1890. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1891. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1892. EXPECT_EQ("", req.get_param_value("test", id));
  1893. EXPECT_EQ("", req.form.get_field("test", id));
  1894. EXPECT_EQ("", req.form.get_file("test", id).content);
  1895. }
  1896. }
  1897. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1898. Headers headers;
  1899. headers.emplace("Host", "example.com");
  1900. headers.emplace("Accept-Encoding", "gzip");
  1901. headers.emplace("User-Agent", "test");
  1902. headers.emplace("Accept-Encoding", "deflate");
  1903. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1904. "Accept-Encoding=deflate ",
  1905. entries_to_string(headers));
  1906. }
  1907. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1908. Headers headers = {{"Content-Type", "text/html"},
  1909. {"CONTENT-TYPE", "text/xml"}};
  1910. EXPECT_EQ(2U, headers.count("content-type"));
  1911. auto it = headers.find("content-type");
  1912. ASSERT_TRUE(it != headers.end());
  1913. EXPECT_EQ("text/html", it->second);
  1914. }
  1915. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1916. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1917. // drop only those fields and leave everything positioned between them.
  1918. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1919. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1920. auto rng = headers.equal_range("a");
  1921. headers.erase(rng.first, rng.second);
  1922. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1923. }
  1924. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1925. Headers headers = {
  1926. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1927. EXPECT_EQ(3U, headers.erase("A"));
  1928. EXPECT_EQ(0U, headers.count("A"));
  1929. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1932. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1933. headers.emplace_front("Host", "example.com");
  1934. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1935. entries_to_string(headers));
  1936. }
  1937. TEST(ParseHeaderValueTest, Range) {
  1938. {
  1939. Ranges ranges;
  1940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1941. EXPECT_TRUE(ret);
  1942. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1943. }
  1944. {
  1945. Ranges ranges;
  1946. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1947. EXPECT_TRUE(ret);
  1948. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1949. }
  1950. {
  1951. Ranges ranges;
  1952. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1953. EXPECT_TRUE(ret);
  1954. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1955. }
  1956. {
  1957. Ranges ranges;
  1958. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1959. EXPECT_FALSE(ret);
  1960. }
  1961. {
  1962. Ranges ranges;
  1963. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1964. EXPECT_TRUE(ret);
  1965. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1966. }
  1967. {
  1968. Ranges ranges;
  1969. auto ret =
  1970. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1971. EXPECT_TRUE(ret);
  1972. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1977. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1978. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1979. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1980. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1981. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1982. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1983. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1989. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1990. EXPECT_FALSE(
  1991. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1992. EXPECT_TRUE(ranges.empty());
  1993. }
  1994. {
  1995. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1996. // remainder of the representation, so it stays accepted.
  1997. Ranges ranges;
  1998. auto ret =
  1999. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2000. EXPECT_TRUE(ret);
  2001. ASSERT_EQ(1u, ranges.size());
  2002. EXPECT_EQ(0, ranges[0].first);
  2003. EXPECT_EQ(-1, ranges[0].second);
  2004. }
  2005. // RFC 9110 14.1: range unit names are case-insensitive.
  2006. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2007. Ranges ranges;
  2008. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2009. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2010. }
  2011. }
  2012. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2013. Request req;
  2014. req.set_header("Accept-Encoding", "gzip");
  2015. Response res;
  2016. res.set_header("Content-Type", "text/plain");
  2017. auto ret = detail::encoding_type(req, res);
  2018. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2019. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2020. #else
  2021. EXPECT_TRUE(ret == detail::EncodingType::None);
  2022. #endif
  2023. }
  2024. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2025. Request req;
  2026. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2027. Response res;
  2028. res.set_header("Content-Type", "text/plain");
  2029. auto ret = detail::encoding_type(req, res);
  2030. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2031. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2032. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2036. #else
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. #endif
  2039. }
  2040. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2041. Request req;
  2042. req.set_header("Accept-Encoding",
  2043. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2044. Response res;
  2045. res.set_header("Content-Type", "text/plain");
  2046. auto ret = detail::encoding_type(req, res);
  2047. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2048. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2049. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2050. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2051. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2052. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2053. #else
  2054. EXPECT_TRUE(ret == detail::EncodingType::None);
  2055. #endif
  2056. }
  2057. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2058. // All supported encodings rejected with q=0 should return None
  2059. Request req;
  2060. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2061. Response res;
  2062. res.set_header("Content-Type", "text/plain");
  2063. auto ret = detail::encoding_type(req, res);
  2064. EXPECT_TRUE(ret == detail::EncodingType::None);
  2065. }
  2066. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2067. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2068. Request req;
  2069. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2070. Response res;
  2071. res.set_header("Content-Type", "text/plain");
  2072. auto ret = detail::encoding_type(req, res);
  2073. EXPECT_TRUE(ret == detail::EncodingType::None);
  2074. }
  2075. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2076. Request req;
  2077. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2078. Response res;
  2079. res.set_header("Content-Type", "text/plain");
  2080. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2081. }
  2082. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2083. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2092. // RFC 7231: Accept-Encoding values are case-insensitive
  2093. Request req;
  2094. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2095. Response res;
  2096. res.set_header("Content-Type", "text/plain");
  2097. auto ret = detail::encoding_type(req, res);
  2098. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2100. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2101. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2102. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2103. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2104. #else
  2105. EXPECT_TRUE(ret == detail::EncodingType::None);
  2106. #endif
  2107. }
  2108. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2109. // q value should determine priority, not hardcoded order
  2110. Request req;
  2111. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2112. Response res;
  2113. res.set_header("Content-Type", "text/plain");
  2114. auto ret = detail::encoding_type(req, res);
  2115. // gzip has highest q=1.0, so it should be selected even though
  2116. // br and zstd are also supported
  2117. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2118. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2119. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2120. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2121. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2122. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2123. #else
  2124. EXPECT_TRUE(ret == detail::EncodingType::None);
  2125. #endif
  2126. }
  2127. TEST(BufferStreamTest, read) {
  2128. detail::BufferStream strm1;
  2129. Stream &strm = strm1;
  2130. EXPECT_EQ(5, strm.write("hello"));
  2131. char buf[512];
  2132. EXPECT_EQ(2, strm.read(buf, 2));
  2133. EXPECT_EQ('h', buf[0]);
  2134. EXPECT_EQ('e', buf[1]);
  2135. EXPECT_EQ(2, strm.read(buf, 2));
  2136. EXPECT_EQ('l', buf[0]);
  2137. EXPECT_EQ('l', buf[1]);
  2138. EXPECT_EQ(1, strm.read(buf, 1));
  2139. EXPECT_EQ('o', buf[0]);
  2140. EXPECT_EQ(0, strm.read(buf, 1));
  2141. }
  2142. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2143. auto host = "www.httpwatch.com";
  2144. auto ip = hosted_at(host);
  2145. EXPECT_EQ("23.96.13.243", ip);
  2146. std::vector<std::string> addrs;
  2147. hosted_at(host, addrs);
  2148. EXPECT_EQ(1u, addrs.size());
  2149. }
  2150. #if 0 // It depends on each test environment...
  2151. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2152. auto host = "www.youtube.com";
  2153. std::vector<std::string> addrs;
  2154. hosted_at(host, addrs);
  2155. EXPECT_EQ(20u, addrs.size());
  2156. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2157. EXPECT_TRUE(it != addrs.end());
  2158. }
  2159. #endif
  2160. class ChunkedEncodingTest : public ::testing::Test {
  2161. protected:
  2162. ChunkedEncodingTest()
  2163. : cli_(HOST, PORT)
  2164. #ifdef CPPHTTPLIB_SSL_ENABLED
  2165. ,
  2166. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2167. #endif
  2168. {
  2169. cli_.set_connection_timeout(2);
  2170. #ifdef CPPHTTPLIB_SSL_ENABLED
  2171. cli_.enable_server_certificate_verification(false);
  2172. #endif
  2173. }
  2174. virtual void SetUp() {
  2175. read_file("./image.jpg", image_data_);
  2176. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2177. res.set_content("Hello World!", "text/plain");
  2178. });
  2179. svr_.Get(
  2180. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2181. res.set_chunked_content_provider(
  2182. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2183. size_t remaining = image_data_.size() - offset;
  2184. if (remaining == 0) {
  2185. sink.done();
  2186. } else {
  2187. constexpr size_t CHUNK_SIZE = 1024;
  2188. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2189. sink.write(&image_data_[offset], send_size);
  2190. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2191. }
  2192. return true;
  2193. });
  2194. });
  2195. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2196. svr_.wait_until_ready();
  2197. }
  2198. virtual void TearDown() {
  2199. svr_.stop();
  2200. if (!request_threads_.empty()) {
  2201. std::this_thread::sleep_for(std::chrono::seconds(1));
  2202. for (auto &t : request_threads_) {
  2203. t.join();
  2204. }
  2205. }
  2206. t_.join();
  2207. }
  2208. #ifdef CPPHTTPLIB_SSL_ENABLED
  2209. SSLClient cli_;
  2210. SSLServer svr_;
  2211. #else
  2212. Client cli_;
  2213. Server svr_;
  2214. #endif
  2215. thread t_;
  2216. std::vector<thread> request_threads_;
  2217. std::string image_data_;
  2218. };
  2219. TEST_F(ChunkedEncodingTest, NormalGet) {
  2220. auto res = cli_.Get("/chunked");
  2221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2222. std::string out;
  2223. read_file("./image.jpg", out);
  2224. EXPECT_EQ(StatusCode::OK_200, res->status);
  2225. EXPECT_EQ(out, res->body);
  2226. }
  2227. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2228. std::string body;
  2229. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2230. body.append(data, data_length);
  2231. return true;
  2232. });
  2233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2234. std::string out;
  2235. read_file("./image.jpg", out);
  2236. EXPECT_EQ(StatusCode::OK_200, res->status);
  2237. EXPECT_EQ(out, body);
  2238. }
  2239. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2240. std::string body;
  2241. auto res = cli_.Get(
  2242. "/chunked",
  2243. [&](const Response &response) {
  2244. EXPECT_EQ(StatusCode::OK_200, response.status);
  2245. return true;
  2246. },
  2247. [&](const char *data, size_t data_length) {
  2248. body.append(data, data_length);
  2249. return true;
  2250. });
  2251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2252. std::string out;
  2253. read_file("./image.jpg", out);
  2254. EXPECT_EQ(StatusCode::OK_200, res->status);
  2255. EXPECT_EQ(out, body);
  2256. }
  2257. TEST(RangeTest, FromHTTPBin_Online) {
  2258. auto host = "httpbingo.org";
  2259. auto path = std::string{"/range/32"};
  2260. #ifdef CPPHTTPLIB_SSL_ENABLED
  2261. auto port = 443;
  2262. SSLClient cli(host, port);
  2263. #else
  2264. auto port = 80;
  2265. Client cli(host, port);
  2266. #endif
  2267. cli.set_connection_timeout(5);
  2268. {
  2269. auto res = cli.Get(path);
  2270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2271. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2272. EXPECT_EQ(StatusCode::OK_200, res->status);
  2273. }
  2274. {
  2275. Headers headers = {make_range_header({{1, -1}})};
  2276. auto res = cli.Get(path, headers);
  2277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2278. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2280. }
  2281. {
  2282. Headers headers = {make_range_header({{1, 10}})};
  2283. auto res = cli.Get(path, headers);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("bcdefghijk", res->body);
  2286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2287. }
  2288. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2289. // entire resource, while the original httpbin returned 200. Both are
  2290. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2291. {
  2292. Headers headers = {make_range_header({{0, 31}})};
  2293. auto res = cli.Get(path, headers);
  2294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2295. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2296. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2297. res->status == StatusCode::PartialContent_206);
  2298. }
  2299. {
  2300. Headers headers = {make_range_header({{0, -1}})};
  2301. auto res = cli.Get(path, headers);
  2302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2304. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2305. res->status == StatusCode::PartialContent_206);
  2306. }
  2307. // go-httpbin returns 206 with clamped range for over-range requests,
  2308. // while the original httpbin returned 416. Both behaviors are observed
  2309. // in real servers, so we only verify the request succeeds.
  2310. {
  2311. Headers headers = {make_range_header({{0, 32}})};
  2312. auto res = cli.Get(path, headers);
  2313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2314. }
  2315. }
  2316. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2317. auto host = "unresolvableaddress.local";
  2318. auto path = std::string{"/"};
  2319. #ifdef CPPHTTPLIB_SSL_ENABLED
  2320. auto port = 443;
  2321. SSLClient cli(host, port);
  2322. #else
  2323. auto port = 80;
  2324. Client cli(host, port);
  2325. #endif
  2326. cli.set_connection_timeout(1);
  2327. {
  2328. auto res = cli.Get(path);
  2329. ASSERT_FALSE(res);
  2330. }
  2331. std::this_thread::sleep_for(std::chrono::seconds(8));
  2332. }
  2333. #if defined(__linux__) && defined(__GLIBC__) && \
  2334. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2335. // Forward declaration: in split builds split.py strips `inline` and moves the
  2336. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2337. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2338. // against the symbol in both header-only and split builds.
  2339. namespace httplib {
  2340. namespace detail {
  2341. int getaddrinfo_with_timeout(const char *node, const char *service,
  2342. const struct addrinfo *hints,
  2343. struct addrinfo **res, time_t timeout_sec);
  2344. } // namespace detail
  2345. } // namespace httplib
  2346. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2347. //
  2348. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2349. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2350. // gai_suspend() call hits the connection timeout the function calls
  2351. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2352. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2353. // still alive and still references the now-destroyed stack frame.
  2354. //
  2355. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2356. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2357. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2358. // and runs them in a container.
  2359. namespace {
  2360. bool should_run_issue_2431_tests() {
  2361. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2362. return v && *v && std::string(v) != "0";
  2363. }
  2364. std::string unique_unresolvable_host(int n) {
  2365. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2366. // glibc still asks the configured nameserver — which is exactly the path
  2367. // we want to exercise. A unique label per call avoids the resolver cache.
  2368. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2369. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2370. std::to_string(n) + ".invalid";
  2371. }
  2372. } // namespace
  2373. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2374. if (!should_run_issue_2431_tests()) {
  2375. GTEST_SKIP()
  2376. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2377. }
  2378. for (int i = 0; i < 8; ++i) {
  2379. struct addrinfo hints;
  2380. memset(&hints, 0, sizeof(hints));
  2381. hints.ai_family = AF_UNSPEC;
  2382. hints.ai_socktype = SOCK_STREAM;
  2383. auto host = unique_unresolvable_host(i);
  2384. struct addrinfo *result = nullptr;
  2385. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2386. &result, /*timeout_sec=*/1);
  2387. if (rc == 0 && result) { freeaddrinfo(result); }
  2388. }
  2389. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2390. // stack region they still believe holds their gaicb.
  2391. std::this_thread::sleep_for(std::chrono::seconds(3));
  2392. }
  2393. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2394. if (!should_run_issue_2431_tests()) {
  2395. GTEST_SKIP()
  2396. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2397. }
  2398. std::atomic<bool> stop{false};
  2399. std::vector<std::thread> threads;
  2400. for (int t = 0; t < 8; ++t) {
  2401. threads.emplace_back([t, &stop] {
  2402. int i = 0;
  2403. while (!stop.load(std::memory_order_relaxed)) {
  2404. struct addrinfo hints;
  2405. memset(&hints, 0, sizeof(hints));
  2406. hints.ai_family = AF_UNSPEC;
  2407. hints.ai_socktype = SOCK_STREAM;
  2408. auto host = unique_unresolvable_host(t * 100000 + i++);
  2409. struct addrinfo *result = nullptr;
  2410. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2411. &result, /*timeout_sec=*/1);
  2412. if (rc == 0 && result) { freeaddrinfo(result); }
  2413. }
  2414. });
  2415. }
  2416. std::this_thread::sleep_for(std::chrono::seconds(8));
  2417. stop.store(true, std::memory_order_relaxed);
  2418. for (auto &th : threads) {
  2419. th.join();
  2420. }
  2421. std::this_thread::sleep_for(std::chrono::seconds(3));
  2422. }
  2423. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2424. if (!should_run_issue_2431_tests()) {
  2425. GTEST_SKIP()
  2426. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2427. }
  2428. std::atomic<bool> stop{false};
  2429. std::vector<std::thread> threads;
  2430. for (int t = 0; t < 8; ++t) {
  2431. threads.emplace_back([t, &stop] {
  2432. int i = 0;
  2433. while (!stop.load(std::memory_order_relaxed)) {
  2434. auto host = unique_unresolvable_host(t * 100000 + i++);
  2435. Client cli(host, 80);
  2436. cli.set_connection_timeout(1, 0);
  2437. cli.set_read_timeout(1, 0);
  2438. cli.set_write_timeout(1, 0);
  2439. (void)cli.Get("/");
  2440. }
  2441. });
  2442. }
  2443. std::this_thread::sleep_for(std::chrono::seconds(8));
  2444. stop.store(true, std::memory_order_relaxed);
  2445. for (auto &th : threads) {
  2446. th.join();
  2447. }
  2448. std::this_thread::sleep_for(std::chrono::seconds(3));
  2449. }
  2450. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2451. TEST(ConnectionErrorTest, InvalidHost) {
  2452. auto host = "-abcde.com";
  2453. #ifdef CPPHTTPLIB_SSL_ENABLED
  2454. auto port = 443;
  2455. SSLClient cli(host, port);
  2456. #else
  2457. auto port = 80;
  2458. Client cli(host, port);
  2459. #endif
  2460. cli.set_connection_timeout(std::chrono::seconds(2));
  2461. auto res = cli.Get("/");
  2462. ASSERT_TRUE(!res);
  2463. EXPECT_EQ(Error::Connection, res.error());
  2464. }
  2465. TEST(ConnectionErrorTest, InvalidHost2) {
  2466. auto host = "httpcan.org/";
  2467. #ifdef CPPHTTPLIB_SSL_ENABLED
  2468. SSLClient cli(host);
  2469. #else
  2470. Client cli(host);
  2471. #endif
  2472. cli.set_connection_timeout(std::chrono::seconds(2));
  2473. auto res = cli.Get("/");
  2474. ASSERT_TRUE(!res);
  2475. EXPECT_EQ(Error::Connection, res.error());
  2476. }
  2477. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2478. auto host = "httpcan.org/";
  2479. #ifdef CPPHTTPLIB_SSL_ENABLED
  2480. SSLClient cli(host);
  2481. #else
  2482. Client cli(host);
  2483. #endif
  2484. cli.set_connection_timeout(std::chrono::seconds(2));
  2485. auto res = cli.Get("/");
  2486. ASSERT_TRUE(!res);
  2487. stringstream s;
  2488. s << "error code: " << res.error();
  2489. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2490. }
  2491. TEST(ConnectionErrorTest, InvalidPort) {
  2492. auto host = "localhost";
  2493. auto port = 44380;
  2494. #ifdef CPPHTTPLIB_SSL_ENABLED
  2495. SSLClient cli(host, port);
  2496. #else
  2497. Client cli(host, port);
  2498. #endif
  2499. cli.set_connection_timeout(std::chrono::seconds(2));
  2500. auto res = cli.Get("/");
  2501. ASSERT_TRUE(!res);
  2502. EXPECT_TRUE(Error::Connection == res.error() ||
  2503. Error::ConnectionTimeout == res.error());
  2504. }
  2505. TEST(ConnectionErrorTest, Timeout_Online) {
  2506. auto host = "google.com";
  2507. #ifdef CPPHTTPLIB_SSL_ENABLED
  2508. auto port = 44380;
  2509. SSLClient cli(host, port);
  2510. #else
  2511. auto port = 8080;
  2512. Client cli(host, port);
  2513. #endif
  2514. cli.set_connection_timeout(std::chrono::seconds(2));
  2515. // only probe one address type so that the error reason
  2516. // correlates to the timed-out IPv4, not the unsupported
  2517. // IPv6 connection attempt
  2518. cli.set_address_family(AF_INET);
  2519. auto res = cli.Get("/");
  2520. ASSERT_TRUE(!res);
  2521. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2522. }
  2523. TEST(CancelTest, NoCancel_Online) {
  2524. auto host = "httpbingo.org";
  2525. auto path = std::string{"/range/32"};
  2526. #ifdef CPPHTTPLIB_SSL_ENABLED
  2527. auto port = 443;
  2528. SSLClient cli(host, port);
  2529. #else
  2530. auto port = 80;
  2531. Client cli(host, port);
  2532. #endif
  2533. cli.set_connection_timeout(std::chrono::seconds(5));
  2534. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2536. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2537. EXPECT_EQ(StatusCode::OK_200, res->status);
  2538. }
  2539. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2540. // Use /bytes with a large payload so that the DownloadProgress callback
  2541. // (which only fires for Content-Length responses) is invoked before the
  2542. // entire body is received, giving cancellation a chance to fire.
  2543. auto host = "httpbingo.org";
  2544. auto path = std::string{"/bytes/524288"};
  2545. #ifdef CPPHTTPLIB_SSL_ENABLED
  2546. auto port = 443;
  2547. SSLClient cli(host, port);
  2548. #else
  2549. auto port = 80;
  2550. Client cli(host, port);
  2551. #endif
  2552. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2553. cli.set_connection_timeout(std::chrono::seconds(5));
  2554. ASSERT_TRUE(!res);
  2555. EXPECT_EQ(Error::Canceled, res.error());
  2556. }
  2557. TEST(CancelTest, WithCancelLargePayload_Online) {
  2558. auto host = "httpbingo.org";
  2559. auto path = std::string{"/bytes/524288"};
  2560. #ifdef CPPHTTPLIB_SSL_ENABLED
  2561. auto port = 443;
  2562. SSLClient cli(host, port);
  2563. #else
  2564. auto port = 80;
  2565. Client cli(host, port);
  2566. #endif
  2567. cli.set_connection_timeout(std::chrono::seconds(5));
  2568. uint32_t count = 0;
  2569. auto res =
  2570. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2571. ASSERT_TRUE(!res);
  2572. EXPECT_EQ(Error::Canceled, res.error());
  2573. }
  2574. TEST(CancelTest, NoCancelPost) {
  2575. Server svr;
  2576. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2577. res.set_content("Hello World!", "text/plain");
  2578. });
  2579. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2580. auto se = detail::scope_exit([&] {
  2581. svr.stop();
  2582. thread.join();
  2583. ASSERT_FALSE(svr.is_running());
  2584. });
  2585. svr.wait_until_ready();
  2586. Client cli(HOST, PORT);
  2587. cli.set_connection_timeout(std::chrono::seconds(5));
  2588. auto res =
  2589. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2590. "application/json", [](uint64_t, uint64_t) { return true; });
  2591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2592. EXPECT_EQ("Hello World!", res->body);
  2593. EXPECT_EQ(StatusCode::OK_200, res->status);
  2594. }
  2595. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2596. Server svr;
  2597. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2598. res.set_content("Hello World!", "text/plain");
  2599. });
  2600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2601. auto se = detail::scope_exit([&] {
  2602. svr.stop();
  2603. thread.join();
  2604. ASSERT_FALSE(svr.is_running());
  2605. });
  2606. svr.wait_until_ready();
  2607. Client cli(HOST, PORT);
  2608. cli.set_connection_timeout(std::chrono::seconds(5));
  2609. auto res =
  2610. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2611. "application/json", [](uint64_t, uint64_t) { return false; });
  2612. ASSERT_TRUE(!res);
  2613. EXPECT_EQ(Error::Canceled, res.error());
  2614. }
  2615. TEST(CancelTest, WithCancelLargePayloadPost) {
  2616. Server svr;
  2617. svr.set_payload_max_length(200 * 1024 * 1024);
  2618. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2619. res.set_content(LARGE_DATA, "text/plain");
  2620. });
  2621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2622. auto se = detail::scope_exit([&] {
  2623. svr.stop();
  2624. thread.join();
  2625. ASSERT_FALSE(svr.is_running());
  2626. });
  2627. svr.wait_until_ready();
  2628. Client cli(HOST, PORT);
  2629. cli.set_payload_max_length(200 * 1024 * 1024);
  2630. cli.set_connection_timeout(std::chrono::seconds(5));
  2631. auto res =
  2632. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2633. "application/json", [](uint64_t, uint64_t) { return false; });
  2634. ASSERT_TRUE(!res);
  2635. EXPECT_EQ(Error::Canceled, res.error());
  2636. }
  2637. TEST(CancelTest, NoCancelPut) {
  2638. Server svr;
  2639. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2640. res.set_content("Hello World!", "text/plain");
  2641. });
  2642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2643. auto se = detail::scope_exit([&] {
  2644. svr.stop();
  2645. thread.join();
  2646. ASSERT_FALSE(svr.is_running());
  2647. });
  2648. svr.wait_until_ready();
  2649. Client cli(HOST, PORT);
  2650. cli.set_connection_timeout(std::chrono::seconds(5));
  2651. auto res =
  2652. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2653. "application/json", [](uint64_t, uint64_t) { return true; });
  2654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2655. EXPECT_EQ("Hello World!", res->body);
  2656. EXPECT_EQ(StatusCode::OK_200, res->status);
  2657. }
  2658. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2659. Server svr;
  2660. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2661. res.set_content("Hello World!", "text/plain");
  2662. });
  2663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2664. auto se = detail::scope_exit([&] {
  2665. svr.stop();
  2666. thread.join();
  2667. ASSERT_FALSE(svr.is_running());
  2668. });
  2669. svr.wait_until_ready();
  2670. Client cli(HOST, PORT);
  2671. cli.set_connection_timeout(std::chrono::seconds(5));
  2672. auto res =
  2673. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2674. "application/json", [](uint64_t, uint64_t) { return false; });
  2675. ASSERT_TRUE(!res);
  2676. EXPECT_EQ(Error::Canceled, res.error());
  2677. }
  2678. TEST(CancelTest, WithCancelLargePayloadPut) {
  2679. Server svr;
  2680. svr.set_payload_max_length(200 * 1024 * 1024);
  2681. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2682. res.set_content(LARGE_DATA, "text/plain");
  2683. });
  2684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2685. auto se = detail::scope_exit([&] {
  2686. svr.stop();
  2687. thread.join();
  2688. ASSERT_FALSE(svr.is_running());
  2689. });
  2690. svr.wait_until_ready();
  2691. Client cli(HOST, PORT);
  2692. cli.set_payload_max_length(200 * 1024 * 1024);
  2693. cli.set_connection_timeout(std::chrono::seconds(5));
  2694. auto res =
  2695. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2696. "application/json", [](uint64_t, uint64_t) { return false; });
  2697. ASSERT_TRUE(!res);
  2698. EXPECT_EQ(Error::Canceled, res.error());
  2699. }
  2700. TEST(CancelTest, NoCancelPatch) {
  2701. Server svr;
  2702. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2703. res.set_content("Hello World!", "text/plain");
  2704. });
  2705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2706. auto se = detail::scope_exit([&] {
  2707. svr.stop();
  2708. thread.join();
  2709. ASSERT_FALSE(svr.is_running());
  2710. });
  2711. svr.wait_until_ready();
  2712. Client cli(HOST, PORT);
  2713. cli.set_connection_timeout(std::chrono::seconds(5));
  2714. auto res =
  2715. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2716. "application/json", [](uint64_t, uint64_t) { return true; });
  2717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2718. EXPECT_EQ("Hello World!", res->body);
  2719. EXPECT_EQ(StatusCode::OK_200, res->status);
  2720. }
  2721. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2722. Server svr;
  2723. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2724. res.set_content("Hello World!", "text/plain");
  2725. });
  2726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2727. auto se = detail::scope_exit([&] {
  2728. svr.stop();
  2729. thread.join();
  2730. ASSERT_FALSE(svr.is_running());
  2731. });
  2732. svr.wait_until_ready();
  2733. Client cli(HOST, PORT);
  2734. cli.set_connection_timeout(std::chrono::seconds(5));
  2735. auto res =
  2736. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2737. "application/json", [](uint64_t, uint64_t) { return false; });
  2738. ASSERT_TRUE(!res);
  2739. EXPECT_EQ(Error::Canceled, res.error());
  2740. }
  2741. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2742. Server svr;
  2743. svr.set_payload_max_length(200 * 1024 * 1024);
  2744. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2745. res.set_content(LARGE_DATA, "text/plain");
  2746. });
  2747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2748. auto se = detail::scope_exit([&] {
  2749. svr.stop();
  2750. thread.join();
  2751. ASSERT_FALSE(svr.is_running());
  2752. });
  2753. svr.wait_until_ready();
  2754. Client cli(HOST, PORT);
  2755. cli.set_payload_max_length(200 * 1024 * 1024);
  2756. cli.set_connection_timeout(std::chrono::seconds(5));
  2757. auto res =
  2758. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2759. "application/json", [](uint64_t, uint64_t) { return false; });
  2760. ASSERT_TRUE(!res);
  2761. EXPECT_EQ(Error::Canceled, res.error());
  2762. }
  2763. TEST(CancelTest, NoCancelDelete) {
  2764. Server svr;
  2765. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2766. res.set_content("Hello World!", "text/plain");
  2767. });
  2768. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2769. auto se = detail::scope_exit([&] {
  2770. svr.stop();
  2771. thread.join();
  2772. ASSERT_FALSE(svr.is_running());
  2773. });
  2774. svr.wait_until_ready();
  2775. Client cli(HOST, PORT);
  2776. cli.set_connection_timeout(std::chrono::seconds(5));
  2777. auto res =
  2778. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2779. "application/json", [](uint64_t, uint64_t) { return true; });
  2780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2781. EXPECT_EQ("Hello World!", res->body);
  2782. EXPECT_EQ(StatusCode::OK_200, res->status);
  2783. }
  2784. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2785. Server svr;
  2786. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2787. res.set_content("Hello World!", "text/plain");
  2788. });
  2789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2790. auto se = detail::scope_exit([&] {
  2791. svr.stop();
  2792. thread.join();
  2793. ASSERT_FALSE(svr.is_running());
  2794. });
  2795. svr.wait_until_ready();
  2796. Client cli(HOST, PORT);
  2797. cli.set_connection_timeout(std::chrono::seconds(5));
  2798. auto res =
  2799. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2800. "application/json", [](uint64_t, uint64_t) { return false; });
  2801. ASSERT_TRUE(!res);
  2802. EXPECT_EQ(Error::Canceled, res.error());
  2803. }
  2804. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2805. Server svr;
  2806. svr.set_payload_max_length(200 * 1024 * 1024);
  2807. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2808. res.set_content(LARGE_DATA, "text/plain");
  2809. });
  2810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2811. auto se = detail::scope_exit([&] {
  2812. svr.stop();
  2813. thread.join();
  2814. ASSERT_FALSE(svr.is_running());
  2815. });
  2816. svr.wait_until_ready();
  2817. Client cli(HOST, PORT);
  2818. cli.set_payload_max_length(200 * 1024 * 1024);
  2819. cli.set_connection_timeout(std::chrono::seconds(5));
  2820. auto res =
  2821. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2822. "application/json", [](uint64_t, uint64_t) { return false; });
  2823. ASSERT_TRUE(!res);
  2824. EXPECT_EQ(Error::Canceled, res.error());
  2825. }
  2826. static std::string remove_whitespace(const std::string &input) {
  2827. std::string output;
  2828. output.reserve(input.size());
  2829. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2830. [](unsigned char c) { return !std::isspace(c); });
  2831. return output;
  2832. }
  2833. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2834. auto host = "httpbingo.org";
  2835. auto path = std::string{"/basic-auth/hello/world"};
  2836. #ifdef CPPHTTPLIB_SSL_ENABLED
  2837. auto port = 443;
  2838. SSLClient cli(host, port);
  2839. #else
  2840. auto port = 80;
  2841. Client cli(host, port);
  2842. #endif
  2843. {
  2844. auto res = cli.Get(path);
  2845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2846. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2847. }
  2848. {
  2849. auto res = cli.Get(
  2850. path, Headers{make_basic_authentication_header("hello", "world")});
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. auto body = remove_whitespace(res->body);
  2853. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2854. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2855. EXPECT_EQ(StatusCode::OK_200, res->status);
  2856. }
  2857. {
  2858. cli.set_basic_auth("hello", "world");
  2859. auto res = cli.Get(path);
  2860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2861. auto body = remove_whitespace(res->body);
  2862. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2863. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2864. EXPECT_EQ(StatusCode::OK_200, res->status);
  2865. }
  2866. {
  2867. cli.set_basic_auth("hello", "bad");
  2868. auto res = cli.Get(path);
  2869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2870. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2871. }
  2872. {
  2873. cli.set_basic_auth("bad", "world");
  2874. auto res = cli.Get(path);
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2877. }
  2878. }
  2879. #ifdef CPPHTTPLIB_SSL_ENABLED
  2880. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2881. auto host = "httpbingo.org";
  2882. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2883. auto paths = std::vector<std::string>{
  2884. "/digest-auth/auth/hello/world/MD5",
  2885. "/digest-auth/auth/hello/world/SHA-256",
  2886. };
  2887. auto port = 443;
  2888. SSLClient cli(host, port);
  2889. {
  2890. auto res = cli.Get(unauth_path);
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2893. }
  2894. {
  2895. cli.set_digest_auth("hello", "world");
  2896. for (const auto &path : paths) {
  2897. auto res = cli.Get(path.c_str());
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. auto body = remove_whitespace(res->body);
  2900. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2901. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2902. EXPECT_EQ(StatusCode::OK_200, res->status);
  2903. }
  2904. cli.set_digest_auth("hello", "bad");
  2905. for (const auto &path : paths) {
  2906. auto res = cli.Get(path.c_str());
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2909. }
  2910. }
  2911. }
  2912. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2913. // comma-separated list of challenges, and each challenge may itself carry a
  2914. // comma-separated auth-param list, so a server can legally offer Basic
  2915. // before Digest, either as two field lines or packed into one. Runs one 401
  2916. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2917. // value() joins them in receipt order) and checks that the retry carries a
  2918. // well-formed Digest Authorization header naming expected_realm.
  2919. static void
  2920. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2921. const std::string &expected_realm) {
  2922. std::atomic<int> hits{0};
  2923. Server svr;
  2924. svr.Get("/x", [&](const Request &req, Response &res) {
  2925. if (++hits == 1) {
  2926. res.status = StatusCode::Unauthorized_401;
  2927. for (const auto &challenge : challenges) {
  2928. res.set_header("WWW-Authenticate", challenge);
  2929. }
  2930. } else {
  2931. auto authorization = req.get_header_value("Authorization");
  2932. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2933. EXPECT_NE(std::string::npos,
  2934. authorization.find("realm=\"" + expected_realm + "\""));
  2935. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2936. res.set_content("ok", "text/plain");
  2937. }
  2938. });
  2939. auto port = svr.bind_to_any_port(HOST);
  2940. std::thread t([&]() { svr.listen_after_bind(); });
  2941. auto se = detail::scope_exit([&] {
  2942. svr.stop();
  2943. t.join();
  2944. });
  2945. svr.wait_until_ready();
  2946. Client cli(HOST, port);
  2947. cli.set_digest_auth("hello", "world");
  2948. auto res = cli.Get("/x");
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. EXPECT_EQ(2, hits.load());
  2951. }
  2952. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2953. static const char *kDigestChallenge =
  2954. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2955. "algorithm=MD5";
  2956. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2957. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2958. "testrealm");
  2959. }
  2960. // Same challenge list with the schemes in the opposite order, to make sure
  2961. // the fix above didn't just special-case "Basic first".
  2962. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2963. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2964. "testrealm");
  2965. }
  2966. // A comma inside a quoted auth-param value must not be mistaken for the
  2967. // separator between two challenges (or two auth-params).
  2968. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2969. run_digest_challenge_list_test(
  2970. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2971. "algorithm=MD5"},
  2972. "test,realm");
  2973. }
  2974. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2975. // the params and leaves out the fragment.
  2976. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2977. Server svr;
  2978. std::string uri, target;
  2979. svr.Get("/a b", [&](const Request &req, Response &res) {
  2980. auto auth = req.get_header_value("Authorization");
  2981. if (auth.empty()) {
  2982. res.status = StatusCode::Unauthorized_401;
  2983. res.set_header("WWW-Authenticate",
  2984. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  2985. return;
  2986. }
  2987. auto b = auth.find("uri=\"") + 5;
  2988. uri = auth.substr(b, auth.find('"', b) - b);
  2989. target = req.target;
  2990. });
  2991. auto port = svr.bind_to_any_port(HOST);
  2992. std::thread t([&]() { svr.listen_after_bind(); });
  2993. auto se = detail::scope_exit([&] {
  2994. svr.stop();
  2995. t.join();
  2996. });
  2997. svr.wait_until_ready();
  2998. Client cli(HOST, port);
  2999. cli.set_digest_auth("hello", "world");
  3000. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3002. EXPECT_EQ("/a%20b?x=1", target);
  3003. EXPECT_EQ(target, uri);
  3004. }
  3005. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3006. // make_digest_authentication_header() dereferences both unconditionally, so
  3007. // a server sending a challenge missing either one must not be treated as
  3008. // usable -- doing so used to crash the client with std::out_of_range.
  3009. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3010. Server svr;
  3011. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3012. res.status = StatusCode::Unauthorized_401;
  3013. res.set_header("WWW-Authenticate", challenge);
  3014. });
  3015. auto port = svr.bind_to_any_port(HOST);
  3016. std::thread t([&]() { svr.listen_after_bind(); });
  3017. auto se = detail::scope_exit([&] {
  3018. svr.stop();
  3019. t.join();
  3020. });
  3021. svr.wait_until_ready();
  3022. Client cli(HOST, port);
  3023. cli.set_digest_auth("hello", "world");
  3024. auto res = cli.Get("/x");
  3025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3026. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3027. }
  3028. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3029. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3030. }
  3031. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3032. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3033. }
  3034. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3035. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3036. }
  3037. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3038. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3039. // when storing the values, so the header builder has to re-escape them (and
  3040. // keep algorithm a bare token); otherwise the value breaks out of its
  3041. // quoted-string and injects extra auth-params into the client's Authorization.
  3042. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3043. std::atomic<int> hits{0};
  3044. std::string authorization;
  3045. Server svr;
  3046. svr.Get("/x", [&](const Request &req, Response &res) {
  3047. if (++hits == 1) {
  3048. res.status = StatusCode::Unauthorized_401;
  3049. // On the wire the quotes embedded in the values are backslash-escaped.
  3050. res.set_header("WWW-Authenticate",
  3051. "Digest realm=\"testrealm\", "
  3052. "nonce=\"n\\\"; injected=\\\"x\", "
  3053. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3054. } else {
  3055. authorization = req.get_header_value("Authorization");
  3056. res.set_content("ok", "text/plain");
  3057. }
  3058. });
  3059. auto port = svr.bind_to_any_port(HOST);
  3060. std::thread t([&]() { svr.listen_after_bind(); });
  3061. auto se = detail::scope_exit([&] {
  3062. svr.stop();
  3063. t.join();
  3064. });
  3065. svr.wait_until_ready();
  3066. Client cli(HOST, port);
  3067. cli.set_digest_auth("hello", "world");
  3068. auto res = cli.Get("/x");
  3069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3070. EXPECT_EQ(2, hits.load());
  3071. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3072. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3073. // inside its quoted-string rather than starting an "injected" auth-param.
  3074. EXPECT_NE(std::string::npos,
  3075. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3076. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3077. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3078. }
  3079. #endif
  3080. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3081. auto host = "google.com";
  3082. auto another_host = "example.com";
  3083. auto wrong_ip = "0.0.0.0";
  3084. #ifdef CPPHTTPLIB_SSL_ENABLED
  3085. SSLClient cli(host);
  3086. #else
  3087. Client cli(host);
  3088. #endif
  3089. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3090. auto res = cli.Get("/");
  3091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3093. }
  3094. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3095. auto host = "google.com";
  3096. auto wrong_ip = "0.0.0.0";
  3097. #ifdef CPPHTTPLIB_SSL_ENABLED
  3098. SSLClient cli(host);
  3099. #else
  3100. Client cli(host);
  3101. #endif
  3102. cli.set_hostname_addr_map({{host, wrong_ip}});
  3103. auto res = cli.Get("/");
  3104. ASSERT_TRUE(!res);
  3105. EXPECT_EQ(Error::Connection, res.error());
  3106. }
  3107. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3108. // A mapped value that is not an IP literal must be resolved. "localhost"
  3109. // resolves from the hosts file, so this test needs no external DNS.
  3110. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3111. auto host = "target.invalid";
  3112. Server svr;
  3113. std::string received_host;
  3114. svr.Get("/hi", [&](const Request &req, Response &res) {
  3115. received_host = req.get_header_value("Host");
  3116. res.set_content("Hello World!", "text/plain");
  3117. });
  3118. auto port = svr.bind_to_any_port(HOST);
  3119. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3120. auto se = detail::scope_exit([&] {
  3121. svr.stop();
  3122. thread.join();
  3123. ASSERT_FALSE(svr.is_running());
  3124. });
  3125. svr.wait_until_ready();
  3126. Client cli(host, port);
  3127. cli.set_hostname_addr_map({{host, HOST}});
  3128. auto res = cli.Get("/hi");
  3129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3130. EXPECT_EQ(StatusCode::OK_200, res->status);
  3131. // The mapping only redirects the connection; the identity stays host_.
  3132. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3133. }
  3134. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3135. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3136. auto host = "target.invalid";
  3137. Server svr;
  3138. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3139. res.set_content("Hello World!", "text/plain");
  3140. });
  3141. auto port = svr.bind_to_any_port("127.0.0.1");
  3142. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3143. auto se = detail::scope_exit([&] {
  3144. svr.stop();
  3145. thread.join();
  3146. ASSERT_FALSE(svr.is_running());
  3147. });
  3148. svr.wait_until_ready();
  3149. Client cli(host, port);
  3150. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3151. auto res = cli.Get("/hi");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. }
  3155. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3156. // An empty mapped value must leave host_ as the connection target. Without
  3157. // that guard the empty value would become the host argument, getaddrinfo
  3158. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3159. // loopback - silently connecting somewhere the caller never asked for.
  3160. // The server listens on loopback, so such a fallback would succeed and is
  3161. // therefore observable as a failure of this test.
  3162. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3163. Server svr;
  3164. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3165. res.set_content("Hello World!", "text/plain");
  3166. });
  3167. auto port = svr.bind_to_any_port(HOST);
  3168. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3169. auto se = detail::scope_exit([&] {
  3170. svr.stop();
  3171. thread.join();
  3172. ASSERT_FALSE(svr.is_running());
  3173. });
  3174. svr.wait_until_ready();
  3175. Client cli(blackhole, port);
  3176. cli.set_hostname_addr_map({{blackhole, ""}});
  3177. cli.set_connection_timeout(1);
  3178. auto res = cli.Get("/hi");
  3179. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3180. }
  3181. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3182. auto host = "httpbingo.org";
  3183. auto path = std::string{"/absolute-redirect/3"};
  3184. #ifdef CPPHTTPLIB_SSL_ENABLED
  3185. SSLClient cli(host);
  3186. #else
  3187. Client cli(host);
  3188. #endif
  3189. cli.set_follow_location(true);
  3190. auto res = cli.Get(path);
  3191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3192. EXPECT_EQ(StatusCode::OK_200, res->status);
  3193. }
  3194. TEST(RedirectTest, Redirect_Online) {
  3195. auto host = "httpbingo.org";
  3196. auto path = std::string{"/redirect/3"};
  3197. #ifdef CPPHTTPLIB_SSL_ENABLED
  3198. SSLClient cli(host);
  3199. #else
  3200. Client cli(host);
  3201. #endif
  3202. cli.set_follow_location(true);
  3203. auto res = cli.Get(path);
  3204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3205. EXPECT_EQ(StatusCode::OK_200, res->status);
  3206. }
  3207. TEST(RelativeRedirectTest, Redirect_Online) {
  3208. auto host = "httpbingo.org";
  3209. auto path = std::string{"/relative-redirect/3"};
  3210. #ifdef CPPHTTPLIB_SSL_ENABLED
  3211. SSLClient cli(host);
  3212. #else
  3213. Client cli(host);
  3214. #endif
  3215. cli.set_follow_location(true);
  3216. auto res = cli.Get(path);
  3217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3218. EXPECT_EQ(StatusCode::OK_200, res->status);
  3219. }
  3220. TEST(TooManyRedirectTest, Redirect_Online) {
  3221. auto host = "httpbingo.org";
  3222. auto path = std::string{"/redirect/21"};
  3223. #ifdef CPPHTTPLIB_SSL_ENABLED
  3224. SSLClient cli(host);
  3225. #else
  3226. Client cli(host);
  3227. #endif
  3228. cli.set_follow_location(true);
  3229. auto res = cli.Get(path);
  3230. ASSERT_TRUE(!res);
  3231. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3232. }
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. TEST(YahooRedirectTest, Redirect_Online) {
  3235. Client cli("yahoo.com");
  3236. auto res = cli.Get("/");
  3237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3238. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3239. cli.set_follow_location(true);
  3240. res = cli.Get("/");
  3241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3244. }
  3245. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3246. #define REDIR_HOST "httpbingo.org"
  3247. #define REDIR_PATH "/redirect-to"
  3248. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3249. SSLClient cli(REDIR_HOST);
  3250. cli.set_follow_location(true);
  3251. auto res =
  3252. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. }
  3256. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3257. SSLClient cli(REDIR_HOST);
  3258. cli.set_follow_location(true);
  3259. Params params;
  3260. params.emplace("url", "http://example.com");
  3261. params.emplace("status_code", "302");
  3262. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3264. EXPECT_EQ(StatusCode::OK_200, res->status);
  3265. }
  3266. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3267. SSLClient cli(REDIR_HOST);
  3268. cli.set_follow_location(true);
  3269. Params params;
  3270. params.emplace("url", "http://example.com");
  3271. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3273. EXPECT_EQ(StatusCode::OK_200, res->status);
  3274. }
  3275. TEST(UrlWithSpace, Redirect_Online) {
  3276. SSLClient cli("edge.forgecdn.net");
  3277. cli.set_follow_location(true);
  3278. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3282. }
  3283. #endif
  3284. #if !defined(_WIN32) && !defined(_WIN64)
  3285. TEST(ReceiveSignals, Signal) {
  3286. auto setupSignalHandlers = []() {
  3287. struct sigaction act;
  3288. sigemptyset(&act.sa_mask);
  3289. act.sa_flags = SA_SIGINFO;
  3290. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3291. switch (sig) {
  3292. case SIGINT:
  3293. default: break;
  3294. }
  3295. };
  3296. ::sigaction(SIGINT, &act, nullptr);
  3297. };
  3298. Server svr;
  3299. int port = 0;
  3300. auto thread = std::thread([&]() {
  3301. setupSignalHandlers();
  3302. port = svr.bind_to_any_port(HOST);
  3303. svr.listen_after_bind();
  3304. });
  3305. auto se = detail::scope_exit([&] {
  3306. svr.stop();
  3307. thread.join();
  3308. ASSERT_FALSE(svr.is_running());
  3309. });
  3310. svr.wait_until_ready();
  3311. ASSERT_TRUE(svr.is_running());
  3312. pthread_kill(thread.native_handle(), SIGINT);
  3313. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3314. ASSERT_TRUE(svr.is_running());
  3315. }
  3316. #endif
  3317. TEST(RedirectToDifferentPort, Redirect) {
  3318. Server svr1;
  3319. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3320. res.set_content("Hello World!", "text/plain");
  3321. });
  3322. int svr1_port = 0;
  3323. auto thread1 = std::thread([&]() {
  3324. svr1_port = svr1.bind_to_any_port(HOST);
  3325. svr1.listen_after_bind();
  3326. });
  3327. Server svr2;
  3328. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3329. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3330. });
  3331. int svr2_port = 0;
  3332. auto thread2 = std::thread([&]() {
  3333. svr2_port = svr2.bind_to_any_port(HOST);
  3334. svr2.listen_after_bind();
  3335. });
  3336. auto se = detail::scope_exit([&] {
  3337. svr2.stop();
  3338. thread2.join();
  3339. svr1.stop();
  3340. thread1.join();
  3341. ASSERT_FALSE(svr2.is_running());
  3342. ASSERT_FALSE(svr1.is_running());
  3343. });
  3344. svr1.wait_until_ready();
  3345. svr2.wait_until_ready();
  3346. Client cli("localhost", svr2_port);
  3347. cli.set_follow_location(true);
  3348. auto res = cli.Get("/2");
  3349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. EXPECT_EQ("Hello World!", res->body);
  3352. }
  3353. // GET /redir on one server redirects to /target on another port, so the
  3354. // client follows it with a new client.
  3355. static Result
  3356. GetThroughRedirectToDifferentPort(Server::Handler target,
  3357. const std::function<void(Client &)> &setup,
  3358. const Headers &headers = Headers()) {
  3359. Server target_svr;
  3360. target_svr.Get("/target", target);
  3361. int target_port = 0;
  3362. auto target_thread = std::thread([&]() {
  3363. target_port = target_svr.bind_to_any_port(HOST);
  3364. target_svr.listen_after_bind();
  3365. });
  3366. Server origin_svr;
  3367. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3368. res.set_redirect(
  3369. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3370. });
  3371. int origin_port = 0;
  3372. auto origin_thread = std::thread([&]() {
  3373. origin_port = origin_svr.bind_to_any_port(HOST);
  3374. origin_svr.listen_after_bind();
  3375. });
  3376. auto se = detail::scope_exit([&] {
  3377. origin_svr.stop();
  3378. origin_thread.join();
  3379. target_svr.stop();
  3380. target_thread.join();
  3381. });
  3382. target_svr.wait_until_ready();
  3383. origin_svr.wait_until_ready();
  3384. Client cli("localhost", origin_port);
  3385. cli.set_follow_location(true);
  3386. setup(cli);
  3387. return cli.Get("/redir", headers);
  3388. }
  3389. static void
  3390. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3391. std::string captured_authorization;
  3392. auto result = GetThroughRedirectToDifferentPort(
  3393. [&](const Request &req, Response &res) {
  3394. captured_authorization = req.get_header_value("Authorization");
  3395. res.set_content("OK", "text/plain");
  3396. },
  3397. set_auth);
  3398. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3399. EXPECT_EQ(StatusCode::OK_200, result->status);
  3400. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3401. EXPECT_TRUE(captured_authorization.empty());
  3402. }
  3403. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3404. TestDoNotForwardCredentialsOnRedirect(
  3405. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3406. }
  3407. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3408. TestDoNotForwardCredentialsOnRedirect(
  3409. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3410. }
  3411. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3412. std::string captured_cookie;
  3413. auto result = GetThroughRedirectToDifferentPort(
  3414. [&](const Request &req, Response &res) {
  3415. captured_cookie = req.get_header_value("Cookie");
  3416. res.set_content("OK", "text/plain");
  3417. },
  3418. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3419. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3420. EXPECT_EQ(StatusCode::OK_200, result->status);
  3421. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3422. EXPECT_TRUE(captured_cookie.empty());
  3423. }
  3424. TEST(RedirectToSamePort, ForwardCookie) {
  3425. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3426. // header so that ordinary session flows keep working.
  3427. Server svr;
  3428. std::string captured_cookie;
  3429. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3430. res.set_redirect("/target", 302);
  3431. });
  3432. svr.Get("/target", [&](const Request &req, Response &res) {
  3433. captured_cookie = req.get_header_value("Cookie");
  3434. res.set_content("OK", "text/plain");
  3435. });
  3436. auto port = svr.bind_to_any_port(HOST);
  3437. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3438. auto se = detail::scope_exit([&] {
  3439. svr.stop();
  3440. thread.join();
  3441. ASSERT_FALSE(svr.is_running());
  3442. });
  3443. svr.wait_until_ready();
  3444. Client cli(HOST, port);
  3445. cli.set_follow_location(true);
  3446. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3447. auto res = cli.Get("/redir", headers);
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3451. }
  3452. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3453. std::string authorization;
  3454. std::string trace_id;
  3455. auto result = GetThroughRedirectToDifferentPort(
  3456. [&](const Request &req, Response &res) {
  3457. authorization = req.get_header_value("Authorization");
  3458. trace_id = req.get_header_value("X-Trace-Id");
  3459. res.set_content("OK", "text/plain");
  3460. },
  3461. [](Client &cli) {
  3462. cli.set_default_headers(
  3463. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3464. });
  3465. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3466. EXPECT_EQ(StatusCode::OK_200, result->status);
  3467. // Like a header given with the request, a default one goes along unless it
  3468. // carries credentials (RFC 9110 15.4).
  3469. EXPECT_TRUE(authorization.empty());
  3470. EXPECT_EQ("42", trace_id);
  3471. }
  3472. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3473. auto result = GetThroughRedirectToDifferentPort(
  3474. [](const Request &, Response &res) {
  3475. res.set_content(std::string(2048, 'x'), "text/plain");
  3476. },
  3477. [](Client &cli) { cli.set_payload_max_length(1024); });
  3478. EXPECT_FALSE(result);
  3479. }
  3480. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3481. auto result = GetThroughRedirectToDifferentPort(
  3482. [](const Request &req, Response &res) {
  3483. // Answer after a second, or once the client gives up.
  3484. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3485. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3486. }
  3487. res.set_content("late", "text/plain");
  3488. },
  3489. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3490. ASSERT_FALSE(result);
  3491. EXPECT_EQ(Error::Read, result.error());
  3492. }
  3493. #ifdef CPPHTTPLIB_SSL_ENABLED
  3494. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3495. auto result = GetThroughRedirectToDifferentPort(
  3496. [](const Request &, Response &res) {
  3497. res.status = StatusCode::Unauthorized_401;
  3498. res.set_header("WWW-Authenticate",
  3499. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3500. },
  3501. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3502. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3503. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3504. }
  3505. #endif
  3506. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3507. Server svr;
  3508. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3509. // Port number that overflows int — should not crash
  3510. res.set_redirect("http://localhost:99999999999999999999/target");
  3511. });
  3512. auto port = svr.bind_to_any_port(HOST);
  3513. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3514. auto se = detail::scope_exit([&] {
  3515. svr.stop();
  3516. thread.join();
  3517. ASSERT_FALSE(svr.is_running());
  3518. });
  3519. svr.wait_until_ready();
  3520. Client cli(HOST, port);
  3521. cli.set_follow_location(true);
  3522. auto res = cli.Get("/redir");
  3523. // Should fail gracefully, not crash (no valid response due to bad port)
  3524. EXPECT_FALSE(res);
  3525. }
  3526. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3527. Server svr;
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3530. // The server's own port followed by junk must not be followed
  3531. res.set_redirect("http://" + std::string(HOST) + ":" +
  3532. std::to_string(port) + "junk/target");
  3533. });
  3534. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3535. res.set_content("target", "text/plain");
  3536. });
  3537. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3538. auto se = detail::scope_exit([&] {
  3539. svr.stop();
  3540. thread.join();
  3541. ASSERT_FALSE(svr.is_running());
  3542. });
  3543. svr.wait_until_ready();
  3544. Client cli(HOST, port);
  3545. cli.set_follow_location(true);
  3546. auto res = cli.Get("/redir");
  3547. EXPECT_FALSE(res);
  3548. }
  3549. TEST(RedirectFromPageWithContent, Redirect) {
  3550. Server svr;
  3551. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3552. res.set_content("___", "text/plain");
  3553. res.set_redirect("/2");
  3554. });
  3555. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3556. res.set_content("Hello World!", "text/plain");
  3557. });
  3558. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3559. auto se = detail::scope_exit([&] {
  3560. svr.stop();
  3561. th.join();
  3562. ASSERT_FALSE(svr.is_running());
  3563. });
  3564. svr.wait_until_ready();
  3565. {
  3566. Client cli("localhost", PORT);
  3567. cli.set_follow_location(true);
  3568. std::string body;
  3569. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3570. body.append(data, data_length);
  3571. return true;
  3572. });
  3573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3574. EXPECT_EQ(StatusCode::OK_200, res->status);
  3575. EXPECT_EQ("Hello World!", body);
  3576. }
  3577. {
  3578. Client cli("localhost", PORT);
  3579. std::string body;
  3580. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3581. body.append(data, data_length);
  3582. return true;
  3583. });
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ(StatusCode::Found_302, res->status);
  3586. EXPECT_EQ("___", body);
  3587. }
  3588. }
  3589. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3590. Server svr;
  3591. auto port_str = std::to_string(PORT);
  3592. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3593. auto expected_host = "[::1]:" + port_str;
  3594. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3595. res.set_content("___", "text/plain");
  3596. // res.set_redirect("/2");
  3597. res.set_redirect(redirect_url);
  3598. });
  3599. svr.Get("/2", [&](const Request &req, Response &res) {
  3600. auto host_header = req.headers.find("Host");
  3601. ASSERT_TRUE(host_header != req.headers.end());
  3602. EXPECT_EQ(expected_host, host_header->second);
  3603. res.set_content("Hello World!", "text/plain");
  3604. });
  3605. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. th.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3612. // actually starts anything, so the condition !svr.is_running() will
  3613. // always remain true, and the loop never stops.
  3614. // This basically counts how many milliseconds have passed since the
  3615. // call to svr.listen(), and if after 5 seconds nothing started yet
  3616. // aborts the test.
  3617. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3618. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3619. ASSERT_LT(milliseconds, 5000U);
  3620. }
  3621. {
  3622. Client cli("::1", PORT);
  3623. cli.set_follow_location(true);
  3624. std::string body;
  3625. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3626. body.append(data, data_length);
  3627. return true;
  3628. });
  3629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3630. EXPECT_EQ(StatusCode::OK_200, res->status);
  3631. EXPECT_EQ("Hello World!", body);
  3632. }
  3633. {
  3634. Client cli("::1", PORT);
  3635. std::string body;
  3636. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3637. body.append(data, data_length);
  3638. return true;
  3639. });
  3640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3641. EXPECT_EQ(StatusCode::Found_302, res->status);
  3642. EXPECT_EQ("___", body);
  3643. }
  3644. }
  3645. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3646. Server svr;
  3647. svr.Get("/foo", [](const Request &req, Response &res) {
  3648. auto a = req.params.find("a");
  3649. if (a != req.params.end()) {
  3650. res.set_content((*a).second, "text/plain");
  3651. res.status = StatusCode::OK_200;
  3652. } else {
  3653. res.status = StatusCode::BadRequest_400;
  3654. }
  3655. });
  3656. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3657. auto se = detail::scope_exit([&] {
  3658. svr.stop();
  3659. thread.join();
  3660. ASSERT_FALSE(svr.is_running());
  3661. });
  3662. svr.wait_until_ready();
  3663. {
  3664. Client cli(HOST, PORT);
  3665. cli.set_path_encode(false);
  3666. auto res = cli.Get("/foo?a=explicitly+encoded");
  3667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3668. EXPECT_EQ(StatusCode::OK_200, res->status);
  3669. // This expects it back with a space, as the `+` won't have been
  3670. // url-encoded, and server-side the params get decoded turning `+`
  3671. // into spaces.
  3672. EXPECT_EQ("explicitly encoded", res->body);
  3673. }
  3674. }
  3675. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3676. // When path encoding is disabled the client must transmit the supplied
  3677. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3678. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3679. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3680. // than a space (0x20). Assert on the raw wire target to catch this.
  3681. Server svr;
  3682. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3683. svr.Get("/foo", [&](const Request &req, Response &res) {
  3684. EXPECT_EQ(expected_target, req.target);
  3685. res.status = StatusCode::OK_200;
  3686. });
  3687. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3688. auto se = detail::scope_exit([&] {
  3689. svr.stop();
  3690. thread.join();
  3691. ASSERT_FALSE(svr.is_running());
  3692. });
  3693. svr.wait_until_ready();
  3694. {
  3695. Client cli(HOST, PORT);
  3696. cli.set_path_encode(false);
  3697. auto res = cli.Get(expected_target.c_str());
  3698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3699. EXPECT_EQ(StatusCode::OK_200, res->status);
  3700. }
  3701. }
  3702. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3703. // `open_stream()` used to skip the path encoding that the buffered send
  3704. // path applies, so the same `path` produced different bytes in the request
  3705. // line depending on which API was used. Assert the two agree.
  3706. Server svr;
  3707. std::string target;
  3708. svr.Get(".*", [&](const Request &req, Response &res) {
  3709. target = req.target;
  3710. res.status = StatusCode::OK_200;
  3711. });
  3712. auto port = svr.bind_to_any_port(HOST);
  3713. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3714. auto se = detail::scope_exit([&] {
  3715. svr.stop();
  3716. thread.join();
  3717. ASSERT_FALSE(svr.is_running());
  3718. });
  3719. svr.wait_until_ready();
  3720. struct {
  3721. const char *path;
  3722. const char *expected;
  3723. } cases[] = {
  3724. {"/a b?x=1", "/a%20b?x=1"},
  3725. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3726. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3727. };
  3728. for (const auto &c : cases) {
  3729. Client cli(HOST, port);
  3730. target.clear();
  3731. auto res = cli.Get(c.path);
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3734. auto buffered_target = target;
  3735. target.clear();
  3736. auto handle = cli.open_stream("GET", c.path);
  3737. EXPECT_TRUE(handle.is_valid())
  3738. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3739. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3740. }
  3741. }
  3742. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3743. // The `set_path_encode(false)` contract — transmit the supplied target
  3744. // verbatim — must hold for the streaming API too.
  3745. Server svr;
  3746. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3747. std::string target;
  3748. svr.Get("/foo", [&](const Request &req, Response &res) {
  3749. target = req.target;
  3750. res.status = StatusCode::OK_200;
  3751. });
  3752. auto port = svr.bind_to_any_port(HOST);
  3753. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3754. auto se = detail::scope_exit([&] {
  3755. svr.stop();
  3756. thread.join();
  3757. ASSERT_FALSE(svr.is_running());
  3758. });
  3759. svr.wait_until_ready();
  3760. {
  3761. Client cli(HOST, port);
  3762. cli.set_path_encode(false);
  3763. auto handle = cli.open_stream("GET", expected_target);
  3764. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3765. EXPECT_EQ(expected_target, target);
  3766. }
  3767. }
  3768. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3769. // With path encoding enabled a CR/LF in the target is percent-encoded
  3770. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3771. // write_request_line still backstops `set_path_encode(false)`, which is
  3772. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3773. Server svr;
  3774. // Captured before routing: the decoded path contains a newline, which a
  3775. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3776. std::string target;
  3777. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3778. target = req.target;
  3779. res.status = StatusCode::OK_200;
  3780. return Server::HandlerResponse::Handled;
  3781. });
  3782. auto port = svr.bind_to_any_port(HOST);
  3783. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3784. auto se = detail::scope_exit([&] {
  3785. svr.stop();
  3786. thread.join();
  3787. ASSERT_FALSE(svr.is_running());
  3788. });
  3789. svr.wait_until_ready();
  3790. {
  3791. Client cli(HOST, port);
  3792. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3793. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3794. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3798. // Every control character is percent-encoded, not just CR/LF, so the target
  3799. // passes the request-target check in write_request_line.
  3800. Server svr;
  3801. std::string target;
  3802. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3803. target = req.target;
  3804. res.status = StatusCode::OK_200;
  3805. return Server::HandlerResponse::Handled;
  3806. });
  3807. auto port = svr.bind_to_any_port(HOST);
  3808. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3809. auto se = detail::scope_exit([&] {
  3810. svr.stop();
  3811. thread.join();
  3812. ASSERT_FALSE(svr.is_running());
  3813. });
  3814. svr.wait_until_ready();
  3815. {
  3816. Client cli(HOST, port);
  3817. auto res = cli.Get("/a\tb\x1b\x7f");
  3818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3819. EXPECT_EQ("/a%09b%1B%7F", target);
  3820. }
  3821. }
  3822. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3823. // Nothing may reach the wire: a raw CR/LF target would split the request
  3824. // line and inject headers.
  3825. Server svr;
  3826. // Pre-routing so that "not called" means nothing reached the server at all,
  3827. // rather than merely failing to match a handler pattern.
  3828. auto handler_called = false;
  3829. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3830. handler_called = true;
  3831. res.status = StatusCode::OK_200;
  3832. return Server::HandlerResponse::Handled;
  3833. });
  3834. auto port = svr.bind_to_any_port(HOST);
  3835. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3836. auto se = detail::scope_exit([&] {
  3837. svr.stop();
  3838. thread.join();
  3839. ASSERT_FALSE(svr.is_running());
  3840. });
  3841. svr.wait_until_ready();
  3842. {
  3843. Client cli(HOST, port);
  3844. cli.set_path_encode(false);
  3845. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3846. EXPECT_FALSE(handle.is_valid());
  3847. EXPECT_EQ(Error::Write, handle.error);
  3848. EXPECT_FALSE(handler_called);
  3849. }
  3850. }
  3851. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3852. // Which of the two branches runs is decided by whether the query component
  3853. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3854. // an empty query and must still fall back to building one from
  3855. // `req.params`, while a non-empty query must win over `req.params`.
  3856. Server svr;
  3857. std::string target;
  3858. svr.Get("/foo", [&](const Request &req, Response &res) {
  3859. target = req.target;
  3860. res.status = StatusCode::OK_200;
  3861. });
  3862. auto port = svr.bind_to_any_port(HOST);
  3863. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3864. auto se = detail::scope_exit([&] {
  3865. svr.stop();
  3866. thread.join();
  3867. ASSERT_FALSE(svr.is_running());
  3868. });
  3869. svr.wait_until_ready();
  3870. {
  3871. // Trailing `?` -> empty query component -> `req.params` is used.
  3872. Client cli(HOST, port);
  3873. Request req;
  3874. req.method = "GET";
  3875. req.path = "/foo?";
  3876. req.params.emplace("a", "1");
  3877. target.clear();
  3878. auto res = cli.send(req);
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. EXPECT_EQ("/foo?a=1", target);
  3881. }
  3882. {
  3883. // Non-empty query in `req.path` -> `req.params` is not appended.
  3884. Client cli(HOST, port);
  3885. Request req;
  3886. req.method = "GET";
  3887. req.path = "/foo?b=2";
  3888. req.params.emplace("a", "1");
  3889. target.clear();
  3890. auto res = cli.send(req);
  3891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3892. EXPECT_EQ("/foo?b=2", target);
  3893. }
  3894. }
  3895. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3896. Server svr;
  3897. svr.Get("/", [](const Request &req, Response &) {
  3898. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3899. });
  3900. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3901. auto se = detail::scope_exit([&] {
  3902. svr.stop();
  3903. thread.join();
  3904. ASSERT_FALSE(svr.is_running());
  3905. });
  3906. svr.wait_until_ready();
  3907. {
  3908. Client cli(HOST, PORT);
  3909. cli.set_path_encode(false);
  3910. auto res = cli.Get("/?something=%0A");
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. }
  3914. }
  3915. TEST(BindServerTest, BindDualStack) {
  3916. Server svr;
  3917. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3918. res.set_content("Hello World!", "text/plain");
  3919. });
  3920. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3921. auto se = detail::scope_exit([&] {
  3922. svr.stop();
  3923. thread.join();
  3924. ASSERT_FALSE(svr.is_running());
  3925. });
  3926. svr.wait_until_ready();
  3927. {
  3928. Client cli("127.0.0.1", PORT);
  3929. auto res = cli.Get("/1");
  3930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3931. EXPECT_EQ(StatusCode::OK_200, res->status);
  3932. EXPECT_EQ("Hello World!", res->body);
  3933. }
  3934. {
  3935. Client cli("::1", PORT);
  3936. auto res = cli.Get("/1");
  3937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3938. EXPECT_EQ(StatusCode::OK_200, res->status);
  3939. EXPECT_EQ("Hello World!", res->body);
  3940. }
  3941. }
  3942. TEST(BindServerTest, BindAndListenSeparately) {
  3943. Server svr;
  3944. int port = svr.bind_to_any_port("0.0.0.0");
  3945. ASSERT_TRUE(svr.is_valid());
  3946. ASSERT_TRUE(port > 0);
  3947. svr.stop();
  3948. }
  3949. // Reports whether anything is still listening on a loopback port. A plain
  3950. // connect() is used instead of a Client request because a socket left bound by
  3951. // mistake accepts the connection into its backlog and never answers, which
  3952. // would hang the test instead of failing it.
  3953. static bool is_loopback_port_accepting(int port) {
  3954. sockaddr_in addr{};
  3955. addr.sin_family = AF_INET;
  3956. addr.sin_port = htons(static_cast<uint16_t>(port));
  3957. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3958. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3959. EXPECT_NE(sock, INVALID_SOCKET);
  3960. if (sock == INVALID_SOCKET) { return false; }
  3961. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3962. static_cast<socklen_t>(sizeof(addr)));
  3963. detail::close_socket(sock);
  3964. return ret == 0;
  3965. }
  3966. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3967. Server svr;
  3968. auto port = svr.bind_to_any_port("127.0.0.1");
  3969. ASSERT_TRUE(port > 0);
  3970. svr.stop();
  3971. // bind_to_any_port() already called listen(2), so until stop() closed the
  3972. // descriptor the port kept accepting connections into the backlog. ASSERT
  3973. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3974. // below blocks forever in the accept loop.
  3975. ASSERT_FALSE(is_loopback_port_accepting(port));
  3976. // Nothing is left to accept on, so listen_after_bind() must report failure
  3977. // instead of returning success without ever serving.
  3978. EXPECT_FALSE(svr.listen_after_bind());
  3979. // The failed listen marks the server decommissioned, so a waiter returns
  3980. // instead of spinning forever.
  3981. svr.wait_until_ready();
  3982. }
  3983. #ifdef CPPHTTPLIB_SSL_ENABLED
  3984. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3986. CLIENT_CA_CERT_DIR);
  3987. int port = svr.bind_to_any_port("0.0.0.0");
  3988. ASSERT_TRUE(svr.is_valid());
  3989. ASSERT_TRUE(port > 0);
  3990. svr.stop();
  3991. }
  3992. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3993. // or a rejected CustomRoute() registration would not stop the server binding.
  3994. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3996. CLIENT_CA_CERT_DIR);
  3997. ASSERT_TRUE(svr.is_valid());
  3998. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3999. EXPECT_FALSE(svr.is_valid());
  4000. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4001. }
  4002. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4003. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4004. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4005. int port = svr.bind_to_any_port("0.0.0.0");
  4006. ASSERT_TRUE(svr.is_valid());
  4007. ASSERT_TRUE(port > 0);
  4008. svr.stop();
  4009. }
  4010. TEST(BindServerTest, UpdateCertsPem) {
  4011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4012. int port = svr.bind_to_any_port("0.0.0.0");
  4013. ASSERT_TRUE(svr.is_valid());
  4014. ASSERT_TRUE(port > 0);
  4015. // Read PEM files
  4016. std::string cert_pem, key_pem, ca_pem;
  4017. read_file(SERVER_CERT_FILE, cert_pem);
  4018. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4019. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4020. // Update server certificates using PEM API
  4021. ASSERT_TRUE(
  4022. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4023. ASSERT_TRUE(svr.is_valid());
  4024. svr.stop();
  4025. }
  4026. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4027. // Start server with client CA (enables client auth)
  4028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4029. ASSERT_TRUE(svr.is_valid());
  4030. bool handler_called = false;
  4031. svr.Get("/test", [&](const Request &req, Response &res) {
  4032. handler_called = true;
  4033. // Verify client certificate is present
  4034. auto cert = req.peer_cert();
  4035. EXPECT_TRUE(static_cast<bool>(cert));
  4036. res.set_content("ok", "text/plain");
  4037. });
  4038. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4039. auto se = detail::scope_exit([&] {
  4040. svr.stop();
  4041. t.join();
  4042. ASSERT_FALSE(svr.is_running());
  4043. });
  4044. svr.wait_until_ready();
  4045. // Read PEM files
  4046. std::string cert_pem, key_pem, ca_pem;
  4047. read_file(SERVER_CERT_FILE, cert_pem);
  4048. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4049. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4050. // Update server certificates and client CA using PEM API while server running
  4051. ASSERT_TRUE(
  4052. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4053. // Connect with client certificate
  4054. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4055. cli.enable_server_certificate_verification(false);
  4056. cli.set_connection_timeout(30);
  4057. auto res = cli.Get("/test");
  4058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4059. ASSERT_EQ(StatusCode::OK_200, res->status);
  4060. ASSERT_TRUE(handler_called);
  4061. EXPECT_EQ("ok", res->body);
  4062. }
  4063. // Puts a CA that did not sign the client's certificate in the old one's place.
  4064. static bool replace_client_ca(SSLServer &svr) {
  4065. std::string cert_pem, key_pem, ca_pem;
  4066. read_file(SERVER_CERT_FILE, cert_pem);
  4067. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4068. read_file(SERVER_CERT2_FILE, ca_pem);
  4069. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4070. ca_pem.c_str());
  4071. }
  4072. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4074. ASSERT_TRUE(svr.is_valid());
  4075. svr.Get("/test", [](const Request &, Response &res) {
  4076. res.set_content("ok", "text/plain");
  4077. });
  4078. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4079. auto se = detail::scope_exit([&] {
  4080. svr.stop();
  4081. t.join();
  4082. ASSERT_FALSE(svr.is_running());
  4083. });
  4084. svr.wait_until_ready();
  4085. auto get = [] {
  4086. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4087. cli.enable_server_certificate_verification(false);
  4088. return cli.Get("/test");
  4089. };
  4090. ASSERT_TRUE(get());
  4091. ASSERT_TRUE(replace_client_ca(svr));
  4092. EXPECT_FALSE(get());
  4093. }
  4094. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4095. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4097. ASSERT_TRUE(svr.is_valid());
  4098. tls::set_verify_callback(svr.tls_context(),
  4099. [](const tls::VerifyContext &) -> bool {
  4100. throw std::runtime_error("verify");
  4101. });
  4102. svr.Get("/test", [](const Request &, Response &res) {
  4103. res.set_content("ok", "text/plain");
  4104. });
  4105. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4106. auto se = detail::scope_exit([&] {
  4107. svr.stop();
  4108. t.join();
  4109. ASSERT_FALSE(svr.is_running());
  4110. });
  4111. svr.wait_until_ready();
  4112. auto get = [] {
  4113. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4114. cli.enable_server_certificate_verification(false);
  4115. return cli.Get("/test");
  4116. };
  4117. EXPECT_FALSE(get());
  4118. // The handshake is over, so an update does not wait for it.
  4119. std::string cert_pem, key_pem;
  4120. read_file(SERVER_CERT_FILE, cert_pem);
  4121. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4122. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4123. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4124. return v.preverify_ok;
  4125. });
  4126. auto res = get();
  4127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4128. EXPECT_EQ("ok", res->body);
  4129. }
  4130. #endif
  4131. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4132. // Sends each request over a new connection with a client certificate,
  4133. // resuming the session of the one before when there is one.
  4134. class ResumingClient {
  4135. public:
  4136. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4137. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4138. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4139. SSL_FILETYPE_PEM);
  4140. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4141. // callback, not through SSL_get1_session().
  4142. SSL_CTX_set_app_data(ctx_, this);
  4143. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4144. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4145. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4146. auto self = static_cast<ResumingClient *>(
  4147. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4148. SSL_SESSION_free(self->session_);
  4149. self->session_ = session;
  4150. return 1; // Keeps the reference
  4151. });
  4152. }
  4153. ~ResumingClient() {
  4154. SSL_SESSION_free(session_);
  4155. SSL_CTX_free(ctx_);
  4156. }
  4157. // Tells whether the request was answered.
  4158. bool get() {
  4159. auto error = Error::Success;
  4160. auto sock = detail::create_client_socket(
  4161. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4162. /*connection_timeout_sec=*/5, 0,
  4163. /*read_timeout_sec=*/5, 0,
  4164. /*write_timeout_sec=*/5, 0, std::string(), error);
  4165. if (sock == INVALID_SOCKET) { return false; }
  4166. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4167. auto ssl = SSL_new(ctx_);
  4168. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4169. SSL_set_fd(ssl, static_cast<int>(sock));
  4170. if (session_) { SSL_set_session(ssl, session_); }
  4171. if (SSL_connect(ssl) != 1) { return false; }
  4172. reused_ = SSL_session_reused(ssl) == 1;
  4173. // Reading the response also takes in a TLS 1.3 session ticket.
  4174. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4175. "Connection: close\r\n\r\n";
  4176. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4177. std::string res;
  4178. char buf[256];
  4179. int n;
  4180. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4181. res.append(buf, static_cast<size_t>(n));
  4182. }
  4183. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4184. SSL_shutdown(ssl);
  4185. return res.find("200 OK") != std::string::npos;
  4186. }
  4187. // Whether the last connection resumed a session
  4188. bool reused() const { return reused_; }
  4189. private:
  4190. SSL_CTX *ctx_;
  4191. SSL_SESSION *session_ = nullptr;
  4192. bool reused_ = false;
  4193. };
  4194. // A client that resumes its session gets through, but not once the client CA
  4195. // has changed, as a resumed session does not show the certificate again.
  4196. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4198. ASSERT_TRUE(svr.is_valid());
  4199. svr.Get("/test", [](const Request &, Response &res) {
  4200. res.set_content("ok", "text/plain");
  4201. });
  4202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4203. auto se = detail::scope_exit([&] {
  4204. svr.stop();
  4205. t.join();
  4206. ASSERT_FALSE(svr.is_running());
  4207. });
  4208. svr.wait_until_ready();
  4209. ResumingClient cli;
  4210. ASSERT_TRUE(cli.get());
  4211. ASSERT_TRUE(cli.get());
  4212. EXPECT_TRUE(cli.reused());
  4213. ASSERT_TRUE(replace_client_ca(svr));
  4214. EXPECT_FALSE(cli.get());
  4215. }
  4216. // A resumed session does not show the certificate again, so the server does
  4217. // not resume one with a verify callback to run on it.
  4218. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4220. ASSERT_TRUE(svr.is_valid());
  4221. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4222. return v.preverify_ok;
  4223. });
  4224. svr.Get("/test", [](const Request &, Response &res) {
  4225. res.set_content("ok", "text/plain");
  4226. });
  4227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4228. auto se = detail::scope_exit([&] {
  4229. svr.stop();
  4230. t.join();
  4231. ASSERT_FALSE(svr.is_running());
  4232. });
  4233. svr.wait_until_ready();
  4234. ResumingClient cli;
  4235. ASSERT_TRUE(cli.get());
  4236. ASSERT_TRUE(cli.get());
  4237. EXPECT_FALSE(cli.reused());
  4238. }
  4239. #endif
  4240. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4241. // wolfSSL shares its session cache between contexts, so a resumed session
  4242. // could carry a client certificate checked against another server's CA, or
  4243. // against a client CA since replaced.
  4244. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4246. ASSERT_TRUE(svr.is_valid());
  4247. // Trusts a CA that did not sign the client's certificate.
  4248. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4249. ASSERT_TRUE(other.is_valid());
  4250. for (auto s : {&svr, &other}) {
  4251. s->Get("/test", [](const Request &, Response &res) {
  4252. res.set_content("ok", "text/plain");
  4253. });
  4254. }
  4255. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4256. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4257. auto se = detail::scope_exit([&] {
  4258. other.stop();
  4259. svr.stop();
  4260. t2.join();
  4261. t.join();
  4262. });
  4263. svr.wait_until_ready();
  4264. other.wait_until_ready();
  4265. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4266. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4267. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4268. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4269. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4270. ASSERT_EQ(WOLFSSL_SUCCESS,
  4271. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4272. WOLFSSL_FILETYPE_PEM));
  4273. WOLFSSL_SESSION *session = nullptr;
  4274. auto session_se = detail::scope_exit([&] {
  4275. if (session) { wolfSSL_SESSION_free(session); }
  4276. });
  4277. // A request over a new connection, resuming `session` when there is one and
  4278. // keeping the connection's own in its place. Tells whether it was answered.
  4279. auto get = [&](int port) {
  4280. auto error = Error::Success;
  4281. auto sock = detail::create_client_socket(
  4282. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4283. /*connection_timeout_sec=*/5, 0,
  4284. /*read_timeout_sec=*/5, 0,
  4285. /*write_timeout_sec=*/5, 0, std::string(), error);
  4286. if (sock == INVALID_SOCKET) { return false; }
  4287. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4288. auto ssl = wolfSSL_new(ctx);
  4289. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4290. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4291. if (session) { wolfSSL_set_session(ssl, session); }
  4292. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4293. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4294. "Connection: close\r\n\r\n";
  4295. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4296. std::string res;
  4297. char buf[256];
  4298. int n;
  4299. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4300. res.append(buf, static_cast<size_t>(n));
  4301. }
  4302. wolfSSL_shutdown(ssl);
  4303. if (session) { wolfSSL_SESSION_free(session); }
  4304. session = wolfSSL_get1_session(ssl);
  4305. return res.find("200 OK") != std::string::npos;
  4306. };
  4307. ASSERT_TRUE(get(PORT));
  4308. EXPECT_FALSE(get(PORT + 1));
  4309. ASSERT_TRUE(get(PORT));
  4310. ASSERT_TRUE(replace_client_ca(svr));
  4311. EXPECT_FALSE(get(PORT));
  4312. }
  4313. #endif
  4314. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4315. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4316. ASSERT_TRUE(svr.is_valid());
  4317. svr.Get("/test", [](const Request &, Response &res) {
  4318. res.set_content("ok", "text/plain");
  4319. });
  4320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4321. auto se = detail::scope_exit([&] {
  4322. svr.stop();
  4323. t.join();
  4324. ASSERT_FALSE(svr.is_running());
  4325. });
  4326. svr.wait_until_ready();
  4327. // A connection that sends no ClientHello keeps its handshake in progress,
  4328. // once the server has had a moment to start it.
  4329. auto error = Error::Success;
  4330. auto sock = detail::create_client_socket(
  4331. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4332. /*connection_timeout_sec=*/5, 0,
  4333. /*read_timeout_sec=*/5, 0,
  4334. /*write_timeout_sec=*/5, 0, std::string(), error);
  4335. ASSERT_NE(INVALID_SOCKET, sock);
  4336. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4337. std::string cert_pem, key_pem;
  4338. read_file(SERVER_CERT_FILE, cert_pem);
  4339. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4340. auto update = std::async(std::launch::async, [&]() {
  4341. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4342. });
  4343. EXPECT_EQ(std::future_status::timeout,
  4344. update.wait_for(std::chrono::milliseconds(200)));
  4345. detail::close_socket(sock);
  4346. EXPECT_TRUE(update.get());
  4347. SSLClient cli(HOST, PORT);
  4348. cli.enable_server_certificate_verification(false);
  4349. auto res = cli.Get("/test");
  4350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4351. EXPECT_EQ(StatusCode::OK_200, res->status);
  4352. }
  4353. #endif
  4354. TEST(ErrorHandlerTest, ContentLength) {
  4355. Server svr;
  4356. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4357. res.status = StatusCode::OK_200;
  4358. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4359. "text/html"); // <= Content-Length still 13
  4360. });
  4361. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4362. res.set_content("Hello World!\n", "text/plain");
  4363. res.status = 524;
  4364. });
  4365. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4366. auto se = detail::scope_exit([&] {
  4367. svr.stop();
  4368. thread.join();
  4369. ASSERT_FALSE(svr.is_running());
  4370. });
  4371. svr.wait_until_ready();
  4372. {
  4373. Client cli(HOST, PORT);
  4374. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4376. EXPECT_EQ(StatusCode::OK_200, res->status);
  4377. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4378. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4379. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4380. }
  4381. }
  4382. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4383. TEST(ExceptionTest, WithoutExceptionHandler) {
  4384. Server svr;
  4385. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4386. throw std::runtime_error("exception...");
  4387. });
  4388. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4389. throw std::runtime_error("exception\r\n...");
  4390. });
  4391. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4392. auto se = detail::scope_exit([&] {
  4393. svr.stop();
  4394. listen_thread.join();
  4395. ASSERT_FALSE(svr.is_running());
  4396. });
  4397. svr.wait_until_ready();
  4398. Client cli("localhost", PORT);
  4399. {
  4400. auto res = cli.Get("/exception");
  4401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4402. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4403. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4404. }
  4405. {
  4406. auto res = cli.Get("/unknown");
  4407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4408. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4409. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4410. }
  4411. }
  4412. TEST(ExceptionTest, WithExceptionHandler) {
  4413. Server svr;
  4414. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4415. std::exception_ptr ep) {
  4416. EXPECT_FALSE(ep == nullptr);
  4417. try {
  4418. std::rethrow_exception(ep);
  4419. } catch (std::exception &e) {
  4420. EXPECT_EQ("abc", std::string(e.what()));
  4421. } catch (...) {}
  4422. res.status = StatusCode::InternalServerError_500;
  4423. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4424. "text/html"); // <= Content-Length still 13 at this point
  4425. });
  4426. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4427. res.set_content("Hello World!\n", "text/plain");
  4428. throw std::runtime_error("abc");
  4429. });
  4430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4431. auto se = detail::scope_exit([&] {
  4432. svr.stop();
  4433. thread.join();
  4434. ASSERT_FALSE(svr.is_running());
  4435. });
  4436. svr.wait_until_ready();
  4437. for (size_t i = 0; i < 10; i++) {
  4438. Client cli(HOST, PORT);
  4439. for (size_t j = 0; j < 100; j++) {
  4440. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4442. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4443. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4444. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4445. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4446. }
  4447. cli.set_keep_alive(true);
  4448. for (size_t j = 0; j < 100; j++) {
  4449. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4451. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4452. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4453. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4454. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4455. }
  4456. }
  4457. }
  4458. TEST(ExceptionTest, AndErrorHandler) {
  4459. Server svr;
  4460. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4461. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4462. });
  4463. svr.set_exception_handler(
  4464. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4465. EXPECT_FALSE(ep == nullptr);
  4466. try {
  4467. std::rethrow_exception(ep);
  4468. } catch (std::exception &e) {
  4469. res.set_content(e.what(), "text/html");
  4470. } catch (...) {}
  4471. res.status = StatusCode::InternalServerError_500;
  4472. });
  4473. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4474. throw std::runtime_error("EXCEPTION");
  4475. });
  4476. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4477. res.set_content("ERROR", "text/html");
  4478. res.status = StatusCode::InternalServerError_500;
  4479. });
  4480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. Client cli(HOST, PORT);
  4488. {
  4489. auto res = cli.Get("/exception");
  4490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4491. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4492. EXPECT_EQ("EXCEPTION", res->body);
  4493. }
  4494. {
  4495. auto res = cli.Get("/error");
  4496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4497. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4498. EXPECT_EQ("ERROR", res->body);
  4499. }
  4500. {
  4501. auto res = cli.Get("/invalid");
  4502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4504. EXPECT_EQ("NOT_FOUND", res->body);
  4505. }
  4506. }
  4507. #endif
  4508. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4509. // process_request() wraps only routing() in a try/catch, so an exception from
  4510. // any other user callback used to unwind into the task queue - which does not
  4511. // catch - and terminate the process. Each test below runs the server on a
  4512. // single worker thread: a guard that catches the exception but still loses the
  4513. // thread would otherwise be hidden by a spare worker serving the follow-up
  4514. // request. Note that a regression here aborts the whole test binary rather
  4515. // than failing one test.
  4516. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4517. Server svr;
  4518. svr.new_task_queue = [] { return new ThreadPool(1); };
  4519. std::atomic<int> reported{0};
  4520. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4521. if (err == Error::UserCallbackException) { reported++; }
  4522. });
  4523. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4524. res.set_content_provider(
  4525. 1024, "text/plain",
  4526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4527. sink.write("hello", 5);
  4528. throw std::runtime_error("from the content provider");
  4529. });
  4530. });
  4531. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4532. res.set_content("ok", "text/plain");
  4533. });
  4534. auto port = svr.bind_to_any_port(HOST);
  4535. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4536. auto se = detail::scope_exit([&] {
  4537. svr.stop();
  4538. listen_thread.join();
  4539. ASSERT_FALSE(svr.is_running());
  4540. });
  4541. svr.wait_until_ready();
  4542. {
  4543. Client cli(HOST, port);
  4544. cli.set_read_timeout(5, 0);
  4545. EXPECT_FALSE(cli.Get("/throw"));
  4546. }
  4547. EXPECT_TRUE(svr.is_running());
  4548. EXPECT_EQ(1, reported.load());
  4549. // A request on a fresh connection is still served.
  4550. {
  4551. Client cli(HOST, port);
  4552. auto res = cli.Get("/ok");
  4553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4554. EXPECT_EQ(StatusCode::OK_200, res->status);
  4555. EXPECT_EQ("ok", res->body);
  4556. }
  4557. }
  4558. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4559. Server svr;
  4560. svr.new_task_queue = [] { return new ThreadPool(1); };
  4561. std::atomic<bool> should_throw{true};
  4562. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4563. res.set_content("hi", "text/plain");
  4564. });
  4565. svr.set_post_routing_handler(
  4566. [&](const Request & /*req*/, Response & /*res*/) {
  4567. if (should_throw) {
  4568. throw std::runtime_error("from the post-routing handler");
  4569. }
  4570. });
  4571. auto port = svr.bind_to_any_port(HOST);
  4572. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4573. auto se = detail::scope_exit([&] {
  4574. svr.stop();
  4575. listen_thread.join();
  4576. ASSERT_FALSE(svr.is_running());
  4577. });
  4578. svr.wait_until_ready();
  4579. {
  4580. Client cli(HOST, port);
  4581. cli.set_read_timeout(5, 0);
  4582. EXPECT_FALSE(cli.Get("/hi"));
  4583. }
  4584. EXPECT_TRUE(svr.is_running());
  4585. should_throw = false;
  4586. {
  4587. Client cli(HOST, port);
  4588. auto res = cli.Get("/hi");
  4589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("hi", res->body);
  4592. }
  4593. }
  4594. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4595. // The guard reports the caught exception through the error logger, which is
  4596. // a user callback too. A logger that throws has to be contained as well, or
  4597. // the process would terminate from inside the catch.
  4598. Server svr;
  4599. svr.new_task_queue = [] { return new ThreadPool(1); };
  4600. std::atomic<int> reported{0};
  4601. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4602. if (err == Error::UserCallbackException) {
  4603. reported++;
  4604. throw std::runtime_error("from the error logger");
  4605. }
  4606. });
  4607. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4608. res.set_content_provider(
  4609. 1024, "text/plain",
  4610. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4611. sink.write("hello", 5);
  4612. throw std::runtime_error("from the content provider");
  4613. });
  4614. });
  4615. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4616. res.set_content("ok", "text/plain");
  4617. });
  4618. auto port = svr.bind_to_any_port(HOST);
  4619. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4620. auto se = detail::scope_exit([&] {
  4621. svr.stop();
  4622. listen_thread.join();
  4623. ASSERT_FALSE(svr.is_running());
  4624. });
  4625. svr.wait_until_ready();
  4626. {
  4627. Client cli(HOST, port);
  4628. cli.set_read_timeout(5, 0);
  4629. EXPECT_FALSE(cli.Get("/throw"));
  4630. }
  4631. EXPECT_TRUE(svr.is_running());
  4632. EXPECT_EQ(1, reported.load());
  4633. {
  4634. Client cli(HOST, port);
  4635. auto res = cli.Get("/ok");
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. EXPECT_EQ("ok", res->body);
  4639. }
  4640. }
  4641. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4642. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4643. // so the exception unwinds through the ws::WebSocket object on its way to
  4644. // the guard. None of the HTTP cases above cross that.
  4645. Server svr;
  4646. svr.new_task_queue = [] { return new ThreadPool(1); };
  4647. std::atomic<int> reported{0};
  4648. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4649. if (err == Error::UserCallbackException) { reported++; }
  4650. });
  4651. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4652. throw std::runtime_error("from the WebSocket handler");
  4653. });
  4654. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4655. res.set_content("ok", "text/plain");
  4656. });
  4657. auto port = svr.bind_to_any_port(HOST);
  4658. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4659. auto se = detail::scope_exit([&] {
  4660. svr.stop();
  4661. listen_thread.join();
  4662. ASSERT_FALSE(svr.is_running());
  4663. });
  4664. svr.wait_until_ready();
  4665. {
  4666. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4667. "/ws");
  4668. auto res = client.connect();
  4669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4670. // The server dropped the connection instead of dying.
  4671. std::string msg;
  4672. EXPECT_FALSE(client.read(msg));
  4673. client.close();
  4674. }
  4675. EXPECT_TRUE(svr.is_running());
  4676. EXPECT_EQ(1, reported.load());
  4677. {
  4678. Client cli(HOST, port);
  4679. auto res = cli.Get("/ok");
  4680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. EXPECT_EQ("ok", res->body);
  4683. }
  4684. }
  4685. #ifdef CPPHTTPLIB_SSL_ENABLED
  4686. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4687. // SSLServer::process_and_close_socket() is a separate overload with its own
  4688. // guard, so it is exercised on its own.
  4689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4690. ASSERT_TRUE(svr.is_valid());
  4691. svr.new_task_queue = [] { return new ThreadPool(1); };
  4692. std::atomic<int> reported{0};
  4693. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4694. if (err == Error::UserCallbackException) { reported++; }
  4695. });
  4696. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4697. res.set_content_provider(
  4698. 1024, "text/plain",
  4699. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4700. sink.write("hello", 5);
  4701. throw std::runtime_error("from the content provider");
  4702. });
  4703. });
  4704. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4705. res.set_content("ok", "text/plain");
  4706. });
  4707. auto port = svr.bind_to_any_port(HOST);
  4708. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4709. auto se = detail::scope_exit([&] {
  4710. svr.stop();
  4711. listen_thread.join();
  4712. ASSERT_FALSE(svr.is_running());
  4713. });
  4714. svr.wait_until_ready();
  4715. {
  4716. SSLClient cli(HOST, port);
  4717. cli.enable_server_certificate_verification(false);
  4718. cli.set_read_timeout(5, 0);
  4719. EXPECT_FALSE(cli.Get("/throw"));
  4720. }
  4721. EXPECT_TRUE(svr.is_running());
  4722. EXPECT_EQ(1, reported.load());
  4723. {
  4724. SSLClient cli(HOST, port);
  4725. cli.enable_server_certificate_verification(false);
  4726. auto res = cli.Get("/ok");
  4727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4728. EXPECT_EQ(StatusCode::OK_200, res->status);
  4729. EXPECT_EQ("ok", res->body);
  4730. }
  4731. }
  4732. #endif
  4733. #endif
  4734. TEST(NoContentTest, ContentLength) {
  4735. Server svr;
  4736. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4737. res.status = StatusCode::NoContent_204;
  4738. });
  4739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4740. auto se = detail::scope_exit([&] {
  4741. svr.stop();
  4742. thread.join();
  4743. ASSERT_FALSE(svr.is_running());
  4744. });
  4745. svr.wait_until_ready();
  4746. {
  4747. Client cli(HOST, PORT);
  4748. auto res = cli.Get("/hi");
  4749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4750. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4751. // RFC 9110 8.6: none in a 204 response
  4752. EXPECT_FALSE(res->has_header("Content-Length"));
  4753. }
  4754. }
  4755. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4756. Server svr;
  4757. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4758. res.set_header("Content-Length", "5");
  4759. res.set_content("hello world", "text/plain");
  4760. });
  4761. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4762. // A body that reads as the last chunk, were it taken as chunked
  4763. res.set_header("Transfer-Encoding", "chunked");
  4764. res.set_content("0\r\n\r\n", "text/plain");
  4765. });
  4766. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4767. res.set_header("Content-Length", "2");
  4768. res.set_content_provider(5, "text/plain",
  4769. [](size_t offset, size_t length, DataSink &sink) {
  4770. sink.write(&"hello"[offset], length);
  4771. return true;
  4772. });
  4773. });
  4774. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4775. res.set_header("Content-Length", "1234");
  4776. });
  4777. thread t = thread([&] { svr.listen(HOST, PORT); });
  4778. auto se = detail::scope_exit([&] {
  4779. svr.stop();
  4780. t.join();
  4781. ASSERT_FALSE(svr.is_running());
  4782. });
  4783. svr.wait_until_ready();
  4784. Client cli(HOST, PORT);
  4785. cli.set_read_timeout(1, 0);
  4786. auto expect_body = [&](const Result &res, const std::string &body) {
  4787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4788. EXPECT_EQ(body, res->body);
  4789. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4790. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4791. };
  4792. Headers identity{{"Accept-Encoding", ""}};
  4793. expect_body(cli.Get("/body", identity), "hello world");
  4794. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4795. expect_body(cli.Get("/body",
  4796. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4797. "he");
  4798. expect_body(cli.Get("/provider", identity), "hello");
  4799. expect_body(cli.Get("/empty", identity), "");
  4800. // A HEAD response may give the length of the body a GET would get.
  4801. auto res = cli.Head("/empty");
  4802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4803. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4804. }
  4805. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4806. Server svr;
  4807. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4808. res.set_content("short", "text/plain");
  4809. });
  4810. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4811. res.body += " with a footer";
  4812. res.set_header("Transfer-Encoding", "chunked");
  4813. });
  4814. thread t = thread([&] { svr.listen(HOST, PORT); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. t.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. Client cli(HOST, PORT);
  4822. cli.set_read_timeout(1, 0);
  4823. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4825. EXPECT_EQ("short with a footer", res->body);
  4826. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4827. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4828. }
  4829. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4830. Server svr;
  4831. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4832. res.set_header("Content-Length", "3");
  4833. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4834. sink.write("abc", 3);
  4835. sink.done();
  4836. return true;
  4837. });
  4838. });
  4839. thread t = thread([&] { svr.listen(HOST, PORT); });
  4840. auto se = detail::scope_exit([&] {
  4841. svr.stop();
  4842. t.join();
  4843. ASSERT_FALSE(svr.is_running());
  4844. });
  4845. svr.wait_until_ready();
  4846. Client cli(HOST, PORT);
  4847. cli.set_keep_alive(true);
  4848. auto res = cli.Get("/");
  4849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4850. EXPECT_EQ("abc", res->body);
  4851. EXPECT_FALSE(res->has_header("Content-Length"));
  4852. EXPECT_EQ("close", res->get_header_value("Connection"));
  4853. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4854. // No body to delimit
  4855. auto head = cli.Head("/");
  4856. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4857. EXPECT_FALSE(head->has_header("Connection"));
  4858. }
  4859. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4860. #ifdef CPPHTTPLIB_SSL_ENABLED
  4861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4862. ASSERT_TRUE(svr.is_valid());
  4863. #else
  4864. Server svr;
  4865. #endif
  4866. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4867. if (req.path == "/routing_handler") {
  4868. res.set_header("PRE_ROUTING", "on");
  4869. res.set_content("Routing Handler", "text/plain");
  4870. return httplib::Server::HandlerResponse::Handled;
  4871. }
  4872. return httplib::Server::HandlerResponse::Unhandled;
  4873. });
  4874. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4875. res.set_content("Error", "text/html");
  4876. });
  4877. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4878. if (req.path == "/routing_handler") {
  4879. res.set_header("POST_ROUTING", "on");
  4880. }
  4881. });
  4882. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4883. res.set_content("Hello World!\n", "text/plain");
  4884. });
  4885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4886. auto se = detail::scope_exit([&] {
  4887. svr.stop();
  4888. thread.join();
  4889. ASSERT_FALSE(svr.is_running());
  4890. });
  4891. svr.wait_until_ready();
  4892. {
  4893. #ifdef CPPHTTPLIB_SSL_ENABLED
  4894. SSLClient cli(HOST, PORT);
  4895. cli.enable_server_certificate_verification(false);
  4896. #else
  4897. Client cli(HOST, PORT);
  4898. #endif
  4899. auto res = cli.Get("/routing_handler");
  4900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4901. EXPECT_EQ(StatusCode::OK_200, res->status);
  4902. EXPECT_EQ("Routing Handler", res->body);
  4903. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4904. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4905. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4906. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4907. }
  4908. {
  4909. #ifdef CPPHTTPLIB_SSL_ENABLED
  4910. SSLClient cli(HOST, PORT);
  4911. cli.enable_server_certificate_verification(false);
  4912. #else
  4913. Client cli(HOST, PORT);
  4914. #endif
  4915. auto res = cli.Get("/hi");
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. EXPECT_EQ("Hello World!\n", res->body);
  4919. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4920. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4921. }
  4922. {
  4923. #ifdef CPPHTTPLIB_SSL_ENABLED
  4924. SSLClient cli(HOST, PORT);
  4925. cli.enable_server_certificate_verification(false);
  4926. #else
  4927. Client cli(HOST, PORT);
  4928. #endif
  4929. auto res = cli.Get("/aaa");
  4930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4932. EXPECT_EQ("Error", res->body);
  4933. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4934. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4935. }
  4936. }
  4937. TEST(RequestHandlerTest, PreRequestHandler) {
  4938. auto route_path = "/user/:user";
  4939. Server svr;
  4940. svr.Get("/hi", [](const Request &, Response &res) {
  4941. res.set_content("hi", "text/plain");
  4942. });
  4943. svr.Get(route_path, [](const Request &req, Response &res) {
  4944. res.set_content(req.path_params.at("user"), "text/plain");
  4945. });
  4946. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4947. if (req.matched_route == route_path) {
  4948. auto user = req.path_params.at("user");
  4949. if (user != "john") {
  4950. res.status = StatusCode::Forbidden_403;
  4951. res.set_content("error", "text/html");
  4952. return Server::HandlerResponse::Handled;
  4953. }
  4954. }
  4955. return Server::HandlerResponse::Unhandled;
  4956. });
  4957. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4958. auto se = detail::scope_exit([&] {
  4959. svr.stop();
  4960. thread.join();
  4961. ASSERT_FALSE(svr.is_running());
  4962. });
  4963. svr.wait_until_ready();
  4964. Client cli(HOST, PORT);
  4965. {
  4966. auto res = cli.Get("/hi");
  4967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. EXPECT_EQ("hi", res->body);
  4970. }
  4971. {
  4972. auto res = cli.Get("/user/john");
  4973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. EXPECT_EQ("john", res->body);
  4976. }
  4977. {
  4978. auto res = cli.Get("/user/invalid-user");
  4979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4980. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4981. EXPECT_EQ("error", res->body);
  4982. }
  4983. }
  4984. // The pre-request handler must run before the request body is read, so a
  4985. // rejected request never forces the server to buffer a (potentially large)
  4986. // body. Here the posted body is larger than the payload limit: if the body
  4987. // were read first the server would answer 413, but because the pre-request
  4988. // handler runs first it answers 403 and the body is never read.
  4989. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4990. Server svr;
  4991. svr.set_payload_max_length(8);
  4992. auto handler_ran = false;
  4993. svr.Post("/reject", [&](const Request &req, Response &res) {
  4994. handler_ran = true;
  4995. res.set_content(req.body, "text/plain");
  4996. });
  4997. svr.Post("/accept", [](const Request &req, Response &res) {
  4998. res.set_content(req.body, "text/plain");
  4999. });
  5000. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5001. if (req.matched_route == "/reject") {
  5002. res.status = StatusCode::Forbidden_403;
  5003. res.set_content("denied", "text/plain");
  5004. return Server::HandlerResponse::Handled;
  5005. }
  5006. return Server::HandlerResponse::Unhandled;
  5007. });
  5008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5009. auto se = detail::scope_exit([&] {
  5010. svr.stop();
  5011. thread.join();
  5012. ASSERT_FALSE(svr.is_running());
  5013. });
  5014. svr.wait_until_ready();
  5015. Client cli(HOST, PORT);
  5016. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5017. // rejects with 403 before the body is read, so 413 is never reached.
  5018. {
  5019. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5021. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5022. EXPECT_EQ("denied", res->body);
  5023. EXPECT_FALSE(handler_ran);
  5024. }
  5025. // An approved route still reads the body and enforces the payload limit.
  5026. {
  5027. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5029. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5030. }
  5031. }
  5032. TEST(UserDataTest, BasicOperations) {
  5033. httplib::UserData ud;
  5034. // Initially empty
  5035. EXPECT_FALSE(ud.has("key"));
  5036. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5037. // set and get
  5038. ud.set("key", 42);
  5039. EXPECT_TRUE(ud.has("key"));
  5040. auto *p = ud.get<int>("key");
  5041. ASSERT_NE(nullptr, p);
  5042. EXPECT_EQ(42, *p);
  5043. // Type mismatch → nullptr
  5044. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5045. // Overwrite with different type
  5046. ud.set("key", std::string("hello"));
  5047. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5048. auto *s = ud.get<std::string>("key");
  5049. ASSERT_NE(nullptr, s);
  5050. EXPECT_EQ("hello", *s);
  5051. // erase
  5052. ud.erase("key");
  5053. EXPECT_FALSE(ud.has("key"));
  5054. // clear
  5055. ud.set("a", 1);
  5056. ud.set("b", 2);
  5057. ud.clear();
  5058. EXPECT_FALSE(ud.has("a"));
  5059. EXPECT_FALSE(ud.has("b"));
  5060. }
  5061. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5062. struct AuthCtx {
  5063. std::string user_id;
  5064. };
  5065. Server svr;
  5066. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5067. res.user_data.set("auth", AuthCtx{"alice"});
  5068. return Server::HandlerResponse::Unhandled;
  5069. });
  5070. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5071. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5072. ASSERT_NE(nullptr, ctx);
  5073. res.set_content("Hello " + ctx->user_id, "text/plain");
  5074. });
  5075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5076. auto se = detail::scope_exit([&] {
  5077. svr.stop();
  5078. thread.join();
  5079. ASSERT_FALSE(svr.is_running());
  5080. });
  5081. svr.wait_until_ready();
  5082. Client cli(HOST, PORT);
  5083. auto res = cli.Get("/me");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ("Hello alice", res->body);
  5087. }
  5088. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5089. struct RoleCtx {
  5090. std::string role;
  5091. };
  5092. Server svr;
  5093. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5094. res.user_data.set("role", RoleCtx{"admin"});
  5095. return Server::HandlerResponse::Unhandled;
  5096. });
  5097. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5098. auto *ctx = res.user_data.get<RoleCtx>("role");
  5099. ASSERT_NE(nullptr, ctx);
  5100. res.set_content(ctx->role, "text/plain");
  5101. });
  5102. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5103. auto se = detail::scope_exit([&] {
  5104. svr.stop();
  5105. thread.join();
  5106. ASSERT_FALSE(svr.is_running());
  5107. });
  5108. svr.wait_until_ready();
  5109. Client cli(HOST, PORT);
  5110. auto res = cli.Get("/role");
  5111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5112. EXPECT_EQ(StatusCode::OK_200, res->status);
  5113. EXPECT_EQ("admin", res->body);
  5114. }
  5115. TEST(InvalidFormatTest, StatusCode) {
  5116. Server svr;
  5117. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5118. res.set_content("Hello World!\n", "text/plain");
  5119. res.status = 9999; // Status should be a three-digit code...
  5120. });
  5121. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5122. auto se = detail::scope_exit([&] {
  5123. svr.stop();
  5124. thread.join();
  5125. ASSERT_FALSE(svr.is_running());
  5126. });
  5127. svr.wait_until_ready();
  5128. {
  5129. Client cli(HOST, PORT);
  5130. auto res = cli.Get("/hi");
  5131. ASSERT_FALSE(res);
  5132. }
  5133. }
  5134. TEST(URLFragmentTest, WithFragment) {
  5135. Server svr;
  5136. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5137. EXPECT_TRUE(req.target == "/hi");
  5138. });
  5139. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5140. auto se = detail::scope_exit([&] {
  5141. svr.stop();
  5142. thread.join();
  5143. ASSERT_FALSE(svr.is_running());
  5144. });
  5145. svr.wait_until_ready();
  5146. {
  5147. Client cli(HOST, PORT);
  5148. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5149. EXPECT_TRUE(res);
  5150. EXPECT_EQ(StatusCode::OK_200, res->status);
  5151. res = cli.Get("/hi%23key1=val1=key2=val2");
  5152. EXPECT_TRUE(res);
  5153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5154. }
  5155. }
  5156. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5157. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5158. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5159. Server svr;
  5160. std::vector<std::string> targets;
  5161. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5162. targets.push_back(req.target);
  5163. });
  5164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5165. auto se = detail::scope_exit([&] {
  5166. svr.stop();
  5167. thread.join();
  5168. ASSERT_FALSE(svr.is_running());
  5169. });
  5170. svr.wait_until_ready();
  5171. Client cli(HOST, PORT);
  5172. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5173. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5174. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5175. // A '?' after the '#' belongs to the fragment, not to the query.
  5176. Request req;
  5177. req.method = "GET";
  5178. req.path = "/hi#f?x=1";
  5179. req.params.emplace("a", "1");
  5180. Response res;
  5181. auto error = Error::Success;
  5182. EXPECT_TRUE(cli.send(req, res, error));
  5183. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5184. "/hi?a=1"}),
  5185. targets);
  5186. }
  5187. TEST(HeaderWriter, SetHeaderWriter) {
  5188. Server svr;
  5189. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5190. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5191. return detail::write_headers(strm, hdrs);
  5192. });
  5193. svr.Get("/hi", [](const Request &req, Response &res) {
  5194. auto it = req.headers.find("CustomClientHeader");
  5195. EXPECT_TRUE(it != req.headers.end());
  5196. EXPECT_EQ(it->second, "CustomClientValue");
  5197. res.set_content("Hello World!\n", "text/plain");
  5198. });
  5199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5200. auto se = detail::scope_exit([&] {
  5201. svr.stop();
  5202. thread.join();
  5203. ASSERT_FALSE(svr.is_running());
  5204. });
  5205. svr.wait_until_ready();
  5206. {
  5207. Client cli(HOST, PORT);
  5208. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5209. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5210. return detail::write_headers(strm, hdrs);
  5211. });
  5212. auto res = cli.Get("/hi");
  5213. EXPECT_TRUE(res);
  5214. EXPECT_EQ(StatusCode::OK_200, res->status);
  5215. auto it = res->headers.find("CustomServerHeader");
  5216. EXPECT_TRUE(it != res->headers.end());
  5217. EXPECT_EQ(it->second, "CustomServerValue");
  5218. }
  5219. }
  5220. class ServerTest : public ::testing::Test {
  5221. protected:
  5222. ServerTest()
  5223. : cli_(HOST, PORT)
  5224. #ifdef CPPHTTPLIB_SSL_ENABLED
  5225. ,
  5226. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5227. #endif
  5228. {
  5229. #ifdef CPPHTTPLIB_SSL_ENABLED
  5230. cli_.enable_server_certificate_verification(false);
  5231. #endif
  5232. // Allow LARGE_DATA (100MB) responses
  5233. cli_.set_payload_max_length(200 * 1024 * 1024);
  5234. }
  5235. virtual void SetUp() {
  5236. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5237. svr_.set_payload_max_length(200 * 1024 * 1024);
  5238. svr_.set_mount_point("/", "./www");
  5239. svr_.set_mount_point("/mount", "./www2");
  5240. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5241. svr_.Get("/hi",
  5242. [&](const Request & /*req*/, Response &res) {
  5243. res.set_content("Hello World!", "text/plain");
  5244. })
  5245. .Get("/file_content",
  5246. [&](const Request & /*req*/, Response &res) {
  5247. res.set_file_content("./www/dir/test.html");
  5248. })
  5249. .Get("/file_content_with_content_type",
  5250. [&](const Request & /*req*/, Response &res) {
  5251. res.set_file_content("./www/file", "text/plain");
  5252. })
  5253. .Get("/invalid_file_content",
  5254. [&](const Request & /*req*/, Response &res) {
  5255. res.set_file_content("./www/dir/invalid_file_path");
  5256. })
  5257. .Get("/http_response_splitting",
  5258. [&](const Request & /*req*/, Response &res) {
  5259. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5260. EXPECT_EQ(0U, res.headers.size());
  5261. EXPECT_FALSE(res.has_header("a"));
  5262. res.set_header("a", "1\nSet-Cookie: a=1");
  5263. EXPECT_EQ(0U, res.headers.size());
  5264. EXPECT_FALSE(res.has_header("a"));
  5265. res.set_header("a", "1\rSet-Cookie: a=1");
  5266. EXPECT_EQ(0U, res.headers.size());
  5267. EXPECT_FALSE(res.has_header("a"));
  5268. res.set_header("a\r\nb", "0");
  5269. EXPECT_EQ(0U, res.headers.size());
  5270. EXPECT_FALSE(res.has_header("a"));
  5271. res.set_header("a\rb", "0");
  5272. EXPECT_EQ(0U, res.headers.size());
  5273. EXPECT_FALSE(res.has_header("a"));
  5274. res.set_header("a\nb", "0");
  5275. EXPECT_EQ(0U, res.headers.size());
  5276. EXPECT_FALSE(res.has_header("a"));
  5277. res.set_redirect("1\r\nSet-Cookie: a=1");
  5278. EXPECT_EQ(0U, res.headers.size());
  5279. EXPECT_FALSE(res.has_header("Location"));
  5280. })
  5281. .Get("/slow",
  5282. [&](const Request & /*req*/, Response &res) {
  5283. std::this_thread::sleep_for(std::chrono::seconds(4));
  5284. res.set_content("slow", "text/plain");
  5285. })
  5286. #if 0
  5287. .Post("/slowpost",
  5288. [&](const Request & /*req*/, Response &res) {
  5289. std::this_thread::sleep_for(std::chrono::seconds(2));
  5290. res.set_content("slow", "text/plain");
  5291. })
  5292. #endif
  5293. .Get("/remote_addr",
  5294. [&](const Request &req, Response &res) {
  5295. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5296. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5297. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5298. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5299. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5300. #endif
  5301. res.set_content(req.remote_addr, "text/plain");
  5302. })
  5303. .Get("/local_addr",
  5304. [&](const Request &req, Response &res) {
  5305. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5306. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5307. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5308. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5309. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5310. #endif
  5311. auto local_addr = req.local_addr;
  5312. auto local_port = std::to_string(req.local_port);
  5313. res.set_content(local_addr.append(":").append(local_port),
  5314. "text/plain");
  5315. })
  5316. .Get("/endwith%",
  5317. [&](const Request & /*req*/, Response &res) {
  5318. res.set_content("Hello World!", "text/plain");
  5319. })
  5320. .Get("/a\\+\\+b",
  5321. [&](const Request &req, Response &res) {
  5322. ASSERT_TRUE(req.has_param("a +b"));
  5323. auto val = req.get_param_value("a +b");
  5324. res.set_content(val, "text/plain");
  5325. })
  5326. .Get("/", [&](const Request & /*req*/,
  5327. Response &res) { res.set_redirect("/hi"); })
  5328. .Post("/1",
  5329. [](const Request & /*req*/, Response &res) {
  5330. res.set_redirect("/2", StatusCode::SeeOther_303);
  5331. })
  5332. .Get("/2",
  5333. [](const Request & /*req*/, Response &res) {
  5334. res.set_content("redirected.", "text/plain");
  5335. res.status = StatusCode::OK_200;
  5336. })
  5337. .Post("/person",
  5338. [&](const Request &req, Response &res) {
  5339. if (req.has_param("name") && req.has_param("note")) {
  5340. persons_[req.get_param_value("name")] =
  5341. req.get_param_value("note");
  5342. } else {
  5343. res.status = StatusCode::BadRequest_400;
  5344. }
  5345. })
  5346. .Put("/person",
  5347. [&](const Request &req, Response &res) {
  5348. if (req.has_param("name") && req.has_param("note")) {
  5349. persons_[req.get_param_value("name")] =
  5350. req.get_param_value("note");
  5351. } else {
  5352. res.status = StatusCode::BadRequest_400;
  5353. }
  5354. })
  5355. .Get("/person/(.*)",
  5356. [&](const Request &req, Response &res) {
  5357. string name = req.matches[1];
  5358. if (persons_.find(name) != persons_.end()) {
  5359. auto note = persons_[name];
  5360. res.set_content(note, "text/plain");
  5361. } else {
  5362. res.status = StatusCode::NotFound_404;
  5363. }
  5364. })
  5365. .Delete("/person",
  5366. [&](const Request &req, Response &res) {
  5367. if (req.has_param("name")) {
  5368. string name = req.get_param_value("name");
  5369. if (persons_.find(name) != persons_.end()) {
  5370. persons_.erase(name);
  5371. res.set_content("DELETED", "text/plain");
  5372. } else {
  5373. res.status = StatusCode::NotFound_404;
  5374. }
  5375. } else {
  5376. res.status = StatusCode::BadRequest_400;
  5377. }
  5378. })
  5379. .Post("/x-www-form-urlencoded-json",
  5380. [&](const Request &req, Response &res) {
  5381. auto json = req.get_param_value("json");
  5382. ASSERT_EQ(JSON_DATA, json);
  5383. res.set_content(json, "appliation/json");
  5384. res.status = StatusCode::OK_200;
  5385. })
  5386. .Get("/streamed-chunked",
  5387. [&](const Request & /*req*/, Response &res) {
  5388. res.set_chunked_content_provider(
  5389. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5390. sink.os << "123";
  5391. sink.os << "456";
  5392. sink.os << "789";
  5393. sink.done();
  5394. return true;
  5395. });
  5396. })
  5397. .Get("/streamed-chunked-with-prohibited-trailer",
  5398. [&](const Request & /*req*/, Response &res) {
  5399. auto i = new int(0);
  5400. // Declare both a prohibited trailer (Content-Length) and an
  5401. // allowed one
  5402. res.set_header("Trailer", "Content-Length, X-Allowed");
  5403. res.set_chunked_content_provider(
  5404. "text/plain",
  5405. [i](size_t /*offset*/, DataSink &sink) {
  5406. switch (*i) {
  5407. case 0: sink.os << "123"; break;
  5408. case 1: sink.os << "456"; break;
  5409. case 2: sink.os << "789"; break;
  5410. case 3: {
  5411. sink.done_with_trailer(
  5412. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5413. } break;
  5414. }
  5415. (*i)++;
  5416. return true;
  5417. },
  5418. [i](bool success) {
  5419. EXPECT_TRUE(success);
  5420. delete i;
  5421. });
  5422. })
  5423. .Get("/streamed-chunked2",
  5424. [&](const Request & /*req*/, Response &res) {
  5425. auto i = new int(0);
  5426. res.set_chunked_content_provider(
  5427. "text/plain",
  5428. [i](size_t /*offset*/, DataSink &sink) {
  5429. switch (*i) {
  5430. case 0: sink.os << "123"; break;
  5431. case 1: sink.os << "456"; break;
  5432. case 2: sink.os << "789"; break;
  5433. case 3: sink.done(); break;
  5434. }
  5435. (*i)++;
  5436. return true;
  5437. },
  5438. [i](bool success) {
  5439. EXPECT_TRUE(success);
  5440. delete i;
  5441. });
  5442. })
  5443. .Get("/streamed-chunked-with-trailer",
  5444. [&](const Request & /*req*/, Response &res) {
  5445. auto i = new int(0);
  5446. res.set_header("Trailer", "Dummy1, Dummy2");
  5447. res.set_chunked_content_provider(
  5448. "text/plain",
  5449. [i](size_t /*offset*/, DataSink &sink) {
  5450. switch (*i) {
  5451. case 0: sink.os << "123"; break;
  5452. case 1: sink.os << "456"; break;
  5453. case 2: sink.os << "789"; break;
  5454. case 3: {
  5455. sink.done_with_trailer(
  5456. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5457. } break;
  5458. }
  5459. (*i)++;
  5460. return true;
  5461. },
  5462. [i](bool success) {
  5463. EXPECT_TRUE(success);
  5464. delete i;
  5465. });
  5466. })
  5467. .Get("/streamed",
  5468. [&](const Request & /*req*/, Response &res) {
  5469. res.set_content_provider(
  5470. 6, "text/plain",
  5471. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5472. sink.os << (offset < 3 ? "a" : "b");
  5473. return true;
  5474. });
  5475. })
  5476. .Get("/streamed-without-length",
  5477. [&](const Request & /*req*/, Response &res) {
  5478. auto data = new std::string("abcdefg");
  5479. res.set_content_provider(
  5480. "text/plain",
  5481. [data](size_t offset, DataSink &sink) {
  5482. if (offset < data->size()) {
  5483. sink.os << data->substr(offset);
  5484. }
  5485. sink.done();
  5486. return true;
  5487. },
  5488. [data](bool success) {
  5489. EXPECT_TRUE(success);
  5490. delete data;
  5491. });
  5492. })
  5493. .Get("/streamed-with-range",
  5494. [&](const Request &req, Response &res) {
  5495. auto data = new std::string("abcdefg");
  5496. // An explicit status keeps the server from picking the 206 it
  5497. // would otherwise choose for a ranged request, so the response
  5498. // is not a partial representation.
  5499. auto status = req.get_param_value("status");
  5500. if (status == "200") {
  5501. res.status = StatusCode::OK_200;
  5502. } else if (status == "403") {
  5503. res.status = StatusCode::Forbidden_403;
  5504. }
  5505. res.set_content_provider(
  5506. data->size(), "text/plain",
  5507. [data](size_t offset, size_t length, DataSink &sink) {
  5508. size_t DATA_CHUNK_SIZE = 4;
  5509. const auto &d = *data;
  5510. auto out_len =
  5511. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5512. auto ret =
  5513. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5514. EXPECT_TRUE(ret);
  5515. return true;
  5516. },
  5517. [data, &req](bool success) {
  5518. EXPECT_EQ(success, !req.has_param("error"));
  5519. delete data;
  5520. });
  5521. })
  5522. .Get("/streamed-cancel",
  5523. [&](const Request & /*req*/, Response &res) {
  5524. res.set_content_provider(
  5525. size_t(-1), "text/plain",
  5526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5527. sink.os << "data_chunk";
  5528. return true;
  5529. });
  5530. })
  5531. .Get("/regex-with-delimiter",
  5532. [&](const Request &req, Response & /*res*/) {
  5533. ASSERT_TRUE(req.has_param("key"));
  5534. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5535. })
  5536. .Get("/with-range",
  5537. [&](const Request & /*req*/, Response &res) {
  5538. res.set_content("abcdefg", "text/plain");
  5539. })
  5540. .Get("/test-start-time",
  5541. [&](const Request &req, Response & /*res*/) {
  5542. EXPECT_NE(req.start_time_,
  5543. std::chrono::steady_clock::time_point::min());
  5544. })
  5545. .Get("/with-range-customized-response",
  5546. [&](const Request & /*req*/, Response &res) {
  5547. res.status = StatusCode::BadRequest_400;
  5548. res.set_content(JSON_DATA, "application/json");
  5549. })
  5550. .Post("/chunked",
  5551. [&](const Request &req, Response & /*res*/) {
  5552. EXPECT_EQ(req.body, "dechunked post body");
  5553. })
  5554. .Post("/large-chunked",
  5555. [&](const Request &req, Response & /*res*/) {
  5556. std::string expected(6 * 30 * 1024u, 'a');
  5557. EXPECT_EQ(req.body, expected);
  5558. })
  5559. .Post("/multipart",
  5560. [&](const Request &req, Response & /*res*/) {
  5561. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5562. req.form.get_field_count("text2") +
  5563. req.form.get_field_count("file3") +
  5564. req.form.get_field_count("file4"));
  5565. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5566. req.form.get_file_count("file2"));
  5567. ASSERT_TRUE(!req.form.has_file("???"));
  5568. ASSERT_TRUE(!req.form.has_field("???"));
  5569. ASSERT_TRUE(req.body.empty());
  5570. {
  5571. const auto &text = req.form.get_field("text1");
  5572. EXPECT_EQ("text default", text);
  5573. }
  5574. {
  5575. const auto &text = req.form.get_field("text2");
  5576. EXPECT_EQ("aωb", text);
  5577. }
  5578. {
  5579. const auto &file = req.form.get_file("file1");
  5580. EXPECT_EQ("hello.txt", file.filename);
  5581. EXPECT_EQ("text/plain", file.content_type);
  5582. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5583. }
  5584. {
  5585. const auto &file = req.form.get_file("file2");
  5586. EXPECT_EQ("world.json", file.filename);
  5587. EXPECT_EQ("application/json", file.content_type);
  5588. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5589. }
  5590. {
  5591. const auto &text = req.form.get_field("file3");
  5592. EXPECT_EQ(0u, text.size());
  5593. }
  5594. {
  5595. const auto &text = req.form.get_field("file4");
  5596. EXPECT_EQ(0u, text.size());
  5597. }
  5598. })
  5599. .Post("/multipart/multi_file_values",
  5600. [&](const Request &req, Response & /*res*/) {
  5601. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5602. req.form.get_field_count("multi_text1"));
  5603. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5604. ASSERT_TRUE(!req.form.has_file("???"));
  5605. ASSERT_TRUE(!req.form.has_field("???"));
  5606. ASSERT_TRUE(req.body.empty());
  5607. {
  5608. const auto &text = req.form.get_field("text");
  5609. EXPECT_EQ("default text", text);
  5610. }
  5611. {
  5612. const auto &text1_values = req.form.get_fields("multi_text1");
  5613. EXPECT_EQ(2u, text1_values.size());
  5614. EXPECT_EQ("aaaaa", text1_values[0]);
  5615. EXPECT_EQ("bbbbb", text1_values[1]);
  5616. }
  5617. {
  5618. const auto &file1_values = req.form.get_files("multi_file1");
  5619. EXPECT_EQ(2u, file1_values.size());
  5620. auto file1 = file1_values[0];
  5621. EXPECT_EQ(file1.filename, "hello.txt");
  5622. EXPECT_EQ(file1.content_type, "text/plain");
  5623. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5624. auto file2 = file1_values[1];
  5625. EXPECT_EQ(file2.filename, "world.json");
  5626. EXPECT_EQ(file2.content_type, "application/json");
  5627. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5628. }
  5629. })
  5630. .Post("/empty",
  5631. [&](const Request &req, Response &res) {
  5632. EXPECT_EQ(req.body, "");
  5633. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5634. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5635. res.set_content("empty", "text/plain");
  5636. })
  5637. .Post("/empty-no-content-type",
  5638. [&](const Request &req, Response &res) {
  5639. EXPECT_EQ(req.body, "");
  5640. EXPECT_FALSE(req.has_header("Content-Type"));
  5641. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5642. res.set_content("empty-no-content-type", "text/plain");
  5643. })
  5644. .Post("/path-only",
  5645. [&](const Request &req, Response &res) {
  5646. EXPECT_EQ(req.body, "");
  5647. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5648. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5649. res.set_content("path-only", "text/plain");
  5650. })
  5651. .Post("/path-headers-only",
  5652. [&](const Request &req, Response &res) {
  5653. EXPECT_EQ(req.body, "");
  5654. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5655. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5656. EXPECT_EQ("world", req.get_header_value("hello"));
  5657. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5658. res.set_content("path-headers-only", "text/plain");
  5659. })
  5660. .Post("/post-large",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(req.body, LARGE_DATA);
  5663. res.set_content(req.body, "text/plain");
  5664. })
  5665. .Post("/post-loopback",
  5666. [&](const Request &, Response &res,
  5667. ContentReader const &content_reader) {
  5668. std::string body;
  5669. content_reader([&](const char *data, size_t data_length) {
  5670. body.append(data, data_length);
  5671. return true;
  5672. });
  5673. res.set_content(body, "text/plain");
  5674. })
  5675. .Put("/put-loopback",
  5676. [&](const Request &, Response &res,
  5677. ContentReader const &content_reader) {
  5678. std::string body;
  5679. content_reader([&](const char *data, size_t data_length) {
  5680. body.append(data, data_length);
  5681. return true;
  5682. });
  5683. res.set_content(body, "text/plain");
  5684. })
  5685. .Patch("/patch-loopback",
  5686. [&](const Request &, Response &res,
  5687. ContentReader const &content_reader) {
  5688. std::string body;
  5689. content_reader([&](const char *data, size_t data_length) {
  5690. body.append(data, data_length);
  5691. return true;
  5692. });
  5693. res.set_content(body, "text/plain");
  5694. })
  5695. .Put("/empty-no-content-type",
  5696. [&](const Request &req, Response &res) {
  5697. EXPECT_EQ(req.body, "");
  5698. EXPECT_FALSE(req.has_header("Content-Type"));
  5699. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5700. res.set_content("empty-no-content-type", "text/plain");
  5701. })
  5702. .Put("/put",
  5703. [&](const Request &req, Response &res) {
  5704. EXPECT_EQ(req.body, "PUT");
  5705. res.set_content(req.body, "text/plain");
  5706. })
  5707. .Put("/put-large",
  5708. [&](const Request &req, Response &res) {
  5709. EXPECT_EQ(req.body, LARGE_DATA);
  5710. res.set_content(req.body, "text/plain");
  5711. })
  5712. .Patch("/patch",
  5713. [&](const Request &req, Response &res) {
  5714. EXPECT_EQ(req.body, "PATCH");
  5715. res.set_content(req.body, "text/plain");
  5716. })
  5717. .Delete("/delete",
  5718. [&](const Request & /*req*/, Response &res) {
  5719. res.set_content("DELETE", "text/plain");
  5720. })
  5721. .Delete("/delete-body",
  5722. [&](const Request &req, Response &res) {
  5723. EXPECT_EQ(req.body, "content");
  5724. res.set_content(req.body, "text/plain");
  5725. })
  5726. .Options(R"(\*)",
  5727. [&](const Request & /*req*/, Response &res) {
  5728. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5729. })
  5730. .CustomRoute("PROPFIND", "/dav/:id",
  5731. [&](const Request &req, Response &res) {
  5732. res.set_header("x-body-size",
  5733. std::to_string(req.body.size()));
  5734. res.set_header("x-matched-route", req.matched_route);
  5735. res.set_header("x-dav-id", req.path_params.at("id"));
  5736. res.status = StatusCode::MultiStatus_207;
  5737. res.set_content(req.body, "application/xml");
  5738. })
  5739. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5740. [&](const Request &req, Response &res) {
  5741. res.set_header("x-dav-match", req.matches[1]);
  5742. res.status = StatusCode::MultiStatus_207;
  5743. })
  5744. .CustomRoute("MKCOL", "/dav-mkcol",
  5745. [&](const Request &req, Response &res) {
  5746. EXPECT_TRUE(req.body.empty());
  5747. res.status = StatusCode::Created_201;
  5748. })
  5749. .CustomRoute(
  5750. "REPORT", "/dav-report",
  5751. [&](const Request & /*req*/, Response &res,
  5752. const ContentReader &content_reader) {
  5753. std::string body;
  5754. content_reader([&](const char *data, size_t data_length) {
  5755. body.append(data, data_length);
  5756. return true;
  5757. });
  5758. res.set_header("x-body-size", std::to_string(body.size()));
  5759. res.status = StatusCode::MultiStatus_207;
  5760. res.set_content(body, "application/xml");
  5761. })
  5762. .Get("/request-target",
  5763. [&](const Request &req, Response & /*res*/) {
  5764. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5765. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5766. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5767. })
  5768. .Get("/long-query-value",
  5769. [&](const Request &req, Response & /*res*/) {
  5770. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5771. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5772. })
  5773. .Get("/too-long-query-value",
  5774. [&](const Request &req, Response & /*res*/) {
  5775. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5776. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5777. })
  5778. .Get("/array-param",
  5779. [&](const Request &req, Response & /*res*/) {
  5780. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5781. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5782. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5783. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5784. })
  5785. .Get("/array-param-values",
  5786. [&](const Request &req, Response & /*res*/) {
  5787. auto values = req.get_param_values("array");
  5788. EXPECT_EQ(3u, values.size());
  5789. EXPECT_EQ("value1", values[0]);
  5790. EXPECT_EQ("value2", values[1]);
  5791. EXPECT_EQ("value3", values[2]);
  5792. auto empty = req.get_param_values("nonexistent");
  5793. EXPECT_TRUE(empty.empty());
  5794. })
  5795. .Post("/validate-no-multiple-headers",
  5796. [&](const Request &req, Response & /*res*/) {
  5797. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5798. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5799. })
  5800. .Post("/content_receiver",
  5801. [&](const Request &req, Response &res,
  5802. const ContentReader &content_reader) {
  5803. if (req.is_multipart_form_data()) {
  5804. std::vector<FormData> items;
  5805. content_reader(
  5806. [&](const FormData &file) {
  5807. items.push_back(file);
  5808. return true;
  5809. },
  5810. [&](const char *data, size_t data_length) {
  5811. items.back().content.append(data, data_length);
  5812. return true;
  5813. });
  5814. EXPECT_EQ(5u, items.size());
  5815. {
  5816. const auto &file = get_file_value(items, "text1");
  5817. EXPECT_TRUE(file.filename.empty());
  5818. EXPECT_EQ("text default", file.content);
  5819. }
  5820. {
  5821. const auto &file = get_file_value(items, "text2");
  5822. EXPECT_TRUE(file.filename.empty());
  5823. EXPECT_EQ("aωb", file.content);
  5824. }
  5825. {
  5826. const auto &file = get_file_value(items, "file1");
  5827. EXPECT_EQ("hello.txt", file.filename);
  5828. EXPECT_EQ("text/plain", file.content_type);
  5829. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5830. }
  5831. {
  5832. const auto &file = get_file_value(items, "file2");
  5833. EXPECT_EQ("world.json", file.filename);
  5834. EXPECT_EQ("application/json", file.content_type);
  5835. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5836. }
  5837. {
  5838. const auto &file = get_file_value(items, "file3");
  5839. EXPECT_TRUE(file.filename.empty());
  5840. EXPECT_EQ("application/octet-stream", file.content_type);
  5841. EXPECT_EQ(0u, file.content.size());
  5842. }
  5843. } else {
  5844. std::string body;
  5845. content_reader([&](const char *data, size_t data_length) {
  5846. EXPECT_EQ(7U, data_length);
  5847. body.append(data, data_length);
  5848. return true;
  5849. });
  5850. EXPECT_EQ(body, "content");
  5851. res.set_content(body, "text/plain");
  5852. }
  5853. })
  5854. .Put("/content_receiver",
  5855. [&](const Request & /*req*/, Response &res,
  5856. const ContentReader &content_reader) {
  5857. std::string body;
  5858. content_reader([&](const char *data, size_t data_length) {
  5859. body.append(data, data_length);
  5860. return true;
  5861. });
  5862. EXPECT_EQ(body, "content");
  5863. res.set_content(body, "text/plain");
  5864. })
  5865. .Patch("/content_receiver",
  5866. [&](const Request & /*req*/, Response &res,
  5867. const ContentReader &content_reader) {
  5868. std::string body;
  5869. content_reader([&](const char *data, size_t data_length) {
  5870. body.append(data, data_length);
  5871. return true;
  5872. });
  5873. EXPECT_EQ(body, "content");
  5874. res.set_content(body, "text/plain");
  5875. })
  5876. .Post("/query-string-and-body",
  5877. [&](const Request &req, Response & /*res*/) {
  5878. ASSERT_TRUE(req.has_param("key"));
  5879. EXPECT_EQ(req.get_param_value("key"), "value");
  5880. EXPECT_EQ(req.body, "content");
  5881. })
  5882. .Get("/last-request",
  5883. [&](const Request &req, Response & /*res*/) {
  5884. EXPECT_EQ("close", req.get_header_value("Connection"));
  5885. })
  5886. .Get(R"(/redirect/(\d+))",
  5887. [&](const Request &req, Response &res) {
  5888. auto num = std::stoi(req.matches[1]) + 1;
  5889. std::string url = "/redirect/" + std::to_string(num);
  5890. res.set_redirect(url);
  5891. })
  5892. .Post("/binary",
  5893. [&](const Request &req, Response &res) {
  5894. EXPECT_EQ(4U, req.body.size());
  5895. EXPECT_EQ("application/octet-stream",
  5896. req.get_header_value("Content-Type"));
  5897. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5898. res.set_content(req.body, "application/octet-stream");
  5899. })
  5900. .Put("/binary",
  5901. [&](const Request &req, Response &res) {
  5902. EXPECT_EQ(4U, req.body.size());
  5903. EXPECT_EQ("application/octet-stream",
  5904. req.get_header_value("Content-Type"));
  5905. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5906. res.set_content(req.body, "application/octet-stream");
  5907. })
  5908. .Patch("/binary",
  5909. [&](const Request &req, Response &res) {
  5910. EXPECT_EQ(4U, req.body.size());
  5911. EXPECT_EQ("application/octet-stream",
  5912. req.get_header_value("Content-Type"));
  5913. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5914. res.set_content(req.body, "application/octet-stream");
  5915. })
  5916. .Delete("/binary",
  5917. [&](const Request &req, Response &res) {
  5918. EXPECT_EQ(4U, req.body.size());
  5919. EXPECT_EQ("application/octet-stream",
  5920. req.get_header_value("Content-Type"));
  5921. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5922. res.set_content(req.body, "application/octet-stream");
  5923. })
  5924. .Get("/issue1772",
  5925. [&](const Request & /*req*/, Response &res) {
  5926. res.status = 401;
  5927. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5928. })
  5929. .Delete("/issue609",
  5930. [](const httplib::Request &, httplib::Response &res,
  5931. const httplib::ContentReader &) {
  5932. res.set_content("ok", "text/plain");
  5933. })
  5934. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5935. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5936. .Get("/compress",
  5937. [&](const Request & /*req*/, Response &res) {
  5938. res.set_content(
  5939. "12345678901234567890123456789012345678901234567890123456789"
  5940. "01234567890123456789012345678901234567890",
  5941. "text/plain");
  5942. })
  5943. .Get("/compress-with-charset",
  5944. [&](const Request & /*req*/, Response &res) {
  5945. res.set_content(
  5946. "12345678901234567890123456789012345678901234567890123456789"
  5947. "01234567890123456789012345678901234567890",
  5948. "application/json; charset=utf-8");
  5949. })
  5950. .Get("/nocompress",
  5951. [&](const Request & /*req*/, Response &res) {
  5952. res.set_content(
  5953. "12345678901234567890123456789012345678901234567890123456789"
  5954. "01234567890123456789012345678901234567890",
  5955. "application/octet-stream");
  5956. })
  5957. .Post("/compress-multipart",
  5958. [&](const Request &req, Response & /*res*/) {
  5959. EXPECT_EQ(2u, req.form.fields.size());
  5960. ASSERT_TRUE(!req.form.has_field("???"));
  5961. {
  5962. const auto &text = req.form.get_field("key1");
  5963. EXPECT_EQ("test", text);
  5964. }
  5965. {
  5966. const auto &text = req.form.get_field("key2");
  5967. EXPECT_EQ("--abcdefg123", text);
  5968. }
  5969. })
  5970. #endif
  5971. ;
  5972. persons_["john"] = "programmer";
  5973. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5974. svr_.wait_until_ready();
  5975. }
  5976. virtual void TearDown() {
  5977. svr_.stop();
  5978. if (!request_threads_.empty()) {
  5979. std::this_thread::sleep_for(std::chrono::seconds(1));
  5980. for (auto &t : request_threads_) {
  5981. t.join();
  5982. }
  5983. }
  5984. t_.join();
  5985. }
  5986. map<string, string> persons_;
  5987. #ifdef CPPHTTPLIB_SSL_ENABLED
  5988. SSLClient cli_;
  5989. SSLServer svr_;
  5990. #else
  5991. Client cli_;
  5992. Server svr_;
  5993. #endif
  5994. thread t_;
  5995. std::vector<thread> request_threads_;
  5996. };
  5997. TEST_F(ServerTest, GetMethod200) {
  5998. auto res = cli_.Get("/hi");
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. EXPECT_EQ("HTTP/1.1", res->version);
  6001. EXPECT_EQ(StatusCode::OK_200, res->status);
  6002. EXPECT_EQ("OK", res->reason);
  6003. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6004. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6005. EXPECT_EQ("Hello World!", res->body);
  6006. }
  6007. TEST_F(ServerTest, GetEmptyFile) {
  6008. auto res = cli_.Get("/empty_file");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::OK_200, res->status);
  6011. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6012. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6013. EXPECT_EQ("", res->body);
  6014. }
  6015. TEST_F(ServerTest, GetFileContent) {
  6016. auto res = cli_.Get("/file_content");
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6021. EXPECT_EQ("test.html", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetFileContentWithRange) {
  6024. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6027. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6028. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6029. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6030. EXPECT_EQ("est", res->body);
  6031. }
  6032. TEST_F(ServerTest, GetFileContentWithContentType) {
  6033. auto res = cli_.Get("/file_content_with_content_type");
  6034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6037. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6038. EXPECT_EQ("file\n", res->body);
  6039. }
  6040. TEST_F(ServerTest, GetInvalidFileContent) {
  6041. auto res = cli_.Get("/invalid_file_content");
  6042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6044. }
  6045. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6046. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. EXPECT_EQ("HTTP/1.1", res->version);
  6049. EXPECT_EQ(StatusCode::OK_200, res->status);
  6050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6051. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6052. EXPECT_EQ("Hello World!", res->body);
  6053. }
  6054. TEST_F(ServerTest, GetMethod302) {
  6055. auto res = cli_.Get("/");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ(StatusCode::Found_302, res->status);
  6058. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6059. }
  6060. TEST_F(ServerTest, GetMethod302Redirect) {
  6061. cli_.set_follow_location(true);
  6062. auto res = cli_.Get("/");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ(StatusCode::OK_200, res->status);
  6065. EXPECT_EQ("Hello World!", res->body);
  6066. EXPECT_EQ("/hi", res->location);
  6067. }
  6068. TEST_F(ServerTest, GetMethod404) {
  6069. auto res = cli_.Get("/invalid");
  6070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6071. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6072. }
  6073. TEST_F(ServerTest, HeadMethod200) {
  6074. auto res = cli_.Head("/hi");
  6075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6076. EXPECT_EQ(StatusCode::OK_200, res->status);
  6077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6078. EXPECT_TRUE(res->body.empty());
  6079. }
  6080. TEST_F(ServerTest, HeadMethod200Static) {
  6081. auto res = cli_.Head("/mount/dir/index.html");
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::OK_200, res->status);
  6084. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6085. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6086. EXPECT_TRUE(res->body.empty());
  6087. }
  6088. TEST_F(ServerTest, HeadMethod404) {
  6089. auto res = cli_.Head("/invalid");
  6090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6092. EXPECT_TRUE(res->body.empty());
  6093. }
  6094. TEST_F(ServerTest, GetMethodPersonJohn) {
  6095. auto res = cli_.Get("/person/john");
  6096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6097. EXPECT_EQ(StatusCode::OK_200, res->status);
  6098. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6099. EXPECT_EQ("programmer", res->body);
  6100. }
  6101. TEST_F(ServerTest, PostMethod1) {
  6102. auto res = cli_.Get("/person/john1");
  6103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6104. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6105. res = cli_.Post("/person", "name=john1&note=coder",
  6106. "application/x-www-form-urlencoded");
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. ASSERT_EQ(StatusCode::OK_200, res->status);
  6109. res = cli_.Get("/person/john1");
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. ASSERT_EQ(StatusCode::OK_200, res->status);
  6112. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6113. ASSERT_EQ("coder", res->body);
  6114. }
  6115. TEST_F(ServerTest, PostMethod2) {
  6116. auto res = cli_.Get("/person/john2");
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6119. Params params;
  6120. params.emplace("name", "john2");
  6121. params.emplace("note", "coder");
  6122. res = cli_.Post("/person", params);
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. ASSERT_EQ(StatusCode::OK_200, res->status);
  6125. res = cli_.Get("/person/john2");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. ASSERT_EQ(StatusCode::OK_200, res->status);
  6128. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6129. ASSERT_EQ("coder", res->body);
  6130. }
  6131. TEST_F(ServerTest, PutMethod3) {
  6132. auto res = cli_.Get("/person/john3");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6135. Params params;
  6136. params.emplace("name", "john3");
  6137. params.emplace("note", "coder");
  6138. res = cli_.Put("/person", params);
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. ASSERT_EQ(StatusCode::OK_200, res->status);
  6141. res = cli_.Get("/person/john3");
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. ASSERT_EQ(StatusCode::OK_200, res->status);
  6144. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6145. ASSERT_EQ("coder", res->body);
  6146. }
  6147. TEST_F(ServerTest, DeleteMethod1) {
  6148. auto res = cli_.Get("/person/john4");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6151. Params params;
  6152. params.emplace("name", "john4");
  6153. params.emplace("note", "coder");
  6154. res = cli_.Post("/person", params);
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. ASSERT_EQ(StatusCode::OK_200, res->status);
  6157. res = cli_.Get("/person/john4");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6161. ASSERT_EQ("coder", res->body);
  6162. Params delete_params;
  6163. delete_params.emplace("name", "john4");
  6164. res = cli_.Delete("/person", delete_params);
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. ASSERT_EQ(StatusCode::OK_200, res->status);
  6167. ASSERT_EQ("DELETED", res->body);
  6168. res = cli_.Get("/person/john4");
  6169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6170. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6171. }
  6172. TEST_F(ServerTest, DeleteMethod2) {
  6173. auto res = cli_.Get("/person/john5");
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6176. Params params;
  6177. params.emplace("name", "john5");
  6178. params.emplace("note", "developer");
  6179. res = cli_.Post("/person", params);
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. ASSERT_EQ(StatusCode::OK_200, res->status);
  6182. res = cli_.Get("/person/john5");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. ASSERT_EQ(StatusCode::OK_200, res->status);
  6185. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6186. ASSERT_EQ("developer", res->body);
  6187. Params delete_params;
  6188. delete_params.emplace("name", "john5");
  6189. Headers headers;
  6190. headers.emplace("Custom-Header", "test-value");
  6191. res = cli_.Delete("/person", headers, delete_params);
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. ASSERT_EQ(StatusCode::OK_200, res->status);
  6194. ASSERT_EQ("DELETED", res->body);
  6195. res = cli_.Get("/person/john5");
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6198. }
  6199. TEST_F(ServerTest, DeleteMethod3) {
  6200. auto res = cli_.Get("/person/john6");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6203. Params params;
  6204. params.emplace("name", "john6");
  6205. params.emplace("note", "tester");
  6206. res = cli_.Post("/person", params);
  6207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6208. ASSERT_EQ(StatusCode::OK_200, res->status);
  6209. res = cli_.Get("/person/john6");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. ASSERT_EQ(StatusCode::OK_200, res->status);
  6212. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6213. ASSERT_EQ("tester", res->body);
  6214. Params delete_params;
  6215. delete_params.emplace("name", "john6");
  6216. Headers headers;
  6217. headers.emplace("Custom-Header", "test-value");
  6218. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. ASSERT_EQ(StatusCode::OK_200, res->status);
  6221. ASSERT_EQ("DELETED", res->body);
  6222. res = cli_.Get("/person/john6");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6225. }
  6226. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6227. Params params;
  6228. params.emplace("json", JSON_DATA);
  6229. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. ASSERT_EQ(StatusCode::OK_200, res->status);
  6232. ASSERT_EQ(JSON_DATA, res->body);
  6233. }
  6234. TEST_F(ServerTest, PostEmptyContent) {
  6235. auto res = cli_.Post("/empty", "", "text/plain");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. ASSERT_EQ(StatusCode::OK_200, res->status);
  6238. ASSERT_EQ("empty", res->body);
  6239. }
  6240. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6241. auto res = cli_.Post("/empty-no-content-type");
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. ASSERT_EQ(StatusCode::OK_200, res->status);
  6244. ASSERT_EQ("empty-no-content-type", res->body);
  6245. }
  6246. TEST_F(ServerTest, PostPathOnly) {
  6247. auto res = cli_.Post("/path-only");
  6248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6249. ASSERT_EQ(StatusCode::OK_200, res->status);
  6250. ASSERT_EQ("path-only", res->body);
  6251. }
  6252. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6253. auto res = cli_.Post("/path-headers-only",
  6254. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. ASSERT_EQ(StatusCode::OK_200, res->status);
  6257. ASSERT_EQ("path-headers-only", res->body);
  6258. }
  6259. TEST_F(ServerTest, PostLarge) {
  6260. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6262. ASSERT_EQ(StatusCode::OK_200, res->status);
  6263. EXPECT_EQ(LARGE_DATA, res->body);
  6264. }
  6265. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6266. auto res = cli_.Put("/empty-no-content-type");
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. ASSERT_EQ(StatusCode::OK_200, res->status);
  6269. ASSERT_EQ("empty-no-content-type", res->body);
  6270. }
  6271. TEST_F(ServerTest, GetMethodDir) {
  6272. auto res = cli_.Get("/dir/");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6276. auto body = R"(<html>
  6277. <head>
  6278. </head>
  6279. <body>
  6280. <a href="/dir/test.html">Test</a>
  6281. <a href="/hi">hi</a>
  6282. </body>
  6283. </html>
  6284. )";
  6285. EXPECT_EQ(body, res->body);
  6286. }
  6287. TEST_F(ServerTest, GetMethodDirTest) {
  6288. auto res = cli_.Get("/dir/test.html");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6292. EXPECT_EQ("test.html", res->body);
  6293. }
  6294. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6295. auto res = cli_.Get("/dir/../dir/test.html");
  6296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6297. EXPECT_EQ(StatusCode::OK_200, res->status);
  6298. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6299. EXPECT_EQ("test.html", res->body);
  6300. }
  6301. TEST_F(ServerTest, GetMethodInvalidPath) {
  6302. auto res = cli_.Get("/dir/../test.html");
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6305. }
  6306. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6307. auto res = cli_.Get("/../www/dir/test.html");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6310. }
  6311. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6312. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6315. }
  6316. TEST_F(ServerTest, GetMethodDirMountTest) {
  6317. auto res = cli_.Get("/mount/dir/test.html");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::OK_200, res->status);
  6320. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6321. EXPECT_EQ("test.html", res->body);
  6322. }
  6323. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6324. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ(StatusCode::OK_200, res->status);
  6327. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6328. EXPECT_EQ("test.html", res->body);
  6329. }
  6330. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6331. auto res = cli_.Get("/mount/dir/../test.html");
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6334. }
  6335. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6336. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6339. }
  6340. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6341. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6343. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6344. }
  6345. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6346. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6349. }
  6350. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6351. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6354. }
  6355. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6356. auto res = cli_.Get("/mount/dir");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6359. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6360. }
  6361. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6362. auto res = cli_.Get("//dir");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6365. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6366. }
  6367. TEST_F(ServerTest, PostMethod303) {
  6368. auto res = cli_.Post("/1", "body", "text/plain");
  6369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6370. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6371. EXPECT_EQ("/2", res->get_header_value("Location"));
  6372. }
  6373. TEST_F(ServerTest, PostMethod303Redirect) {
  6374. cli_.set_follow_location(true);
  6375. auto res = cli_.Post("/1", "body", "text/plain");
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::OK_200, res->status);
  6378. EXPECT_EQ("redirected.", res->body);
  6379. EXPECT_EQ("/2", res->location);
  6380. }
  6381. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6382. auto res = cli_.Get("/dir/test.abcde");
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6386. EXPECT_EQ("abcde", res->body);
  6387. }
  6388. TEST_F(ServerTest, StaticFileRange) {
  6389. auto res =
  6390. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6392. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6393. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6394. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6395. EXPECT_EQ(true, res->has_header("Content-Range"));
  6396. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6397. EXPECT_EQ(std::string("cd"), res->body);
  6398. }
  6399. TEST_F(ServerTest, StaticFileRanges) {
  6400. auto res = cli_.Get("/dir/test.abcde",
  6401. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6403. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6404. EXPECT_TRUE(
  6405. res->get_header_value("Content-Type")
  6406. .find(
  6407. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6408. 0);
  6409. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6410. }
  6411. TEST_F(ServerTest, StaticFileRangeHead) {
  6412. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6415. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6416. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6417. EXPECT_EQ(true, res->has_header("Content-Range"));
  6418. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6419. }
  6420. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6421. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6424. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6425. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6426. EXPECT_EQ(true, res->has_header("Content-Range"));
  6427. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6428. res->get_header_value("Content-Range"));
  6429. EXPECT_EQ("LAST\n", res->body);
  6430. }
  6431. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6432. auto res =
  6433. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6435. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6436. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6437. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6438. EXPECT_EQ(true, res->has_header("Content-Range"));
  6439. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6440. }
  6441. TEST_F(ServerTest, StaticFileBigFile) {
  6442. auto res = cli_.Get("/dir/1MB.txt");
  6443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6444. EXPECT_EQ(StatusCode::OK_200, res->status);
  6445. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6446. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6447. }
  6448. TEST_F(ServerTest, InvalidBaseDirMount) {
  6449. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6450. }
  6451. TEST_F(ServerTest, Binary) {
  6452. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6453. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6454. "application/octet-stream");
  6455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6456. ASSERT_EQ(StatusCode::OK_200, res->status);
  6457. ASSERT_EQ(4U, res->body.size());
  6458. res = cli_.Put("/binary", binary.data(), binary.size(),
  6459. "application/octet-stream");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. ASSERT_EQ(StatusCode::OK_200, res->status);
  6462. ASSERT_EQ(4U, res->body.size());
  6463. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6464. "application/octet-stream");
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. ASSERT_EQ(StatusCode::OK_200, res->status);
  6467. ASSERT_EQ(4U, res->body.size());
  6468. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6469. "application/octet-stream");
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. ASSERT_EQ(StatusCode::OK_200, res->status);
  6472. ASSERT_EQ(4U, res->body.size());
  6473. }
  6474. TEST_F(ServerTest, BinaryString) {
  6475. auto binary = std::string("\x00\x01\x02\x03", 4);
  6476. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. ASSERT_EQ(StatusCode::OK_200, res->status);
  6479. ASSERT_EQ(4U, res->body.size());
  6480. res = cli_.Put("/binary", binary, "application/octet-stream");
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. ASSERT_EQ(StatusCode::OK_200, res->status);
  6483. ASSERT_EQ(4U, res->body.size());
  6484. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. ASSERT_EQ(StatusCode::OK_200, res->status);
  6487. ASSERT_EQ(4U, res->body.size());
  6488. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. ASSERT_EQ(StatusCode::OK_200, res->status);
  6491. ASSERT_EQ(4U, res->body.size());
  6492. }
  6493. TEST_F(ServerTest, EmptyRequest) {
  6494. auto res = cli_.Get("");
  6495. ASSERT_TRUE(!res);
  6496. EXPECT_EQ(Error::Connection, res.error());
  6497. }
  6498. TEST_F(ServerTest, LongRequest) {
  6499. std::string request;
  6500. for (size_t i = 0; i < 545; i++) {
  6501. request += "/TooLongRequest";
  6502. }
  6503. request += "OK";
  6504. auto res = cli_.Get(request.c_str());
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6507. }
  6508. TEST_F(ServerTest, TooLongRequest) {
  6509. std::string request;
  6510. for (size_t i = 0; i < 546; i++) {
  6511. request += "/TooLongRequest";
  6512. }
  6513. request += "_NG";
  6514. auto start = std::chrono::high_resolution_clock::now();
  6515. cli_.set_keep_alive(true);
  6516. auto res = cli_.Get(request.c_str());
  6517. auto end = std::chrono::high_resolution_clock::now();
  6518. auto elapsed =
  6519. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6520. .count();
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6523. EXPECT_LE(elapsed, 1000);
  6524. EXPECT_EQ("close", res->get_header_value("Connection"));
  6525. EXPECT_FALSE(cli_.is_socket_open());
  6526. }
  6527. TEST_F(ServerTest, AlmostTooLongRequest) {
  6528. // test for #2046 - URI length check shouldn't include other content on req
  6529. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6530. // leading /, space, HTTP/1.1)
  6531. std::string request =
  6532. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6533. auto res = cli_.Get(request.c_str());
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6536. }
  6537. TEST_F(ServerTest, LongHeader) {
  6538. Request req;
  6539. req.method = "GET";
  6540. req.path = "/hi";
  6541. std::string host_and_port;
  6542. host_and_port += HOST;
  6543. host_and_port += ":";
  6544. host_and_port += std::to_string(PORT);
  6545. req.headers.emplace("Host", host_and_port.c_str());
  6546. req.headers.emplace("Accept", "*/*");
  6547. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6548. req.headers.emplace(
  6549. "Header-Name",
  6550. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6551. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6552. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6553. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6554. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6555. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6556. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6557. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6558. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6559. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6560. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6561. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6562. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6563. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6564. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6565. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6578. "@@@@@@@@@@@@@@@@");
  6579. auto res = std::make_shared<Response>();
  6580. auto error = Error::Success;
  6581. auto ret = cli_.send(req, *res, error);
  6582. ASSERT_TRUE(ret);
  6583. EXPECT_EQ(StatusCode::OK_200, res->status);
  6584. }
  6585. TEST_F(ServerTest, LongQueryValue) {
  6586. auto start = std::chrono::high_resolution_clock::now();
  6587. cli_.set_keep_alive(true);
  6588. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6589. auto end = std::chrono::high_resolution_clock::now();
  6590. auto elapsed =
  6591. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6592. .count();
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6595. EXPECT_LE(elapsed, 1000);
  6596. EXPECT_EQ("close", res->get_header_value("Connection"));
  6597. EXPECT_FALSE(cli_.is_socket_open());
  6598. }
  6599. TEST_F(ServerTest, TooLongQueryValue) {
  6600. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6601. ASSERT_FALSE(res);
  6602. EXPECT_EQ(Error::Read, res.error());
  6603. }
  6604. TEST_F(ServerTest, TooLongHeader) {
  6605. Request req;
  6606. req.method = "GET";
  6607. req.path = "/hi";
  6608. std::string host_and_port;
  6609. host_and_port += HOST;
  6610. host_and_port += ":";
  6611. host_and_port += std::to_string(PORT);
  6612. req.headers.emplace("Host", host_and_port.c_str());
  6613. req.headers.emplace("Accept", "*/*");
  6614. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6615. req.headers.emplace(
  6616. "Header-Name",
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6645. "@@@@@@@@@@@@@@@@@");
  6646. auto res = std::make_shared<Response>();
  6647. auto error = Error::Success;
  6648. auto ret = cli_.send(req, *res, error);
  6649. ASSERT_TRUE(ret);
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. }
  6652. TEST_F(ServerTest, HeaderCountAtLimit) {
  6653. // Test with headers just under the 100 limit
  6654. httplib::Headers headers;
  6655. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6656. // This should keep us just under the 100 header limit
  6657. for (int i = 0; i < 95; i++) {
  6658. std::string name = "X-Test-Header-" + std::to_string(i);
  6659. std::string value = "value" + std::to_string(i);
  6660. headers.emplace(name, value);
  6661. }
  6662. // This should work fine as we're under the limit
  6663. auto res = cli_.Get("/hi", headers);
  6664. EXPECT_TRUE(res);
  6665. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6666. }
  6667. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6668. // Test with many headers to exceed the 100 limit
  6669. httplib::Headers headers;
  6670. // Add 150 headers to definitely exceed the 100 limit
  6671. for (int i = 0; i < 150; i++) {
  6672. std::string name = "X-Test-Header-" + std::to_string(i);
  6673. std::string value = "value" + std::to_string(i);
  6674. headers.emplace(name, value);
  6675. }
  6676. // This should fail due to exceeding header count limit
  6677. cli_.set_keep_alive(true);
  6678. auto res = cli_.Get("/hi", headers);
  6679. // The server should respond with 400 Bad Request
  6680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6681. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6682. EXPECT_EQ("close", res->get_header_value("Connection"));
  6683. EXPECT_FALSE(cli_.is_socket_open());
  6684. }
  6685. TEST_F(ServerTest, PercentEncoding) {
  6686. auto res = cli_.Get("/e%6edwith%");
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::OK_200, res->status);
  6689. }
  6690. TEST_F(ServerTest, PercentEncodingUnicode) {
  6691. auto res = cli_.Get("/e%u006edwith%");
  6692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6693. EXPECT_EQ(StatusCode::OK_200, res->status);
  6694. }
  6695. TEST_F(ServerTest, InvalidPercentEncoding) {
  6696. auto res = cli_.Get("/%endwith%");
  6697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6699. }
  6700. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6701. auto res = cli_.Get("/%uendwith%");
  6702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6704. }
  6705. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6706. auto res = cli_.Get("/hello?aaa=bbb%");
  6707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6709. }
  6710. TEST_F(ServerTest, PlusSignEncoding) {
  6711. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::OK_200, res->status);
  6714. EXPECT_EQ("a +b", res->body);
  6715. }
  6716. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6717. // This test simulates a potential DoS attack using many headers
  6718. // to verify our security fix prevents memory exhaustion
  6719. httplib::Headers attack_headers;
  6720. // Attempt to add many headers like an attacker would (200 headers to far
  6721. // exceed limit)
  6722. for (int i = 0; i < 200; i++) {
  6723. std::string name = "X-Attack-Header-" + std::to_string(i);
  6724. std::string value = "attack_payload_" + std::to_string(i);
  6725. attack_headers.emplace(name, value);
  6726. }
  6727. // Try to POST with excessive headers
  6728. cli_.set_keep_alive(true);
  6729. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6730. // Should either fail or return 400 Bad Request due to security limit
  6731. if (res) {
  6732. // If we get a response, it should be 400 Bad Request
  6733. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6734. EXPECT_EQ("close", res->get_header_value("Connection"));
  6735. }
  6736. EXPECT_FALSE(cli_.is_socket_open());
  6737. }
  6738. TEST_F(ServerTest, MultipartFormData) {
  6739. UploadFormDataItems items = {
  6740. {"text1", "text default", "", ""},
  6741. {"text2", "aωb", "", ""},
  6742. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6743. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6744. {"file3", "", "", "application/octet-stream"},
  6745. {"file4", "", "", " application/json tmp-string "}};
  6746. auto res = cli_.Post("/multipart", items);
  6747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6748. EXPECT_EQ(StatusCode::OK_200, res->status);
  6749. }
  6750. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6751. UploadFormDataItems items = {
  6752. {"text", "default text", "", ""},
  6753. {"multi_text1", "aaaaa", "", ""},
  6754. {"multi_text1", "bbbbb", "", ""},
  6755. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6756. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6757. "application/json"},
  6758. };
  6759. auto res = cli_.Post("/multipart/multi_file_values", items);
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ(StatusCode::OK_200, res->status);
  6762. }
  6763. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6764. auto res = cli_.Get("/hi");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6768. EXPECT_EQ("Hello World!", res->body);
  6769. }
  6770. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6771. Request req;
  6772. req.method = "POST";
  6773. req.path = "/chunked";
  6774. std::string host_and_port;
  6775. host_and_port += HOST;
  6776. host_and_port += ":";
  6777. host_and_port += std::to_string(PORT);
  6778. req.headers.emplace("Host", host_and_port.c_str());
  6779. req.headers.emplace("Accept", "*/*");
  6780. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6781. req.headers.emplace("Content-Type", "text/plain");
  6782. req.headers.emplace("Content-Length", "0");
  6783. req.headers.emplace(
  6784. "Transfer-Encoding",
  6785. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6786. // Client does not chunk, so make a chunked body manually.
  6787. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6788. auto res = std::make_shared<Response>();
  6789. auto error = Error::Success;
  6790. auto ret = cli_.send(req, *res, error);
  6791. ASSERT_TRUE(ret);
  6792. EXPECT_EQ(StatusCode::OK_200, res->status);
  6793. }
  6794. template <typename ClientT>
  6795. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6796. int expected_status) {
  6797. Request req;
  6798. req.method = "POST";
  6799. req.path = "/chunked";
  6800. std::string host_and_port;
  6801. host_and_port += HOST;
  6802. host_and_port += ":";
  6803. host_and_port += std::to_string(PORT);
  6804. req.headers.emplace("Host", host_and_port.c_str());
  6805. req.headers.emplace("Content-Length", "0");
  6806. req.headers.emplace("Transfer-Encoding", "chunked");
  6807. req.body = body;
  6808. auto res = std::make_shared<Response>();
  6809. auto error = Error::Success;
  6810. ASSERT_TRUE(cli.send(req, *res, error));
  6811. EXPECT_EQ(expected_status, res->status);
  6812. }
  6813. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6814. // rather than treat them as valid lengths.
  6815. template <typename ClientT>
  6816. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6817. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6818. }
  6819. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6820. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6821. }
  6822. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6823. expect_chunked_body_rejected(
  6824. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6825. }
  6826. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6827. // chunk-size line carries no CR, LF or other control character ahead of its
  6828. // terminator. Such a line must be refused rather than read as extension text.
  6829. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6830. expect_chunked_body_rejected(
  6831. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6832. }
  6833. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6834. expect_chunked_body_rejected(
  6835. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6836. }
  6837. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6838. expect_chunked_body_rejected(
  6839. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6840. }
  6841. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6842. // The literal stays split: a hex escape consumes every hex digit that
  6843. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6844. expect_chunked_body_rejected(
  6845. cli_, "4;a\x01"
  6846. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6847. }
  6848. TEST_F(ServerTest, AcceptsChunkExtension) {
  6849. expect_chunked_body_status(cli_,
  6850. "4;name=value\r\ndech\r\n"
  6851. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6852. "0;last\r\n\r\n",
  6853. StatusCode::OK_200);
  6854. }
  6855. TEST_F(ServerTest, GetStreamed2) {
  6856. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6859. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6860. EXPECT_EQ(true, res->has_header("Content-Range"));
  6861. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6862. EXPECT_EQ(std::string("ab"), res->body);
  6863. }
  6864. TEST_F(ServerTest, GetStreamed) {
  6865. auto res = cli_.Get("/streamed");
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6869. EXPECT_EQ(std::string("aaabbb"), res->body);
  6870. }
  6871. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6872. auto res = cli_.Get("/streamed-without-length",
  6873. Headers{make_range_header({{0, -1}})});
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ(false, res->has_header("Content-Length"));
  6877. EXPECT_EQ(false, res->has_header("Content-Range"));
  6878. EXPECT_EQ(std::string("abcdefg"), res->body);
  6879. }
  6880. TEST_F(ServerTest, GetStreamedWithRange1) {
  6881. auto res =
  6882. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6885. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6886. EXPECT_EQ(true, res->has_header("Content-Range"));
  6887. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6888. EXPECT_EQ(std::string("def"), res->body);
  6889. }
  6890. TEST_F(ServerTest, GetStreamedWithRange2) {
  6891. auto res =
  6892. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6895. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6896. EXPECT_EQ(true, res->has_header("Content-Range"));
  6897. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6898. EXPECT_EQ(std::string("bcdefg"), res->body);
  6899. }
  6900. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6901. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6904. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6905. EXPECT_EQ(true, res->has_header("Content-Range"));
  6906. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6907. EXPECT_EQ(std::string("efg"), res->body);
  6908. }
  6909. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6910. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6911. // the entire representation.
  6912. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6913. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6916. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6917. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6918. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6919. }
  6920. }
  6921. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6922. auto res =
  6923. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6926. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6927. EXPECT_EQ(false, res->has_header("Content-Range"));
  6928. EXPECT_EQ(0U, res->body.size());
  6929. }
  6930. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6931. // Only a 206 is served as a partial representation. Under any other status
  6932. // `apply_ranges()` reported the full content length, so the body must match
  6933. // that header, and the content provider must never be asked for an offset
  6934. // outside the representation.
  6935. auto check = [&](int status, const char *range) {
  6936. auto path =
  6937. std::string("/streamed-with-range?status=") + std::to_string(status);
  6938. auto ctx = path + " Range: " + range;
  6939. auto res = cli_.Get(path, Headers{{"Range", range}});
  6940. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6941. EXPECT_EQ(status, res->status) << ctx;
  6942. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6944. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6945. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6946. };
  6947. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6948. check(403, "bytes=3-5");
  6949. // The offset is far past the representation.
  6950. check(403, "bytes=100000-100200");
  6951. // `first_pos` is still -1 here, and the bounds asserts in
  6952. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6953. check(403, "bytes=-3");
  6954. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6955. // multipart branch would have written one that is empty.
  6956. check(403, "bytes=1-2, 4-5");
  6957. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6958. // covers the whole representation.
  6959. check(200, "bytes=3-5");
  6960. check(200, "bytes=1-2, 4-5");
  6961. }
  6962. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6963. auto res =
  6964. cli_.Get("/streamed-with-range",
  6965. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6966. "92233720368547758079223372036854775807"}});
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6969. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6970. EXPECT_EQ(false, res->has_header("Content-Range"));
  6971. EXPECT_EQ(0U, res->body.size());
  6972. }
  6973. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6974. auto res = cli_.Get(
  6975. "/with-range",
  6976. Headers{{"Range",
  6977. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6978. {"Accept-Encoding", ""}});
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6981. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6982. EXPECT_EQ(true, res->has_header("Content-Range"));
  6983. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6984. EXPECT_EQ(std::string("abcdefg"), res->body);
  6985. }
  6986. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6987. auto res = cli_.Get("/with-range", Headers{
  6988. {"Range", "bytes=0-"},
  6989. {"Accept-Encoding", ""},
  6990. });
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6993. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6994. EXPECT_EQ(true, res->has_header("Content-Range"));
  6995. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6996. EXPECT_EQ(std::string("abcdefg"), res->body);
  6997. }
  6998. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6999. auto res = cli_.Get("/streamed-with-range",
  7000. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7003. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7004. EXPECT_EQ(false, res->has_header("Content-Range"));
  7005. EXPECT_EQ(267U, res->body.size());
  7006. // Check that both range contents are present
  7007. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7008. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7009. // Check that Content-Range headers are present for both ranges
  7010. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7011. std::string::npos);
  7012. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7013. std::string::npos);
  7014. }
  7015. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7016. Ranges ranges;
  7017. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7018. ranges.emplace_back(0, -1);
  7019. }
  7020. auto res = cli_.Get("/streamed-with-range?error",
  7021. Headers{{make_range_header(ranges)}});
  7022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7023. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7024. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7025. EXPECT_EQ(false, res->has_header("Content-Range"));
  7026. EXPECT_EQ(0U, res->body.size());
  7027. }
  7028. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7029. auto res = cli_.Get("/streamed-with-range",
  7030. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7033. EXPECT_EQ(5U, res->body.size());
  7034. // Check that overlapping ranges are coalesced into a single range
  7035. EXPECT_EQ("bcdef", res->body);
  7036. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7037. // Should be single range, not multipart
  7038. EXPECT_TRUE(res->has_header("Content-Range"));
  7039. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7042. auto res = cli_.Get("/streamed-with-range",
  7043. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7046. EXPECT_EQ(268U, res->body.size());
  7047. // Check that both range contents are present
  7048. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7049. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7050. // Check that Content-Range headers are present for both ranges
  7051. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7052. std::string::npos);
  7053. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7054. std::string::npos);
  7055. }
  7056. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7057. auto res = cli_.Get("/streamed-with-range",
  7058. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7061. EXPECT_EQ(269U, res->body.size());
  7062. // Check that both duplicate range contents are present
  7063. size_t first_abc = res->body.find("abc\r\n");
  7064. EXPECT_TRUE(first_abc != std::string::npos);
  7065. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7066. EXPECT_TRUE(second_abc != std::string::npos);
  7067. // Check that Content-Range headers are present for both ranges
  7068. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7069. EXPECT_TRUE(first_range != std::string::npos);
  7070. size_t second_range =
  7071. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7072. EXPECT_TRUE(second_range != std::string::npos);
  7073. }
  7074. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7075. auto res =
  7076. cli_.Get("/streamed-with-range?error",
  7077. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7079. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7080. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7081. EXPECT_EQ(false, res->has_header("Content-Range"));
  7082. EXPECT_EQ(0U, res->body.size());
  7083. }
  7084. TEST_F(ServerTest, GetStreamedEndless) {
  7085. uint64_t offset = 0;
  7086. auto res = cli_.Get("/streamed-cancel",
  7087. [&](const char * /*data*/, uint64_t data_length) {
  7088. if (offset < 100) {
  7089. offset += data_length;
  7090. return true;
  7091. }
  7092. return false;
  7093. });
  7094. ASSERT_TRUE(!res);
  7095. EXPECT_EQ(Error::Canceled, res.error());
  7096. }
  7097. TEST_F(ServerTest, ClientStop) {
  7098. std::atomic_size_t count{4};
  7099. std::vector<std::thread> threads;
  7100. for (auto i = count.load(); i != 0; --i) {
  7101. threads.emplace_back([&]() {
  7102. auto res = cli_.Get("/streamed-cancel",
  7103. [&](const char *, uint64_t) { return true; });
  7104. --count;
  7105. ASSERT_TRUE(!res);
  7106. EXPECT_TRUE(res.error() == Error::Canceled ||
  7107. res.error() == Error::Read || res.error() == Error::Write);
  7108. });
  7109. }
  7110. std::this_thread::sleep_for(std::chrono::seconds(2));
  7111. while (count != 0) {
  7112. cli_.stop();
  7113. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7114. }
  7115. for (auto &t : threads) {
  7116. t.join();
  7117. }
  7118. }
  7119. TEST_F(ServerTest, GetWithRange1) {
  7120. auto res = cli_.Get("/with-range", Headers{
  7121. make_range_header({{3, 5}}),
  7122. {"Accept-Encoding", ""},
  7123. });
  7124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7125. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7126. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7127. EXPECT_EQ(true, res->has_header("Content-Range"));
  7128. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7129. EXPECT_EQ(std::string("def"), res->body);
  7130. }
  7131. TEST_F(ServerTest, GetWithRange2) {
  7132. auto res = cli_.Get("/with-range", Headers{
  7133. make_range_header({{1, -1}}),
  7134. {"Accept-Encoding", ""},
  7135. });
  7136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7137. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7138. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7139. EXPECT_EQ(true, res->has_header("Content-Range"));
  7140. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7141. EXPECT_EQ(std::string("bcdefg"), res->body);
  7142. }
  7143. TEST_F(ServerTest, GetWithRange3) {
  7144. auto res = cli_.Get("/with-range", Headers{
  7145. make_range_header({{0, 0}}),
  7146. {"Accept-Encoding", ""},
  7147. });
  7148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7149. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7150. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7151. EXPECT_EQ(true, res->has_header("Content-Range"));
  7152. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7153. EXPECT_EQ(std::string("a"), res->body);
  7154. }
  7155. TEST_F(ServerTest, GetWithRange4) {
  7156. auto res = cli_.Get("/with-range", Headers{
  7157. make_range_header({{-1, 2}}),
  7158. {"Accept-Encoding", ""},
  7159. });
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7162. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7163. EXPECT_EQ(true, res->has_header("Content-Range"));
  7164. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7165. EXPECT_EQ(std::string("fg"), res->body);
  7166. }
  7167. TEST_F(ServerTest, GetWithRange5) {
  7168. auto res = cli_.Get("/with-range", Headers{
  7169. make_range_header({{0, 5}}),
  7170. {"Accept-Encoding", ""},
  7171. });
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7174. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7175. EXPECT_EQ(true, res->has_header("Content-Range"));
  7176. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7177. EXPECT_EQ(std::string("abcdef"), res->body);
  7178. }
  7179. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7180. auto res =
  7181. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7184. }
  7185. TEST_F(ServerTest, GetWithRangeMultipart) {
  7186. auto res =
  7187. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7190. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7191. EXPECT_EQ(false, res->has_header("Content-Range"));
  7192. EXPECT_EQ(267U, res->body.size());
  7193. }
  7194. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7195. auto res = cli_.Get("/with-range",
  7196. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7198. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7199. }
  7200. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7201. auto res = cli_.Get("/with-range-customized-response",
  7202. Headers{{make_range_header({{1, 2}})}});
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7205. EXPECT_EQ(true, res->has_header("Content-Length"));
  7206. EXPECT_EQ(false, res->has_header("Content-Range"));
  7207. EXPECT_EQ(JSON_DATA, res->body);
  7208. }
  7209. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7210. auto res = cli_.Get("/with-range-customized-response",
  7211. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7214. EXPECT_EQ(true, res->has_header("Content-Length"));
  7215. EXPECT_EQ(false, res->has_header("Content-Range"));
  7216. EXPECT_EQ(JSON_DATA, res->body);
  7217. }
  7218. TEST_F(ServerTest, Issue1772) {
  7219. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7222. }
  7223. TEST_F(ServerTest, Issue609) {
  7224. auto res = cli_.Delete("/issue609");
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::OK_200, res->status);
  7227. EXPECT_EQ(std::string("ok"), res->body);
  7228. }
  7229. TEST_F(ServerTest, GetStreamedChunked) {
  7230. auto res = cli_.Get("/streamed-chunked");
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::OK_200, res->status);
  7233. EXPECT_EQ(std::string("123456789"), res->body);
  7234. }
  7235. TEST_F(ServerTest, GetStreamedChunked2) {
  7236. auto res = cli_.Get("/streamed-chunked2");
  7237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7238. EXPECT_EQ(StatusCode::OK_200, res->status);
  7239. EXPECT_EQ(std::string("123456789"), res->body);
  7240. }
  7241. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7242. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ(std::string("123456789"), res->body);
  7246. EXPECT_TRUE(res->has_header("Trailer"));
  7247. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7248. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7249. // Trailers are now stored separately from headers (security fix)
  7250. EXPECT_EQ(2U, res->trailers.size());
  7251. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7252. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7253. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7254. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7255. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7256. // Verify trailers are NOT in headers (security verification)
  7257. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7258. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7259. }
  7260. TEST_F(ServerTest, LargeChunkedPost) {
  7261. Request req;
  7262. req.method = "POST";
  7263. req.path = "/large-chunked";
  7264. std::string host_and_port;
  7265. host_and_port += HOST;
  7266. host_and_port += ":";
  7267. host_and_port += std::to_string(PORT);
  7268. req.headers.emplace("Host", host_and_port.c_str());
  7269. req.headers.emplace("Accept", "*/*");
  7270. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7271. req.headers.emplace("Content-Type", "text/plain");
  7272. req.headers.emplace("Content-Length", "0");
  7273. req.headers.emplace("Transfer-Encoding", "chunked");
  7274. std::string long_string(30 * 1024u, 'a');
  7275. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7276. // Attempt to make a large enough post to exceed OS buffers, to test that
  7277. // the server handles short reads if the full chunk data isn't available.
  7278. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7279. auto res = std::make_shared<Response>();
  7280. auto error = Error::Success;
  7281. auto ret = cli_.send(req, *res, error);
  7282. ASSERT_TRUE(ret);
  7283. EXPECT_EQ(StatusCode::OK_200, res->status);
  7284. }
  7285. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7286. auto res = cli_.Get("/remote_addr");
  7287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7288. EXPECT_EQ(StatusCode::OK_200, res->status);
  7289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7290. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7291. }
  7292. TEST_F(ServerTest, GetMethodLocalAddr) {
  7293. auto res = cli_.Get("/local_addr");
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::OK_200, res->status);
  7296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7297. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7298. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7299. }
  7300. TEST_F(ServerTest, HTTPResponseSplitting) {
  7301. auto res = cli_.Get("/http_response_splitting");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. }
  7305. TEST_F(ServerTest, SlowRequest) {
  7306. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7307. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7308. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7309. }
  7310. #if 0
  7311. TEST_F(ServerTest, SlowPost) {
  7312. char buffer[64 * 1024];
  7313. memset(buffer, 0x42, sizeof(buffer));
  7314. auto res = cli_.Post(
  7315. "/slowpost", 64 * 1024 * 1024,
  7316. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7317. auto ret = sink.write(buffer, sizeof(buffer));
  7318. EXPECT_TRUE(ret);
  7319. return true;
  7320. },
  7321. "text/plain");
  7322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7323. EXPECT_EQ(StatusCode::OK_200, res->status);
  7324. }
  7325. TEST_F(ServerTest, SlowPostFail) {
  7326. char buffer[64 * 1024];
  7327. memset(buffer, 0x42, sizeof(buffer));
  7328. cli_.set_write_timeout(std::chrono::seconds(0));
  7329. auto res = cli_.Post(
  7330. "/slowpost", 64 * 1024 * 1024,
  7331. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7332. sink.write(buffer, sizeof(buffer));
  7333. return true;
  7334. },
  7335. "text/plain");
  7336. ASSERT_TRUE(!res);
  7337. EXPECT_EQ(Error::Write, res.error());
  7338. }
  7339. #endif
  7340. TEST_F(ServerTest, Put) {
  7341. auto res = cli_.Put("/put", "PUT", "text/plain");
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::OK_200, res->status);
  7344. EXPECT_EQ("PUT", res->body);
  7345. }
  7346. TEST_F(ServerTest, PutWithContentProvider) {
  7347. auto res = cli_.Put(
  7348. "/put", 3,
  7349. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7350. sink.os << "PUT";
  7351. return true;
  7352. },
  7353. "text/plain");
  7354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7355. EXPECT_EQ(StatusCode::OK_200, res->status);
  7356. EXPECT_EQ("PUT", res->body);
  7357. }
  7358. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7359. auto res = cli_.Post(
  7360. "/post", 42,
  7361. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7362. return false;
  7363. },
  7364. "text/plain");
  7365. ASSERT_TRUE(!res);
  7366. EXPECT_EQ(Error::Canceled, res.error());
  7367. }
  7368. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7369. auto res = cli_.Put(
  7370. "/put",
  7371. [](size_t /*offset*/, DataSink &sink) {
  7372. sink.os << "PUT";
  7373. sink.done();
  7374. return true;
  7375. },
  7376. "text/plain");
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::OK_200, res->status);
  7379. EXPECT_EQ("PUT", res->body);
  7380. }
  7381. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7382. auto res = cli_.Post(
  7383. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7384. "text/plain");
  7385. ASSERT_TRUE(!res);
  7386. EXPECT_EQ(Error::Canceled, res.error());
  7387. }
  7388. TEST_F(ServerTest, PostLoopBack) {
  7389. std::string body;
  7390. auto res = cli_.Post(
  7391. "/post-loopback", 9,
  7392. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7393. EXPECT_EQ(9u, length);
  7394. sink.write("123", 3);
  7395. sink.write("456", 3);
  7396. sink.write("789", 3);
  7397. return true;
  7398. },
  7399. "text/plain",
  7400. [&body](const char *data, size_t data_length) {
  7401. body.append(data, data_length);
  7402. return true;
  7403. });
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::OK_200, res->status);
  7406. EXPECT_EQ("123456789", body);
  7407. }
  7408. TEST_F(ServerTest, PutLoopBack) {
  7409. std::string body;
  7410. auto res = cli_.Put(
  7411. "/put-loopback", 9,
  7412. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7413. EXPECT_EQ(9u, length);
  7414. sink.write("123", 3);
  7415. sink.write("456", 3);
  7416. sink.write("789", 3);
  7417. return true;
  7418. },
  7419. "text/plain",
  7420. [&body](const char *data, size_t data_length) {
  7421. body.append(data, data_length);
  7422. return true;
  7423. });
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ("123456789", body);
  7427. }
  7428. TEST_F(ServerTest, PatchLoopBack) {
  7429. std::string body;
  7430. auto res = cli_.Patch(
  7431. "/patch-loopback", 9,
  7432. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7433. EXPECT_EQ(9u, length);
  7434. sink.write("123", 3);
  7435. sink.write("456", 3);
  7436. sink.write("789", 3);
  7437. return true;
  7438. },
  7439. "text/plain",
  7440. [&body](const char *data, size_t data_length) {
  7441. body.append(data, data_length);
  7442. return true;
  7443. });
  7444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7445. EXPECT_EQ(StatusCode::OK_200, res->status);
  7446. EXPECT_EQ("123456789", body);
  7447. }
  7448. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7449. std::string body;
  7450. auto res = cli_.Post(
  7451. "/post-loopback",
  7452. [](size_t /*offset*/, DataSink &sink) {
  7453. sink.write("123", 3);
  7454. sink.write("456", 3);
  7455. sink.write("789", 3);
  7456. sink.done();
  7457. return true;
  7458. },
  7459. "text/plain",
  7460. [&body](const char *data, size_t data_length) {
  7461. body.append(data, data_length);
  7462. return true;
  7463. });
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. EXPECT_EQ("123456789", body);
  7467. }
  7468. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7469. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7470. cli_.set_compress(true);
  7471. auto res = cli_.Put(
  7472. "/put", 3,
  7473. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7474. sink.os << "PUT";
  7475. return true;
  7476. },
  7477. "text/plain");
  7478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7479. EXPECT_EQ(StatusCode::OK_200, res->status);
  7480. EXPECT_EQ("PUT", res->body);
  7481. }
  7482. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7483. cli_.set_compress(true);
  7484. auto res = cli_.Post(
  7485. "/post", 42,
  7486. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7487. return false;
  7488. },
  7489. "text/plain");
  7490. ASSERT_TRUE(!res);
  7491. EXPECT_EQ(Error::Canceled, res.error());
  7492. }
  7493. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7494. cli_.set_compress(true);
  7495. auto res = cli_.Put(
  7496. "/put",
  7497. [](size_t /*offset*/, DataSink &sink) {
  7498. sink.os << "PUT";
  7499. sink.done();
  7500. return true;
  7501. },
  7502. "text/plain");
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. EXPECT_EQ("PUT", res->body);
  7506. }
  7507. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7508. cli_.set_compress(true);
  7509. auto res = cli_.Post(
  7510. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7511. "text/plain");
  7512. ASSERT_TRUE(!res);
  7513. EXPECT_EQ(Error::Canceled, res.error());
  7514. }
  7515. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7516. cli_.set_compress(true);
  7517. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7519. EXPECT_EQ(StatusCode::OK_200, res->status);
  7520. EXPECT_EQ(LARGE_DATA, res->body);
  7521. }
  7522. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7523. #ifdef CPPHTTPLIB_SSL_ENABLED
  7524. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7525. Client cli(s.c_str());
  7526. cli.enable_server_certificate_verification(false);
  7527. #else
  7528. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7529. Client cli(s.c_str());
  7530. #endif
  7531. cli.set_compress(true);
  7532. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7534. EXPECT_EQ(StatusCode::OK_200, res->status);
  7535. EXPECT_EQ(LARGE_DATA, res->body);
  7536. // The compressed size should be less than a 10th of the original. May vary
  7537. // depending on the zlib library.
  7538. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7539. static_cast<uint64_t>(10 * 1024 * 1024));
  7540. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7541. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7542. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7543. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7544. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7545. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7546. #endif
  7547. }
  7548. TEST_F(ServerTest, PutContentWithDeflate) {
  7549. cli_.set_compress(false);
  7550. Headers headers;
  7551. headers.emplace("Content-Encoding", "deflate");
  7552. // PUT in deflate format:
  7553. auto res = cli_.Put("/put", headers,
  7554. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ("PUT", res->body);
  7558. }
  7559. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7560. Headers headers;
  7561. headers.emplace("Accept-Encoding", "gzip, deflate");
  7562. auto res = cli_.Get("/streamed-chunked", headers);
  7563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7564. EXPECT_EQ(StatusCode::OK_200, res->status);
  7565. EXPECT_EQ(std::string("123456789"), res->body);
  7566. }
  7567. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7568. Headers headers;
  7569. headers.emplace("Accept-Encoding", "gzip, deflate");
  7570. auto res = cli_.Get("/streamed-chunked2", headers);
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ(std::string("123456789"), res->body);
  7574. }
  7575. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7576. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. }
  7580. TEST(GzipDecompressor, ChunkedDecompression) {
  7581. std::string data;
  7582. for (size_t i = 0; i < 32 * 1024; ++i) {
  7583. data.push_back(static_cast<char>('a' + i % 26));
  7584. }
  7585. std::string compressed_data;
  7586. {
  7587. httplib::detail::gzip_compressor compressor;
  7588. bool result = compressor.compress(
  7589. data.data(), data.size(),
  7590. /*last=*/true,
  7591. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7592. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7593. compressed_data_size);
  7594. return true;
  7595. });
  7596. ASSERT_TRUE(result);
  7597. }
  7598. std::string decompressed_data;
  7599. {
  7600. httplib::detail::gzip_decompressor decompressor;
  7601. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7602. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7603. size_t chunk_size = 130;
  7604. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7605. chunk_begin += chunk_size) {
  7606. size_t current_chunk_size =
  7607. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7608. bool result = decompressor.decompress(
  7609. compressed_data.data() + chunk_begin, current_chunk_size,
  7610. [&](const char *decompressed_data_chunk,
  7611. size_t decompressed_data_chunk_size) {
  7612. decompressed_data.insert(decompressed_data.size(),
  7613. decompressed_data_chunk,
  7614. decompressed_data_chunk_size);
  7615. return true;
  7616. });
  7617. ASSERT_TRUE(result);
  7618. }
  7619. }
  7620. ASSERT_EQ(data, decompressed_data);
  7621. }
  7622. TEST(GzipDecompressor, DeflateDecompression) {
  7623. std::string original_text = "Raw deflate without gzip";
  7624. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7625. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7626. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7627. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7628. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7629. std::string decompressed_data;
  7630. {
  7631. httplib::detail::gzip_decompressor decompressor;
  7632. bool result = decompressor.decompress(
  7633. compressed_data.data(), compressed_data.size(),
  7634. [&](const char *decompressed_data_chunk,
  7635. size_t decompressed_data_chunk_size) {
  7636. decompressed_data.insert(decompressed_data.size(),
  7637. decompressed_data_chunk,
  7638. decompressed_data_chunk_size);
  7639. return true;
  7640. });
  7641. ASSERT_TRUE(result);
  7642. }
  7643. ASSERT_EQ(original_text, decompressed_data);
  7644. }
  7645. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7646. std::string original_text = "Raw deflate without gzip";
  7647. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7648. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7649. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7650. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7651. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7652. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7653. std::string decompressed_data;
  7654. {
  7655. httplib::detail::gzip_decompressor decompressor;
  7656. bool result = decompressor.decompress(
  7657. compressed_data.data(), compressed_data.size(),
  7658. [&](const char *decompressed_data_chunk,
  7659. size_t decompressed_data_chunk_size) {
  7660. decompressed_data.insert(decompressed_data.size(),
  7661. decompressed_data_chunk,
  7662. decompressed_data_chunk_size);
  7663. return true;
  7664. });
  7665. ASSERT_TRUE(result);
  7666. }
  7667. ASSERT_EQ(original_text, decompressed_data);
  7668. }
  7669. #endif
  7670. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7671. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7672. Headers headers;
  7673. headers.emplace("Accept-Encoding", "br");
  7674. auto res = cli_.Get("/streamed-chunked", headers);
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(StatusCode::OK_200, res->status);
  7677. EXPECT_EQ(std::string("123456789"), res->body);
  7678. }
  7679. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7680. Headers headers;
  7681. headers.emplace("Accept-Encoding", "br");
  7682. auto res = cli_.Get("/streamed-chunked2", headers);
  7683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7684. EXPECT_EQ(StatusCode::OK_200, res->status);
  7685. EXPECT_EQ(std::string("123456789"), res->body);
  7686. }
  7687. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7688. cli_.set_compress(true);
  7689. auto res = cli_.Put(
  7690. "/put", 3,
  7691. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7692. sink.os << "PUT";
  7693. return true;
  7694. },
  7695. "text/plain");
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ("PUT", res->body);
  7699. }
  7700. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7701. cli_.set_compress(true);
  7702. auto res = cli_.Put(
  7703. "/put",
  7704. [](size_t /*offset*/, DataSink &sink) {
  7705. sink.os << "PUT";
  7706. sink.done();
  7707. return true;
  7708. },
  7709. "text/plain");
  7710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7711. EXPECT_EQ(StatusCode::OK_200, res->status);
  7712. EXPECT_EQ("PUT", res->body);
  7713. }
  7714. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7715. cli_.set_compress(true);
  7716. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7718. EXPECT_EQ(StatusCode::OK_200, res->status);
  7719. EXPECT_EQ(LARGE_DATA, res->body);
  7720. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7721. }
  7722. #endif
  7723. TEST_F(ServerTest, Patch) {
  7724. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PATCH", res->body);
  7728. }
  7729. TEST_F(ServerTest, Delete) {
  7730. auto res = cli_.Delete("/delete");
  7731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. EXPECT_EQ("DELETE", res->body);
  7734. }
  7735. TEST_F(ServerTest, DeleteContentReceiver) {
  7736. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::OK_200, res->status);
  7739. EXPECT_EQ("content", res->body);
  7740. }
  7741. TEST_F(ServerTest, Options) {
  7742. auto res = cli_.Options("*");
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7746. EXPECT_TRUE(res->body.empty());
  7747. }
  7748. TEST_F(ServerTest, URL) {
  7749. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. }
  7753. TEST_F(ServerTest, ArrayParam) {
  7754. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::OK_200, res->status);
  7757. }
  7758. TEST_F(ServerTest, ArrayParamValues) {
  7759. auto res =
  7760. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. }
  7764. TEST_F(ServerTest, NoMultipleHeaders) {
  7765. Headers headers = {{"Content-Length", "5"}};
  7766. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7767. "text/plain");
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. }
  7771. TEST_F(ServerTest, PostContentReceiver) {
  7772. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7774. ASSERT_EQ(StatusCode::OK_200, res->status);
  7775. ASSERT_EQ("content", res->body);
  7776. }
  7777. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7778. UploadFormDataItems items = {
  7779. {"text1", "text default", "", ""},
  7780. {"text2", "aωb", "", ""},
  7781. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7782. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7783. {"file3", "", "", "application/octet-stream"},
  7784. };
  7785. auto res = cli_.Post("/content_receiver", items);
  7786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7787. EXPECT_EQ(StatusCode::OK_200, res->status);
  7788. }
  7789. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7790. UploadFormDataItems items = {
  7791. {"text1", "text default", "", ""},
  7792. {"text2", "aωb", "", ""},
  7793. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7794. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7795. {"file3", "", "", "application/octet-stream"},
  7796. };
  7797. auto boundary = std::string("+++++");
  7798. std::string body;
  7799. for (const auto &item : items) {
  7800. body += "--" + boundary + "\r\n";
  7801. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7802. if (!item.filename.empty()) {
  7803. body += "; filename=\"" + item.filename + "\"";
  7804. }
  7805. body += "\r\n";
  7806. if (!item.content_type.empty()) {
  7807. body += "Content-Type: " + item.content_type + "\r\n";
  7808. }
  7809. body += "\r\n";
  7810. body += item.content + "\r\n";
  7811. }
  7812. body += "--" + boundary + "--\r\n";
  7813. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7814. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7816. EXPECT_EQ(StatusCode::OK_200, res->status);
  7817. }
  7818. TEST(MultipartFormDataTest, FieldEscaping) {
  7819. Server svr;
  7820. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7821. const ContentReader &content_reader) {
  7822. ASSERT_TRUE(req.is_multipart_form_data());
  7823. std::vector<FormData> received;
  7824. content_reader(
  7825. [&](const FormData &file) {
  7826. received.push_back(file);
  7827. return true;
  7828. },
  7829. [&](const char *data, size_t data_length) {
  7830. received.back().content.append(data, data_length);
  7831. return true;
  7832. });
  7833. // '"', CR and LF in names and filenames are escaped following the
  7834. // WHATWG HTML standard, so each part still parses as a single part
  7835. // with no injected headers. Content types get CR/LF escaped too,
  7836. // while '"' (legal there, e.g. quoted charset) is preserved.
  7837. ASSERT_EQ(4U, received.size());
  7838. EXPECT_EQ("na%22me", received[0].name);
  7839. EXPECT_EQ("quoted name", received[0].content);
  7840. EXPECT_EQ("file", received[1].name);
  7841. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7842. received[1].filename);
  7843. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7844. EXPECT_EQ("injected", received[1].content);
  7845. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7846. EXPECT_EQ("my%22file.txt", received[2].filename);
  7847. EXPECT_EQ("cr lf name", received[2].content);
  7848. EXPECT_EQ("typed", received[3].name);
  7849. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7850. received[3].content_type);
  7851. EXPECT_EQ("typed content", received[3].content);
  7852. });
  7853. auto port = svr.bind_to_any_port("localhost");
  7854. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7855. auto se = detail::scope_exit([&] {
  7856. svr.stop();
  7857. t.join();
  7858. ASSERT_FALSE(svr.is_running());
  7859. });
  7860. svr.wait_until_ready();
  7861. Client cli("localhost", port);
  7862. UploadFormDataItems items = {
  7863. {"na\"me", "quoted name", "", ""},
  7864. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7865. "application/octet-stream"},
  7866. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7867. {"typed", "typed content", "",
  7868. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7869. };
  7870. auto res = cli.Post("/post", items);
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. }
  7874. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7875. const UploadFormDataItems items = {
  7876. {"name1", "Content 1", "", ""},
  7877. {"name2", "Content 2", "file2.txt", "text/plain"},
  7878. };
  7879. Server svr;
  7880. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7881. const ContentReader &content_reader) {
  7882. ASSERT_TRUE(req.is_multipart_form_data());
  7883. std::vector<FormData> received;
  7884. content_reader(
  7885. [&](const FormData &file) {
  7886. received.push_back(file);
  7887. return true;
  7888. },
  7889. [&](const char *data, size_t data_length) {
  7890. received.back().content.append(data, data_length);
  7891. return true;
  7892. });
  7893. ASSERT_EQ(2U, received.size());
  7894. EXPECT_EQ("name1", received[0].name);
  7895. EXPECT_EQ("Content 1", received[0].content);
  7896. EXPECT_EQ("name2", received[1].name);
  7897. EXPECT_EQ("Content 2", received[1].content);
  7898. EXPECT_EQ("file2.txt", received[1].filename);
  7899. EXPECT_EQ("text/plain", received[1].content_type);
  7900. });
  7901. auto port = svr.bind_to_any_port("localhost");
  7902. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7903. auto se = detail::scope_exit([&] {
  7904. svr.stop();
  7905. t.join();
  7906. ASSERT_FALSE(svr.is_running());
  7907. });
  7908. svr.wait_until_ready();
  7909. Client cli("localhost", port);
  7910. // Whole-body serialization with a generated boundary
  7911. {
  7912. MultipartFormDataWriter writer;
  7913. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7914. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7915. writer.content_type());
  7916. auto body = writer.serialize(items);
  7917. EXPECT_EQ(body.size(), writer.content_length(items));
  7918. auto res = cli.Post("/post", body, writer.content_type());
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. }
  7922. // Per-part framing with a custom boundary via a content provider
  7923. {
  7924. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7925. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7926. MultipartFormDataWriter writer("custom-boundary_123");
  7927. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7928. std::string body;
  7929. for (const auto &item : items) {
  7930. body += writer.item_begin(item);
  7931. body += item.content;
  7932. body += MultipartFormDataWriter::item_end();
  7933. }
  7934. body += writer.finish();
  7935. EXPECT_EQ(body.size(), writer.content_length(items));
  7936. auto res = cli.Post(
  7937. "/post", body.size(),
  7938. [&](size_t offset, size_t length, DataSink &sink) {
  7939. sink.write(body.data() + offset, length);
  7940. return true;
  7941. },
  7942. writer.content_type());
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. EXPECT_EQ(StatusCode::OK_200, res->status);
  7945. }
  7946. }
  7947. TEST_F(ServerTest, PostContentReceiverGzip) {
  7948. cli_.set_compress(true);
  7949. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7951. ASSERT_EQ(StatusCode::OK_200, res->status);
  7952. ASSERT_EQ("content", res->body);
  7953. }
  7954. TEST_F(ServerTest, PutContentReceiver) {
  7955. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. ASSERT_EQ(StatusCode::OK_200, res->status);
  7958. ASSERT_EQ("content", res->body);
  7959. }
  7960. TEST_F(ServerTest, PatchContentReceiver) {
  7961. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7963. ASSERT_EQ(StatusCode::OK_200, res->status);
  7964. ASSERT_EQ("content", res->body);
  7965. }
  7966. template <typename ClientType>
  7967. void TestWithHeadersAndContentReceiver(
  7968. ClientType &cli,
  7969. std::function<Result(ClientType &, const std::string &, const Headers &,
  7970. const std::string &, const std::string &,
  7971. ContentReceiver, DownloadProgress)>
  7972. request_func) {
  7973. Headers headers;
  7974. headers.emplace("X-Custom-Header", "test-value");
  7975. std::string received_body;
  7976. auto res = request_func(
  7977. cli, "/content_receiver", headers, "content", "application/json",
  7978. [&](const char *data, size_t data_length) {
  7979. received_body.append(data, data_length);
  7980. return true;
  7981. },
  7982. nullptr);
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ("content", received_body);
  7986. }
  7987. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7988. #ifdef CPPHTTPLIB_SSL_ENABLED
  7989. using ClientT = SSLClient;
  7990. #else
  7991. using ClientT = Client;
  7992. #endif
  7993. TestWithHeadersAndContentReceiver<ClientT>(
  7994. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7995. const std::string &body, const std::string &content_type,
  7996. ContentReceiver receiver, DownloadProgress progress) {
  7997. return cli.Post(path, headers, body, content_type, receiver, progress);
  7998. });
  7999. }
  8000. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8001. #ifdef CPPHTTPLIB_SSL_ENABLED
  8002. using ClientT = SSLClient;
  8003. #else
  8004. using ClientT = Client;
  8005. #endif
  8006. TestWithHeadersAndContentReceiver<ClientT>(
  8007. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8008. const std::string &body, const std::string &content_type,
  8009. ContentReceiver receiver, DownloadProgress progress) {
  8010. return cli.Put(path, headers, body, content_type, receiver, progress);
  8011. });
  8012. }
  8013. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8014. #ifdef CPPHTTPLIB_SSL_ENABLED
  8015. using ClientT = SSLClient;
  8016. #else
  8017. using ClientT = Client;
  8018. #endif
  8019. TestWithHeadersAndContentReceiver<ClientT>(
  8020. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8021. const std::string &body, const std::string &content_type,
  8022. ContentReceiver receiver, DownloadProgress progress) {
  8023. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8024. });
  8025. }
  8026. template <typename ClientType>
  8027. void TestWithHeadersAndContentReceiverWithProgress(
  8028. ClientType &cli,
  8029. std::function<Result(ClientType &, const std::string &, const Headers &,
  8030. const std::string &, const std::string &,
  8031. ContentReceiver, DownloadProgress)>
  8032. request_func) {
  8033. Headers headers;
  8034. headers.emplace("X-Test-Header", "progress-test");
  8035. std::string received_body;
  8036. auto progress_called = false;
  8037. auto res = request_func(
  8038. cli, "/content_receiver", headers, "content", "text/plain",
  8039. [&](const char *data, size_t data_length) {
  8040. received_body.append(data, data_length);
  8041. return true;
  8042. },
  8043. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8044. progress_called = true;
  8045. return true;
  8046. });
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. EXPECT_EQ("content", received_body);
  8050. EXPECT_TRUE(progress_called);
  8051. }
  8052. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8053. #ifdef CPPHTTPLIB_SSL_ENABLED
  8054. using ClientT = SSLClient;
  8055. #else
  8056. using ClientT = Client;
  8057. #endif
  8058. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8059. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8060. const std::string &body, const std::string &content_type,
  8061. ContentReceiver receiver, DownloadProgress progress) {
  8062. return cli.Post(path, headers, body, content_type, receiver, progress);
  8063. });
  8064. }
  8065. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8066. #ifdef CPPHTTPLIB_SSL_ENABLED
  8067. using ClientT = SSLClient;
  8068. #else
  8069. using ClientT = Client;
  8070. #endif
  8071. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8072. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8073. const std::string &body, const std::string &content_type,
  8074. ContentReceiver receiver, DownloadProgress progress) {
  8075. return cli.Put(path, headers, body, content_type, receiver, progress);
  8076. });
  8077. }
  8078. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8079. #ifdef CPPHTTPLIB_SSL_ENABLED
  8080. using ClientT = SSLClient;
  8081. #else
  8082. using ClientT = Client;
  8083. #endif
  8084. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8085. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8086. const std::string &body, const std::string &content_type,
  8087. ContentReceiver receiver, DownloadProgress progress) {
  8088. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8089. });
  8090. }
  8091. template <typename ClientType>
  8092. void TestWithHeadersAndContentReceiverError(
  8093. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8094. const Headers &, const std::string &,
  8095. const std::string &, ContentReceiver)>
  8096. request_func) {
  8097. Headers headers;
  8098. headers.emplace("X-Error-Test", "true");
  8099. std::string received_body;
  8100. auto receiver_failed = false;
  8101. auto res =
  8102. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8103. [&](const char *data, size_t data_length) {
  8104. received_body.append(data, data_length);
  8105. receiver_failed = true;
  8106. return false;
  8107. });
  8108. ASSERT_FALSE(res);
  8109. EXPECT_TRUE(receiver_failed);
  8110. }
  8111. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8112. #ifdef CPPHTTPLIB_SSL_ENABLED
  8113. using ClientT = SSLClient;
  8114. #else
  8115. using ClientT = Client;
  8116. #endif
  8117. TestWithHeadersAndContentReceiverError<ClientT>(
  8118. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8119. const std::string &body, const std::string &content_type,
  8120. ContentReceiver receiver) {
  8121. return cli.Post(path, headers, body, content_type, receiver);
  8122. });
  8123. }
  8124. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8125. #ifdef CPPHTTPLIB_SSL_ENABLED
  8126. using ClientT = SSLClient;
  8127. #else
  8128. using ClientT = Client;
  8129. #endif
  8130. TestWithHeadersAndContentReceiverError<ClientT>(
  8131. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8132. const std::string &body, const std::string &content_type,
  8133. ContentReceiver receiver) {
  8134. return cli.Put(path, headers, body, content_type, receiver);
  8135. });
  8136. }
  8137. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8138. #ifdef CPPHTTPLIB_SSL_ENABLED
  8139. using ClientT = SSLClient;
  8140. #else
  8141. using ClientT = Client;
  8142. #endif
  8143. TestWithHeadersAndContentReceiverError<ClientT>(
  8144. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8145. const std::string &body, const std::string &content_type,
  8146. ContentReceiver receiver) {
  8147. return cli.Patch(path, headers, body, content_type, receiver);
  8148. });
  8149. }
  8150. TEST_F(ServerTest, PostQueryStringAndBody) {
  8151. auto res =
  8152. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. ASSERT_EQ(StatusCode::OK_200, res->status);
  8155. }
  8156. TEST_F(ServerTest, HTTP2Magic) {
  8157. Request req;
  8158. req.method = "PRI";
  8159. req.path = "*";
  8160. req.body = "SM";
  8161. auto res = std::make_shared<Response>();
  8162. auto error = Error::Success;
  8163. auto ret = cli_.send(req, *res, error);
  8164. ASSERT_TRUE(ret);
  8165. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8166. }
  8167. TEST_F(ServerTest, KeepAlive) {
  8168. auto res = cli_.Get("/hi");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8172. EXPECT_EQ("Hello World!", res->body);
  8173. res = cli_.Get("/hi");
  8174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8175. EXPECT_EQ(StatusCode::OK_200, res->status);
  8176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8177. EXPECT_EQ("Hello World!", res->body);
  8178. res = cli_.Get("/hi");
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::OK_200, res->status);
  8181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8182. EXPECT_EQ("Hello World!", res->body);
  8183. res = cli_.Get("/not-exist");
  8184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8186. res = cli_.Post("/empty", "", "text/plain");
  8187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8188. EXPECT_EQ(StatusCode::OK_200, res->status);
  8189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8190. EXPECT_EQ("empty", res->body);
  8191. EXPECT_EQ("close", res->get_header_value("Connection"));
  8192. res = cli_.Post(
  8193. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8194. "text/plain");
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::OK_200, res->status);
  8197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8198. EXPECT_EQ("empty", res->body);
  8199. cli_.set_keep_alive(false);
  8200. res = cli_.Get("/last-request");
  8201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8202. EXPECT_EQ(StatusCode::OK_200, res->status);
  8203. EXPECT_EQ("close", res->get_header_value("Connection"));
  8204. }
  8205. TEST_F(ServerTest, TooManyRedirect) {
  8206. cli_.set_follow_location(true);
  8207. auto res = cli_.Get("/redirect/0");
  8208. ASSERT_TRUE(!res);
  8209. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8210. }
  8211. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8212. Request req;
  8213. req.method = "FOOBAR";
  8214. req.path = "/hi";
  8215. cli_.set_keep_alive(true);
  8216. auto res = cli_.send(req);
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8219. EXPECT_EQ("close", res->get_header_value("Connection"));
  8220. EXPECT_FALSE(cli_.is_socket_open());
  8221. }
  8222. TEST_F(ServerTest, CustomRouteReadsBody) {
  8223. const std::string xml =
  8224. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8225. Request req;
  8226. req.method = "PROPFIND";
  8227. req.path = "/dav/dir";
  8228. req.set_header("Depth", "1");
  8229. req.body = xml;
  8230. auto res = cli_.send(req);
  8231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8232. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8233. EXPECT_EQ(xml, res->body);
  8234. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8235. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8236. }
  8237. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8238. Request req;
  8239. req.method = "PROPFIND";
  8240. req.path = "/dav/42";
  8241. auto res = cli_.send(req);
  8242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8243. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8244. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8245. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8246. }
  8247. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8248. Request req;
  8249. req.method = "PROPFIND";
  8250. req.path = "/dav-re/123";
  8251. auto res = cli_.send(req);
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8254. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8255. }
  8256. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8257. Request req;
  8258. req.method = "MKCOL";
  8259. req.path = "/dav-mkcol";
  8260. auto res = cli_.send(req);
  8261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8262. EXPECT_EQ(StatusCode::Created_201, res->status);
  8263. }
  8264. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8265. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8266. Request req;
  8267. req.method = "REPORT";
  8268. req.path = "/dav-report";
  8269. req.body = xml;
  8270. auto res = cli_.send(req);
  8271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8272. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8273. EXPECT_EQ(xml, res->body);
  8274. }
  8275. // A content reader route must fire even when the request carries no body,
  8276. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8277. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8278. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8279. Request req;
  8280. req.method = "REPORT";
  8281. req.path = "/dav-report";
  8282. auto res = cli_.send(req);
  8283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8284. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8285. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8286. }
  8287. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8288. Request req;
  8289. req.method = "PROPFIND";
  8290. req.path = "/not-dav";
  8291. auto res = cli_.send(req);
  8292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8293. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8294. }
  8295. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8296. Request req;
  8297. req.method = "UNLOCK";
  8298. req.path = "/dav/dir";
  8299. cli_.set_keep_alive(true);
  8300. auto res = cli_.send(req);
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8303. EXPECT_EQ("close", res->get_header_value("Connection"));
  8304. EXPECT_FALSE(cli_.is_socket_open());
  8305. }
  8306. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8307. // The mount point serves this path, but only for GET and HEAD.
  8308. auto get_res = cli_.Get("/dir/index.html");
  8309. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8310. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8311. Request req;
  8312. req.method = "PROPFIND";
  8313. req.path = "/dir/index.html";
  8314. auto res = cli_.send(req);
  8315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8317. }
  8318. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8319. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8320. cli_.set_keep_alive(true);
  8321. for (auto i = 0; i < 2; i++) {
  8322. Request req;
  8323. req.method = "PROPFIND";
  8324. req.path = "/dav/dir";
  8325. req.body = xml;
  8326. auto res = cli_.send(req);
  8327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8328. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8329. EXPECT_EQ(xml, res->body);
  8330. EXPECT_TRUE(cli_.is_socket_open());
  8331. }
  8332. // A built-in method must still be served on the same connection.
  8333. cli_.set_keep_alive(false);
  8334. auto res = cli_.Get("/hi");
  8335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. EXPECT_EQ("close", res->get_header_value("Connection"));
  8338. }
  8339. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8340. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8341. Request req;
  8342. req.method = "PROPFIND";
  8343. req.path = "/dav/dir";
  8344. req.set_header("Expect", "100-continue");
  8345. req.body = xml;
  8346. auto res = cli_.send(req);
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8349. EXPECT_EQ(xml, res->body);
  8350. }
  8351. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8352. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8353. TEST_F(ServerTest, Gzip) {
  8354. Headers headers;
  8355. headers.emplace("Accept-Encoding", "gzip, deflate");
  8356. auto res = cli_.Get("/compress", headers);
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8361. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8362. "7890123456789012345678901234567890",
  8363. res->body);
  8364. EXPECT_EQ(StatusCode::OK_200, res->status);
  8365. }
  8366. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8367. Headers headers;
  8368. headers.emplace("Accept-Encoding", "gzip, deflate");
  8369. auto res = cli_.Get("/compress-with-charset", headers);
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8372. EXPECT_EQ("application/json; charset=utf-8",
  8373. res->get_header_value("Content-Type"));
  8374. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8375. "7890123456789012345678901234567890",
  8376. res->body);
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. }
  8379. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8380. Headers headers;
  8381. headers.emplace("Accept-Encoding", "");
  8382. auto res = cli_.Get("/compress", headers);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8386. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8387. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8388. "7890123456789012345678901234567890",
  8389. res->body);
  8390. EXPECT_EQ(StatusCode::OK_200, res->status);
  8391. }
  8392. TEST_F(ServerTest, GzipWithContentReceiver) {
  8393. Headers headers;
  8394. headers.emplace("Accept-Encoding", "gzip, deflate");
  8395. std::string body;
  8396. auto res =
  8397. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8398. EXPECT_EQ(100U, data_length);
  8399. body.append(data, data_length);
  8400. return true;
  8401. });
  8402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8403. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8404. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8405. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8406. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8407. "7890123456789012345678901234567890",
  8408. body);
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. }
  8411. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8412. Headers headers;
  8413. headers.emplace("Accept-Encoding", "gzip, deflate");
  8414. cli_.set_decompress(false);
  8415. auto res = cli_.Get("/compress", headers);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8419. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8420. EXPECT_EQ(33U, res->body.size());
  8421. EXPECT_EQ(StatusCode::OK_200, res->status);
  8422. }
  8423. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8424. Headers headers;
  8425. headers.emplace("Accept-Encoding", "");
  8426. std::string body;
  8427. auto res =
  8428. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8429. EXPECT_EQ(100U, data_length);
  8430. body.append(data, data_length);
  8431. return true;
  8432. });
  8433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8434. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8435. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8436. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8437. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8438. "7890123456789012345678901234567890",
  8439. body);
  8440. EXPECT_EQ(StatusCode::OK_200, res->status);
  8441. }
  8442. TEST_F(ServerTest, NoGzip) {
  8443. Headers headers;
  8444. headers.emplace("Accept-Encoding", "gzip, deflate");
  8445. auto res = cli_.Get("/nocompress", headers);
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8448. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8449. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8450. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8451. "7890123456789012345678901234567890",
  8452. res->body);
  8453. EXPECT_EQ(StatusCode::OK_200, res->status);
  8454. }
  8455. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8456. Headers headers;
  8457. headers.emplace("Accept-Encoding", "gzip, deflate");
  8458. std::string body;
  8459. auto res = cli_.Get("/nocompress", headers,
  8460. [&](const char *data, size_t data_length) {
  8461. EXPECT_EQ(100U, data_length);
  8462. body.append(data, data_length);
  8463. return true;
  8464. });
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8467. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8468. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8469. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8470. "7890123456789012345678901234567890",
  8471. body);
  8472. EXPECT_EQ(StatusCode::OK_200, res->status);
  8473. }
  8474. TEST_F(ServerTest, MultipartFormDataGzip) {
  8475. UploadFormDataItems items = {
  8476. {"key1", "test", "", ""},
  8477. {"key2", "--abcdefg123", "", ""},
  8478. };
  8479. cli_.set_compress(true);
  8480. auto res = cli_.Post("/compress-multipart", items);
  8481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8482. EXPECT_EQ(StatusCode::OK_200, res->status);
  8483. }
  8484. #endif
  8485. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8486. // Static file compression is opt-in, so these run their own server rather than
  8487. // flipping it on for the shared ServerTest fixture, which would silently
  8488. // rewrite what every other static file test is asserting.
  8489. class StaticFileCompressionTest : public ::testing::Test {
  8490. protected:
  8491. void TearDown() override {
  8492. if (t_.joinable()) {
  8493. svr_.stop();
  8494. t_.join();
  8495. }
  8496. }
  8497. int start(const std::function<void(Server &)> &configure = nullptr) {
  8498. // Serves the same tree as a directory of build-time compressed assets
  8499. // would be served: the mount point names the coding the files are already
  8500. // stored in. Registered before "/" so it is the one that matches.
  8501. svr_.set_mount_point("/pre-encoded", "./www",
  8502. {{"Content-Encoding", "gzip"}});
  8503. svr_.set_mount_point("/", "./www");
  8504. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8505. res.set_file_content("./www/dir/index.html", "text/html");
  8506. });
  8507. svr_.Get("/pre-encoded-file-content",
  8508. [](const Request & /*req*/, Response &res) {
  8509. res.set_header("Content-Encoding", "gzip");
  8510. res.set_file_content("./www/dir/index.html", "text/html");
  8511. });
  8512. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8513. res.set_content_provider(
  8514. 6, "text/plain",
  8515. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8516. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8517. return true;
  8518. });
  8519. });
  8520. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8521. res.set_content_provider(
  8522. 1000, "text/plain",
  8523. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8524. if (offset < 100) {
  8525. std::string data(100, 'A');
  8526. sink.write(data.data(), data.size());
  8527. return true;
  8528. }
  8529. std::this_thread::sleep_for(std::chrono::seconds(2));
  8530. std::string data(900, 'B');
  8531. sink.write(data.data(), data.size());
  8532. return true;
  8533. });
  8534. });
  8535. if (configure) { configure(svr_); }
  8536. auto port = svr_.bind_to_any_port(HOST);
  8537. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8538. svr_.wait_until_ready();
  8539. return port;
  8540. }
  8541. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8542. // Every file under ./www except 1MB.txt is smaller than the default
  8543. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8544. // it out of the way.
  8545. static void enable_without_floor(Server &svr) {
  8546. svr.set_static_file_compression(true);
  8547. svr.set_static_file_compression_min_length(0);
  8548. }
  8549. Server svr_;
  8550. std::thread t_;
  8551. };
  8552. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8553. auto port = start();
  8554. Client cli(HOST, port);
  8555. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8557. EXPECT_EQ(StatusCode::OK_200, res->status);
  8558. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8559. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8560. EXPECT_EQ(1048576U, res->body.size());
  8561. }
  8562. TEST_F(StaticFileCompressionTest, MountPoint) {
  8563. auto port = start(enable);
  8564. Client cli(HOST, port);
  8565. cli.set_decompress(false);
  8566. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8570. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8571. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8572. // The response stays self-delimiting: a length, not a chunked body.
  8573. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8574. EXPECT_EQ(std::to_string(res->body.size()),
  8575. res->get_header_value("Content-Length"));
  8576. EXPECT_LT(res->body.size(), 1048576U);
  8577. EXPECT_FALSE(res->body.empty());
  8578. }
  8579. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8580. auto port = start(enable);
  8581. Client cli(HOST, port);
  8582. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. EXPECT_EQ(StatusCode::OK_200, res->status);
  8585. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8586. EXPECT_EQ(1048576U, res->body.size());
  8587. }
  8588. TEST_F(StaticFileCompressionTest, FileContent) {
  8589. auto port = start(enable_without_floor);
  8590. Client cli(HOST, port);
  8591. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8593. EXPECT_EQ(StatusCode::OK_200, res->status);
  8594. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8595. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8596. EXPECT_EQ(104U, res->body.size());
  8597. }
  8598. // A handler that serves an already-encoded file names the coding itself. The
  8599. // file-backed path decided its coding from Accept-Encoding and the content
  8600. // type alone, so it compressed the stored bytes a second time and appended a
  8601. // second Content-Encoding field line.
  8602. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8603. auto port = start(enable_without_floor);
  8604. Client cli(HOST, port);
  8605. cli.set_decompress(false);
  8606. auto res = cli.Get("/pre-encoded-file-content",
  8607. Headers{{"Accept-Encoding", "gzip"}});
  8608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8609. EXPECT_EQ(StatusCode::OK_200, res->status);
  8610. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8611. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8612. // Vary belongs to a coding the server chose, and it chose none here.
  8613. EXPECT_FALSE(res->has_header("Vary"));
  8614. // The file travels exactly as it is stored on disk.
  8615. EXPECT_EQ(104U, res->body.size());
  8616. }
  8617. // The 1MB file clears the default floor, so this one runs the configuration a
  8618. // deployment would actually have.
  8619. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8620. auto port = start(enable);
  8621. Client cli(HOST, port);
  8622. cli.set_decompress(false);
  8623. auto res =
  8624. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8626. EXPECT_EQ(StatusCode::OK_200, res->status);
  8627. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8628. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8629. EXPECT_FALSE(res->has_header("Vary"));
  8630. EXPECT_EQ(1048576U, res->body.size());
  8631. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8632. }
  8633. TEST_F(StaticFileCompressionTest, Head) {
  8634. auto port = start(enable);
  8635. Client cli(HOST, port);
  8636. cli.set_decompress(false);
  8637. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8638. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8639. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8641. EXPECT_EQ(StatusCode::OK_200, res->status);
  8642. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8643. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8644. // HEAD still reports the size a GET would return.
  8645. EXPECT_EQ(get->get_header_value("Content-Length"),
  8646. res->get_header_value("Content-Length"));
  8647. EXPECT_TRUE(res->body.empty());
  8648. }
  8649. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8650. auto port = start(enable);
  8651. Client cli(HOST, port);
  8652. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8653. {"Accept-Encoding", "gzip"}});
  8654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8656. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8657. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8658. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8659. EXPECT_EQ("cd", res->body);
  8660. }
  8661. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8662. auto port = start(enable);
  8663. Client cli(HOST, port);
  8664. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. EXPECT_EQ(StatusCode::OK_200, res->status);
  8667. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8668. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8669. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8670. }
  8671. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8672. auto port = start(enable);
  8673. Client cli(HOST, port);
  8674. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8676. EXPECT_EQ(StatusCode::OK_200, res->status);
  8677. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8678. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8679. EXPECT_TRUE(res->body.empty());
  8680. }
  8681. TEST_F(StaticFileCompressionTest, MinLength) {
  8682. auto port = start(enable);
  8683. Client cli(HOST, port);
  8684. // 104 bytes, well under the default floor. Compressing it would add the
  8685. // gzip header and trailer to a body that already fits in one packet.
  8686. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8688. EXPECT_EQ(StatusCode::OK_200, res->status);
  8689. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8690. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8691. }
  8692. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8693. auto port = start([](Server &svr) {
  8694. svr.set_static_file_compression(true);
  8695. svr.set_static_file_compression_min_length(1);
  8696. });
  8697. Client cli(HOST, port);
  8698. cli.set_decompress(false);
  8699. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8702. // A 9-byte file comes back larger than it went in, because gzip's header and
  8703. // trailer outweigh anything deflate can save. That is the end of the range
  8704. // the floor exists to keep out.
  8705. EXPECT_GT(res->body.size(), 9U);
  8706. }
  8707. TEST_F(StaticFileCompressionTest, MaxLength) {
  8708. auto port = start([](Server &svr) {
  8709. svr.set_static_file_compression(true);
  8710. svr.set_static_file_compression_min_length(0);
  8711. svr.set_static_file_compression_max_length(1024);
  8712. });
  8713. Client cli(HOST, port);
  8714. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8715. // defines `small` as a macro on Windows.
  8716. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8717. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8718. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8719. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8720. // Under it: compressed.
  8721. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8722. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8723. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8724. }
  8725. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8726. auto port = start(enable_without_floor);
  8727. Client cli(HOST, port);
  8728. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8729. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8730. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8731. auto identity_etag = identity->get_header_value("ETag");
  8732. ASSERT_FALSE(identity_etag.empty());
  8733. auto gzipped =
  8734. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8735. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8736. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8737. auto gzip_etag = gzipped->get_header_value("ETag");
  8738. ASSERT_FALSE(gzip_etag.empty());
  8739. // Two representations, two validators.
  8740. EXPECT_NE(identity_etag, gzip_etag);
  8741. // Each one revalidates against the request that would produce it...
  8742. auto fresh =
  8743. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8744. {"If-None-Match", gzip_etag}});
  8745. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8746. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8747. auto fresh_identity =
  8748. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8749. {"If-None-Match", identity_etag}});
  8750. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8751. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8752. // ...and not against the other representation.
  8753. auto crossed =
  8754. cli.Get("/dir/index.html",
  8755. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8756. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8757. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8758. }
  8759. // The opt-in covers responses the server reads off disk itself. A caller's own
  8760. // known-length provider keeps its Content-Length and, more importantly, keeps
  8761. // delivering incrementally: routing it through a compressor would hold every
  8762. // write back until zlib's window filled.
  8763. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8764. auto port = start(enable);
  8765. Client cli(HOST, port);
  8766. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8768. EXPECT_EQ(StatusCode::OK_200, res->status);
  8769. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8770. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8771. EXPECT_EQ("aaabbb", res->body);
  8772. }
  8773. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8774. auto port = start(enable);
  8775. Client cli(HOST, port);
  8776. cli.set_read_timeout(1, 0);
  8777. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8778. Headers{{"Accept-Encoding", "gzip"}});
  8779. ASSERT_TRUE(handle.is_valid());
  8780. // The provider writes 100 bytes and then stalls for longer than the read
  8781. // timeout. Those first bytes have to arrive anyway: run the response through
  8782. // a compressor and zlib holds them until its window fills, so the read would
  8783. // come back empty instead.
  8784. char buf[256];
  8785. auto n = handle.read(buf, sizeof(buf));
  8786. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8787. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8788. }
  8789. #endif
  8790. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8791. TEST_F(ServerTest, Brotli) {
  8792. Headers headers;
  8793. headers.emplace("Accept-Encoding", "br");
  8794. auto res = cli_.Get("/compress", headers);
  8795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8796. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8797. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8798. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8799. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8800. "7890123456789012345678901234567890",
  8801. res->body);
  8802. EXPECT_EQ(StatusCode::OK_200, res->status);
  8803. }
  8804. #endif
  8805. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8806. TEST_F(ServerTest, Zstd) {
  8807. Headers headers;
  8808. headers.emplace("Accept-Encoding", "zstd");
  8809. auto res = cli_.Get("/compress", headers);
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8812. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8813. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8814. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8815. "7890123456789012345678901234567890",
  8816. res->body);
  8817. EXPECT_EQ(StatusCode::OK_200, res->status);
  8818. }
  8819. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8820. Headers headers;
  8821. headers.emplace("Accept-Encoding", "");
  8822. auto res = cli_.Get("/compress", headers);
  8823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8824. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8825. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8826. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8827. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8828. "7890123456789012345678901234567890",
  8829. res->body);
  8830. EXPECT_EQ(StatusCode::OK_200, res->status);
  8831. }
  8832. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8833. Headers headers;
  8834. headers.emplace("Accept-Encoding", "zstd");
  8835. std::string body;
  8836. auto res =
  8837. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8838. EXPECT_EQ(100U, data_length);
  8839. body.append(data, data_length);
  8840. return true;
  8841. });
  8842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8843. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8844. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8845. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8846. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8847. "7890123456789012345678901234567890",
  8848. body);
  8849. EXPECT_EQ(StatusCode::OK_200, res->status);
  8850. }
  8851. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8852. Headers headers;
  8853. headers.emplace("Accept-Encoding", "zstd");
  8854. cli_.set_decompress(false);
  8855. auto res = cli_.Get("/compress", headers);
  8856. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8857. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8858. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8859. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8861. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8862. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8863. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8864. EXPECT_EQ(StatusCode::OK_200, res->status);
  8865. ASSERT_EQ(26U, res->body.size());
  8866. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8867. 0);
  8868. }
  8869. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8870. Headers headers;
  8871. headers.emplace("Accept-Encoding", "");
  8872. std::string body;
  8873. auto res =
  8874. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8875. EXPECT_EQ(100U, data_length);
  8876. body.append(data, data_length);
  8877. return true;
  8878. });
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8881. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8882. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8883. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8884. "7890123456789012345678901234567890",
  8885. body);
  8886. EXPECT_EQ(StatusCode::OK_200, res->status);
  8887. }
  8888. TEST_F(ServerTest, NoZstd) {
  8889. Headers headers;
  8890. headers.emplace("Accept-Encoding", "zstd");
  8891. auto res = cli_.Get("/nocompress", headers);
  8892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8893. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8894. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8895. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8896. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8897. "7890123456789012345678901234567890",
  8898. res->body);
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. }
  8901. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8902. Headers headers;
  8903. headers.emplace("Accept-Encoding", "zstd");
  8904. std::string body;
  8905. auto res = cli_.Get("/nocompress", headers,
  8906. [&](const char *data, size_t data_length) {
  8907. EXPECT_EQ(100U, data_length);
  8908. body.append(data, data_length);
  8909. return true;
  8910. });
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8913. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8914. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8915. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8916. "7890123456789012345678901234567890",
  8917. body);
  8918. EXPECT_EQ(StatusCode::OK_200, res->status);
  8919. }
  8920. // TODO: How to enable zstd ??
  8921. TEST_F(ServerTest, MultipartFormDataZstd) {
  8922. UploadFormDataItems items = {
  8923. {"key1", "test", "", ""},
  8924. {"key2", "--abcdefg123", "", ""},
  8925. };
  8926. Headers headers;
  8927. headers.emplace("Accept-Encoding", "zstd");
  8928. cli_.set_compress(true);
  8929. auto res = cli_.Post("/compress-multipart", headers, items);
  8930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8931. EXPECT_EQ(StatusCode::OK_200, res->status);
  8932. }
  8933. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8934. Headers headers;
  8935. headers.emplace("Accept-Encoding", "zstd");
  8936. cli_.set_compress(true);
  8937. auto res = cli_.Put(
  8938. "/put", headers, 3,
  8939. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8940. sink.os << "PUT";
  8941. return true;
  8942. },
  8943. "text/plain");
  8944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8945. EXPECT_EQ(StatusCode::OK_200, res->status);
  8946. EXPECT_EQ("PUT", res->body);
  8947. }
  8948. // Pre-compression logging tests
  8949. TEST_F(ServerTest, PreCompressionLogging) {
  8950. // Test data for compression (matches the actual /compress endpoint content)
  8951. const std::string test_content =
  8952. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8953. "3456789012345678901234567890";
  8954. // Variables to capture logging data
  8955. std::string pre_compression_body;
  8956. std::string pre_compression_content_type;
  8957. std::string pre_compression_content_encoding;
  8958. std::string post_compression_body;
  8959. std::string post_compression_content_type;
  8960. std::string post_compression_content_encoding;
  8961. // Set up pre-compression logger
  8962. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8963. const Response &res) {
  8964. pre_compression_body = res.body;
  8965. pre_compression_content_type = res.get_header_value("Content-Type");
  8966. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8967. });
  8968. // Set up post-compression logger
  8969. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8970. post_compression_body = res.body;
  8971. post_compression_content_type = res.get_header_value("Content-Type");
  8972. post_compression_content_encoding =
  8973. res.get_header_value("Content-Encoding");
  8974. });
  8975. // Test with gzip compression
  8976. Headers headers;
  8977. headers.emplace("Accept-Encoding", "gzip");
  8978. auto res = cli_.Get("/compress", headers);
  8979. // Verify response was compressed
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ(StatusCode::OK_200, res->status);
  8982. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8983. // Verify pre-compression logger captured uncompressed content
  8984. EXPECT_EQ(test_content, pre_compression_body);
  8985. EXPECT_EQ("text/plain", pre_compression_content_type);
  8986. EXPECT_TRUE(pre_compression_content_encoding
  8987. .empty()); // No encoding header before compression
  8988. // Verify post-compression logger captured compressed content
  8989. EXPECT_NE(test_content,
  8990. post_compression_body); // Should be different after compression
  8991. EXPECT_EQ("text/plain", post_compression_content_type);
  8992. EXPECT_EQ("gzip", post_compression_content_encoding);
  8993. // Verify compressed content is smaller
  8994. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8995. }
  8996. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8997. const std::string test_content =
  8998. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8999. "3456789012345678901234567890";
  9000. std::string pre_compression_body;
  9001. std::string post_compression_body;
  9002. svr_.set_pre_compression_logger(
  9003. [&](const Request & /*req*/, const Response &res) {
  9004. pre_compression_body = res.body;
  9005. });
  9006. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9007. post_compression_body = res.body;
  9008. });
  9009. Headers headers;
  9010. headers.emplace("Accept-Encoding", "br");
  9011. auto res = cli_.Get("/compress", headers);
  9012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9013. EXPECT_EQ(StatusCode::OK_200, res->status);
  9014. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9015. // Verify pre-compression content is uncompressed
  9016. EXPECT_EQ(test_content, pre_compression_body);
  9017. // Verify post-compression content is compressed
  9018. EXPECT_NE(test_content, post_compression_body);
  9019. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9020. }
  9021. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9022. const std::string test_content =
  9023. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9024. "3456789012345678901234567890";
  9025. std::string pre_compression_body;
  9026. std::string post_compression_body;
  9027. svr_.set_pre_compression_logger(
  9028. [&](const Request & /*req*/, const Response &res) {
  9029. pre_compression_body = res.body;
  9030. });
  9031. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9032. post_compression_body = res.body;
  9033. });
  9034. // Request without compression (use /nocompress endpoint)
  9035. Headers headers;
  9036. auto res = cli_.Get("/nocompress", headers);
  9037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9038. EXPECT_EQ(StatusCode::OK_200, res->status);
  9039. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9040. // Pre-compression logger should not be called when no compression is applied
  9041. EXPECT_TRUE(
  9042. pre_compression_body.empty()); // Pre-compression logger not called
  9043. EXPECT_EQ(
  9044. test_content,
  9045. post_compression_body); // Post-compression logger captures final content
  9046. }
  9047. TEST_F(ServerTest, LoggerSeesContentLength) {
  9048. size_t logged_content_length = 0;
  9049. std::string logged_content_length_header;
  9050. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9051. logged_content_length = res.content_length_;
  9052. logged_content_length_header = res.get_header_value("Content-Length");
  9053. });
  9054. auto res = cli_.Get("/nocompress");
  9055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. EXPECT_EQ(res->body.size(), logged_content_length);
  9058. EXPECT_EQ(std::to_string(logged_content_length),
  9059. logged_content_length_header);
  9060. }
  9061. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9062. const std::string test_content =
  9063. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9064. "3456789012345678901234567890";
  9065. std::string pre_compression_body;
  9066. bool pre_logger_called = false;
  9067. // Set only pre-compression logger
  9068. svr_.set_pre_compression_logger(
  9069. [&](const Request & /*req*/, const Response &res) {
  9070. pre_compression_body = res.body;
  9071. pre_logger_called = true;
  9072. });
  9073. Headers headers;
  9074. headers.emplace("Accept-Encoding", "gzip");
  9075. auto res = cli_.Get("/compress", headers);
  9076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9077. EXPECT_EQ(StatusCode::OK_200, res->status);
  9078. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9079. // Verify pre-compression logger was called
  9080. EXPECT_TRUE(pre_logger_called);
  9081. EXPECT_EQ(test_content, pre_compression_body);
  9082. }
  9083. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9084. {
  9085. // Test with Expect: 100-continue header - success case
  9086. // Server returns 100 Continue, client sends body, server returns 200 OK
  9087. Request req;
  9088. req.method = "POST";
  9089. req.path = "/post-large";
  9090. req.set_header("Expect", "100-continue");
  9091. req.body = LARGE_DATA;
  9092. Response res;
  9093. auto error = Error::Success;
  9094. cli_.set_keep_alive(true);
  9095. auto ret = cli_.send(req, res, error);
  9096. EXPECT_TRUE(ret);
  9097. EXPECT_EQ(StatusCode::OK_200, res.status);
  9098. EXPECT_EQ(LARGE_DATA, res.body);
  9099. }
  9100. {
  9101. // Test with Expect: 100-continue header - error case
  9102. // Client should not send the body when server returns an error
  9103. Request req;
  9104. req.method = "POST";
  9105. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9106. req.set_header("Expect", "100-continue");
  9107. req.body = LARGE_DATA;
  9108. Response res;
  9109. auto error = Error::Success;
  9110. auto start = std::chrono::high_resolution_clock::now();
  9111. cli_.set_keep_alive(true);
  9112. auto ret = cli_.send(req, res, error);
  9113. auto end = std::chrono::high_resolution_clock::now();
  9114. auto elapsed =
  9115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9116. .count();
  9117. // With Expect: 100-continue, request completes successfully but with error
  9118. EXPECT_TRUE(ret);
  9119. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9120. EXPECT_EQ("close", res.get_header_value("Connection"));
  9121. EXPECT_FALSE(cli_.is_socket_open());
  9122. EXPECT_LE(elapsed, 2000);
  9123. }
  9124. {
  9125. // Send an extra GET request to ensure error recovery without hanging
  9126. Request req;
  9127. req.method = "GET";
  9128. req.path = "/hi";
  9129. auto start = std::chrono::high_resolution_clock::now();
  9130. auto res = cli_.send(req);
  9131. auto end = std::chrono::high_resolution_clock::now();
  9132. auto elapsed =
  9133. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9134. .count();
  9135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. EXPECT_EQ("Hello World!", res->body);
  9138. EXPECT_LE(elapsed, 500);
  9139. }
  9140. }
  9141. TEST(ZstdDecompressor, ChunkedDecompression) {
  9142. std::string data;
  9143. for (size_t i = 0; i < 32 * 1024; ++i) {
  9144. data.push_back(static_cast<char>('a' + i % 26));
  9145. }
  9146. std::string compressed_data;
  9147. {
  9148. httplib::detail::zstd_compressor compressor;
  9149. bool result = compressor.compress(
  9150. data.data(), data.size(),
  9151. /*last=*/true,
  9152. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9153. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9154. compressed_data_size);
  9155. return true;
  9156. });
  9157. ASSERT_TRUE(result);
  9158. }
  9159. std::string decompressed_data;
  9160. {
  9161. httplib::detail::zstd_decompressor decompressor;
  9162. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9163. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9164. size_t chunk_size = 130;
  9165. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9166. chunk_begin += chunk_size) {
  9167. size_t current_chunk_size =
  9168. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9169. bool result = decompressor.decompress(
  9170. compressed_data.data() + chunk_begin, current_chunk_size,
  9171. [&](const char *decompressed_data_chunk,
  9172. size_t decompressed_data_chunk_size) {
  9173. decompressed_data.insert(decompressed_data.size(),
  9174. decompressed_data_chunk,
  9175. decompressed_data_chunk_size);
  9176. return true;
  9177. });
  9178. ASSERT_TRUE(result);
  9179. }
  9180. }
  9181. ASSERT_EQ(data, decompressed_data);
  9182. }
  9183. TEST(ZstdDecompressor, Decompress) {
  9184. std::string original_text = "Compressed with ZSTD";
  9185. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9186. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9187. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9188. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9189. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9190. std::string decompressed_data;
  9191. {
  9192. httplib::detail::zstd_decompressor decompressor;
  9193. bool result = decompressor.decompress(
  9194. compressed_data.data(), compressed_data.size(),
  9195. [&](const char *decompressed_data_chunk,
  9196. size_t decompressed_data_chunk_size) {
  9197. decompressed_data.insert(decompressed_data.size(),
  9198. decompressed_data_chunk,
  9199. decompressed_data_chunk_size);
  9200. return true;
  9201. });
  9202. ASSERT_TRUE(result);
  9203. }
  9204. ASSERT_EQ(original_text, decompressed_data);
  9205. }
  9206. #endif
  9207. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9208. // separate chunks so that the server sees each part in its own read(). Used to
  9209. // place a read boundary at a specific offset of a request body.
  9210. static bool send_request_in_parts(time_t read_timeout_sec,
  9211. const std::vector<std::string> &parts,
  9212. std::string *resp = nullptr,
  9213. int port = PORT) {
  9214. auto error = Error::Success;
  9215. auto client_sock = detail::create_client_socket(
  9216. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9217. /*connection_timeout_sec=*/5, 0,
  9218. /*read_timeout_sec=*/5, 0,
  9219. /*write_timeout_sec=*/5, 0, std::string(), error);
  9220. if (client_sock == INVALID_SOCKET) { return false; }
  9221. auto ret = detail::process_client_socket(
  9222. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9223. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9224. for (size_t i = 0; i < parts.size(); i++) {
  9225. const auto &part = parts[i];
  9226. if (part.size() !=
  9227. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9228. return false;
  9229. }
  9230. if (i + 1 < parts.size()) {
  9231. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9232. }
  9233. }
  9234. char buf[512];
  9235. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9236. while (line_reader.getline()) {
  9237. if (resp) { *resp += line_reader.ptr(); }
  9238. }
  9239. return true;
  9240. });
  9241. detail::close_socket(client_sock);
  9242. return ret;
  9243. }
  9244. // Sends a raw request to a server listening at HOST:PORT.
  9245. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9246. std::string *resp = nullptr, int port = PORT) {
  9247. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9248. }
  9249. #ifdef CPPHTTPLIB_SSL_ENABLED
  9250. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9251. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9252. ASSERT_TRUE(svr.is_valid());
  9253. svr.set_read_timeout(1, 0);
  9254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9255. auto se = detail::scope_exit([&] {
  9256. svr.stop();
  9257. t.join();
  9258. ASSERT_FALSE(svr.is_running());
  9259. });
  9260. svr.wait_until_ready();
  9261. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9262. // keeps each wait well within the read timeout. The server gives up a
  9263. // second in, so the bytes sent after that fail.
  9264. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9265. parts.resize(26, std::string(1, '\0'));
  9266. EXPECT_FALSE(send_request_in_parts(5, parts));
  9267. }
  9268. #endif
  9269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9270. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9271. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9272. const std::vector<std::string> &parts,
  9273. std::string *resp = nullptr,
  9274. int port = PORT) {
  9275. auto error = Error::Success;
  9276. auto sock = detail::create_client_socket(
  9277. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9278. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9279. /*write_timeout_sec=*/5, 0, std::string(), error);
  9280. if (sock == INVALID_SOCKET) { return false; }
  9281. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9282. auto ctx = SSL_CTX_new(TLS_client_method());
  9283. auto ssl = SSL_new(ctx);
  9284. auto ssl_se = detail::scope_exit([&] {
  9285. SSL_free(ssl);
  9286. SSL_CTX_free(ctx);
  9287. });
  9288. SSL_set_fd(ssl, static_cast<int>(sock));
  9289. if (SSL_connect(ssl) != 1) { return false; }
  9290. for (size_t i = 0; i < parts.size(); i++) {
  9291. const auto &part = parts[i];
  9292. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9293. static_cast<int>(part.size())) {
  9294. return false;
  9295. }
  9296. if (i + 1 < parts.size()) {
  9297. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9298. }
  9299. }
  9300. char buf[512];
  9301. int n;
  9302. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9303. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9304. }
  9305. return true;
  9306. }
  9307. #endif
  9308. // The request line, then a header value a byte at a time.
  9309. static std::vector<std::string> slow_request_head_parts() {
  9310. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9311. parts.resize(26, "a");
  9312. parts.emplace_back("\r\n\r\n");
  9313. return parts;
  9314. }
  9315. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9316. // within the one-second read timeout. The server gives up a second in, before
  9317. // the head is complete.
  9318. static void
  9319. expect_slow_request_head_dropped(Server &svr,
  9320. const std::function<std::string()> &send) {
  9321. std::atomic<bool> handled(false);
  9322. svr.Get("/", [&](const Request &, Response &res) {
  9323. handled = true;
  9324. res.set_content("ok", "text/plain");
  9325. });
  9326. svr.set_read_timeout(1, 0);
  9327. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9328. auto se = detail::scope_exit([&] {
  9329. svr.stop();
  9330. t.join();
  9331. ASSERT_FALSE(svr.is_running());
  9332. });
  9333. svr.wait_until_ready();
  9334. auto resp = send();
  9335. EXPECT_FALSE(handled);
  9336. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9337. }
  9338. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9339. Server svr;
  9340. expect_slow_request_head_dropped(svr, [] {
  9341. std::string resp;
  9342. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9343. return resp;
  9344. });
  9345. }
  9346. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9347. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9349. ASSERT_TRUE(svr.is_valid());
  9350. expect_slow_request_head_dropped(svr, [] {
  9351. std::string resp;
  9352. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9353. return resp;
  9354. });
  9355. }
  9356. #endif
  9357. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9358. Server svr;
  9359. std::string header_value;
  9360. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9361. header_value = req.get_header_value("foo");
  9362. res.set_content("ok", "text/plain");
  9363. });
  9364. thread t = thread([&] { svr.listen(HOST, PORT); });
  9365. auto se = detail::scope_exit([&] {
  9366. svr.stop();
  9367. t.join();
  9368. ASSERT_FALSE(svr.is_running());
  9369. });
  9370. svr.wait_until_ready();
  9371. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9372. // like characters are not treated the same - use vertical tab and escape.
  9373. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9374. "foo: \t \v bar \x1B\t \r\n"
  9375. "Connection: close\r\n"
  9376. "\r\n";
  9377. std::string res;
  9378. ASSERT_TRUE(send_request(5, req, &res));
  9379. EXPECT_EQ(header_value, "");
  9380. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9381. }
  9382. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9383. Server svr;
  9384. std::string received;
  9385. svr.Get("/order", [&](const Request &req, Response &res) {
  9386. received = entries_to_string(req.headers);
  9387. res.set_content("ok", "text/plain");
  9388. });
  9389. auto port = svr.bind_to_any_port(HOST);
  9390. thread t = thread([&] { svr.listen_after_bind(); });
  9391. auto se = detail::scope_exit([&] {
  9392. svr.stop();
  9393. t.join();
  9394. ASSERT_FALSE(svr.is_running());
  9395. });
  9396. svr.wait_until_ready();
  9397. const std::string req = "GET /order HTTP/1.1\r\n"
  9398. "Host: localhost\r\n"
  9399. "X-First: 1\r\n"
  9400. "X-Dup: a\r\n"
  9401. "X-Second: 2\r\n"
  9402. "X-Dup: b\r\n"
  9403. "Connection: close\r\n"
  9404. "\r\n";
  9405. std::string res;
  9406. ASSERT_TRUE(send_request(5, req, &res, port));
  9407. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9408. EXPECT_EQ(
  9409. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9410. received);
  9411. }
  9412. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9413. Server svr;
  9414. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9415. res.set_header("Set-Cookie", "first=1");
  9416. res.set_header("X-Between", "y");
  9417. res.set_header("Set-Cookie", "second=2");
  9418. res.set_content("ok", "text/plain");
  9419. });
  9420. auto port = svr.bind_to_any_port(HOST);
  9421. thread t = thread([&] { svr.listen_after_bind(); });
  9422. auto se = detail::scope_exit([&] {
  9423. svr.stop();
  9424. t.join();
  9425. ASSERT_FALSE(svr.is_running());
  9426. });
  9427. svr.wait_until_ready();
  9428. Client cli(HOST, port);
  9429. auto res = cli.Get("/cookies");
  9430. ASSERT_TRUE(res);
  9431. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9432. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9433. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9434. }
  9435. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9436. Server svr;
  9437. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9438. auto i = new int(0);
  9439. res.set_header("Trailer", "X-Safe, X-Reflected");
  9440. res.set_chunked_content_provider(
  9441. "text/plain",
  9442. [i](size_t /*offset*/, DataSink &sink) {
  9443. if (*i == 0) {
  9444. sink.os << "body";
  9445. } else {
  9446. Headers trailer;
  9447. // A valid trailer that must survive.
  9448. trailer.emplace("X-Safe", "safe");
  9449. // Attacker-controlled value carrying CR/LF (response splitting).
  9450. trailer.emplace("X-Reflected",
  9451. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9452. // Attacker-controlled name carrying CR/LF.
  9453. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9454. sink.done_with_trailer(trailer);
  9455. }
  9456. (*i)++;
  9457. return true;
  9458. },
  9459. [i](bool /*success*/) { delete i; });
  9460. });
  9461. thread t = thread([&] { svr.listen(HOST, PORT); });
  9462. auto se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. t.join();
  9465. ASSERT_FALSE(svr.is_running());
  9466. });
  9467. svr.wait_until_ready();
  9468. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9469. "Host: " + HOST +
  9470. "\r\n"
  9471. "Connection: close\r\n"
  9472. "\r\n";
  9473. std::string res;
  9474. ASSERT_TRUE(send_request(5, req, &res));
  9475. // The injected fields must not appear anywhere in the raw response.
  9476. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9477. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9478. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9479. // Invalid trailers are dropped entirely, matching set_header().
  9480. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9481. // The valid trailer still passes through.
  9482. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9483. }
  9484. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9485. Server svr;
  9486. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9487. // res.headers is a public field an application can populate directly,
  9488. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9489. // A valid header that must survive.
  9490. res.headers.emplace("X-Safe", "safe");
  9491. // Attacker-controlled value carrying CR/LF (response splitting).
  9492. res.headers.emplace("X-Reflected",
  9493. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9494. // Attacker-controlled name carrying CR/LF.
  9495. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9496. res.set_content("body", "text/plain");
  9497. });
  9498. thread t = thread([&] { svr.listen(HOST, PORT); });
  9499. auto se = detail::scope_exit([&] {
  9500. svr.stop();
  9501. t.join();
  9502. ASSERT_FALSE(svr.is_running());
  9503. });
  9504. svr.wait_until_ready();
  9505. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9506. "Host: " + HOST +
  9507. "\r\n"
  9508. "Connection: close\r\n"
  9509. "\r\n";
  9510. std::string res;
  9511. ASSERT_TRUE(send_request(5, req, &res));
  9512. // The injected fields must not appear anywhere in the raw response.
  9513. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9514. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9515. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9516. // Invalid headers are dropped entirely, matching set_header().
  9517. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9518. // The valid header still passes through.
  9519. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9520. }
  9521. // Forward declaration: in split builds split.py strips `inline` and moves the
  9522. // definition into httplib.cc, so detail::write_request_line is not visible from
  9523. // the public httplib.h. Re-declaring it here lets the tests link against the
  9524. // symbol in both header-only and split builds.
  9525. namespace httplib {
  9526. namespace detail {
  9527. ssize_t write_request_line(Stream &strm, const std::string &method,
  9528. const std::string &path);
  9529. } // namespace detail
  9530. } // namespace httplib
  9531. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9532. // A well-formed target is written verbatim.
  9533. {
  9534. detail::BufferStream strm;
  9535. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9536. EXPECT_GT(n, 0);
  9537. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9538. }
  9539. // A target carrying CR/LF, SP or other control octets must be rejected
  9540. // before anything reaches the wire, otherwise it splits the request line and
  9541. // injects a header or a whole request.
  9542. const std::string evil_targets[] = {
  9543. "/a\r\nInjected: pwned",
  9544. "/a\rInjected",
  9545. "/a\nInjected",
  9546. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9547. "/a b",
  9548. "/a\tb",
  9549. "/a\x7f",
  9550. };
  9551. for (const auto &evil : evil_targets) {
  9552. detail::BufferStream strm;
  9553. auto n = detail::write_request_line(strm, "GET", evil);
  9554. EXPECT_LT(n, 0);
  9555. EXPECT_TRUE(strm.get_buffer().empty());
  9556. }
  9557. }
  9558. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9559. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9560. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9561. // target reaches write_request. The client must fail cleanly with
  9562. // Error::Write instead of putting a request-line-less, header-injecting
  9563. // request on the wire.
  9564. Server svr;
  9565. svr.Get("/a", [](const Request &, Response &res) {
  9566. res.set_content("ok", "text/plain");
  9567. });
  9568. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9569. auto se = detail::scope_exit([&] {
  9570. svr.stop();
  9571. thread.join();
  9572. ASSERT_FALSE(svr.is_running());
  9573. });
  9574. svr.wait_until_ready();
  9575. {
  9576. Client cli(HOST, PORT);
  9577. cli.set_path_encode(false);
  9578. // The request is rejected before anything is written, so the connection
  9579. // stays silent and the subsequent response read would otherwise block for
  9580. // the full default read timeout. Shorten it -- the assertion is on the
  9581. // error, not the timeout.
  9582. cli.set_read_timeout(1, 0);
  9583. auto res = cli.Get("/a\r\nInjected: pwned");
  9584. EXPECT_FALSE(res);
  9585. EXPECT_EQ(Error::Write, res.error());
  9586. }
  9587. }
  9588. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9589. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9590. // including extension methods.
  9591. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9592. for (const auto &method : good_methods) {
  9593. detail::BufferStream strm;
  9594. auto n = detail::write_request_line(strm, method, "/");
  9595. EXPECT_GT(n, 0);
  9596. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9597. }
  9598. // A method carrying CR/LF would split the request line and smuggle a whole
  9599. // request ahead of the real one. A space or an empty method corrupts the
  9600. // request line. All must be rejected before anything reaches the wire.
  9601. const std::string evil_methods[] = {
  9602. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9603. "GET\r\nInjected: pwned",
  9604. "GET\r",
  9605. "GET\n",
  9606. "GE T",
  9607. "",
  9608. };
  9609. for (const auto &evil : evil_methods) {
  9610. detail::BufferStream strm;
  9611. auto n = detail::write_request_line(strm, evil, "/");
  9612. EXPECT_LT(n, 0);
  9613. EXPECT_TRUE(strm.get_buffer().empty());
  9614. }
  9615. }
  9616. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9617. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9618. // through Client::send must fail with Error::Write and no request, neither
  9619. // the smuggled one nor the real one, may reach the server.
  9620. Server svr;
  9621. std::atomic<int> request_count(0);
  9622. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9623. request_count++;
  9624. res.status = StatusCode::OK_200;
  9625. return Server::HandlerResponse::Handled;
  9626. });
  9627. auto port = svr.bind_to_any_port(HOST);
  9628. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9629. auto se = detail::scope_exit([&] {
  9630. svr.stop();
  9631. thread.join();
  9632. ASSERT_FALSE(svr.is_running());
  9633. });
  9634. svr.wait_until_ready();
  9635. {
  9636. Client cli(HOST, port);
  9637. const std::string evil_methods[] = {
  9638. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9639. "GE T",
  9640. "",
  9641. };
  9642. for (const auto &evil : evil_methods) {
  9643. Request req;
  9644. req.method = evil;
  9645. req.path = "/";
  9646. auto res = cli.send(req);
  9647. EXPECT_FALSE(res);
  9648. EXPECT_EQ(Error::Write, res.error());
  9649. }
  9650. auto handle =
  9651. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9652. EXPECT_FALSE(handle.is_valid());
  9653. EXPECT_EQ(Error::Write, handle.error);
  9654. // A valid request on the same client still goes through.
  9655. auto res = cli.Get("/");
  9656. ASSERT_TRUE(res);
  9657. EXPECT_EQ(StatusCode::OK_200, res->status);
  9658. }
  9659. EXPECT_EQ(1, request_count.load());
  9660. }
  9661. // Sends a raw request and verifies that there isn't a crash or exception.
  9662. static void test_raw_request(const std::string &req,
  9663. std::string *out = nullptr) {
  9664. Server svr;
  9665. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9666. res.set_content("ok", "text/plain");
  9667. });
  9668. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9669. res.set_content("ok", "text/plain");
  9670. });
  9671. svr.Get("/header_field_value_check",
  9672. [&](const Request & /*req*/, Response &res) {
  9673. res.set_content("ok", "text/plain");
  9674. });
  9675. svr.CustomRoute("PROPFIND", "/dav",
  9676. [&](const Request & /*req*/, Response &res) {
  9677. res.status = StatusCode::MultiStatus_207;
  9678. });
  9679. // Server read timeout must be longer than the client read timeout for the
  9680. // bug to reproduce, probably to force the server to process a request
  9681. // without a trailing blank line.
  9682. const time_t client_read_timeout_sec = 1;
  9683. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9684. bool listen_thread_ok = false;
  9685. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9686. auto se = detail::scope_exit([&] {
  9687. svr.stop();
  9688. t.join();
  9689. ASSERT_FALSE(svr.is_running());
  9690. EXPECT_TRUE(listen_thread_ok);
  9691. });
  9692. svr.wait_until_ready();
  9693. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9694. }
  9695. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9696. // A certain header line causes an exception if the header property is parsed
  9697. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9698. test_raw_request(
  9699. "GET /hi HTTP/1.1\r\n"
  9700. " : "
  9701. " "
  9702. " ");
  9703. }
  9704. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9705. // A certain header line causes an exception if the header property *name* is
  9706. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9707. // greedy matcher and requires backtracking when there are a lot of ":"
  9708. // characters.
  9709. // This occurs with libc++ but not libstdc++.
  9710. test_raw_request(
  9711. "GET /hi HTTP/1.1\r\n"
  9712. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9713. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9714. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9715. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9716. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9717. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9718. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9719. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9720. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9721. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9722. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9723. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9724. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9725. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9726. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9727. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9728. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9729. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9730. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9731. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9732. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9733. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9734. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9735. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9736. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9737. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9738. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9739. "&&&%%%");
  9740. }
  9741. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9742. // Make sure this doesn't crash the server.
  9743. // In a previous version of the header line regex, the "\r" rendered the line
  9744. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9745. // a new position where the leading white space ended and the field value
  9746. // began.
  9747. // The crash occurs with libc++ but not libstdc++.
  9748. test_raw_request("GET /hi HTTP/1.1\r\n"
  9749. "a:" +
  9750. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9751. "\r\n"
  9752. "\r\n");
  9753. }
  9754. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9755. const char *rejected[] = {
  9756. // RFC 9112 §3: one SP between the parts, and nothing else
  9757. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9758. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9759. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9760. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9761. // A request-target has no fragment
  9762. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9763. // An HTTP/1.1 request needs a Host
  9764. "GET /hi HTTP/1.1\r\n\r\n",
  9765. };
  9766. for (auto request : rejected) {
  9767. std::string out;
  9768. test_raw_request(request, &out);
  9769. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9770. }
  9771. std::string out;
  9772. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9773. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9774. }
  9775. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9776. // RFC 9112 §6.1
  9777. const char *requests[] = {
  9778. "PUT /put_hi HTTP/1.1\r\n"
  9779. "Host: localhost\r\n"
  9780. "Content-Length: 0\r\n"
  9781. "Transfer-Encoding: chunked\r\n"
  9782. "\r\n"
  9783. "0\r\n\r\n",
  9784. "PUT /put_hi HTTP/1.0\r\n"
  9785. "Connection: keep-alive\r\n"
  9786. "Transfer-Encoding: chunked\r\n"
  9787. "\r\n"
  9788. "0\r\n\r\n",
  9789. };
  9790. for (auto request : requests) {
  9791. std::string out;
  9792. test_raw_request(request, &out);
  9793. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9794. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9795. }
  9796. }
  9797. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9798. std::string out;
  9799. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9800. "Content-Type: text/plain\r\n"
  9801. "Transfer-Encoding: chunked\r\n"
  9802. "\r\n"
  9803. "nothex\r\n",
  9804. &out);
  9805. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9806. }
  9807. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9808. std::string out;
  9809. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9810. "Content-Type: text/plain\r\n"
  9811. "Transfer-Encoding: chunked\r\n"
  9812. "\r\n"
  9813. "3\r\n"
  9814. "xyz\r\n"
  9815. "NaN\r\n",
  9816. &out);
  9817. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9818. }
  9819. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9820. std::string out;
  9821. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9822. "Content-Type: text/plain\r\n"
  9823. "Transfer-Encoding: chunked\r\n"
  9824. "\r\n"
  9825. // Length is too large for 64 bits.
  9826. "1ffffffffffffffff\r\n"
  9827. "xyz\r\n",
  9828. &out);
  9829. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9830. }
  9831. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9832. test_raw_request("GET /hi HTTP/1.1\r\n"
  9833. "Content-Type: text/plain\r\n\r");
  9834. }
  9835. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9836. std::string out;
  9837. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9838. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9839. }
  9840. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9841. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9842. std::string out;
  9843. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9844. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9845. }
  9846. }
  9847. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9848. std::string out;
  9849. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9850. "Host: localhost\r\n"
  9851. "Connection: close\r\n\r\n",
  9852. &out);
  9853. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9854. }
  9855. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9856. Server svr;
  9857. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9858. EXPECT_TRUE(!req.remote_addr.empty());
  9859. });
  9860. thread t = thread([&] { svr.listen(HOST, PORT); });
  9861. auto se = detail::scope_exit([&] {
  9862. svr.stop();
  9863. t.join();
  9864. ASSERT_FALSE(svr.is_running());
  9865. });
  9866. svr.wait_until_ready();
  9867. // Send an invalid request line to trigger Bad Request
  9868. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9869. std::string out;
  9870. ASSERT_TRUE(send_request(5, bad_req, &out));
  9871. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9872. }
  9873. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9874. // answered right away rather than blocking on a read that waits for EOF.
  9875. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9876. std::string out;
  9877. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9878. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9879. }
  9880. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9881. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9882. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9883. for (const auto *method : methods) {
  9884. Server svr;
  9885. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9886. EXPECT_FALSE(svr.is_valid()) << method;
  9887. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9888. }
  9889. }
  9890. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9891. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9892. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9893. for (const auto *method : methods) {
  9894. Server svr;
  9895. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9896. EXPECT_FALSE(svr.is_valid()) << method;
  9897. }
  9898. }
  9899. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9900. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9901. "COPY", "MOVE", "LOCK",
  9902. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9903. Server svr;
  9904. for (const auto *method : methods) {
  9905. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9906. }
  9907. EXPECT_TRUE(svr.is_valid());
  9908. }
  9909. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9910. Server svr;
  9911. svr.CustomRoute("POST", "/x",
  9912. [](const Request &, Response &, const ContentReader &) {});
  9913. EXPECT_FALSE(svr.is_valid());
  9914. }
  9915. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9916. Server svr;
  9917. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9918. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9919. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9920. EXPECT_FALSE(svr.is_valid());
  9921. }
  9922. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9923. Server svr;
  9924. auto captured = Error::Success;
  9925. svr.set_error_logger(
  9926. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9927. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9928. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9929. }
  9930. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9931. std::string out;
  9932. std::string request(
  9933. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9934. test_raw_request(request, &out);
  9935. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9936. }
  9937. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9938. std::string out;
  9939. std::string request(
  9940. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9941. test_raw_request(request, &out);
  9942. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9943. }
  9944. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9945. std::string out;
  9946. std::string request(
  9947. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9948. test_raw_request(request, &out);
  9949. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9950. }
  9951. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9952. std::string out;
  9953. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9954. "Host: localhost\r\n"
  9955. "Test: \r\n\r\n",
  9956. &out);
  9957. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9958. }
  9959. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9960. Server svr;
  9961. std::string x_custom;
  9962. std::string cookie;
  9963. std::string xff;
  9964. std::string x_unicode;
  9965. std::string x_iis;
  9966. svr.Get("/check", [&](const Request &req, Response &res) {
  9967. x_custom = req.get_header_value("X-Custom");
  9968. cookie = req.get_header_value("Cookie");
  9969. xff = req.get_header_value("X-Forwarded-For");
  9970. x_unicode = req.get_header_value("X-Unicode");
  9971. x_iis = req.get_header_value("X-IIS");
  9972. res.set_content("ok", "text/plain");
  9973. });
  9974. thread t = thread([&] { svr.listen(HOST, PORT); });
  9975. auto se = detail::scope_exit([&] {
  9976. svr.stop();
  9977. t.join();
  9978. ASSERT_FALSE(svr.is_running());
  9979. });
  9980. svr.wait_until_ready();
  9981. const std::string req = "GET /check HTTP/1.1\r\n"
  9982. "Host: localhost\r\n"
  9983. "X-Custom: a%0D%0AInjected: b\r\n"
  9984. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9985. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9986. "X-Unicode: %E3%81%82\r\n"
  9987. "X-IIS: %u00E9\r\n"
  9988. "Connection: close\r\n"
  9989. "\r\n";
  9990. std::string res;
  9991. ASSERT_TRUE(send_request(5, req, &res));
  9992. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9993. // Every value must be returned verbatim (wire form), with no decoding.
  9994. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9995. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9996. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9997. EXPECT_EQ("%E3%81%82", x_unicode);
  9998. EXPECT_EQ("%u00E9", x_iis);
  9999. }
  10000. // Applications that previously relied on automatic percent-decoding can
  10001. // reproduce the old behavior by explicitly calling decode_path_component()
  10002. // or, for RFC 3986 conformance, decode_uri_component().
  10003. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10004. Server svr;
  10005. std::string decoded;
  10006. svr.Get("/check", [&](const Request &req, Response &res) {
  10007. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10008. res.set_content("ok", "text/plain");
  10009. });
  10010. thread t = thread([&] { svr.listen(HOST, PORT); });
  10011. auto se = detail::scope_exit([&] {
  10012. svr.stop();
  10013. t.join();
  10014. ASSERT_FALSE(svr.is_running());
  10015. });
  10016. svr.wait_until_ready();
  10017. const std::string req = "GET /check HTTP/1.1\r\n"
  10018. "Host: localhost\r\n"
  10019. "X-Custom: hello%20world\r\n"
  10020. "Connection: close\r\n"
  10021. "\r\n";
  10022. std::string res;
  10023. ASSERT_TRUE(send_request(5, req, &res));
  10024. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10025. EXPECT_EQ("hello world", decoded);
  10026. }
  10027. // Regression test for #2033. Browsers send Referer values that include
  10028. // percent-encoded characters such as %0A inside the URL. Decoding the
  10029. // header value would either trip the post-decode CR/LF/NUL guard (the
  10030. // original bug, returning 400) or, after that guard was relaxed, silently
  10031. // store a literal LF — both unacceptable. The wire form must round-trip.
  10032. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10033. Server svr;
  10034. std::string referer;
  10035. svr.Get("/check", [&](const Request &req, Response &res) {
  10036. referer = req.get_header_value("Referer");
  10037. res.set_content("ok", "text/plain");
  10038. });
  10039. thread t = thread([&] { svr.listen(HOST, PORT); });
  10040. auto se = detail::scope_exit([&] {
  10041. svr.stop();
  10042. t.join();
  10043. ASSERT_FALSE(svr.is_running());
  10044. });
  10045. svr.wait_until_ready();
  10046. const std::string req = "GET /check HTTP/1.1\r\n"
  10047. "Host: localhost\r\n"
  10048. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10049. "Connection: close\r\n"
  10050. "\r\n";
  10051. std::string res;
  10052. ASSERT_TRUE(send_request(5, req, &res));
  10053. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10054. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10055. }
  10056. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10057. Server svr;
  10058. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10059. res.set_header("Cache-Control", "no-cache");
  10060. res.set_chunked_content_provider(
  10061. "text/event-stream", [](size_t offset, DataSink &sink) {
  10062. std::string s = "data:";
  10063. s += std::to_string(offset);
  10064. s += "\n\n";
  10065. auto ret = sink.write(s.data(), s.size());
  10066. EXPECT_TRUE(ret);
  10067. std::this_thread::sleep_for(std::chrono::seconds(1));
  10068. return true;
  10069. });
  10070. });
  10071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10072. svr.wait_until_ready();
  10073. Client client(HOST, PORT);
  10074. const Headers headers = {{"Accept", "text/event-stream"}};
  10075. auto get_thread = std::thread([&client, &headers]() {
  10076. auto res = client.Get(
  10077. "/events", headers,
  10078. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10079. });
  10080. auto se = detail::scope_exit([&] {
  10081. svr.stop();
  10082. get_thread.join();
  10083. listen_thread.join();
  10084. ASSERT_FALSE(svr.is_running());
  10085. });
  10086. // Give GET time to get a few messages.
  10087. std::this_thread::sleep_for(std::chrono::seconds(2));
  10088. }
  10089. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10090. httplib::Server svr;
  10091. svr.Post("/hi",
  10092. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10093. res.status = StatusCode::OK_200;
  10094. });
  10095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10096. svr.wait_until_ready();
  10097. Client cli(HOST, PORT);
  10098. auto res = cli.Post("/hi", "data", "text/plain");
  10099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10100. EXPECT_EQ(StatusCode::OK_200, res->status);
  10101. svr.stop();
  10102. thread.join();
  10103. ASSERT_FALSE(svr.is_running());
  10104. res = cli.Post("/hi", "data", "text/plain");
  10105. ASSERT_FALSE(res);
  10106. }
  10107. TEST(ServerStopTest, ListenFailure) {
  10108. Server svr;
  10109. auto t = thread([&]() {
  10110. auto ret = svr.listen("????", PORT);
  10111. EXPECT_FALSE(ret);
  10112. });
  10113. svr.wait_until_ready();
  10114. svr.stop();
  10115. t.join();
  10116. }
  10117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10118. TEST(ServerStopTest, Decommision) {
  10119. Server svr;
  10120. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10121. for (int i = 0; i < 4; i++) {
  10122. auto is_even = !(i % 2);
  10123. std::thread t{[&] {
  10124. try {
  10125. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10126. if (is_even) {
  10127. throw std::runtime_error("Some thing that happens to go wrong.");
  10128. }
  10129. svr.listen(HOST, PORT);
  10130. } catch (...) { svr.decommission(); }
  10131. }};
  10132. svr.wait_until_ready();
  10133. // Server is up
  10134. {
  10135. Client cli(HOST, PORT);
  10136. auto res = cli.Get("/hi");
  10137. if (is_even) {
  10138. EXPECT_FALSE(res);
  10139. } else {
  10140. EXPECT_TRUE(res);
  10141. EXPECT_EQ("hi...", res->body);
  10142. }
  10143. }
  10144. svr.stop();
  10145. t.join();
  10146. // Server is down...
  10147. {
  10148. Client cli(HOST, PORT);
  10149. auto res = cli.Get("/hi");
  10150. EXPECT_FALSE(res);
  10151. }
  10152. }
  10153. }
  10154. #endif
  10155. // Helper function for string body upload progress tests
  10156. template <typename SetupHandler, typename ClientCall>
  10157. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10158. ClientCall &&client_call,
  10159. const string &body) {
  10160. Server svr;
  10161. setup_handler(svr);
  10162. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10163. auto se = detail::scope_exit([&] {
  10164. svr.stop();
  10165. t.join();
  10166. });
  10167. svr.wait_until_ready();
  10168. Client cli(HOST, PORT);
  10169. vector<uint64_t> progress_values;
  10170. bool progress_called = false;
  10171. auto res =
  10172. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10173. progress_values.push_back(current);
  10174. progress_called = true;
  10175. return true;
  10176. });
  10177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10178. EXPECT_EQ(200, res->status);
  10179. EXPECT_TRUE(progress_called);
  10180. }
  10181. TEST(UploadProgressTest, PostStringBodyBasic) {
  10182. TestStringBodyUploadProgress(
  10183. [](Server &svr) {
  10184. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10185. res.set_content("received", "text/plain");
  10186. });
  10187. },
  10188. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10189. return cli.Post("/test", body, "text/plain", progress_callback);
  10190. },
  10191. "test data for upload progress");
  10192. }
  10193. TEST(UploadProgressTest, PutStringBodyBasic) {
  10194. TestStringBodyUploadProgress(
  10195. [](Server &svr) {
  10196. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10197. res.set_content("put received", "text/plain");
  10198. });
  10199. },
  10200. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10201. return cli.Put("/test", body, "text/plain", progress_callback);
  10202. },
  10203. "put test data for upload progress");
  10204. }
  10205. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10206. TestStringBodyUploadProgress(
  10207. [](Server &svr) {
  10208. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10209. res.set_content("patch received", "text/plain");
  10210. });
  10211. },
  10212. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10213. return cli.Patch("/test", body, "text/plain", progress_callback);
  10214. },
  10215. "patch test data for upload progress");
  10216. }
  10217. // Helper function for content provider upload progress tests
  10218. template <typename SetupHandler, typename ClientCall>
  10219. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10220. ClientCall &&client_call) {
  10221. Server svr;
  10222. setup_handler(svr);
  10223. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10224. auto se = detail::scope_exit([&] {
  10225. svr.stop();
  10226. t.join();
  10227. });
  10228. svr.wait_until_ready();
  10229. Client cli(HOST, PORT);
  10230. vector<uint64_t> progress_values;
  10231. auto res =
  10232. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10233. progress_values.push_back(current);
  10234. return true;
  10235. });
  10236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10237. EXPECT_EQ(200, res->status);
  10238. EXPECT_FALSE(progress_values.empty());
  10239. }
  10240. TEST(UploadProgressTest, PostContentProviderProgress) {
  10241. TestContentProviderUploadProgress(
  10242. [](Server &svr) {
  10243. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10244. res.set_content("provider received", "text/plain");
  10245. });
  10246. },
  10247. [](Client &cli, UploadProgress progress_callback) {
  10248. return cli.Post(
  10249. "/test", 9,
  10250. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10251. sink.os << "test data";
  10252. return true;
  10253. },
  10254. "text/plain", progress_callback);
  10255. });
  10256. }
  10257. // Helper function for multipart upload progress tests
  10258. template <typename SetupHandler, typename ClientCall>
  10259. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10260. ClientCall &&client_call,
  10261. const string &endpoint) {
  10262. Server svr;
  10263. setup_handler(svr);
  10264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10265. auto se = detail::scope_exit([&] {
  10266. svr.stop();
  10267. t.join();
  10268. });
  10269. svr.wait_until_ready();
  10270. Client cli(HOST, PORT);
  10271. vector<uint64_t> progress_values;
  10272. UploadFormDataItems items = {
  10273. {"field1", "value1", "", ""},
  10274. {"field2", "longer value for progress tracking test", "", ""},
  10275. {"file1", "file content data for upload progress", "test.txt",
  10276. "text/plain"}};
  10277. auto res = client_call(cli, endpoint, items,
  10278. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10279. progress_values.push_back(current);
  10280. return true;
  10281. });
  10282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10283. EXPECT_EQ(200, res->status);
  10284. EXPECT_FALSE(progress_values.empty());
  10285. }
  10286. TEST(UploadProgressTest, PostMultipartProgress) {
  10287. TestMultipartUploadProgress(
  10288. [](Server &svr) {
  10289. svr.Post("/multipart", [](const Request &req, Response &res) {
  10290. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10291. res.set_content("multipart received", "text/plain");
  10292. });
  10293. },
  10294. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10295. UploadProgress progress_callback) {
  10296. return cli.Post(endpoint, items, progress_callback);
  10297. },
  10298. "/multipart");
  10299. }
  10300. // Helper function for basic download progress tests
  10301. template <typename SetupHandler, typename ClientCall>
  10302. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10303. ClientCall &&client_call, const string &endpoint,
  10304. size_t expected_content_size) {
  10305. Server svr;
  10306. setup_handler(svr);
  10307. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10308. auto se = detail::scope_exit([&] {
  10309. svr.stop();
  10310. t.join();
  10311. });
  10312. svr.wait_until_ready();
  10313. Client cli(HOST, PORT);
  10314. vector<uint64_t> progress_values;
  10315. auto res = client_call(cli, endpoint,
  10316. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10317. progress_values.push_back(current);
  10318. return true;
  10319. });
  10320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10321. EXPECT_EQ(200, res->status);
  10322. EXPECT_FALSE(progress_values.empty());
  10323. EXPECT_EQ(expected_content_size, res->body.size());
  10324. }
  10325. TEST(DownloadProgressTest, GetBasic) {
  10326. TestBasicDownloadProgress(
  10327. [](Server &svr) {
  10328. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10329. string content(1000, 'D');
  10330. res.set_content(content, "text/plain");
  10331. });
  10332. },
  10333. [](Client &cli, const string &endpoint,
  10334. DownloadProgress progress_callback) {
  10335. return cli.Get(endpoint, progress_callback);
  10336. },
  10337. "/download", 1000u);
  10338. }
  10339. // Helper function for content receiver download progress tests
  10340. template <typename SetupHandler, typename ClientCall>
  10341. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10342. ClientCall &&client_call,
  10343. const string &endpoint,
  10344. size_t expected_content_size) {
  10345. Server svr;
  10346. setup_handler(svr);
  10347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. });
  10352. svr.wait_until_ready();
  10353. Client cli(HOST, PORT);
  10354. vector<uint64_t> progress_values;
  10355. string received_body;
  10356. auto res = client_call(
  10357. cli, endpoint,
  10358. [&](const char *data, size_t data_length) -> bool {
  10359. received_body.append(data, data_length);
  10360. return true;
  10361. },
  10362. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10363. progress_values.push_back(current);
  10364. return true;
  10365. });
  10366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10367. EXPECT_EQ(200, res->status);
  10368. EXPECT_FALSE(progress_values.empty());
  10369. EXPECT_EQ(expected_content_size, received_body.size());
  10370. EXPECT_TRUE(res->body.empty());
  10371. }
  10372. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10373. TestContentReceiverDownloadProgress(
  10374. [](Server &svr) {
  10375. svr.Get("/download-receiver",
  10376. [](const Request & /*req*/, Response &res) {
  10377. string content(2000, 'R');
  10378. res.set_content(content, "text/plain");
  10379. });
  10380. },
  10381. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10382. DownloadProgress progress_callback) {
  10383. return cli.Get(endpoint, content_receiver, progress_callback);
  10384. },
  10385. "/download-receiver", 2000u);
  10386. }
  10387. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10388. // A provider reaching a pass with nothing to hand over - an empty buffer
  10389. // popped off a queue, say - must not be taken to mean the body is finished.
  10390. // It used to end the loop with the terminating chunk unwritten while the
  10391. // server still considered the response complete, so the peer waited for an
  10392. // end that never arrived.
  10393. Server svr;
  10394. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10395. auto step = std::make_shared<int>(0);
  10396. res.set_chunked_content_provider("text/plain",
  10397. [step](size_t /*offset*/, DataSink &sink) {
  10398. switch ((*step)++) {
  10399. case 0: sink.write("", 0); break;
  10400. case 1: sink.write("hello", 5); break;
  10401. default: sink.done(); break;
  10402. }
  10403. return true;
  10404. });
  10405. });
  10406. auto port = svr.bind_to_any_port(HOST);
  10407. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10408. auto listen_se = detail::scope_exit([&] {
  10409. svr.stop();
  10410. listen_thread.join();
  10411. ASSERT_FALSE(svr.is_running());
  10412. });
  10413. svr.wait_until_ready();
  10414. Client cli(HOST, port);
  10415. // Without the fix the body is never terminated, so bound the wait rather
  10416. // than letting the test hang on the default read timeout.
  10417. cli.set_read_timeout(5, 0);
  10418. auto res = cli.Get("/stream");
  10419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10420. EXPECT_EQ(StatusCode::OK_200, res->status);
  10421. EXPECT_EQ("hello", res->body);
  10422. }
  10423. TEST(StreamingTest, NoContentLengthStreaming) {
  10424. Server svr;
  10425. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10426. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10427. if (offset < 6) {
  10428. sink.os << (offset < 3 ? "a" : "b");
  10429. } else {
  10430. sink.done();
  10431. }
  10432. return true;
  10433. });
  10434. });
  10435. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10436. auto listen_se = detail::scope_exit([&] {
  10437. svr.stop();
  10438. listen_thread.join();
  10439. ASSERT_FALSE(svr.is_running());
  10440. });
  10441. svr.wait_until_ready();
  10442. Client client(HOST, PORT);
  10443. auto get_thread = std::thread([&client]() {
  10444. std::string s;
  10445. auto res =
  10446. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10447. s += std::string(data, len);
  10448. return true;
  10449. });
  10450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10451. EXPECT_EQ(StatusCode::OK_200, res->status);
  10452. EXPECT_EQ("aaabbb", s);
  10453. });
  10454. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10455. // Give GET time to get a few messages.
  10456. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10457. }
  10458. TEST(MountTest, Unmount) {
  10459. Server svr;
  10460. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10461. auto se = detail::scope_exit([&] {
  10462. svr.stop();
  10463. listen_thread.join();
  10464. ASSERT_FALSE(svr.is_running());
  10465. });
  10466. svr.wait_until_ready();
  10467. Client cli("localhost", PORT);
  10468. svr.set_mount_point("/mount2", "./www2");
  10469. auto res = cli.Get("/");
  10470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10471. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10472. res = cli.Get("/mount2/dir/test.html");
  10473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10474. EXPECT_EQ(StatusCode::OK_200, res->status);
  10475. svr.set_mount_point("/", "./www");
  10476. res = cli.Get("/dir/");
  10477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10478. EXPECT_EQ(StatusCode::OK_200, res->status);
  10479. svr.remove_mount_point("/");
  10480. res = cli.Get("/dir/");
  10481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10483. svr.remove_mount_point("/mount2");
  10484. res = cli.Get("/mount2/dir/test.html");
  10485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10487. }
  10488. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10489. Server svr;
  10490. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10491. svr.Get("/api/hello", [](const Request &, Response &res) {
  10492. res.set_content("api", "text/plain");
  10493. });
  10494. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10495. auto se = detail::scope_exit([&] {
  10496. svr.stop();
  10497. listen_thread.join();
  10498. ASSERT_FALSE(svr.is_running());
  10499. });
  10500. svr.wait_until_ready();
  10501. Client cli(HOST, PORT);
  10502. auto res = cli.Get("/dir/test.html");
  10503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10504. EXPECT_EQ(StatusCode::OK_200, res->status);
  10505. res = cli.Get("/api/hello");
  10506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10507. EXPECT_EQ(StatusCode::OK_200, res->status);
  10508. EXPECT_EQ("api", res->body);
  10509. }
  10510. TEST(MountTest, PathSegmentBoundary) {
  10511. Server svr;
  10512. svr.set_mount_point("/mount2", "./www2");
  10513. svr.set_mount_point("/", "./www");
  10514. auto port = svr.bind_to_any_port(HOST);
  10515. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10516. auto se = detail::scope_exit([&] {
  10517. svr.stop();
  10518. listen_thread.join();
  10519. ASSERT_FALSE(svr.is_running());
  10520. });
  10521. svr.wait_until_ready();
  10522. Client cli(HOST, port);
  10523. auto res = cli.Get("/mount2/dir/test.html");
  10524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10525. EXPECT_EQ(StatusCode::OK_200, res->status);
  10526. // "/mount2" must not match part-way through a path segment.
  10527. res = cli.Get("/mount2dir/test.html");
  10528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10530. // A mount point ending in '/' keeps matching every path below it.
  10531. res = cli.Get("/dir/test.html");
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::OK_200, res->status);
  10534. }
  10535. TEST(MountTest, Redicect) {
  10536. Server svr;
  10537. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10538. auto se = detail::scope_exit([&] {
  10539. svr.stop();
  10540. listen_thread.join();
  10541. ASSERT_FALSE(svr.is_running());
  10542. });
  10543. svr.set_mount_point("/", "./www");
  10544. svr.wait_until_ready();
  10545. Client cli("localhost", PORT);
  10546. auto res = cli.Get("/dir/");
  10547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10548. EXPECT_EQ(StatusCode::OK_200, res->status);
  10549. res = cli.Get("/dir");
  10550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10551. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10552. res = cli.Get("/file");
  10553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10554. EXPECT_EQ(StatusCode::OK_200, res->status);
  10555. res = cli.Get("/file/");
  10556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10557. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10558. cli.set_follow_location(true);
  10559. res = cli.Get("/dir");
  10560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10561. EXPECT_EQ(StatusCode::OK_200, res->status);
  10562. }
  10563. TEST(MountTest, MultibytesPathName) {
  10564. Server svr;
  10565. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10566. auto se = detail::scope_exit([&] {
  10567. svr.stop();
  10568. listen_thread.join();
  10569. ASSERT_FALSE(svr.is_running());
  10570. });
  10571. svr.set_mount_point("/", "./www");
  10572. svr.wait_until_ready();
  10573. Client cli("localhost", PORT);
  10574. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(StatusCode::OK_200, res->status);
  10577. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10578. }
  10579. #ifdef _WIN32
  10580. // Issue #2435: mmap::open() must succeed even when another handle holds
  10581. // the file open for writing (e.g. an active log file).
  10582. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10583. const char *path = "mmap_concurrent_writer_test.txt";
  10584. const char *content = "hello";
  10585. {
  10586. std::ofstream f(path, std::ios::binary);
  10587. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10588. }
  10589. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10590. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10591. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10592. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10593. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10594. detail::mmap m(path);
  10595. ASSERT_TRUE(m.is_open());
  10596. EXPECT_EQ(strlen(content), m.size());
  10597. char buf[8];
  10598. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10599. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10600. }
  10601. #endif
  10602. #ifndef _WIN32
  10603. // A directory or a device has no size to serve.
  10604. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10605. const char *path = "./mmap_not_regular_test_dir";
  10606. ASSERT_EQ(0, ::mkdir(path, 0755));
  10607. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10608. for (auto p : {path, "/dev/null"}) {
  10609. detail::mmap m(p);
  10610. EXPECT_FALSE(m.is_open()) << p;
  10611. EXPECT_EQ(0U, m.size()) << p;
  10612. }
  10613. Server svr;
  10614. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10615. res.set_file_content("/dev/null");
  10616. });
  10617. auto port = svr.bind_to_any_port(HOST);
  10618. thread t = thread([&] { svr.listen_after_bind(); });
  10619. auto se = detail::scope_exit([&] {
  10620. svr.stop();
  10621. t.join();
  10622. });
  10623. svr.wait_until_ready();
  10624. auto res = Client(HOST, port).Get("/null");
  10625. ASSERT_TRUE(res);
  10626. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10627. }
  10628. #endif
  10629. #ifdef __linux__
  10630. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10631. TEST(MmapTest, FileIsNotMapped) {
  10632. const char *path = "mmap_not_mapped_test.txt";
  10633. {
  10634. std::ofstream f(path, std::ios::binary);
  10635. f << "hello";
  10636. }
  10637. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10638. detail::mmap m(path);
  10639. ASSERT_TRUE(m.is_open());
  10640. std::ifstream maps("/proc/self/maps");
  10641. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10642. std::istreambuf_iterator<char>());
  10643. EXPECT_EQ(std::string::npos, mappings.find(path));
  10644. }
  10645. #endif
  10646. TEST(KeepAliveTest, ReadTimeout) {
  10647. Server svr;
  10648. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10649. std::this_thread::sleep_for(std::chrono::seconds(2));
  10650. res.set_content("a", "text/plain");
  10651. });
  10652. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10653. res.set_content("b", "text/plain");
  10654. });
  10655. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10656. auto se = detail::scope_exit([&] {
  10657. svr.stop();
  10658. listen_thread.join();
  10659. ASSERT_FALSE(svr.is_running());
  10660. });
  10661. svr.wait_until_ready();
  10662. Client cli("localhost", PORT);
  10663. cli.set_keep_alive(true);
  10664. cli.set_read_timeout(std::chrono::seconds(1));
  10665. auto resa = cli.Get("/a");
  10666. ASSERT_FALSE(resa);
  10667. EXPECT_EQ(Error::Read, resa.error());
  10668. auto resb = cli.Get("/b");
  10669. ASSERT_TRUE(resb);
  10670. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10671. EXPECT_EQ("b", resb->body);
  10672. }
  10673. TEST(KeepAliveTest, MaxCount) {
  10674. size_t keep_alive_max_count = 3;
  10675. Server svr;
  10676. svr.set_keep_alive_max_count(keep_alive_max_count);
  10677. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10678. res.set_content("Hello World!", "text/plain");
  10679. });
  10680. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10681. auto se = detail::scope_exit([&] {
  10682. svr.stop();
  10683. listen_thread.join();
  10684. ASSERT_FALSE(svr.is_running());
  10685. });
  10686. svr.wait_until_ready();
  10687. Client cli(HOST, PORT);
  10688. cli.set_keep_alive(true);
  10689. for (size_t i = 0; i < 5; i++) {
  10690. auto result = cli.Get("/hi");
  10691. ASSERT_TRUE(result);
  10692. EXPECT_EQ(StatusCode::OK_200, result->status);
  10693. if (i == keep_alive_max_count - 1) {
  10694. EXPECT_EQ("close", result->get_header_value("Connection"));
  10695. } else {
  10696. EXPECT_FALSE(result->has_header("Connection"));
  10697. }
  10698. }
  10699. }
  10700. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10701. // can pull the next one into the server's buffer. The server must serve it
  10702. // without waiting for the socket to become readable again. The keep-alive
  10703. // timeout outlasts the client's read timeout, so a request left waiting for it
  10704. // shows up as a missing response.
  10705. static void serve_pipelining_routes(Server &svr,
  10706. const std::function<void(int)> &client) {
  10707. svr.set_keep_alive_timeout(5);
  10708. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10709. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10710. });
  10711. svr.Post("/echo", [](const Request &req, Response &res) {
  10712. res.set_content("echo " + req.body, "text/plain");
  10713. });
  10714. auto port = svr.bind_to_any_port(HOST);
  10715. thread t = thread([&] { svr.listen_after_bind(); });
  10716. auto se = detail::scope_exit([&] {
  10717. svr.stop();
  10718. t.join();
  10719. });
  10720. svr.wait_until_ready();
  10721. client(port);
  10722. }
  10723. static std::string
  10724. send_pipelined_requests(const std::vector<std::string> &parts) {
  10725. Server svr;
  10726. std::string res;
  10727. serve_pipelining_routes(svr, [&](int port) {
  10728. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10729. });
  10730. return res;
  10731. }
  10732. static void expect_in_order(const std::string &res,
  10733. const std::vector<std::string> &bodies) {
  10734. size_t pos = 0;
  10735. for (const auto &body : bodies) {
  10736. pos = res.find(body, pos);
  10737. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10738. pos += body.size();
  10739. }
  10740. }
  10741. TEST(KeepAliveTest, PipelinedRequests) {
  10742. auto res = send_pipelined_requests(
  10743. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10744. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10745. "Content-Length: 4\r\n\r\nbody"
  10746. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10747. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10748. }
  10749. // The second request starts in the server's buffer and ends on the socket.
  10750. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10751. auto res =
  10752. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10753. "GET /hi/2 HTTP/1.1\r\nHo",
  10754. "st: localhost\r\nConnection: close\r\n\r\n"});
  10755. expect_in_order(res, {"hi 1", "hi 2"});
  10756. }
  10757. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10758. // CRLF after a body does not turn into a 400 for the next request.
  10759. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10760. auto res = send_pipelined_requests(
  10761. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10762. "Content-Length: 4\r\n\r\nbody\r\n"
  10763. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10764. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10765. expect_in_order(res, {"echo body", "hi 2"});
  10766. }
  10767. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10768. // must not be served as the next request.
  10769. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10770. auto res = send_pipelined_requests(
  10771. {"INVALID REQUEST LINE\r\n\r\n"
  10772. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10773. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10774. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10775. }
  10776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10777. // Over TLS, the next request is held by the TLS library as already decrypted
  10778. // data rather than on the socket.
  10779. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10781. std::string res;
  10782. serve_pipelining_routes(svr, [&](int port) {
  10783. // One part, so all three requests arrive in one TLS record
  10784. EXPECT_TRUE(send_ssl_request_in_parts(
  10785. 2,
  10786. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10787. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10788. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10789. &res, port));
  10790. });
  10791. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10792. }
  10793. #endif
  10794. TEST(KeepAliveTest, Issue1041) {
  10795. Server svr;
  10796. svr.set_keep_alive_timeout(3);
  10797. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10798. res.set_content("Hello World!", "text/plain");
  10799. });
  10800. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10801. auto se = detail::scope_exit([&] {
  10802. svr.stop();
  10803. listen_thread.join();
  10804. ASSERT_FALSE(svr.is_running());
  10805. });
  10806. svr.wait_until_ready();
  10807. Client cli(HOST, PORT);
  10808. cli.set_keep_alive(true);
  10809. auto result = cli.Get("/hi");
  10810. ASSERT_TRUE(result);
  10811. EXPECT_EQ(StatusCode::OK_200, result->status);
  10812. std::this_thread::sleep_for(std::chrono::seconds(5));
  10813. result = cli.Get("/hi");
  10814. ASSERT_TRUE(result);
  10815. EXPECT_EQ(StatusCode::OK_200, result->status);
  10816. }
  10817. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10818. Server svr;
  10819. svr.set_keep_alive_max_count(0);
  10820. std::set<int> remote_ports;
  10821. svr.Get("/hi", [&](const Request &req, Response &res) {
  10822. remote_ports.insert(req.remote_port);
  10823. res.set_content("hi", "text/plain");
  10824. });
  10825. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10826. auto se = detail::scope_exit([&] {
  10827. svr.stop();
  10828. listen_thread.join();
  10829. ASSERT_FALSE(svr.is_running());
  10830. });
  10831. svr.wait_until_ready();
  10832. Client cli(HOST, PORT);
  10833. cli.set_keep_alive(true);
  10834. for (int i = 0; i < 3; i++) {
  10835. auto res = cli.Get("/hi");
  10836. ASSERT_TRUE(res);
  10837. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10838. }
  10839. // All three over one connection
  10840. EXPECT_EQ(1u, remote_ports.size());
  10841. }
  10842. TEST(KeepAliveTest, Issue1959) {
  10843. Server svr;
  10844. svr.set_keep_alive_timeout(5);
  10845. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10846. res.set_content("a", "text/plain");
  10847. });
  10848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10849. auto se = detail::scope_exit([&] {
  10850. if (!svr.is_running()) return;
  10851. svr.stop();
  10852. listen_thread.join();
  10853. ASSERT_FALSE(svr.is_running());
  10854. });
  10855. svr.wait_until_ready();
  10856. Client cli("localhost", PORT);
  10857. cli.set_keep_alive(true);
  10858. using namespace std::chrono;
  10859. auto start = steady_clock::now();
  10860. cli.Get("/a");
  10861. svr.stop();
  10862. listen_thread.join();
  10863. auto end = steady_clock::now();
  10864. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10865. EXPECT_LT(elapsed, 5000);
  10866. }
  10867. #ifdef CPPHTTPLIB_SSL_ENABLED
  10868. TEST(KeepAliveTest, SSLClientReconnection) {
  10869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10870. ASSERT_TRUE(svr.is_valid());
  10871. svr.set_keep_alive_timeout(1);
  10872. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10873. res.set_content("Hello World!", "text/plain");
  10874. });
  10875. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10876. auto se = detail::scope_exit([&] {
  10877. svr.stop();
  10878. listen_thread.join();
  10879. ASSERT_FALSE(svr.is_running());
  10880. });
  10881. svr.wait_until_ready();
  10882. SSLClient cli(HOST, PORT);
  10883. cli.enable_server_certificate_verification(false);
  10884. cli.set_keep_alive(true);
  10885. auto result = cli.Get("/hi");
  10886. ASSERT_TRUE(result);
  10887. EXPECT_EQ(StatusCode::OK_200, result->status);
  10888. result = cli.Get("/hi");
  10889. ASSERT_TRUE(result);
  10890. EXPECT_EQ(StatusCode::OK_200, result->status);
  10891. std::this_thread::sleep_for(std::chrono::seconds(2));
  10892. // Recoonect
  10893. result = cli.Get("/hi");
  10894. ASSERT_TRUE(result);
  10895. EXPECT_EQ(StatusCode::OK_200, result->status);
  10896. result = cli.Get("/hi");
  10897. ASSERT_TRUE(result);
  10898. EXPECT_EQ(StatusCode::OK_200, result->status);
  10899. }
  10900. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10902. ASSERT_TRUE(svr.is_valid());
  10903. svr.set_keep_alive_timeout(1);
  10904. std::string content = "reconnect";
  10905. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10906. res.set_content("Hello World!", "text/plain");
  10907. });
  10908. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10909. auto se = detail::scope_exit([&] {
  10910. svr.stop();
  10911. listen_thread.join();
  10912. ASSERT_FALSE(svr.is_running());
  10913. });
  10914. svr.wait_until_ready();
  10915. SSLClient cli(HOST, PORT);
  10916. cli.enable_server_certificate_verification(false);
  10917. cli.set_keep_alive(true);
  10918. auto result = cli.Post(
  10919. "/hi", content.size(),
  10920. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10921. sink.write(content.c_str(), content.size());
  10922. return true;
  10923. },
  10924. "text/plain");
  10925. ASSERT_TRUE(result);
  10926. EXPECT_EQ(200, result->status);
  10927. std::this_thread::sleep_for(std::chrono::seconds(2));
  10928. // Recoonect
  10929. result = cli.Post(
  10930. "/hi", content.size(),
  10931. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10932. sink.write(content.c_str(), content.size());
  10933. return true;
  10934. },
  10935. "text/plain");
  10936. ASSERT_TRUE(result);
  10937. EXPECT_EQ(200, result->status);
  10938. result = cli.Post(
  10939. "/hi", content.size(),
  10940. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10941. sink.write(content.c_str(), content.size());
  10942. return true;
  10943. },
  10944. "text/plain");
  10945. ASSERT_TRUE(result);
  10946. EXPECT_EQ(200, result->status);
  10947. }
  10948. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10949. using namespace httplib::tls;
  10950. {
  10951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10952. ASSERT_TRUE(svr.is_valid());
  10953. svr.Get("/sni", [&](const Request &req, Response &res) {
  10954. std::string expected = req.sni();
  10955. EXPECT_EQ(expected, req.get_param_value("expected"));
  10956. res.set_content("ok", "text/plain");
  10957. });
  10958. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10959. auto se = detail::scope_exit([&] {
  10960. svr.stop();
  10961. listen_thread.join();
  10962. ASSERT_FALSE(svr.is_running());
  10963. });
  10964. svr.wait_until_ready();
  10965. {
  10966. SSLClient cli("localhost", PORT);
  10967. cli.enable_server_certificate_verification(false);
  10968. auto res = cli.Get("/sni?expected=localhost");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. }
  10971. {
  10972. SSLClient cli("::1", PORT);
  10973. cli.enable_server_certificate_verification(false);
  10974. auto res = cli.Get("/sni?expected=");
  10975. // NOTE: This may fail if the server is listening on IPv4 only
  10976. // (e.g., when localhost resolves to 127.0.0.1 only)
  10977. if (res) {
  10978. EXPECT_EQ(StatusCode::OK_200, res->status);
  10979. } else {
  10980. EXPECT_EQ(Error::Connection, res.error());
  10981. }
  10982. }
  10983. }
  10984. }
  10985. #endif
  10986. TEST(ClientProblemDetectionTest, ContentProvider) {
  10987. Server svr;
  10988. size_t content_length = 1024 * 1024;
  10989. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10990. res.set_content_provider(
  10991. content_length, "text/plain",
  10992. [&](size_t offset, size_t length, DataSink &sink) {
  10993. auto out_len = std::min(length, static_cast<size_t>(1024));
  10994. std::string out(out_len, '@');
  10995. sink.write(out.data(), out_len);
  10996. return offset < 4096;
  10997. },
  10998. [](bool success) { ASSERT_FALSE(success); });
  10999. });
  11000. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11001. res.set_content_provider(
  11002. 0, "text/plain",
  11003. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11004. EXPECT_TRUE(false);
  11005. return true;
  11006. },
  11007. [](bool success) { ASSERT_FALSE(success); });
  11008. });
  11009. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11010. auto se = detail::scope_exit([&] {
  11011. svr.stop();
  11012. listen_thread.join();
  11013. ASSERT_FALSE(svr.is_running());
  11014. });
  11015. svr.wait_until_ready();
  11016. Client cli("localhost", PORT);
  11017. {
  11018. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11019. size_t /*data_length*/) { return false; });
  11020. ASSERT_FALSE(res);
  11021. }
  11022. {
  11023. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11024. size_t /*data_length*/) { return false; });
  11025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11026. }
  11027. }
  11028. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11029. // A provider that reports success without writing anything and without
  11030. // calling done() used to be handed the same offset and length again on every
  11031. // pass, so it spun for as long as the peer stayed connected.
  11032. Server svr;
  11033. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11034. res.set_content("ok", "text/plain");
  11035. });
  11036. auto port = svr.bind_to_any_port(HOST);
  11037. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11038. auto se = detail::scope_exit([&] {
  11039. svr.stop();
  11040. listen_thread.join();
  11041. ASSERT_FALSE(svr.is_running());
  11042. });
  11043. svr.wait_until_ready();
  11044. std::atomic<int> call_count{0};
  11045. Client cli(HOST, port);
  11046. auto res = cli.Post(
  11047. "/", 1024,
  11048. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11049. // Give up after enough passes to show the spin, so that losing the
  11050. // check below fails this test instead of hanging it.
  11051. return ++call_count < 100;
  11052. },
  11053. "text/plain");
  11054. ASSERT_FALSE(res);
  11055. EXPECT_EQ(Error::Write, res.error());
  11056. EXPECT_EQ(1, call_count.load());
  11057. }
  11058. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11059. // A writer only has to assign `write`. The other three used to be left as
  11060. // empty std::functions, so a provider calling one threw
  11061. // std::bad_function_call out of the thread running it and took the whole
  11062. // process down.
  11063. DataSink sink;
  11064. std::string written;
  11065. sink.write = [&](const char *data, size_t data_len) {
  11066. written.append(data, data_len);
  11067. return true;
  11068. };
  11069. EXPECT_TRUE(sink.is_writable());
  11070. sink.done();
  11071. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11072. EXPECT_TRUE(written.empty());
  11073. }
  11074. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11075. // A sink that cannot carry trailers still has to finish.
  11076. DataSink sink;
  11077. auto done_count = 0;
  11078. sink.done = [&]() { done_count++; };
  11079. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11080. EXPECT_EQ(1, done_count);
  11081. }
  11082. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11083. Server svr;
  11084. const std::string body(4096, 'x');
  11085. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11086. res.set_content_provider(body.size(), "text/plain",
  11087. [&](size_t offset, size_t length, DataSink &sink) {
  11088. sink.write(body.data() + offset, length);
  11089. sink.done();
  11090. return true;
  11091. });
  11092. });
  11093. auto port = svr.bind_to_any_port(HOST);
  11094. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11095. auto se = detail::scope_exit([&] {
  11096. svr.stop();
  11097. listen_thread.join();
  11098. ASSERT_FALSE(svr.is_running());
  11099. });
  11100. svr.wait_until_ready();
  11101. Client cli(HOST, port);
  11102. auto res = cli.Get("/");
  11103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11104. EXPECT_EQ(StatusCode::OK_200, res->status);
  11105. EXPECT_EQ(body, res->body);
  11106. }
  11107. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11108. Server svr;
  11109. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11110. res.set_content_provider(
  11111. 1024, "text/plain",
  11112. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11113. sink.write("hello", 5);
  11114. sink.done(); // short of the 1024 bytes the response promised
  11115. return true;
  11116. });
  11117. });
  11118. auto port = svr.bind_to_any_port(HOST);
  11119. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11120. auto se = detail::scope_exit([&] {
  11121. svr.stop();
  11122. listen_thread.join();
  11123. ASSERT_FALSE(svr.is_running());
  11124. });
  11125. svr.wait_until_ready();
  11126. Client cli(HOST, port);
  11127. cli.set_read_timeout(5, 0);
  11128. // The response is short of its Content-Length, so the client cannot read a
  11129. // complete body. What matters is that this returns at all: a no-op done()
  11130. // would leave the writer looping over a provider that never makes progress.
  11131. auto res = cli.Get("/");
  11132. EXPECT_FALSE(res);
  11133. }
  11134. // Read as the next response by a peer that sees it after a framed body.
  11135. static const std::string smuggled_response =
  11136. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11137. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11138. Server svr;
  11139. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11140. res.set_content_provider(
  11141. 5, "text/plain",
  11142. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11143. auto data = "AAAAA" + smuggled_response;
  11144. sink.write(data.data(), data.size());
  11145. return true;
  11146. });
  11147. });
  11148. thread t = thread([&] { svr.listen(HOST, PORT); });
  11149. auto se = detail::scope_exit([&] {
  11150. svr.stop();
  11151. t.join();
  11152. ASSERT_FALSE(svr.is_running());
  11153. });
  11154. svr.wait_until_ready();
  11155. std::string resp;
  11156. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11157. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11158. resp.clear();
  11159. ASSERT_TRUE(send_request(
  11160. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11161. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11162. }
  11163. TEST(NoContentTest, BodyIsNotSent) {
  11164. Server svr;
  11165. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11166. res.status = StatusCode::NoContent_204;
  11167. res.set_content(smuggled_response, "text/plain");
  11168. });
  11169. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11170. res.status = StatusCode::NotModified_304;
  11171. res.set_chunked_content_provider(
  11172. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11173. sink.write(smuggled_response.data(), smuggled_response.size());
  11174. sink.done();
  11175. return true;
  11176. });
  11177. });
  11178. thread t = thread([&] { svr.listen(HOST, PORT); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. t.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.wait_until_ready();
  11185. for (auto path : {"/204", "/304"}) {
  11186. std::string resp;
  11187. ASSERT_TRUE(send_request(
  11188. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11189. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11190. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11191. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11192. }
  11193. }
  11194. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11195. Server svr;
  11196. std::atomic<bool> smuggled(false);
  11197. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11198. res.set_content("ok", "text/plain");
  11199. });
  11200. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11201. smuggled = true;
  11202. });
  11203. auto port = svr.bind_to_any_port(HOST);
  11204. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11205. auto se = detail::scope_exit([&] {
  11206. svr.stop();
  11207. listen_thread.join();
  11208. ASSERT_FALSE(svr.is_running());
  11209. });
  11210. svr.wait_until_ready();
  11211. // What follows the body would be read as the next request.
  11212. Client cli(HOST, port);
  11213. auto res = cli.Post(
  11214. "/", 5,
  11215. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11216. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11217. sink.write(data.data(), data.size());
  11218. return true;
  11219. },
  11220. "text/plain");
  11221. ASSERT_FALSE(res);
  11222. EXPECT_EQ(Error::Write, res.error());
  11223. EXPECT_FALSE(smuggled);
  11224. }
  11225. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11226. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11227. // The compressed path builds the whole body before connecting, so this
  11228. // fails client-side and never reaches a server.
  11229. Client cli(HOST, PORT);
  11230. cli.set_compress(true);
  11231. auto res = cli.Post(
  11232. "/", 1024,
  11233. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11234. sink.write("hello", 5);
  11235. sink.done(); // short of the 1024 bytes the request announced
  11236. return true;
  11237. },
  11238. "text/plain");
  11239. ASSERT_FALSE(res);
  11240. EXPECT_EQ(Error::Write, res.error());
  11241. }
  11242. #endif
  11243. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11244. Server svr;
  11245. svr.set_error_handler([](Request const &, Response &res) -> void {
  11246. res.set_chunked_content_provider(
  11247. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11248. sink.os << "hello";
  11249. sink.os << "world";
  11250. sink.done();
  11251. return true;
  11252. });
  11253. });
  11254. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. listen_thread.join();
  11258. ASSERT_FALSE(svr.is_running());
  11259. });
  11260. svr.wait_until_ready();
  11261. Client cli("localhost", PORT);
  11262. auto res = cli.Get("/");
  11263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11265. EXPECT_EQ("helloworld", res->body);
  11266. }
  11267. // A body set after a content provider must replace it, not be sent through it.
  11268. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11269. Server svr;
  11270. svr.set_mount_point("/", "./www");
  11271. svr.set_file_request_handler([](const Request &req, Response &res) {
  11272. if (req.path == "/dir/test.html") {
  11273. res.status = StatusCode::Forbidden_403;
  11274. res.set_content(std::string(5000, 'D'), "text/plain");
  11275. } else if (req.path == "/file") {
  11276. res.status = StatusCode::Forbidden_403;
  11277. res.body = "Denied";
  11278. }
  11279. });
  11280. auto port = svr.bind_to_any_port(HOST);
  11281. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11282. auto se = detail::scope_exit([&] {
  11283. svr.stop();
  11284. t.join();
  11285. ASSERT_FALSE(svr.is_running());
  11286. });
  11287. svr.wait_until_ready();
  11288. Client cli(HOST, port);
  11289. {
  11290. auto res = cli.Get("/dir/test.html");
  11291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11292. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11293. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11294. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11295. }
  11296. {
  11297. auto res = cli.Get("/file");
  11298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11299. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11300. EXPECT_EQ("Denied", res->body);
  11301. }
  11302. {
  11303. auto res = cli.Get("/dir/index.html");
  11304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11305. EXPECT_EQ(StatusCode::OK_200, res->status);
  11306. EXPECT_EQ(0U, res->body.find("<html>"));
  11307. }
  11308. }
  11309. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11310. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11311. Server svr;
  11312. std::vector<bool> released;
  11313. std::mutex released_mutex;
  11314. auto releaser = [&](bool success) {
  11315. std::lock_guard<std::mutex> guard(released_mutex);
  11316. released.push_back(success);
  11317. };
  11318. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11319. return sink.write(&"hello"[offset], length);
  11320. };
  11321. svr.Get("/sized", [&](const Request &, Response &res) {
  11322. res.status = StatusCode::NotFound_404;
  11323. res.set_content_provider(5, "text/plain", provider, releaser);
  11324. });
  11325. svr.Get("/chunked", [&](const Request &, Response &res) {
  11326. res.status = StatusCode::ServiceUnavailable_503;
  11327. res.set_chunked_content_provider(
  11328. "text/plain",
  11329. [](size_t, DataSink &sink) {
  11330. sink.os << "chunk";
  11331. sink.done();
  11332. return true;
  11333. },
  11334. releaser);
  11335. });
  11336. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11337. res.set_content_provider(5, "text/plain", provider, releaser);
  11338. throw std::runtime_error("after the provider");
  11339. });
  11340. svr.set_error_handler([](const Request &req, Response &res) {
  11341. // Leave the exception handler's content to it.
  11342. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11343. res.set_content(std::string(1000, 'E'), "text/html");
  11344. return Server::HandlerResponse::Handled;
  11345. });
  11346. svr.set_exception_handler(
  11347. [](const Request &, Response &res, std::exception_ptr) {
  11348. res.status = StatusCode::InternalServerError_500;
  11349. res.set_content(std::string(1000, 'X'), "text/html");
  11350. });
  11351. auto port = svr.bind_to_any_port(HOST);
  11352. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. t.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli(HOST, port);
  11360. {
  11361. auto res = cli.Get("/sized");
  11362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11364. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11365. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11366. }
  11367. {
  11368. auto res = cli.Get("/chunked");
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11371. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11372. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11373. }
  11374. {
  11375. auto res = cli.Get("/throw");
  11376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11377. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11378. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11379. }
  11380. std::lock_guard<std::mutex> guard(released_mutex);
  11381. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11382. }
  11383. #endif
  11384. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11385. Server svr;
  11386. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11387. return sink.write(&"abc"[offset], length);
  11388. };
  11389. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11390. res.set_file_content("./www/dir/test.html");
  11391. res.set_content("body", "text/plain");
  11392. });
  11393. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11394. res.set_content(std::string(100, 'B'), "text/plain");
  11395. res.set_file_content("./www/dir/test.html");
  11396. });
  11397. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11398. res.set_content(std::string(100, 'B'), "text/plain");
  11399. res.set_content_provider(3, "text/x-provider", abc);
  11400. });
  11401. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11402. res.set_content_provider(3, "text/x-provider", abc);
  11403. res.set_content(std::string(100, 'B'), "text/plain");
  11404. });
  11405. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11406. res.set_content_provider(3, "text/x-provider", abc);
  11407. res.set_file_content("./www/dir/test.html", "text/x-file");
  11408. });
  11409. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11410. res.set_file_content("./www/dir/test.html");
  11411. res.set_header("Content-Type", "text/x-handler");
  11412. });
  11413. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11414. res.set_content_provider(3, "text/plain", abc);
  11415. res.body = "direct";
  11416. });
  11417. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11418. res.set_file_content("./www/dir/test.html");
  11419. res.body = "direct";
  11420. });
  11421. auto port = svr.bind_to_any_port(HOST);
  11422. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11423. auto se = detail::scope_exit([&] {
  11424. svr.stop();
  11425. t.join();
  11426. ASSERT_FALSE(svr.is_running());
  11427. });
  11428. svr.wait_until_ready();
  11429. Client cli(HOST, port);
  11430. auto expect_body = [&](const char *path, const std::string &body,
  11431. const std::string &type) {
  11432. // Uncompressed, so Content-Length can be compared with the body.
  11433. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11434. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11435. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11436. EXPECT_EQ(body, res->body) << path;
  11437. EXPECT_EQ(std::to_string(body.size()),
  11438. res->get_header_value("Content-Length"))
  11439. << path;
  11440. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11441. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11442. };
  11443. expect_body("/file-then-body", "body", "text/plain");
  11444. expect_body("/body-then-file", "test.html", "text/html");
  11445. expect_body("/body-then-provider", "abc", "text/x-provider");
  11446. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11447. expect_body("/provider-then-file", "test.html", "text/x-file");
  11448. expect_body("/file-then-header", "test.html", "text/x-handler");
  11449. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11450. expect_body("/file-then-direct-body", "direct", "text/plain");
  11451. // Ranges are checked against the body, not the dropped provider.
  11452. {
  11453. auto res = cli.Get("/provider-then-direct-body",
  11454. Headers{{make_range_header({{1, 2}})}});
  11455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11457. EXPECT_EQ("ir", res->body);
  11458. }
  11459. {
  11460. auto res = cli.Get("/file-then-direct-body",
  11461. Headers{{make_range_header({{7, 8}})}});
  11462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11463. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11464. }
  11465. }
  11466. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11467. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11468. const char *path = "./truncated_while_served.txt";
  11469. const size_t size = 32 * 1024 * 1024;
  11470. {
  11471. std::ofstream f(path, std::ios::binary);
  11472. f << std::string(size, 'x');
  11473. }
  11474. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11475. // Over TLS, where the bytes are encrypted in this process rather than
  11476. // copied by send().
  11477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11478. svr.Get("/file", [&](const Request &, Response &res) {
  11479. res.set_file_content(path, "text/plain");
  11480. });
  11481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11482. auto se = detail::scope_exit([&] {
  11483. svr.stop();
  11484. thread.join();
  11485. ASSERT_FALSE(svr.is_running());
  11486. });
  11487. svr.wait_until_ready();
  11488. // The file shrinks once the first bytes are in, as a rewrite in place
  11489. // would, and reading the mapping past its new end used to raise SIGBUS.
  11490. SSLClient cli(HOST, PORT);
  11491. cli.enable_server_certificate_verification(false);
  11492. size_t received = 0;
  11493. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11494. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11495. received += len;
  11496. return true;
  11497. });
  11498. EXPECT_FALSE(res);
  11499. EXPECT_LT(received, size);
  11500. }
  11501. #endif
  11502. // Forward declaration (see the base64_encode note).
  11503. namespace httplib {
  11504. namespace detail {
  11505. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11506. const std::string &content_type,
  11507. EncodingType encoding);
  11508. } // namespace detail
  11509. } // namespace httplib
  11510. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11511. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11512. ASSERT_TRUE(mm->is_open());
  11513. Response res;
  11514. detail::set_file_content_provider(res, mm, "text/html",
  11515. detail::EncodingType::None);
  11516. std::string out;
  11517. DataSink sink;
  11518. sink.write = [&](const char *d, size_t l) {
  11519. out.append(d, l);
  11520. return true;
  11521. };
  11522. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11523. EXPECT_EQ("test.html", out);
  11524. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11525. EXPECT_EQ("test.html", out);
  11526. }
  11527. TEST(LongPollingTest, ClientCloseDetection) {
  11528. Server svr;
  11529. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11530. res.set_chunked_content_provider(
  11531. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11532. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11533. sink.os << "hello";
  11534. auto count = 10;
  11535. while (count > 0 && sink.is_writable()) {
  11536. this_thread::sleep_for(chrono::milliseconds(10));
  11537. count--;
  11538. }
  11539. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11540. return true;
  11541. });
  11542. });
  11543. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11544. auto se = detail::scope_exit([&] {
  11545. svr.stop();
  11546. listen_thread.join();
  11547. ASSERT_FALSE(svr.is_running());
  11548. });
  11549. svr.wait_until_ready();
  11550. Client cli("localhost", PORT);
  11551. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11552. EXPECT_EQ("hello", string(data, data_length));
  11553. return false; // close the socket immediately.
  11554. });
  11555. ASSERT_FALSE(res);
  11556. }
  11557. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11558. Server svr;
  11559. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11560. res.set_chunked_content_provider(
  11561. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11562. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11563. sink.os << "hello";
  11564. EXPECT_TRUE(sink.os.good());
  11565. // Wait for the client to close the connection
  11566. auto count = 10;
  11567. while (count > 0 && sink.is_writable()) {
  11568. this_thread::sleep_for(chrono::milliseconds(10));
  11569. count--;
  11570. }
  11571. // After client disconnect, write repeatedly until the socket
  11572. // write actually fails (small writes may be absorbed by the
  11573. // kernel buffer)
  11574. std::string chunk(1024, 'x');
  11575. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11576. sink.os << chunk;
  11577. }
  11578. EXPECT_TRUE(sink.os.fail());
  11579. return true;
  11580. });
  11581. });
  11582. auto port = svr.bind_to_any_port("localhost");
  11583. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11584. auto se = detail::scope_exit([&] {
  11585. svr.stop();
  11586. listen_thread.join();
  11587. ASSERT_FALSE(svr.is_running());
  11588. });
  11589. svr.wait_until_ready();
  11590. Client cli("localhost", port);
  11591. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11592. EXPECT_EQ("hello", string(data, data_length));
  11593. return false; // close the socket immediately.
  11594. });
  11595. ASSERT_FALSE(res);
  11596. }
  11597. TEST(GetWithParametersTest, GetWithParameters) {
  11598. Server svr;
  11599. svr.Get("/", [&](const Request &req, Response &) {
  11600. EXPECT_EQ("world", req.get_param_value("hello"));
  11601. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11602. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11603. });
  11604. svr.Get("/params", [&](const Request &req, Response &) {
  11605. EXPECT_EQ("world", req.get_param_value("hello"));
  11606. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11607. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11608. });
  11609. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11610. EXPECT_EQ("resource-id", req.matches[1]);
  11611. EXPECT_EQ("foo", req.get_param_value("param1"));
  11612. EXPECT_EQ("bar", req.get_param_value("param2"));
  11613. });
  11614. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11615. EXPECT_EQ("user-id", req.path_params.at("id"));
  11616. EXPECT_EQ("foo", req.get_param_value("param1"));
  11617. EXPECT_EQ("bar", req.get_param_value("param2"));
  11618. });
  11619. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11620. auto se = detail::scope_exit([&] {
  11621. svr.stop();
  11622. listen_thread.join();
  11623. ASSERT_FALSE(svr.is_running());
  11624. });
  11625. svr.wait_until_ready();
  11626. {
  11627. Client cli(HOST, PORT);
  11628. Params params;
  11629. params.emplace("hello", "world");
  11630. params.emplace("hello2", "world2");
  11631. params.emplace("hello3", "world3");
  11632. auto res = cli.Get("/", params, Headers{});
  11633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11634. EXPECT_EQ(StatusCode::OK_200, res->status);
  11635. }
  11636. {
  11637. Client cli(HOST, PORT);
  11638. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11640. EXPECT_EQ(StatusCode::OK_200, res->status);
  11641. }
  11642. {
  11643. Client cli(HOST, PORT);
  11644. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11646. EXPECT_EQ(StatusCode::OK_200, res->status);
  11647. }
  11648. {
  11649. Client cli(HOST, PORT);
  11650. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11652. EXPECT_EQ(StatusCode::OK_200, res->status);
  11653. }
  11654. }
  11655. TEST(GetWithParametersTest, GetWithParameters2) {
  11656. Server svr;
  11657. svr.Get("/", [&](const Request &req, Response &res) {
  11658. auto text = req.get_param_value("hello");
  11659. res.set_content(text, "text/plain");
  11660. });
  11661. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11662. auto se = detail::scope_exit([&] {
  11663. svr.stop();
  11664. listen_thread.join();
  11665. ASSERT_FALSE(svr.is_running());
  11666. });
  11667. svr.wait_until_ready();
  11668. Client cli("localhost", PORT);
  11669. Params params;
  11670. params.emplace("hello", "world");
  11671. std::string body;
  11672. auto res = cli.Get("/", params, Headers{},
  11673. [&](const char *data, size_t data_length) {
  11674. body.append(data, data_length);
  11675. return true;
  11676. });
  11677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11678. EXPECT_EQ(StatusCode::OK_200, res->status);
  11679. EXPECT_EQ("world", body);
  11680. }
  11681. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11682. Server svr;
  11683. svr.Get("/search", [&](const Request &req, Response &res) {
  11684. auto q = req.get_param_value("q");
  11685. res.set_content(q, "text/plain");
  11686. });
  11687. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11688. auto se = detail::scope_exit([&] {
  11689. svr.stop();
  11690. listen_thread.join();
  11691. ASSERT_FALSE(svr.is_running());
  11692. });
  11693. svr.wait_until_ready();
  11694. Client cli("localhost", PORT);
  11695. // Verify that Get(path, params) works without requiring Headers argument
  11696. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11698. EXPECT_EQ(StatusCode::OK_200, res->status);
  11699. EXPECT_EQ("cpp-httplib", res->body);
  11700. }
  11701. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11702. auto host = "httpbingo.org";
  11703. auto path = std::string{"/range/32"};
  11704. #ifdef CPPHTTPLIB_SSL_ENABLED
  11705. SSLClient cli(host);
  11706. #else
  11707. Client cli(host);
  11708. #endif
  11709. cli.set_default_headers({make_range_header({{1, 10}})});
  11710. cli.set_connection_timeout(5);
  11711. {
  11712. auto res = cli.Get(path);
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. EXPECT_EQ("bcdefghijk", res->body);
  11715. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11716. }
  11717. {
  11718. auto res = cli.Get(path);
  11719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11720. EXPECT_EQ("bcdefghijk", res->body);
  11721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11722. }
  11723. }
  11724. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11725. Server svr;
  11726. svr.set_default_headers({{"Hello", "World"}});
  11727. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11728. res.set_content("ok", "text/plain");
  11729. });
  11730. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11731. auto se = detail::scope_exit([&] {
  11732. svr.stop();
  11733. listen_thread.join();
  11734. ASSERT_FALSE(svr.is_running());
  11735. });
  11736. svr.wait_until_ready();
  11737. Client cli("localhost", PORT);
  11738. auto res = cli.Get("/");
  11739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11740. EXPECT_EQ(StatusCode::OK_200, res->status);
  11741. EXPECT_EQ("ok", res->body);
  11742. EXPECT_EQ("World", res->get_header_value("Hello"));
  11743. }
  11744. #ifdef CPPHTTPLIB_SSL_ENABLED
  11745. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11747. ASSERT_TRUE(svr.is_valid());
  11748. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11749. std::this_thread::sleep_for(std::chrono::seconds(2));
  11750. res.set_content("a", "text/plain");
  11751. });
  11752. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11753. res.set_content("b", "text/plain");
  11754. });
  11755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11756. auto se = detail::scope_exit([&] {
  11757. svr.stop();
  11758. listen_thread.join();
  11759. ASSERT_FALSE(svr.is_running());
  11760. });
  11761. svr.wait_until_ready();
  11762. SSLClient cli("localhost", PORT);
  11763. cli.enable_server_certificate_verification(false);
  11764. cli.set_keep_alive(true);
  11765. cli.set_read_timeout(std::chrono::seconds(1));
  11766. auto resa = cli.Get("/a");
  11767. ASSERT_TRUE(!resa);
  11768. EXPECT_EQ(Error::Read, resa.error());
  11769. auto resb = cli.Get("/b");
  11770. ASSERT_TRUE(resb);
  11771. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11772. EXPECT_EQ("b", resb->body);
  11773. }
  11774. // Closing an idle keep-alive connection sends close_notify and returns. The
  11775. // server must not wait for the client's close_notify: an idle client never
  11776. // sends one, so the worker would be held until the read timeout expires, and
  11777. // stop() would wait for it.
  11778. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11780. ASSERT_TRUE(svr.is_valid());
  11781. svr.set_keep_alive_timeout(1);
  11782. svr.set_read_timeout(10, 0);
  11783. svr.Get("/", [](const Request &, Response &res) {
  11784. res.set_content("ok", "text/plain");
  11785. });
  11786. auto port = svr.bind_to_any_port(HOST);
  11787. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11788. auto se = detail::scope_exit([&] {
  11789. if (listen_thread.joinable()) {
  11790. svr.stop();
  11791. listen_thread.join();
  11792. }
  11793. });
  11794. svr.wait_until_ready();
  11795. SSLClient cli(HOST, port);
  11796. cli.enable_server_certificate_verification(false);
  11797. cli.set_keep_alive(true);
  11798. auto res = cli.Get("/");
  11799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11800. EXPECT_EQ(StatusCode::OK_200, res->status);
  11801. // Stay idle past the keep-alive timeout so the server closes the connection.
  11802. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11803. auto start = std::chrono::steady_clock::now();
  11804. svr.stop();
  11805. listen_thread.join();
  11806. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11807. std::chrono::steady_clock::now() - start)
  11808. .count();
  11809. EXPECT_LT(elapsed, 3000);
  11810. }
  11811. #endif
  11812. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11813. protected:
  11814. ServerTestWithAI_PASSIVE()
  11815. : cli_(HOST, PORT)
  11816. #ifdef CPPHTTPLIB_SSL_ENABLED
  11817. ,
  11818. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11819. #endif
  11820. {
  11821. #ifdef CPPHTTPLIB_SSL_ENABLED
  11822. cli_.enable_server_certificate_verification(false);
  11823. #endif
  11824. }
  11825. virtual void SetUp() {
  11826. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11827. res.set_content("Hello World!", "text/plain");
  11828. });
  11829. t_ = thread(
  11830. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11831. svr_.wait_until_ready();
  11832. }
  11833. virtual void TearDown() {
  11834. svr_.stop();
  11835. t_.join();
  11836. }
  11837. #ifdef CPPHTTPLIB_SSL_ENABLED
  11838. SSLClient cli_;
  11839. SSLServer svr_;
  11840. #else
  11841. Client cli_;
  11842. Server svr_;
  11843. #endif
  11844. thread t_;
  11845. };
  11846. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11847. auto res = cli_.Get("/hi");
  11848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11849. EXPECT_EQ(StatusCode::OK_200, res->status);
  11850. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11851. EXPECT_EQ("Hello World!", res->body);
  11852. }
  11853. class ServerUpDownTest : public ::testing::Test {
  11854. protected:
  11855. ServerUpDownTest() : cli_(HOST, PORT) {}
  11856. virtual void SetUp() {
  11857. t_ = thread([&]() {
  11858. svr_.bind_to_any_port(HOST);
  11859. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11860. ASSERT_TRUE(svr_.listen_after_bind());
  11861. });
  11862. svr_.wait_until_ready();
  11863. }
  11864. virtual void TearDown() {
  11865. svr_.stop();
  11866. t_.join();
  11867. }
  11868. Client cli_;
  11869. Server svr_;
  11870. thread t_;
  11871. };
  11872. TEST_F(ServerUpDownTest, QuickStartStop) {
  11873. // Should not crash, especially when run with
  11874. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11875. }
  11876. class PayloadMaxLengthTest : public ::testing::Test {
  11877. protected:
  11878. PayloadMaxLengthTest()
  11879. : cli_(HOST, PORT)
  11880. #ifdef CPPHTTPLIB_SSL_ENABLED
  11881. ,
  11882. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11883. #endif
  11884. {
  11885. #ifdef CPPHTTPLIB_SSL_ENABLED
  11886. cli_.enable_server_certificate_verification(false);
  11887. #endif
  11888. }
  11889. virtual void SetUp() {
  11890. svr_.set_payload_max_length(8);
  11891. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11892. res.set_content("test", "text/plain");
  11893. });
  11894. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11895. svr_.wait_until_ready();
  11896. }
  11897. virtual void TearDown() {
  11898. svr_.stop();
  11899. t_.join();
  11900. }
  11901. #ifdef CPPHTTPLIB_SSL_ENABLED
  11902. SSLClient cli_;
  11903. SSLServer svr_;
  11904. #else
  11905. Client cli_;
  11906. Server svr_;
  11907. #endif
  11908. thread t_;
  11909. };
  11910. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11911. auto res = cli_.Post("/test", "123456789", "text/plain");
  11912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11913. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11914. res = cli_.Post("/test", "12345678", "text/plain");
  11915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11916. EXPECT_EQ(StatusCode::OK_200, res->status);
  11917. }
  11918. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11919. // Test chunked encoding with payload exceeding the 8-byte limit
  11920. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11921. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11924. }
  11925. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11926. // Test chunked encoding with payload within the 8-byte limit
  11927. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11928. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11930. EXPECT_EQ(StatusCode::OK_200, res->status);
  11931. }
  11932. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11933. // Test using send_request to send chunked data exceeding payload limit
  11934. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11935. "Host: " +
  11936. std::string(HOST) + ":" + std::to_string(PORT) +
  11937. "\r\n"
  11938. "Transfer-Encoding: chunked\r\n"
  11939. "Connection: close\r\n"
  11940. "\r\n"
  11941. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11942. "0123456789\r\n"
  11943. "0\r\n" // End chunk
  11944. "\r\n";
  11945. std::string response;
  11946. bool result = send_request(1, chunked_request, &response);
  11947. if (!result) {
  11948. // If send_request fails, it might be because the server closed the
  11949. // connection due to payload limit enforcement, which is acceptable
  11950. SUCCEED()
  11951. << "Server rejected oversized chunked request (connection closed)";
  11952. } else {
  11953. // If we got a response, check if it's an error response or connection was
  11954. // closed early Short response length indicates connection was closed due to
  11955. // payload limit
  11956. if (response.length() <= 10) {
  11957. SUCCEED() << "Server closed connection for oversized chunked request";
  11958. } else {
  11959. // Check for error status codes
  11960. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11961. response.find("Payload Too Large") != std::string::npos ||
  11962. response.find("400") != std::string::npos);
  11963. }
  11964. }
  11965. }
  11966. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11967. // Test request without Content-Length header exceeding payload limit
  11968. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11969. "Host: " +
  11970. std::string(HOST) + ":" +
  11971. std::to_string(PORT) +
  11972. "\r\n"
  11973. "Connection: close\r\n"
  11974. "\r\n";
  11975. // Add payload exceeding the 8-byte limit
  11976. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11977. request_without_content_length += large_payload;
  11978. std::string response;
  11979. bool result = send_request(1, request_without_content_length, &response);
  11980. if (!result) {
  11981. // If send_request fails, server likely closed connection due to payload
  11982. // limit
  11983. SUCCEED() << "Server rejected oversized request without Content-Length "
  11984. "(connection closed)";
  11985. } else {
  11986. // Check if server responded with error or closed connection early
  11987. if (response.length() <= 10) {
  11988. SUCCEED() << "Server closed connection for oversized request without "
  11989. "Content-Length";
  11990. } else {
  11991. // Check for error status codes
  11992. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11993. response.find("Payload Too Large") != std::string::npos ||
  11994. response.find("400") != std::string::npos);
  11995. }
  11996. }
  11997. }
  11998. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11999. // Test request without Content-Length header within payload limit
  12000. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12001. "Host: " +
  12002. std::string(HOST) + ":" +
  12003. std::to_string(PORT) +
  12004. "\r\n"
  12005. "Connection: close\r\n"
  12006. "\r\n";
  12007. // Add payload within the 8-byte limit
  12008. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12009. request_without_content_length += small_payload;
  12010. std::string response;
  12011. bool result = send_request(1, request_without_content_length, &response);
  12012. // For requests without Content-Length, the server may have different behavior
  12013. // The key is that it should not reject due to payload limit for small
  12014. // payloads
  12015. if (result) {
  12016. // Check for any HTTP response (success or error, but not connection closed)
  12017. if (response.length() > 10) {
  12018. SUCCEED()
  12019. << "Server processed request without Content-Length within limit";
  12020. } else {
  12021. // Short response might indicate connection closed, which is acceptable
  12022. SUCCEED() << "Server closed connection for request without "
  12023. "Content-Length (acceptable behavior)";
  12024. }
  12025. } else {
  12026. // Connection failure might be due to protocol requirements
  12027. SUCCEED() << "Connection issue with request without Content-Length "
  12028. "(environment-specific)";
  12029. }
  12030. }
  12031. class LargePayloadMaxLengthTest : public ::testing::Test {
  12032. protected:
  12033. LargePayloadMaxLengthTest()
  12034. : cli_(HOST, PORT)
  12035. #ifdef CPPHTTPLIB_SSL_ENABLED
  12036. ,
  12037. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12038. #endif
  12039. {
  12040. #ifdef CPPHTTPLIB_SSL_ENABLED
  12041. cli_.enable_server_certificate_verification(false);
  12042. #endif
  12043. }
  12044. virtual void SetUp() {
  12045. // Set 10MB payload limit
  12046. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12047. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12048. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12049. res.set_content("Large payload test", "text/plain");
  12050. });
  12051. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12052. svr_.wait_until_ready();
  12053. }
  12054. virtual void TearDown() {
  12055. svr_.stop();
  12056. t_.join();
  12057. }
  12058. #ifdef CPPHTTPLIB_SSL_ENABLED
  12059. SSLClient cli_;
  12060. SSLServer svr_;
  12061. #else
  12062. Client cli_;
  12063. Server svr_;
  12064. #endif
  12065. thread t_;
  12066. };
  12067. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12068. // Test chunked encoding with payload within 10MB limit
  12069. std::string medium_payload(5 * 1024 * 1024,
  12070. 'A'); // 5MB payload, within 10MB limit
  12071. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12073. EXPECT_EQ(StatusCode::OK_200, res->status);
  12074. }
  12075. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12076. // Test chunked encoding with payload exceeding 10MB limit
  12077. std::string large_payload(12 * 1024 * 1024,
  12078. 'B'); // 12MB payload, exceeds 10MB limit
  12079. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12080. // Server may either return 413 or close the connection
  12081. if (res) {
  12082. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12083. } else {
  12084. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12085. }
  12086. }
  12087. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12088. // Test request without Content-Length header within 10MB limit
  12089. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12090. "Host: " +
  12091. std::string(HOST) + ":" +
  12092. std::to_string(PORT) +
  12093. "\r\n"
  12094. "Connection: close\r\n"
  12095. "\r\n";
  12096. // Add 1MB payload (within 10MB limit)
  12097. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12098. request_without_content_length += medium_payload;
  12099. std::string response;
  12100. bool result = send_request(5, request_without_content_length, &response);
  12101. if (result) {
  12102. // Should get a proper HTTP response for payloads within limit
  12103. if (response.length() > 10) {
  12104. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12105. "10MB limit";
  12106. } else {
  12107. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12108. "Content-Length)";
  12109. }
  12110. } else {
  12111. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12112. }
  12113. }
  12114. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12115. // Test request without Content-Length header exceeding 10MB limit
  12116. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12117. "Host: " +
  12118. std::string(HOST) + ":" +
  12119. std::to_string(PORT) +
  12120. "\r\n"
  12121. "Connection: close\r\n"
  12122. "\r\n";
  12123. // Add 12MB payload (exceeds 10MB limit)
  12124. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12125. request_without_content_length += large_payload;
  12126. std::string response;
  12127. bool result = send_request(10, request_without_content_length, &response);
  12128. if (!result) {
  12129. // Server should close connection due to payload limit
  12130. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12131. "(connection closed)";
  12132. } else {
  12133. // Check for error response
  12134. if (response.length() <= 10) {
  12135. SUCCEED()
  12136. << "Server closed connection for 12MB request exceeding 10MB limit";
  12137. } else {
  12138. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12139. response.find("Payload Too Large") != std::string::npos ||
  12140. response.find("400") != std::string::npos);
  12141. }
  12142. }
  12143. }
  12144. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12145. Server svr;
  12146. svr.Get("/", [](const Request &, Response &res) {
  12147. // Claims the most the client accepts, far more than it sends, then drops
  12148. // the connection.
  12149. res.set_content_provider(std::string().max_size(), "text/plain",
  12150. [](size_t, size_t, DataSink &sink) {
  12151. sink.write("abc", 3);
  12152. return false;
  12153. });
  12154. });
  12155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12156. auto se = detail::scope_exit([&] {
  12157. svr.stop();
  12158. thread.join();
  12159. ASSERT_FALSE(svr.is_running());
  12160. });
  12161. svr.wait_until_ready();
  12162. Client cli(HOST, PORT);
  12163. cli.set_payload_max_length(0);
  12164. EXPECT_FALSE(cli.Get("/"));
  12165. }
  12166. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12167. // Stream API does, not as a plain read failure
  12168. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12169. Server svr;
  12170. svr.Get("/big", [](const Request &, Response &res) {
  12171. res.set_content(std::string(100000, 'b'), "text/plain");
  12172. });
  12173. auto port = svr.bind_to_any_port(HOST);
  12174. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12175. auto se = detail::scope_exit([&] {
  12176. svr.stop();
  12177. thread.join();
  12178. });
  12179. svr.wait_until_ready();
  12180. Client cli(HOST, port);
  12181. cli.set_payload_max_length(1000);
  12182. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12183. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12184. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12185. [](const char *, size_t) { return true; });
  12186. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12187. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12188. // Small on the wire, over the limit once decompressed
  12189. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12190. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12191. #endif
  12192. }
  12193. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12194. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12195. // path.
  12196. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12197. Server svr;
  12198. const size_t LIMIT = 64 * 1024; // 64KB
  12199. svr.set_payload_max_length(LIMIT);
  12200. size_t total = 0;
  12201. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12202. const ContentReader &content_reader) {
  12203. content_reader([&](const char * /*data*/, size_t len) {
  12204. total += len;
  12205. return true;
  12206. });
  12207. res.status = 200;
  12208. res.set_content("stream_ok", "text/plain");
  12209. });
  12210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12211. auto se = detail::scope_exit([&] {
  12212. svr.stop();
  12213. thread.join();
  12214. ASSERT_FALSE(svr.is_running());
  12215. });
  12216. svr.wait_until_ready();
  12217. // Prepare 256KB raw data and gzip-compress it
  12218. std::string raw(256 * 1024, 'A');
  12219. std::string gz;
  12220. {
  12221. z_stream zs{};
  12222. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12223. Z_DEFAULT_STRATEGY);
  12224. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12225. zs.avail_in = static_cast<uInt>(raw.size());
  12226. char outbuf[4096];
  12227. int ret;
  12228. do {
  12229. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12230. zs.avail_out = sizeof(outbuf);
  12231. ret = deflate(&zs, Z_FINISH);
  12232. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12233. } while (ret != Z_STREAM_END);
  12234. deflateEnd(&zs);
  12235. }
  12236. Client cli(HOST, PORT);
  12237. cli.set_connection_timeout(std::chrono::seconds(5));
  12238. Headers headers = {{"Content-Encoding", "gzip"}};
  12239. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12240. "application/octet-stream");
  12241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12242. // Server must reject oversized decompressed payloads with 413.
  12243. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12244. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12245. EXPECT_LE(total, LIMIT);
  12246. }
  12247. #ifndef CPPHTTPLIB_SSL_ENABLED
  12248. // For a request with neither Content-Length nor Transfer-Encoding, the
  12249. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12250. // compressed wire bytes straight to the ContentReader without ever routing
  12251. // them through the decompressor, so payload_max_length_ only bounded the
  12252. // compressed size on the wire, not the decompressed size.
  12253. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12254. Server svr;
  12255. const size_t LIMIT = 64 * 1024; // 64KB
  12256. svr.set_payload_max_length(LIMIT);
  12257. size_t total = 0;
  12258. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12259. const ContentReader &content_reader) {
  12260. content_reader([&](const char * /*data*/, size_t len) {
  12261. total += len;
  12262. return true;
  12263. });
  12264. res.status = 200;
  12265. res.set_content("stream_ok", "text/plain");
  12266. });
  12267. auto port = svr.bind_to_any_port(HOST);
  12268. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12269. auto se = detail::scope_exit([&] {
  12270. svr.stop();
  12271. thread.join();
  12272. ASSERT_FALSE(svr.is_running());
  12273. });
  12274. svr.wait_until_ready();
  12275. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12276. // StreamingGzipDecompression test above.
  12277. std::string raw(256 * 1024, 'A');
  12278. std::string gz;
  12279. {
  12280. httplib::detail::gzip_compressor compressor;
  12281. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12282. [&](const char *chunk, size_t len) {
  12283. gz.append(chunk, len);
  12284. return true;
  12285. });
  12286. ASSERT_TRUE(result);
  12287. }
  12288. // Send the gzip body over raw TCP with neither Content-Length nor
  12289. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12290. // kicks in.
  12291. std::string req = "POST /stream HTTP/1.1\r\n"
  12292. "Host: " +
  12293. std::string(HOST) + ":" + std::to_string(port) +
  12294. "\r\n"
  12295. "Content-Encoding: gzip\r\n"
  12296. "Connection: close\r\n"
  12297. "\r\n" +
  12298. gz;
  12299. std::string response;
  12300. ASSERT_TRUE(send_request(5, req, &response, port));
  12301. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12302. EXPECT_LE(total, LIMIT);
  12303. }
  12304. #endif
  12305. #endif
  12306. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12307. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12308. // the payload must be passed through untouched instead of being rejected.
  12309. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12310. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12311. Server svr;
  12312. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12313. res.set_content(body, "image/jpeg");
  12314. res.set_header("Content-Encoding", "UTF-8");
  12315. });
  12316. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12317. res.set_content(body, "image/jpeg");
  12318. res.set_header("Content-Encoding", "identity");
  12319. });
  12320. svr.Post("/echo", [](const Request &req, Response &res) {
  12321. res.set_content(req.body, "image/jpeg");
  12322. });
  12323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12324. auto se = detail::scope_exit([&] {
  12325. svr.stop();
  12326. t.join();
  12327. ASSERT_FALSE(svr.is_running());
  12328. });
  12329. svr.wait_until_ready();
  12330. Client cli(HOST, PORT);
  12331. {
  12332. auto res = cli.Get("/image");
  12333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12334. EXPECT_EQ(StatusCode::OK_200, res->status);
  12335. EXPECT_EQ(body, res->body);
  12336. }
  12337. {
  12338. auto res = cli.Get("/identity");
  12339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12340. EXPECT_EQ(StatusCode::OK_200, res->status);
  12341. EXPECT_EQ(body, res->body);
  12342. }
  12343. {
  12344. // The same applies to a request body reaching the server.
  12345. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12346. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12348. EXPECT_EQ(StatusCode::OK_200, res->status);
  12349. EXPECT_EQ(body, res->body);
  12350. }
  12351. }
  12352. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12353. // gzip-encoded response even when the build has no zlib support.
  12354. static const char GZIPPED_HELLO_WORLD[] = {
  12355. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12356. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12357. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12358. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12359. // A content coding is a whole token, not something the field value merely
  12360. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12361. // as "fibre" look like Brotli, and turned a multi-coding value like
  12362. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12363. // it was never meant to see.
  12364. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12365. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12366. Server svr;
  12367. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12368. res.set_content(body, "image/jpeg");
  12369. res.set_header("Content-Encoding", "fibre");
  12370. });
  12371. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12372. res.set_content(body, "image/jpeg");
  12373. res.set_header("Content-Encoding", "gzip, br");
  12374. });
  12375. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12376. res.set_content(body, "image/jpeg");
  12377. res.set_header("Content-Encoding", "x-zstd-ish");
  12378. });
  12379. auto port = svr.bind_to_any_port(HOST);
  12380. thread t = thread([&]() { svr.listen_after_bind(); });
  12381. auto se = detail::scope_exit([&] {
  12382. svr.stop();
  12383. t.join();
  12384. ASSERT_FALSE(svr.is_running());
  12385. });
  12386. svr.wait_until_ready();
  12387. Client cli(HOST, port);
  12388. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12389. auto res = cli.Get(path);
  12390. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12391. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12392. // Not a coding we recognize, so the payload comes back untouched
  12393. EXPECT_EQ(body, res->body) << path;
  12394. }
  12395. }
  12396. // A content coding cpp-httplib recognizes but was not built with must be
  12397. // reported as such. Handing the still-compressed payload back to the caller
  12398. // would silently corrupt it.
  12399. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12400. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12401. Server svr;
  12402. // "image/jpeg" keeps the server from applying a content coding of its own,
  12403. // so the hand-crafted Content-Encoding below survives.
  12404. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12405. res.set_content(gzipped, "image/jpeg");
  12406. res.set_header("Content-Encoding", "gzip");
  12407. });
  12408. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12409. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12410. res.set_content(gzipped, "image/jpeg");
  12411. res.set_header("Content-Encoding", "GZIP");
  12412. });
  12413. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12414. auto se = detail::scope_exit([&] {
  12415. svr.stop();
  12416. t.join();
  12417. ASSERT_FALSE(svr.is_running());
  12418. });
  12419. svr.wait_until_ready();
  12420. Client cli(HOST, PORT);
  12421. {
  12422. auto res = cli.Get("/gzipped");
  12423. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12425. EXPECT_EQ("Hello World!", res->body);
  12426. #else
  12427. ASSERT_FALSE(res);
  12428. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12429. #endif
  12430. }
  12431. {
  12432. // open_stream() must behave the same way.
  12433. auto handle = cli.open_stream("GET", "/gzipped");
  12434. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12435. ASSERT_TRUE(handle.is_valid());
  12436. std::string received;
  12437. char buf[256];
  12438. ssize_t n;
  12439. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12440. received.append(buf, static_cast<size_t>(n));
  12441. }
  12442. EXPECT_EQ("Hello World!", received);
  12443. #else
  12444. EXPECT_FALSE(handle.is_valid());
  12445. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12446. #endif
  12447. }
  12448. {
  12449. // A differently-cased coding must not be mistaken for an unknown one, or
  12450. // the body would be handed back still compressed.
  12451. auto res = cli.Get("/gzipped-uppercase");
  12452. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12454. EXPECT_EQ("Hello World!", res->body);
  12455. #else
  12456. ASSERT_FALSE(res);
  12457. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12458. #endif
  12459. }
  12460. }
  12461. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12462. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12463. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12464. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12465. // body a second time and appending a second Content-Encoding field line, so
  12466. // clients that decode one coding per listed value handed back raw gzip bytes.
  12467. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12468. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12469. Server svr;
  12470. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12471. // keeps the server from applying a coding of its own.
  12472. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12473. res.set_content(gzipped, "text/plain");
  12474. res.set_header("Content-Encoding", "gzip");
  12475. });
  12476. auto port = svr.bind_to_any_port(HOST);
  12477. thread t = thread([&]() { svr.listen_after_bind(); });
  12478. auto se = detail::scope_exit([&] {
  12479. svr.stop();
  12480. t.join();
  12481. ASSERT_FALSE(svr.is_running());
  12482. });
  12483. svr.wait_until_ready();
  12484. Client cli(HOST, port);
  12485. Headers headers = {{"Accept-Encoding", "gzip"}};
  12486. auto res = cli.Get("/pre-gzipped", headers);
  12487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12488. EXPECT_EQ(StatusCode::OK_200, res->status);
  12489. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12490. EXPECT_EQ("Hello World!", res->body);
  12491. }
  12492. // A chunked provider settles its coding where the headers are written and
  12493. // reuses it at write time. Both ends of that have to hold: a handler's own
  12494. // Content-Encoding suppresses the coding, and a response without one is still
  12495. // compressed as it always was.
  12496. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12497. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12498. const std::string plain = "Hello World! Hello World! Hello World!";
  12499. Server svr;
  12500. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12501. res.set_header("Content-Encoding", "gzip");
  12502. res.set_chunked_content_provider(
  12503. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12504. sink.write(gzipped.data(), gzipped.size());
  12505. sink.done();
  12506. return true;
  12507. });
  12508. });
  12509. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12510. res.set_chunked_content_provider(
  12511. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12512. sink.write(plain.data(), plain.size());
  12513. sink.done();
  12514. return true;
  12515. });
  12516. });
  12517. auto port = svr.bind_to_any_port(HOST);
  12518. thread t = thread([&]() { svr.listen_after_bind(); });
  12519. auto se = detail::scope_exit([&] {
  12520. svr.stop();
  12521. t.join();
  12522. ASSERT_FALSE(svr.is_running());
  12523. });
  12524. svr.wait_until_ready();
  12525. Client cli(HOST, port);
  12526. Headers headers = {{"Accept-Encoding", "gzip"}};
  12527. {
  12528. auto res = cli.Get("/pre-gzipped", headers);
  12529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12530. EXPECT_EQ(StatusCode::OK_200, res->status);
  12531. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12532. EXPECT_EQ("Hello World!", res->body);
  12533. }
  12534. {
  12535. auto res = cli.Get("/negotiated", headers);
  12536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12537. EXPECT_EQ(StatusCode::OK_200, res->status);
  12538. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12539. EXPECT_EQ(plain, res->body);
  12540. }
  12541. }
  12542. #endif
  12543. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12544. // the same message as the comma-joined one, so both have to be read the same
  12545. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12546. // single gzip coding, and a body the sender says was encoded twice was handed
  12547. // back after one pass, still compressed but presented as decoded.
  12548. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12549. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12550. Server svr;
  12551. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12552. res.set_content(body, "image/jpeg");
  12553. res.headers.emplace("Content-Encoding", "gzip");
  12554. res.headers.emplace("Content-Encoding", "gzip");
  12555. });
  12556. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12557. res.set_content(body, "image/jpeg");
  12558. res.set_header("Content-Encoding", "gzip, gzip");
  12559. });
  12560. auto port = svr.bind_to_any_port(HOST);
  12561. thread t = thread([&]() { svr.listen_after_bind(); });
  12562. auto se = detail::scope_exit([&] {
  12563. svr.stop();
  12564. t.join();
  12565. ASSERT_FALSE(svr.is_running());
  12566. });
  12567. svr.wait_until_ready();
  12568. Client cli(HOST, port);
  12569. // Two codings is not something cpp-httplib decodes, so both representations
  12570. // take the pass-through path rather than one of them being gunzipped once.
  12571. for (const char *path : {"/split", "/joined"}) {
  12572. auto res = cli.Get(path);
  12573. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12574. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12575. EXPECT_EQ(body, res->body) << path;
  12576. }
  12577. }
  12578. // Regression test for DoS vulnerability: a malicious server sending a response
  12579. // without Content-Length header must not cause unbounded memory consumption on
  12580. // the client side. The client should stop reading after a reasonable limit,
  12581. // similar to the server-side set_payload_max_length protection.
  12582. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12583. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12584. #ifndef _WIN32
  12585. signal(SIGPIPE, SIG_IGN);
  12586. #endif
  12587. auto server_thread = std::thread([] {
  12588. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12589. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12590. default_socket_options(srv);
  12591. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12592. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12593. sockaddr_in addr{};
  12594. addr.sin_family = AF_INET;
  12595. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12596. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12597. int opt = 1;
  12598. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12599. #ifdef _WIN32
  12600. reinterpret_cast<const char *>(&opt),
  12601. #else
  12602. &opt,
  12603. #endif
  12604. sizeof(opt));
  12605. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12606. ::listen(srv, 1);
  12607. sockaddr_in cli_addr{};
  12608. socklen_t cli_len = sizeof(cli_addr);
  12609. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12610. if (cli != INVALID_SOCKET) {
  12611. char buf[4096];
  12612. ::recv(cli, buf, sizeof(buf), 0);
  12613. // Malicious response: no Content-Length, no chunked encoding
  12614. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12615. "Connection: close\r\n"
  12616. "\r\n";
  12617. ::send(cli,
  12618. #ifdef _WIN32
  12619. static_cast<const char *>(response_header.c_str()),
  12620. static_cast<int>(response_header.size()),
  12621. #else
  12622. response_header.c_str(), response_header.size(),
  12623. #endif
  12624. 0);
  12625. // Send 10MB of data
  12626. std::string chunk(64 * 1024, 'A');
  12627. size_t total_sent = 0;
  12628. while (total_sent < MALICIOUS_DATA_SIZE) {
  12629. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12630. auto sent = ::send(cli,
  12631. #ifdef _WIN32
  12632. static_cast<const char *>(chunk.c_str()),
  12633. static_cast<int>(to_send),
  12634. #else
  12635. chunk.c_str(), to_send,
  12636. #endif
  12637. 0);
  12638. if (sent <= 0) break;
  12639. total_sent += static_cast<size_t>(sent);
  12640. }
  12641. detail::close_socket(cli);
  12642. }
  12643. detail::close_socket(srv);
  12644. });
  12645. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12646. size_t total_read = 0;
  12647. {
  12648. Client cli("127.0.0.1", PORT + 2);
  12649. cli.set_read_timeout(5, 0);
  12650. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12651. auto stream = cli.open_stream("GET", "/malicious");
  12652. ASSERT_TRUE(stream.is_valid());
  12653. char buffer[64 * 1024];
  12654. ssize_t n;
  12655. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12656. total_read += static_cast<size_t>(n);
  12657. }
  12658. } // StreamHandle and Client destroyed here, closing the socket
  12659. server_thread.join();
  12660. // With set_payload_max_length, the client must stop reading before consuming
  12661. // all 10MB. The read loop should be cut off at or near the configured limit.
  12662. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12663. << "Client read " << total_read << " bytes, exceeding the configured "
  12664. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12665. }
  12666. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12667. // the entire response body without truncation.
  12668. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12669. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12670. #ifndef _WIN32
  12671. signal(SIGPIPE, SIG_IGN);
  12672. #endif
  12673. auto server_thread = std::thread([] {
  12674. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12675. default_socket_options(srv);
  12676. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12677. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12678. sockaddr_in addr{};
  12679. addr.sin_family = AF_INET;
  12680. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12681. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12682. int opt = 1;
  12683. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12684. #ifdef _WIN32
  12685. reinterpret_cast<const char *>(&opt),
  12686. #else
  12687. &opt,
  12688. #endif
  12689. sizeof(opt));
  12690. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12691. ::listen(srv, 1);
  12692. sockaddr_in cli_addr{};
  12693. socklen_t cli_len = sizeof(cli_addr);
  12694. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12695. if (cli != INVALID_SOCKET) {
  12696. char buf[4096];
  12697. ::recv(cli, buf, sizeof(buf), 0);
  12698. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12699. "Connection: close\r\n"
  12700. "\r\n";
  12701. ::send(cli,
  12702. #ifdef _WIN32
  12703. static_cast<const char *>(response_header.c_str()),
  12704. static_cast<int>(response_header.size()),
  12705. #else
  12706. response_header.c_str(), response_header.size(),
  12707. #endif
  12708. 0);
  12709. std::string chunk(64 * 1024, 'A');
  12710. size_t total_sent = 0;
  12711. while (total_sent < DATA_SIZE) {
  12712. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12713. auto sent = ::send(cli,
  12714. #ifdef _WIN32
  12715. static_cast<const char *>(chunk.c_str()),
  12716. static_cast<int>(to_send),
  12717. #else
  12718. chunk.c_str(), to_send,
  12719. #endif
  12720. 0);
  12721. if (sent <= 0) break;
  12722. total_sent += static_cast<size_t>(sent);
  12723. }
  12724. #ifdef _WIN32
  12725. ::shutdown(cli, SD_SEND);
  12726. #else
  12727. ::shutdown(cli, SHUT_WR);
  12728. #endif
  12729. // Drain until the client closes its end, ensuring all data is delivered
  12730. char drain[1024];
  12731. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12732. detail::close_socket(cli);
  12733. }
  12734. detail::close_socket(srv);
  12735. });
  12736. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12737. size_t total_read = 0;
  12738. {
  12739. Client cli("127.0.0.1", PORT + 2);
  12740. cli.set_read_timeout(5, 0);
  12741. cli.set_payload_max_length(0); // 0 means no limit
  12742. auto stream = cli.open_stream("GET", "/data");
  12743. ASSERT_TRUE(stream.is_valid());
  12744. char buffer[64 * 1024];
  12745. ssize_t n;
  12746. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12747. total_read += static_cast<size_t>(n);
  12748. }
  12749. }
  12750. server_thread.join();
  12751. EXPECT_EQ(total_read, DATA_SIZE)
  12752. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12753. << " bytes without truncation, but only read " << total_read << " bytes.";
  12754. }
  12755. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12756. // enormous Content-Length must not cause the client to pre-allocate a huge
  12757. // response body buffer. The reservation is capped at payload_max_length_, and
  12758. // the read itself fails when the body exceeds the limit.
  12759. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12760. #ifndef _WIN32
  12761. signal(SIGPIPE, SIG_IGN);
  12762. #endif
  12763. auto server_thread = std::thread([] {
  12764. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12765. default_socket_options(srv);
  12766. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12767. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12768. sockaddr_in addr{};
  12769. addr.sin_family = AF_INET;
  12770. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12771. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12772. int opt = 1;
  12773. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12774. #ifdef _WIN32
  12775. reinterpret_cast<const char *>(&opt),
  12776. #else
  12777. &opt,
  12778. #endif
  12779. sizeof(opt));
  12780. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12781. ::listen(srv, 1);
  12782. sockaddr_in cli_addr{};
  12783. socklen_t cli_len = sizeof(cli_addr);
  12784. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12785. if (cli != INVALID_SOCKET) {
  12786. char buf[4096];
  12787. ::recv(cli, buf, sizeof(buf), 0);
  12788. // Malicious response: claim a 20GB body but send only a tiny payload.
  12789. std::string response = "HTTP/1.1 200 OK\r\n"
  12790. "Content-Length: 20000000000\r\n"
  12791. "\r\n"
  12792. "abc";
  12793. ::send(cli,
  12794. #ifdef _WIN32
  12795. static_cast<const char *>(response.c_str()),
  12796. static_cast<int>(response.size()),
  12797. #else
  12798. response.c_str(), response.size(),
  12799. #endif
  12800. 0);
  12801. detail::close_socket(cli);
  12802. }
  12803. detail::close_socket(srv);
  12804. });
  12805. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12806. {
  12807. Client cli("127.0.0.1", PORT + 2);
  12808. cli.set_read_timeout(5, 0);
  12809. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12810. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12811. // (server claims more bytes than payload_max_length permits), but it must
  12812. // not exhaust memory before getting there.
  12813. auto res = cli.Get("/malicious");
  12814. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12815. }
  12816. server_thread.join();
  12817. }
  12818. // Verify that content_receiver bypasses the default payload_max_length,
  12819. // allowing streaming downloads larger than 100MB without requiring an explicit
  12820. // set_payload_max_length call.
  12821. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12822. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12823. #ifndef _WIN32
  12824. signal(SIGPIPE, SIG_IGN);
  12825. #endif
  12826. auto server_thread = std::thread([] {
  12827. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12828. default_socket_options(srv);
  12829. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12830. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12831. sockaddr_in addr{};
  12832. addr.sin_family = AF_INET;
  12833. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12834. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12835. int opt = 1;
  12836. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12837. #ifdef _WIN32
  12838. reinterpret_cast<const char *>(&opt),
  12839. #else
  12840. &opt,
  12841. #endif
  12842. sizeof(opt));
  12843. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12844. ::listen(srv, 1);
  12845. sockaddr_in cli_addr{};
  12846. socklen_t cli_len = sizeof(cli_addr);
  12847. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12848. if (cli != INVALID_SOCKET) {
  12849. char buf[4096];
  12850. ::recv(cli, buf, sizeof(buf), 0);
  12851. // Response with Content-Length larger than default 100MB limit
  12852. auto content_length = std::to_string(DATA_SIZE);
  12853. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12854. "Content-Length: " +
  12855. content_length +
  12856. "\r\n"
  12857. "Connection: close\r\n"
  12858. "\r\n";
  12859. ::send(cli,
  12860. #ifdef _WIN32
  12861. static_cast<const char *>(response_header.c_str()),
  12862. static_cast<int>(response_header.size()),
  12863. #else
  12864. response_header.c_str(), response_header.size(),
  12865. #endif
  12866. 0);
  12867. std::string chunk(64 * 1024, 'A');
  12868. size_t total_sent = 0;
  12869. while (total_sent < DATA_SIZE) {
  12870. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12871. auto sent = ::send(cli,
  12872. #ifdef _WIN32
  12873. static_cast<const char *>(chunk.c_str()),
  12874. static_cast<int>(to_send),
  12875. #else
  12876. chunk.c_str(), to_send,
  12877. #endif
  12878. 0);
  12879. if (sent <= 0) break;
  12880. total_sent += static_cast<size_t>(sent);
  12881. }
  12882. detail::close_socket(cli);
  12883. }
  12884. detail::close_socket(srv);
  12885. });
  12886. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12887. size_t total_received = 0;
  12888. {
  12889. Client cli("127.0.0.1", PORT + 2);
  12890. cli.set_read_timeout(10, 0);
  12891. // Do NOT call set_payload_max_length — use the default 100MB limit
  12892. auto res =
  12893. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12894. total_received += data_length;
  12895. return true;
  12896. });
  12897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12898. EXPECT_EQ(StatusCode::OK_200, res->status);
  12899. }
  12900. server_thread.join();
  12901. EXPECT_EQ(total_received, DATA_SIZE)
  12902. << "With content_receiver, the client should read all " << DATA_SIZE
  12903. << " bytes despite the default 100MB payload_max_length, but only read "
  12904. << total_received << " bytes.";
  12905. }
  12906. // Verify that an explicit set_payload_max_length smaller than the response is
  12907. // enforced even when a content_receiver is used.
  12908. TEST(ClientVulnerabilityTest,
  12909. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12910. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12911. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12912. #ifndef _WIN32
  12913. signal(SIGPIPE, SIG_IGN);
  12914. #endif
  12915. auto server_thread = std::thread([] {
  12916. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12917. default_socket_options(srv);
  12918. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12919. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12920. sockaddr_in addr{};
  12921. addr.sin_family = AF_INET;
  12922. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12923. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12924. int opt = 1;
  12925. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12926. #ifdef _WIN32
  12927. reinterpret_cast<const char *>(&opt),
  12928. #else
  12929. &opt,
  12930. #endif
  12931. sizeof(opt));
  12932. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12933. ::listen(srv, 1);
  12934. sockaddr_in cli_addr{};
  12935. socklen_t cli_len = sizeof(cli_addr);
  12936. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12937. if (cli != INVALID_SOCKET) {
  12938. char buf[4096];
  12939. ::recv(cli, buf, sizeof(buf), 0);
  12940. auto content_length = std::to_string(DATA_SIZE);
  12941. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12942. "Content-Length: " +
  12943. content_length +
  12944. "\r\n"
  12945. "Connection: close\r\n"
  12946. "\r\n";
  12947. ::send(cli,
  12948. #ifdef _WIN32
  12949. static_cast<const char *>(response_header.c_str()),
  12950. static_cast<int>(response_header.size()),
  12951. #else
  12952. response_header.c_str(), response_header.size(),
  12953. #endif
  12954. 0);
  12955. std::string chunk(64 * 1024, 'A');
  12956. size_t total_sent = 0;
  12957. while (total_sent < DATA_SIZE) {
  12958. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12959. auto sent = ::send(cli,
  12960. #ifdef _WIN32
  12961. static_cast<const char *>(chunk.c_str()),
  12962. static_cast<int>(to_send),
  12963. #else
  12964. chunk.c_str(), to_send,
  12965. #endif
  12966. 0);
  12967. if (sent <= 0) break;
  12968. total_sent += static_cast<size_t>(sent);
  12969. }
  12970. detail::close_socket(cli);
  12971. }
  12972. detail::close_socket(srv);
  12973. });
  12974. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12975. size_t total_received = 0;
  12976. {
  12977. Client cli("127.0.0.1", PORT + 2);
  12978. cli.set_read_timeout(10, 0);
  12979. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12980. auto res =
  12981. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12982. total_received += data_length;
  12983. return true;
  12984. });
  12985. // Should fail because 200MB exceeds the explicit 150MB limit
  12986. EXPECT_FALSE(res);
  12987. }
  12988. server_thread.join();
  12989. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12990. << "Client with content_receiver should respect the explicit "
  12991. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12992. << total_received << " bytes.";
  12993. }
  12994. // Verify that an explicit set_payload_max_length larger than the response
  12995. // allows the content_receiver to read all data successfully.
  12996. TEST(ClientVulnerabilityTest,
  12997. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12998. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12999. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13000. #ifndef _WIN32
  13001. signal(SIGPIPE, SIG_IGN);
  13002. #endif
  13003. auto server_thread = std::thread([] {
  13004. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13005. default_socket_options(srv);
  13006. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13007. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13008. sockaddr_in addr{};
  13009. addr.sin_family = AF_INET;
  13010. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13011. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13012. int opt = 1;
  13013. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13014. #ifdef _WIN32
  13015. reinterpret_cast<const char *>(&opt),
  13016. #else
  13017. &opt,
  13018. #endif
  13019. sizeof(opt));
  13020. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13021. ::listen(srv, 1);
  13022. sockaddr_in cli_addr{};
  13023. socklen_t cli_len = sizeof(cli_addr);
  13024. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13025. if (cli != INVALID_SOCKET) {
  13026. char buf[4096];
  13027. ::recv(cli, buf, sizeof(buf), 0);
  13028. auto content_length = std::to_string(DATA_SIZE);
  13029. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13030. "Content-Length: " +
  13031. content_length +
  13032. "\r\n"
  13033. "Connection: close\r\n"
  13034. "\r\n";
  13035. ::send(cli,
  13036. #ifdef _WIN32
  13037. static_cast<const char *>(response_header.c_str()),
  13038. static_cast<int>(response_header.size()),
  13039. #else
  13040. response_header.c_str(), response_header.size(),
  13041. #endif
  13042. 0);
  13043. std::string chunk(64 * 1024, 'A');
  13044. size_t total_sent = 0;
  13045. while (total_sent < DATA_SIZE) {
  13046. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13047. auto sent = ::send(cli,
  13048. #ifdef _WIN32
  13049. static_cast<const char *>(chunk.c_str()),
  13050. static_cast<int>(to_send),
  13051. #else
  13052. chunk.c_str(), to_send,
  13053. #endif
  13054. 0);
  13055. if (sent <= 0) break;
  13056. total_sent += static_cast<size_t>(sent);
  13057. }
  13058. #ifdef _WIN32
  13059. ::shutdown(cli, SD_SEND);
  13060. #else
  13061. ::shutdown(cli, SHUT_WR);
  13062. #endif
  13063. char drain[1024];
  13064. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13065. detail::close_socket(cli);
  13066. }
  13067. detail::close_socket(srv);
  13068. });
  13069. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13070. size_t total_received = 0;
  13071. {
  13072. Client cli("127.0.0.1", PORT + 2);
  13073. cli.set_read_timeout(10, 0);
  13074. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13075. auto res =
  13076. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13077. total_received += data_length;
  13078. return true;
  13079. });
  13080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13081. EXPECT_EQ(StatusCode::OK_200, res->status);
  13082. }
  13083. server_thread.join();
  13084. EXPECT_EQ(total_received, DATA_SIZE)
  13085. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13086. << " bytes (larger than " << DATA_SIZE
  13087. << " bytes response), content_receiver should read all data, but only "
  13088. "read "
  13089. << total_received << " bytes.";
  13090. }
  13091. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13092. // Regression test for "zip bomb" attack on the client side: a malicious server
  13093. // sends a small gzip-compressed response that decompresses to a huge payload.
  13094. // The client must enforce payload_max_length on the decompressed size.
  13095. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13096. constexpr size_t DECOMPRESSED_SIZE =
  13097. 10 * 1024 * 1024; // 10MB after decompression
  13098. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13099. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13100. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13101. std::string compressed;
  13102. {
  13103. httplib::detail::gzip_compressor compressor;
  13104. bool ok =
  13105. compressor.compress(uncompressed.data(), uncompressed.size(),
  13106. /*last=*/true, [&](const char *buf, size_t len) {
  13107. compressed.append(buf, len);
  13108. return true;
  13109. });
  13110. ASSERT_TRUE(ok);
  13111. }
  13112. // Sanity: compressed data should be much smaller than the decompressed size
  13113. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13114. #ifndef _WIN32
  13115. signal(SIGPIPE, SIG_IGN);
  13116. #endif
  13117. // Set up the listening socket in the main thread so the server is guaranteed
  13118. // to be ready before the client connects (eliminates race condition).
  13119. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13120. default_socket_options(srv);
  13121. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13122. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13123. sockaddr_in addr{};
  13124. addr.sin_family = AF_INET;
  13125. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13126. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13127. int opt = 1;
  13128. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13129. #ifdef _WIN32
  13130. reinterpret_cast<const char *>(&opt),
  13131. #else
  13132. &opt,
  13133. #endif
  13134. sizeof(opt));
  13135. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13136. ASSERT_EQ(0, ::listen(srv, 1));
  13137. auto server_thread = std::thread([&compressed, srv] {
  13138. sockaddr_in cli_addr{};
  13139. socklen_t cli_len = sizeof(cli_addr);
  13140. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13141. if (cli != INVALID_SOCKET) {
  13142. // Read the full HTTP request (until \r\n\r\n)
  13143. char buf[4096];
  13144. size_t total = 0;
  13145. while (total < sizeof(buf)) {
  13146. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13147. if (n <= 0) break;
  13148. total += static_cast<size_t>(n);
  13149. // Check for end of headers
  13150. if (total >= 4) {
  13151. std::string req(buf, total);
  13152. if (req.find("\r\n\r\n") != std::string::npos) break;
  13153. }
  13154. }
  13155. // Malicious response: gzip-compressed body, no Content-Length
  13156. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13157. "Content-Encoding: gzip\r\n"
  13158. "Connection: close\r\n"
  13159. "\r\n";
  13160. ::send(cli,
  13161. #ifdef _WIN32
  13162. static_cast<const char *>(response_header.c_str()),
  13163. static_cast<int>(response_header.size()),
  13164. #else
  13165. response_header.c_str(), response_header.size(),
  13166. #endif
  13167. 0);
  13168. // Send the compressed payload (small on the wire, huge when decompressed)
  13169. size_t total_sent = 0;
  13170. while (total_sent < compressed.size()) {
  13171. auto to_send = std::min(compressed.size() - total_sent,
  13172. static_cast<size_t>(64 * 1024));
  13173. auto sent =
  13174. ::send(cli,
  13175. #ifdef _WIN32
  13176. static_cast<const char *>(compressed.c_str() + total_sent),
  13177. static_cast<int>(to_send),
  13178. #else
  13179. compressed.c_str() + total_sent, to_send,
  13180. #endif
  13181. 0);
  13182. if (sent <= 0) break;
  13183. total_sent += static_cast<size_t>(sent);
  13184. }
  13185. detail::close_socket(cli);
  13186. }
  13187. });
  13188. auto se = detail::scope_exit([&] {
  13189. detail::close_socket(srv);
  13190. server_thread.join();
  13191. });
  13192. size_t total_decompressed = 0;
  13193. {
  13194. Client cli("127.0.0.1", PORT + 3);
  13195. cli.set_read_timeout(5, 0);
  13196. cli.set_decompress(true);
  13197. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13198. auto stream = cli.open_stream("GET", "/zipbomb");
  13199. ASSERT_TRUE(stream.is_valid());
  13200. char buffer[64 * 1024];
  13201. ssize_t n;
  13202. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13203. total_decompressed += static_cast<size_t>(n);
  13204. }
  13205. }
  13206. // The decompressed size must be capped by payload_max_length. Without
  13207. // protection, the client would decompress the full 10MB from a tiny
  13208. // compressed payload, enabling a zip bomb DoS attack.
  13209. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13210. << "Client decompressed " << total_decompressed
  13211. << " bytes from a gzip response. The decompressed size should be "
  13212. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13213. }
  13214. #endif
  13215. TEST(HostAndPortPropertiesTest, NoSSL) {
  13216. httplib::Client cli("www.google.com", 1234);
  13217. ASSERT_EQ("www.google.com", cli.host());
  13218. ASSERT_EQ(1234, cli.port());
  13219. }
  13220. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13221. httplib::Client cli("www.google.com:1234");
  13222. ASSERT_EQ("www.google.com", cli.host());
  13223. ASSERT_EQ(1234, cli.port());
  13224. }
  13225. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13226. // Port number that overflows int — should not crash, client becomes invalid
  13227. httplib::Client cli("http://www.google.com:99999999999999999999");
  13228. ASSERT_FALSE(cli.is_valid());
  13229. }
  13230. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13231. // Port 99999 exceeds valid range (1-65535) — should not crash
  13232. httplib::Client cli("http://www.google.com:99999");
  13233. ASSERT_FALSE(cli.is_valid());
  13234. auto res = cli.Get("/");
  13235. EXPECT_FALSE(res);
  13236. EXPECT_EQ(Error::Connection, res.error());
  13237. }
  13238. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13239. httplib::Client cli("http://user:pass@localhost:1234");
  13240. ASSERT_FALSE(cli.is_valid());
  13241. EXPECT_FALSE(cli.Get("/"));
  13242. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13243. }
  13244. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13245. httplib::Client cli("http://www.google.com:80abc");
  13246. ASSERT_FALSE(cli.is_valid());
  13247. }
  13248. #ifdef CPPHTTPLIB_SSL_ENABLED
  13249. TEST(HostAndPortPropertiesTest, SSL) {
  13250. httplib::SSLClient cli("www.google.com");
  13251. ASSERT_EQ("www.google.com", cli.host());
  13252. ASSERT_EQ(443, cli.port());
  13253. }
  13254. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13255. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13256. std::string cert;
  13257. read_file(CA_CERT_FILE, cert);
  13258. httplib::SSLClient httplib_client("www.google.com");
  13259. // Load CA store first time
  13260. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13261. // Load CA store second time (update)
  13262. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13263. // Verify client is still valid and can make connections
  13264. httplib_client.enable_server_certificate_verification(true);
  13265. auto res = httplib_client.Get("/");
  13266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13267. // Google may return 200 or 301 depending on various factors
  13268. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13269. res->status == StatusCode::MovedPermanently_301);
  13270. }
  13271. TEST(SSLClientTest, ServerNameIndication_Online) {
  13272. auto host = "httpbingo.org";
  13273. auto path = std::string{"/get"};
  13274. SSLClient cli(host, 443);
  13275. auto res = cli.Get(path);
  13276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13277. ASSERT_EQ(StatusCode::OK_200, res->status);
  13278. }
  13279. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13280. // Use a site that will cause SSL verification failure due to self-signed cert
  13281. SSLClient cli("self-signed.badssl.com", 443);
  13282. cli.enable_server_certificate_verification(true);
  13283. auto res = cli.Get("/");
  13284. ASSERT_TRUE(!res);
  13285. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13286. // Verify backend error is captured for SSLServerVerification
  13287. // This occurs when certificate verification fails
  13288. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13289. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13290. EXPECT_NE(0UL, res.ssl_backend_error());
  13291. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13292. // For OpenSSL, ssl_error is 0 for verification errors
  13293. EXPECT_EQ(0, res.ssl_error());
  13294. #if !defined(_WIN32) || \
  13295. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13296. // On non-Windows or when Windows Schannel is disabled, the error comes
  13297. // from OpenSSL's verification
  13298. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13299. res.ssl_backend_error());
  13300. #endif
  13301. #endif
  13302. }
  13303. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13304. // Use a site where hostname doesn't match the certificate
  13305. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13306. SSLClient cli("wrong.host.badssl.com", 443);
  13307. cli.enable_server_certificate_verification(true);
  13308. cli.enable_server_hostname_verification(true);
  13309. auto res = cli.Get("/");
  13310. ASSERT_TRUE(!res);
  13311. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13312. // Verify backend error is captured for hostname verification failure
  13313. EXPECT_NE(0UL, res.ssl_backend_error());
  13314. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13315. // For OpenSSL, ssl_error is 0 for verification errors
  13316. EXPECT_EQ(0, res.ssl_error());
  13317. #if !defined(_WIN32) || \
  13318. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13319. // On non-Windows or when Windows Schannel is disabled, the error comes
  13320. // from OpenSSL's hostname verification
  13321. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13322. res.ssl_backend_error());
  13323. #endif
  13324. #endif
  13325. }
  13326. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13327. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13328. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13329. SSLClient cli("www.google.com", 443);
  13330. cli.enable_server_certificate_verification(true);
  13331. auto res = cli.Get("/");
  13332. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13333. }
  13334. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13335. SSLClient cli("www.google.com", 443);
  13336. cli.enable_server_certificate_verification(true);
  13337. cli.enable_windows_certificate_verification(false);
  13338. auto res = cli.Get("/");
  13339. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13340. }
  13341. // The server sends an intermediate cross-signed by a root Windows trusts,
  13342. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13343. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13344. SSLClient cli("accounts.spotify.com", 443);
  13345. auto res = cli.Get("/");
  13346. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13347. << " ssl_backend_error=" << res.ssl_backend_error();
  13348. }
  13349. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13350. // policy status, which no backend reports for a self-signed certificate.
  13351. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13352. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13353. ASSERT_TRUE(svr.is_valid());
  13354. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13355. auto se = detail::scope_exit([&] {
  13356. svr.stop();
  13357. t.join();
  13358. ASSERT_FALSE(svr.is_running());
  13359. });
  13360. svr.wait_until_ready();
  13361. SSLClient cli("127.0.0.1", PORT);
  13362. cli.set_connection_timeout(30);
  13363. auto res = cli.Get("/");
  13364. ASSERT_FALSE(res);
  13365. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13366. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13367. }
  13368. #endif
  13369. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13370. Client cli("https://google.com");
  13371. auto res = cli.Get("/");
  13372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13373. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13374. }
  13375. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13376. SSLClient cli("google.com");
  13377. cli.set_ca_cert_path(CA_CERT_FILE);
  13378. auto res = cli.Get("/");
  13379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13380. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13381. }
  13382. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13383. SSLClient cli("google.com");
  13384. cli.enable_server_certificate_verification(true);
  13385. cli.set_ca_cert_path("hello");
  13386. auto res = cli.Get("/");
  13387. ASSERT_TRUE(!res);
  13388. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13389. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13390. // should be set
  13391. EXPECT_EQ(0, res.ssl_error());
  13392. // Verify backend error is captured for SSLLoadingCerts
  13393. // This error occurs when loading CA certificates fails
  13394. EXPECT_NE(0UL, res.ssl_backend_error());
  13395. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13396. // OpenSSL specific error codes:
  13397. // > openssl errstr 0x80000002
  13398. // error:80000002:system library::No such file or directory
  13399. // > openssl errstr 0xA000126
  13400. // error:0A000126:SSL routines::unexpected eof while reading
  13401. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13402. res.ssl_backend_error() == 0xA000126);
  13403. #endif
  13404. }
  13405. TEST(SSLClientTest, ServerCertificateVerification4) {
  13406. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13407. ASSERT_TRUE(svr.is_valid());
  13408. svr.Get("/test", [&](const Request &, Response &res) {
  13409. res.set_content("test", "text/plain");
  13410. svr.stop();
  13411. ASSERT_TRUE(true);
  13412. });
  13413. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13414. auto se = detail::scope_exit([&] {
  13415. t.join();
  13416. ASSERT_FALSE(svr.is_running());
  13417. });
  13418. svr.wait_until_ready();
  13419. SSLClient cli("127.0.0.1", PORT);
  13420. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13421. cli.enable_server_certificate_verification(true);
  13422. cli.set_connection_timeout(30);
  13423. auto res = cli.Get("/test");
  13424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13425. ASSERT_EQ(StatusCode::OK_200, res->status);
  13426. }
  13427. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13428. std::string cert;
  13429. read_file(CA_CERT_FILE, cert);
  13430. SSLClient cli("google.com");
  13431. cli.load_ca_cert_store(cert.data(), cert.size());
  13432. const auto res = cli.Get("/");
  13433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13434. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13435. }
  13436. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13437. // clang-format off
  13438. static constexpr char cert[] =
  13439. "GlobalSign Root CA\n"
  13440. "==================\n"
  13441. "-----BEGIN CERTIFICATE-----\n"
  13442. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13443. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13444. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13445. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13446. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13447. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13448. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13449. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13450. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13451. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13452. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13453. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13454. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13455. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13456. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13457. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13458. "-----END CERTIFICATE-----\n";
  13459. // clang-format on
  13460. SSLClient cli("google.com");
  13461. cli.load_ca_cert_store(cert, sizeof(cert));
  13462. const auto res = cli.Get("/");
  13463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13464. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13465. }
  13466. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13467. SSLClient cli("www.youtube.com");
  13468. cli.set_ca_cert_path(CA_CERT_FILE);
  13469. cli.enable_server_certificate_verification(true);
  13470. cli.set_follow_location(true);
  13471. auto res = cli.Get("/");
  13472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13473. ASSERT_EQ(StatusCode::OK_200, res->status);
  13474. }
  13475. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13476. SSLClient cli("wWw.YouTube.Com");
  13477. cli.set_ca_cert_path(CA_CERT_FILE);
  13478. cli.enable_server_certificate_verification(true);
  13479. cli.enable_server_hostname_verification(true);
  13480. cli.set_follow_location(true);
  13481. auto res = cli.Get("/");
  13482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13483. ASSERT_EQ(StatusCode::OK_200, res->status);
  13484. }
  13485. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13486. SSLClient cli("gOoGlE.COm");
  13487. cli.enable_server_certificate_verification(true);
  13488. cli.enable_server_hostname_verification(true);
  13489. cli.set_follow_location(true);
  13490. auto res = cli.Get("/");
  13491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13492. ASSERT_EQ(StatusCode::OK_200, res->status);
  13493. }
  13494. TEST(SSLClientTest, Issue2004_Online) {
  13495. Client client("https://google.com");
  13496. client.set_follow_location(true);
  13497. auto res = client.Get("/");
  13498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13499. ASSERT_EQ(StatusCode::OK_200, res->status);
  13500. auto body = res->body;
  13501. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13502. }
  13503. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13504. // Create SSLClient with invalid cert/key to make is_valid() return false
  13505. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13506. "nonexistent_key.pem");
  13507. // is_valid() should be false due to cert loading failure
  13508. ASSERT_FALSE(cli.is_valid());
  13509. auto res = cli.Get("/");
  13510. ASSERT_FALSE(res);
  13511. EXPECT_EQ(Error::SSLConnection, res.error());
  13512. }
  13513. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13514. // Test for Issue #2251: SSL error not properly reported when client cert
  13515. // and key paths are swapped or mismatched
  13516. // This simulates the scenario where user accidentally swaps the cert and key
  13517. // files
  13518. // Using client cert file as private key and vice versa (completely wrong)
  13519. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13520. // Should fail validation due to cert/key mismatch
  13521. ASSERT_FALSE(cli.is_valid());
  13522. // Attempt to make a request should fail with proper error
  13523. auto res = cli.Get("/");
  13524. ASSERT_FALSE(res);
  13525. EXPECT_EQ(Error::SSLConnection, res.error());
  13526. // SSL error should be recorded in the Result object (this is the key fix for
  13527. // Issue #2251)
  13528. auto backend_error = res.ssl_backend_error();
  13529. EXPECT_NE(0u, backend_error);
  13530. }
  13531. // Tests cert/key mismatch detection at the TLS context level
  13532. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13533. // Test that using mismatched cert/key causes connection failure.
  13534. // We verify this at the SSLClient level rather than through internal
  13535. // TLS API functions.
  13536. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13537. cli.enable_server_certificate_verification(false);
  13538. cli.set_connection_timeout(2);
  13539. // The mismatch should cause a connection or handshake error
  13540. auto res = cli.Get("/test");
  13541. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13542. // Either way, the request should fail
  13543. EXPECT_FALSE(res);
  13544. }
  13545. #endif
  13546. #if 0
  13547. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13548. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13549. ASSERT_TRUE(cli != nullptr);
  13550. cli->set_address_family(AF_INET6);
  13551. cli->set_interface("en0");
  13552. auto res = cli->Get("/get");
  13553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13554. ASSERT_EQ(StatusCode::OK_200, res->status);
  13555. }
  13556. #endif
  13557. // Client certificate tests - work with all TLS backends
  13558. #ifdef CPPHTTPLIB_SSL_ENABLED
  13559. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13560. void ClientCertPresent(
  13561. const std::string &client_cert_file,
  13562. const std::string &client_private_key_file,
  13563. const std::string &client_encrypted_private_key_pass = std::string(),
  13564. const ClientCertServerSetup &setup = nullptr) {
  13565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13566. ASSERT_TRUE(svr.is_valid());
  13567. if (setup) { setup(svr); }
  13568. svr.Get("/test", [&](const Request &req, Response &res) {
  13569. res.set_content("test", "text/plain");
  13570. auto cert = req.peer_cert();
  13571. ASSERT_TRUE(static_cast<bool>(cert));
  13572. std::string common_name = cert.subject_cn();
  13573. EXPECT_EQ("Common Name", common_name);
  13574. });
  13575. auto port = svr.bind_to_any_port(HOST);
  13576. ASSERT_LT(0, port);
  13577. thread t = thread([&]() { svr.listen_after_bind(); });
  13578. auto se = detail::scope_exit([&] {
  13579. svr.stop();
  13580. t.join();
  13581. ASSERT_FALSE(svr.is_running());
  13582. });
  13583. svr.wait_until_ready();
  13584. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13585. client_encrypted_private_key_pass);
  13586. cli.enable_server_certificate_verification(false);
  13587. cli.set_connection_timeout(30);
  13588. auto res = cli.Get("/test");
  13589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13590. ASSERT_EQ(StatusCode::OK_200, res->status);
  13591. }
  13592. TEST(SSLClientServerTest, ClientCertPresent) {
  13593. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13594. }
  13595. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13596. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13597. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13598. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13599. }
  13600. // Expects svr, which must require client certificates, to reject a client
  13601. // that has none
  13602. void RejectsClientWithoutCert(SSLServer &svr) {
  13603. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13604. auto port = svr.bind_to_any_port(HOST);
  13605. ASSERT_LT(0, port);
  13606. thread t = thread([&]() { svr.listen_after_bind(); });
  13607. auto se = detail::scope_exit([&] {
  13608. svr.stop();
  13609. t.join();
  13610. ASSERT_FALSE(svr.is_running());
  13611. });
  13612. svr.wait_until_ready();
  13613. SSLClient cli(HOST, port);
  13614. cli.set_connection_timeout(30);
  13615. // Skip the server certificate check, so that the request fails because the
  13616. // client certificate is missing rather than because cert.pem is not trusted
  13617. cli.enable_server_certificate_verification(false);
  13618. auto res = cli.Get("/test");
  13619. ASSERT_FALSE(res);
  13620. // The server rejects the client during the handshake, or on TLS 1.3 right
  13621. // after it, which the client notices on its first write or read
  13622. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13623. res.error() == Error::Write || res.error() == Error::Read)
  13624. << to_string(res.error());
  13625. if (res.error() == Error::SSLConnection) {
  13626. EXPECT_NE(0UL, res.ssl_backend_error());
  13627. }
  13628. // A rejection noticed on the write keeps the TLS error the write hit
  13629. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13630. }
  13631. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13632. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13633. ASSERT_TRUE(svr.is_valid());
  13634. if (setup) { setup(svr); }
  13635. RejectsClientWithoutCert(svr);
  13636. }
  13637. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13638. // A server that requires client certificates must keep requiring them after
  13639. // setup changes it, and keep accepting a client that has one
  13640. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13641. ClientCertMissing(setup);
  13642. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13643. setup);
  13644. }
  13645. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13646. ClientCertStillRequired([](SSLServer &svr) {
  13647. ASSERT_TRUE(tls::set_verify_callback(
  13648. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13649. });
  13650. }
  13651. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13652. ClientCertStillRequired([](SSLServer &svr) {
  13653. ASSERT_TRUE(tls::set_verify_callback(
  13654. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13655. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13656. });
  13657. }
  13658. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13659. ClientCertStillRequired([](SSLServer &svr) {
  13660. std::string cert_pem, key_pem, ca_pem;
  13661. read_file(SERVER_CERT_FILE, cert_pem);
  13662. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13663. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13664. ASSERT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  13665. ca_pem.c_str()));
  13666. });
  13667. }
  13668. // A TLS error from one request must not show up in a later request's Result
  13669. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13671. ASSERT_TRUE(svr.is_valid());
  13672. svr.Get("/test", [](const Request &, Response &res) {
  13673. res.set_content("test", "text/plain");
  13674. });
  13675. auto port = svr.bind_to_any_port(HOST);
  13676. ASSERT_LT(0, port);
  13677. thread t = thread([&]() { svr.listen_after_bind(); });
  13678. auto se = detail::scope_exit([&] {
  13679. svr.stop();
  13680. t.join();
  13681. ASSERT_FALSE(svr.is_running());
  13682. });
  13683. svr.wait_until_ready();
  13684. SSLClient cli(HOST, port);
  13685. cli.set_connection_timeout(30);
  13686. cli.enable_server_hostname_verification(false);
  13687. // cert.pem is not trusted, so the handshake fails
  13688. ASSERT_FALSE(cli.Get("/test"));
  13689. cli.enable_server_certificate_verification(false);
  13690. auto res = cli.Get("/test");
  13691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13692. EXPECT_EQ(0, res.ssl_error());
  13693. EXPECT_EQ(0UL, res.ssl_backend_error());
  13694. }
  13695. // PEM memory-based constructor tests (works with all TLS backends).
  13696. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13697. // terminator after it.
  13698. void PemMemoryClientCertPresent(
  13699. const std::string &client_cert_file,
  13700. const std::string &client_private_key_file,
  13701. const std::string &client_encrypted_private_key_pass = std::string(),
  13702. bool exact_size = false) {
  13703. // Read PEM files into memory
  13704. std::string server_cert_pem, server_key_pem;
  13705. std::string client_ca_pem;
  13706. std::string client_cert_pem, client_key_pem;
  13707. read_file(SERVER_CERT_FILE, server_cert_pem);
  13708. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13709. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13710. read_file(client_cert_file, client_cert_pem);
  13711. read_file(client_private_key_file, client_key_pem);
  13712. std::list<std::vector<char>> exact_copies;
  13713. auto data = [&](const std::string &pem) -> const char * {
  13714. if (!exact_size) { return pem.c_str(); }
  13715. exact_copies.emplace_back(pem.begin(), pem.end());
  13716. return exact_copies.back().data();
  13717. };
  13718. // Create server with PEM memory
  13719. SSLServer::PemMemory server_pem = {
  13720. data(server_cert_pem),
  13721. server_cert_pem.size(),
  13722. data(server_key_pem),
  13723. server_key_pem.size(),
  13724. data(client_ca_pem),
  13725. client_ca_pem.size(),
  13726. nullptr // no password for server key
  13727. };
  13728. SSLServer svr(server_pem);
  13729. ASSERT_TRUE(svr.is_valid());
  13730. svr.Get("/test", [&](const Request &req, Response &res) {
  13731. res.set_content("test", "text/plain");
  13732. auto cert = req.peer_cert();
  13733. ASSERT_TRUE(static_cast<bool>(cert));
  13734. EXPECT_EQ("Common Name", cert.subject_cn());
  13735. });
  13736. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13737. auto se = detail::scope_exit([&] {
  13738. svr.stop();
  13739. t.join();
  13740. ASSERT_FALSE(svr.is_running());
  13741. });
  13742. svr.wait_until_ready();
  13743. // Create client with PEM memory
  13744. const char *password = client_encrypted_private_key_pass.empty()
  13745. ? nullptr
  13746. : client_encrypted_private_key_pass.c_str();
  13747. SSLClient::PemMemory client_pem = {
  13748. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13749. client_key_pem.size(), password};
  13750. SSLClient cli(HOST, PORT, client_pem);
  13751. cli.enable_server_certificate_verification(false);
  13752. cli.set_connection_timeout(30);
  13753. auto res = cli.Get("/test");
  13754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13755. ASSERT_EQ(StatusCode::OK_200, res->status);
  13756. }
  13757. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13758. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13759. }
  13760. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13761. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13762. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13763. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13764. }
  13765. // A server built from PEM memory with a client CA requires client certificates
  13766. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13767. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13768. read_file(SERVER_CERT_FILE, server_cert_pem);
  13769. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13770. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13771. SSLServer::PemMemory server_pem = {
  13772. server_cert_pem.c_str(),
  13773. server_cert_pem.size(),
  13774. server_key_pem.c_str(),
  13775. server_key_pem.size(),
  13776. client_ca_pem.c_str(),
  13777. client_ca_pem.size(),
  13778. nullptr // no password for server key
  13779. };
  13780. SSLServer svr(server_pem);
  13781. ASSERT_TRUE(svr.is_valid());
  13782. RejectsClientWithoutCert(svr);
  13783. }
  13784. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13785. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13786. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13787. true);
  13788. }
  13789. // A length shorter than the PEM cuts it short, so it no longer loads
  13790. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13791. std::string cert, key;
  13792. read_file(SERVER_CERT_FILE, cert);
  13793. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13794. for (auto cut_cert : {true, false}) {
  13795. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13796. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13797. SSLServer::PemMemory server_pem = {
  13798. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13799. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13800. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13801. key_len, nullptr};
  13802. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13803. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13804. key.c_str(), key_len, nullptr};
  13805. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13806. }
  13807. }
  13808. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13809. class NoListenSSLServer : public SSLServer {
  13810. public:
  13811. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13812. const char *client_ca_cert_file_path,
  13813. const char *client_ca_cert_dir_path = nullptr)
  13814. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13815. client_ca_cert_dir_path),
  13816. stop_(false) {}
  13817. std::atomic_bool stop_;
  13818. private:
  13819. bool process_and_close_socket(socket_t /*sock*/) override {
  13820. // Don't create SSL context
  13821. while (!stop_.load()) {
  13822. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13823. }
  13824. return true;
  13825. }
  13826. };
  13827. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13828. CLIENT_CA_CERT_FILE);
  13829. ASSERT_TRUE(svr.is_valid());
  13830. svr.Get("/test", [&](const Request &, Response &res) {
  13831. res.set_content("test", "text/plain");
  13832. });
  13833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13834. auto se = detail::scope_exit([&] {
  13835. svr.stop_ = true;
  13836. svr.stop();
  13837. t.join();
  13838. ASSERT_FALSE(svr.is_running());
  13839. });
  13840. svr.wait_until_ready();
  13841. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13842. cli.enable_server_certificate_verification(false);
  13843. cli.set_connection_timeout(1);
  13844. auto res = cli.Get("/test");
  13845. ASSERT_TRUE(!res);
  13846. EXPECT_EQ(Error::SSLConnection, res.error());
  13847. // Timeout results in WantRead error code (maps to backend-specific value)
  13848. EXPECT_NE(0, res.ssl_error());
  13849. }
  13850. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13851. // Test SSLServer with client certificate verification using the standard
  13852. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13854. CLIENT_CA_CERT_DIR);
  13855. ASSERT_TRUE(svr.is_valid());
  13856. svr.Get("/test", [&](const Request &req, Response &res) {
  13857. res.set_content("test", "text/plain");
  13858. auto cert = req.peer_cert();
  13859. ASSERT_TRUE(static_cast<bool>(cert));
  13860. auto common_name = cert.subject_cn();
  13861. EXPECT_EQ("Common Name", common_name);
  13862. });
  13863. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13864. auto se = detail::scope_exit([&] {
  13865. svr.stop();
  13866. t.join();
  13867. ASSERT_FALSE(svr.is_running());
  13868. });
  13869. svr.wait_until_ready();
  13870. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13871. cli.enable_server_certificate_verification(false);
  13872. cli.set_connection_timeout(30);
  13873. auto res = cli.Get("/test");
  13874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13875. ASSERT_EQ(StatusCode::OK_200, res->status);
  13876. }
  13877. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13878. // Verifies that wildcard matching and exact matching work consistently
  13879. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13880. using namespace httplib::tls;
  13881. // We need a running server to test against
  13882. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13883. ASSERT_TRUE(svr.is_valid());
  13884. svr.Get("/test", [](const Request &, Response &res) {
  13885. res.set_content("ok", "text/plain");
  13886. });
  13887. thread t([&]() { svr.listen(HOST, PORT); });
  13888. auto se = detail::scope_exit([&] {
  13889. svr.stop();
  13890. t.join();
  13891. });
  13892. svr.wait_until_ready();
  13893. bool verify_callback_called = false;
  13894. bool verify_result_wrong = false;
  13895. SSLClient cli(HOST, PORT);
  13896. cli.enable_server_certificate_verification(true);
  13897. cli.set_ca_cert_path(CA_CERT_FILE);
  13898. cli.set_connection_timeout(5);
  13899. // Note: Test certificate has CN="Common Name", not "localhost"
  13900. bool verify_result_cn = false;
  13901. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13902. verify_callback_called = true;
  13903. if (!ctx.cert) return false;
  13904. // Test 1: "Common Name" should match (our test server cert CN)
  13905. verify_result_cn = ctx.check_hostname("Common Name");
  13906. // Test 2: wrong hostname should not match
  13907. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13908. return true; // Accept for the purpose of this test
  13909. });
  13910. auto res = cli.Get("/test");
  13911. // The request may succeed or fail depending on cert configuration
  13912. // but the callback should have been called
  13913. ASSERT_TRUE(verify_callback_called)
  13914. << "Verify callback should have been called";
  13915. // CN="Common Name" should match our test certificate
  13916. //
  13917. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13918. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13919. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13920. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13921. // <openssl/base.h>, which is included transitively when
  13922. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13923. #if defined(OPENSSL_IS_BORINGSSL)
  13924. EXPECT_FALSE(verify_result_cn)
  13925. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13926. #else
  13927. EXPECT_TRUE(verify_result_cn)
  13928. << "verify_hostname should match 'Common Name' (certificate CN)";
  13929. #endif
  13930. // Wrong hostname should not match
  13931. EXPECT_FALSE(verify_result_wrong)
  13932. << "verify_hostname should not match 'wronghost.example.com'";
  13933. }
  13934. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13935. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13936. // X509_check_ip behavior and must hold for every backend.
  13937. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13938. using namespace httplib::tls;
  13939. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13940. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13941. ASSERT_TRUE(svr.is_valid());
  13942. svr.Get("/test", [](const Request &, Response &res) {
  13943. res.set_content("ok", "text/plain");
  13944. });
  13945. thread t([&]() { svr.listen(HOST, PORT); });
  13946. auto se = detail::scope_exit([&] {
  13947. svr.stop();
  13948. t.join();
  13949. });
  13950. svr.wait_until_ready();
  13951. bool verify_callback_called = false;
  13952. bool ip_matched_via_cn = true;
  13953. SSLClient cli(HOST, PORT);
  13954. cli.enable_server_certificate_verification(true);
  13955. cli.set_ca_cert_path(CA_CERT_FILE);
  13956. cli.set_connection_timeout(5);
  13957. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13958. verify_callback_called = true;
  13959. if (!ctx.cert) return false;
  13960. // The IP appears only in the CN, so it must NOT be accepted.
  13961. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13962. return true; // Accept for the purpose of this test
  13963. });
  13964. cli.Get("/test");
  13965. ASSERT_TRUE(verify_callback_called)
  13966. << "Verify callback should have been called";
  13967. EXPECT_FALSE(ip_matched_via_cn)
  13968. << "An IP host must not be authenticated via the certificate CN";
  13969. }
  13970. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13971. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13972. using namespace httplib::tls;
  13973. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13974. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13975. ASSERT_TRUE(svr.is_valid());
  13976. svr.Get("/test", [](const Request &, Response &res) {
  13977. res.set_content("ok", "text/plain");
  13978. });
  13979. thread t([&]() { svr.listen(HOST, PORT); });
  13980. auto se = detail::scope_exit([&] {
  13981. svr.stop();
  13982. t.join();
  13983. });
  13984. svr.wait_until_ready();
  13985. bool verify_callback_called = false;
  13986. bool san_matched = false;
  13987. bool wrong_ipv6_matched = true;
  13988. bool cn_ipv6_matched = true;
  13989. SSLClient cli(HOST, PORT);
  13990. cli.enable_server_certificate_verification(true);
  13991. cli.set_ca_cert_path(CA_CERT_FILE);
  13992. cli.set_connection_timeout(5);
  13993. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13994. verify_callback_called = true;
  13995. if (!ctx.cert) return false;
  13996. // Matches the IPv6 iPAddress SAN.
  13997. san_matched = ctx.check_hostname("2001:db8::1");
  13998. // A different IPv6 address must not match.
  13999. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14000. // "::1" lives only in the CN, so it must not be accepted.
  14001. cn_ipv6_matched = ctx.check_hostname("::1");
  14002. return true; // Accept for the purpose of this test
  14003. });
  14004. cli.Get("/test");
  14005. ASSERT_TRUE(verify_callback_called)
  14006. << "Verify callback should have been called";
  14007. EXPECT_TRUE(san_matched)
  14008. << "verify_hostname should match an IPv6 iPAddress SAN";
  14009. EXPECT_FALSE(wrong_ipv6_matched)
  14010. << "verify_hostname should not match a non-matching IPv6 address";
  14011. EXPECT_FALSE(cn_ipv6_matched)
  14012. << "An IPv6 host must not be authenticated via the certificate CN";
  14013. }
  14014. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14015. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14016. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14017. using namespace httplib::tls;
  14018. // SANs: DNS:a.zz, IP:42.46.122.122
  14019. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14020. ASSERT_TRUE(svr.is_valid());
  14021. svr.Get("/test", [](const Request &, Response &res) {
  14022. res.set_content("ok", "text/plain");
  14023. });
  14024. auto port = svr.bind_to_any_port(HOST);
  14025. thread t([&]() { svr.listen_after_bind(); });
  14026. auto se = detail::scope_exit([&] {
  14027. svr.stop();
  14028. t.join();
  14029. });
  14030. svr.wait_until_ready();
  14031. bool verify_callback_called = false;
  14032. bool dns_san_matched = false;
  14033. bool ip_san_matched = false;
  14034. bool ip_matched_via_dns_san = true;
  14035. bool dns_matched_via_ip_san = true;
  14036. bool cn_matched_next_to_dns_san = true;
  14037. SSLClient cli(HOST, port);
  14038. cli.enable_server_certificate_verification(true);
  14039. cli.set_ca_cert_path(CA_CERT_FILE);
  14040. cli.set_connection_timeout(5);
  14041. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14042. verify_callback_called = true;
  14043. if (!ctx.cert) return false;
  14044. dns_san_matched = ctx.check_hostname("a.zz");
  14045. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14046. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14047. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14048. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14049. return true; // Accept for the purpose of this test
  14050. });
  14051. cli.Get("/test");
  14052. ASSERT_TRUE(verify_callback_called)
  14053. << "Verify callback should have been called";
  14054. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14055. EXPECT_TRUE(ip_san_matched)
  14056. << "verify_hostname should match an iPAddress SAN";
  14057. EXPECT_FALSE(ip_matched_via_dns_san)
  14058. << "An IP host must not be authenticated via a dNSName SAN";
  14059. EXPECT_FALSE(dns_matched_via_ip_san)
  14060. << "A DNS host must not be authenticated via an iPAddress SAN";
  14061. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14062. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14063. }
  14064. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14065. // "www.*.example.test" names one host and not every host under example.test.
  14066. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14067. using namespace httplib::tls;
  14068. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14069. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14070. ASSERT_TRUE(svr.is_valid());
  14071. svr.Get("/test", [](const Request &, Response &res) {
  14072. res.set_content("ok", "text/plain");
  14073. });
  14074. auto port = svr.bind_to_any_port(HOST);
  14075. thread t([&]() { svr.listen_after_bind(); });
  14076. auto se = detail::scope_exit([&] {
  14077. svr.stop();
  14078. t.join();
  14079. });
  14080. svr.wait_until_ready();
  14081. bool verify_callback_called = false;
  14082. bool leftmost_wildcard_matched = false;
  14083. bool wildcard_spanned_labels = true;
  14084. bool inner_wildcard_matched = true;
  14085. SSLClient cli(HOST, port);
  14086. cli.enable_server_certificate_verification(true);
  14087. cli.set_ca_cert_path(CA_CERT_FILE);
  14088. cli.set_connection_timeout(5);
  14089. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14090. verify_callback_called = true;
  14091. if (!ctx.cert) return false;
  14092. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14093. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14094. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14095. return true; // Accept for the purpose of this test
  14096. });
  14097. cli.Get("/test");
  14098. ASSERT_TRUE(verify_callback_called)
  14099. << "Verify callback should have been called";
  14100. EXPECT_TRUE(leftmost_wildcard_matched)
  14101. << "A leftmost wildcard should match a single label";
  14102. EXPECT_FALSE(wildcard_spanned_labels)
  14103. << "A wildcard label must not match more than one label";
  14104. EXPECT_FALSE(inner_wildcard_matched)
  14105. << "A wildcard outside the leftmost label must not be honoured";
  14106. }
  14107. // sans() must report each SAN entry under its own type.
  14108. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14109. using namespace httplib::tls;
  14110. // SANs: DNS:a.zz, IP:42.46.122.122
  14111. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14112. ASSERT_TRUE(svr.is_valid());
  14113. svr.Get("/test", [](const Request &, Response &res) {
  14114. res.set_content("ok", "text/plain");
  14115. });
  14116. auto port = svr.bind_to_any_port(HOST);
  14117. thread t([&]() { svr.listen_after_bind(); });
  14118. auto se = detail::scope_exit([&] {
  14119. svr.stop();
  14120. t.join();
  14121. });
  14122. svr.wait_until_ready();
  14123. bool verify_callback_called = false;
  14124. std::vector<SanEntry> sans;
  14125. SSLClient cli(HOST, port);
  14126. cli.enable_server_certificate_verification(true);
  14127. cli.set_ca_cert_path(CA_CERT_FILE);
  14128. cli.set_connection_timeout(5);
  14129. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14130. verify_callback_called = true;
  14131. if (!ctx.cert) return false;
  14132. sans = ctx.sans();
  14133. return true; // Accept for the purpose of this test
  14134. });
  14135. cli.Get("/test");
  14136. ASSERT_TRUE(verify_callback_called)
  14137. << "Verify callback should have been called";
  14138. auto has_san = [&](SanType type, const std::string &value) {
  14139. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14140. return san.type == type && san.value == value;
  14141. });
  14142. };
  14143. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14144. << "sans() should report the dNSName SAN";
  14145. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14146. << "sans() should report the iPAddress SAN";
  14147. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14148. << "sans() must not report the dNSName SAN as an address";
  14149. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14150. << "sans() must not report the iPAddress SAN as a DNS name";
  14151. }
  14152. #endif
  14153. // mbedTLS-specific callback constructor test
  14154. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14155. #ifdef CPPHTTPLIB_SSL_ENABLED
  14156. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14158. ASSERT_TRUE(svr.is_valid());
  14159. // Set up a handler to verify client certificate is present
  14160. bool client_cert_verified = false;
  14161. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14162. // Verify that client certificate was provided
  14163. client_cert_verified = true;
  14164. res.set_content("success", "text/plain");
  14165. });
  14166. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14167. auto se = detail::scope_exit([&] {
  14168. svr.stop();
  14169. t.join();
  14170. ASSERT_FALSE(svr.is_running());
  14171. });
  14172. svr.wait_until_ready();
  14173. // Client with certificate
  14174. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14175. cli.enable_server_certificate_verification(false);
  14176. cli.set_connection_timeout(30);
  14177. auto res = cli.Get("/test");
  14178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14179. ASSERT_EQ(StatusCode::OK_200, res->status);
  14180. ASSERT_TRUE(client_cert_verified);
  14181. EXPECT_EQ("success", res->body);
  14182. }
  14183. #endif
  14184. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14185. // backends
  14186. #ifdef CPPHTTPLIB_SSL_ENABLED
  14187. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14188. using namespace httplib::tls;
  14189. // Test that when client CA cert file is provided,
  14190. // the server properly requests and validates client certificates
  14191. // Create a server with client authentication
  14192. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14193. ASSERT_TRUE(svr.is_valid());
  14194. bool handler_called = false;
  14195. svr.Get("/test", [&](const Request &req, Response &res) {
  14196. handler_called = true;
  14197. // Verify that a client certificate was provided
  14198. auto cert = req.peer_cert();
  14199. ASSERT_TRUE(static_cast<bool>(cert));
  14200. // Get the issuer name
  14201. std::string issuer_str = cert.issuer_name();
  14202. ASSERT_FALSE(issuer_str.empty());
  14203. // The client certificate should be issued by our test CA
  14204. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14205. res.set_content("authenticated", "text/plain");
  14206. });
  14207. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14208. auto se = detail::scope_exit([&] {
  14209. svr.stop();
  14210. t.join();
  14211. ASSERT_FALSE(svr.is_running());
  14212. });
  14213. svr.wait_until_ready();
  14214. // Connect with a client certificate issued by the CA
  14215. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14216. cli.enable_server_certificate_verification(false);
  14217. cli.set_connection_timeout(30);
  14218. auto res = cli.Get("/test");
  14219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14220. ASSERT_EQ(StatusCode::OK_200, res->status);
  14221. ASSERT_TRUE(handler_called);
  14222. EXPECT_EQ("authenticated", res->body);
  14223. }
  14224. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14225. using namespace httplib::tls;
  14226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14227. ASSERT_TRUE(svr.is_valid());
  14228. svr.Get("/test", [](const Request &, Response &res) {
  14229. res.set_content("ok", "text/plain");
  14230. });
  14231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14232. auto se = detail::scope_exit([&] {
  14233. svr.stop();
  14234. t.join();
  14235. });
  14236. svr.wait_until_ready();
  14237. SSLClient cli(HOST, PORT);
  14238. cli.enable_server_certificate_verification(false);
  14239. cli.set_connection_timeout(30);
  14240. bool cert_checked = false;
  14241. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14242. if (ctx.cert) {
  14243. auto sans = ctx.sans();
  14244. // Test certificate may or may not have SANs - just verify the API
  14245. // works If SANs exist, verify the types are valid
  14246. for (const auto &san : sans) {
  14247. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14248. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14249. san.type == SanType::OTHER);
  14250. EXPECT_FALSE(san.value.empty());
  14251. }
  14252. cert_checked = true;
  14253. }
  14254. return true;
  14255. });
  14256. auto res = cli.Get("/test");
  14257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14258. EXPECT_TRUE(cert_checked);
  14259. }
  14260. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14261. using namespace httplib::tls;
  14262. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14263. ASSERT_TRUE(svr.is_valid());
  14264. svr.Get("/test", [](const Request &, Response &res) {
  14265. res.set_content("ok", "text/plain");
  14266. });
  14267. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14268. auto se = detail::scope_exit([&] {
  14269. svr.stop();
  14270. t.join();
  14271. });
  14272. svr.wait_until_ready();
  14273. SSLClient cli(HOST, PORT);
  14274. cli.enable_server_certificate_verification(false);
  14275. cli.set_connection_timeout(30);
  14276. bool validity_checked = false;
  14277. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14278. if (ctx.cert) {
  14279. time_t not_before = 0, not_after = 0;
  14280. bool result = ctx.validity(not_before, not_after);
  14281. EXPECT_TRUE(result);
  14282. // Verify that not_before < now < not_after for a valid cert
  14283. time_t now = time(nullptr);
  14284. EXPECT_LT(not_before, now);
  14285. EXPECT_GT(not_after, now);
  14286. validity_checked = true;
  14287. }
  14288. return true;
  14289. });
  14290. auto res = cli.Get("/test");
  14291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14292. EXPECT_TRUE(validity_checked);
  14293. }
  14294. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14295. using namespace httplib::tls;
  14296. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14297. ASSERT_TRUE(svr.is_valid());
  14298. svr.Get("/test", [](const Request &, Response &res) {
  14299. res.set_content("ok", "text/plain");
  14300. });
  14301. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14302. auto se = detail::scope_exit([&] {
  14303. svr.stop();
  14304. t.join();
  14305. });
  14306. svr.wait_until_ready();
  14307. SSLClient cli(HOST, PORT);
  14308. cli.enable_server_certificate_verification(false);
  14309. cli.set_connection_timeout(30);
  14310. bool serial_checked = false;
  14311. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14312. if (ctx.cert) {
  14313. std::string serial = ctx.serial();
  14314. EXPECT_FALSE(serial.empty());
  14315. // Serial should be a hex string
  14316. for (char c : serial) {
  14317. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14318. (c >= 'a' && c <= 'f'));
  14319. }
  14320. serial_checked = true;
  14321. }
  14322. return true;
  14323. });
  14324. auto res = cli.Get("/test");
  14325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14326. EXPECT_TRUE(serial_checked);
  14327. }
  14328. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14329. // Test 1: Valid CA file - no error should be recorded
  14330. {
  14331. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14332. CLIENT_CA_CERT_FILE);
  14333. ASSERT_TRUE(svr.is_valid());
  14334. // With valid setup, last_ssl_error should be 0
  14335. EXPECT_EQ(0, svr.ssl_last_error());
  14336. }
  14337. // Test 2: Invalid CA file content
  14338. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14339. {
  14340. // Create a temporary file with completely invalid content
  14341. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14342. {
  14343. std::ofstream ofs(temp_invalid_ca);
  14344. ofs << "This is not a certificate file at all\n";
  14345. ofs << "Just plain text content\n";
  14346. }
  14347. // Create server with invalid CA file
  14348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14349. // Clean up temporary file
  14350. std::remove(temp_invalid_ca);
  14351. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14352. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14353. // Note: SSL_CTX_load_verify_locations typically fails first,
  14354. // but our error handling code path is still exercised
  14355. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14356. }
  14357. }
  14358. TEST(VerifyCallbackTest, VerifyContextFields) {
  14359. using namespace httplib::tls;
  14360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14361. ASSERT_TRUE(svr.is_valid());
  14362. svr.Get("/test", [](const Request &, Response &res) {
  14363. res.set_content("ok", "text/plain");
  14364. });
  14365. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14366. auto se = detail::scope_exit([&] {
  14367. svr.stop();
  14368. t.join();
  14369. });
  14370. svr.wait_until_ready();
  14371. SSLClient cli(HOST, PORT);
  14372. cli.enable_server_certificate_verification(false);
  14373. cli.set_connection_timeout(30);
  14374. int callback_count = 0;
  14375. bool saw_leaf_cert = false;
  14376. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14377. if (ctx.cert) {
  14378. callback_count++;
  14379. // We should see at least one certificate (the leaf)
  14380. std::string cn = ctx.subject_cn();
  14381. if (!cn.empty()) { saw_leaf_cert = true; }
  14382. // Verify context fields are populated
  14383. EXPECT_NE(ctx.session, nullptr);
  14384. EXPECT_GE(ctx.depth, 0);
  14385. }
  14386. return true;
  14387. });
  14388. auto res = cli.Get("/test");
  14389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14390. EXPECT_GT(callback_count, 0);
  14391. EXPECT_TRUE(saw_leaf_cert);
  14392. }
  14393. // A verifier that accepts runs alongside the built-in verification, and is the
  14394. // only check once that is turned off.
  14395. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14396. using namespace httplib::tls;
  14397. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14398. ASSERT_TRUE(svr.is_valid());
  14399. svr.Get("/test", [](const Request &, Response &res) {
  14400. res.set_content("ok", "text/plain");
  14401. });
  14402. auto port = svr.bind_to_any_port(HOST);
  14403. thread t([&]() { svr.listen_after_bind(); });
  14404. auto se = detail::scope_exit([&] {
  14405. svr.stop();
  14406. t.join();
  14407. });
  14408. svr.wait_until_ready();
  14409. SSLClient cli(HOST, port);
  14410. cli.enable_server_hostname_verification(false);
  14411. auto calls = 0;
  14412. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14413. calls++;
  14414. return true;
  14415. });
  14416. // cert.pem is not trusted
  14417. auto res = cli.Get("/test");
  14418. ASSERT_FALSE(res);
  14419. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14420. EXPECT_GT(calls, 0);
  14421. cli.enable_server_certificate_verification(false);
  14422. res = cli.Get("/test");
  14423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14424. EXPECT_EQ("ok", res->body);
  14425. }
  14426. // A verifier belongs to the client that set it, not to the thread that set it.
  14427. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14428. using namespace httplib::tls;
  14429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14430. ASSERT_TRUE(svr.is_valid());
  14431. svr.Get("/test", [](const Request &, Response &res) {
  14432. res.set_content("ok", "text/plain");
  14433. });
  14434. auto port = svr.bind_to_any_port(HOST);
  14435. thread t([&]() { svr.listen_after_bind(); });
  14436. auto se = detail::scope_exit([&] {
  14437. svr.stop();
  14438. t.join();
  14439. });
  14440. svr.wait_until_ready();
  14441. auto rejecting_calls = 0;
  14442. SSLClient rejecting(HOST, port);
  14443. rejecting.enable_server_certificate_verification(false);
  14444. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14445. rejecting_calls++;
  14446. return false;
  14447. });
  14448. auto accepting_calls = 0;
  14449. SSLClient accepting(HOST, port);
  14450. accepting.enable_server_certificate_verification(false);
  14451. // Set on another thread than the requests below.
  14452. thread([&]() {
  14453. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14454. accepting_calls++;
  14455. return true;
  14456. });
  14457. }).join();
  14458. // Requested on another thread than the verifier was set on.
  14459. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14460. EXPECT_GT(rejecting_calls, 0);
  14461. auto res = accepting.Get("/test");
  14462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14463. EXPECT_GT(accepting_calls, 0);
  14464. }
  14465. // A verifier replaced while a handshake runs it lives until it returns.
  14466. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14467. using namespace httplib::tls;
  14468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14469. ASSERT_TRUE(svr.is_valid());
  14470. svr.Get("/test", [](const Request &, Response &res) {
  14471. res.set_content("ok", "text/plain");
  14472. });
  14473. auto port = svr.bind_to_any_port(HOST);
  14474. thread t([&]() { svr.listen_after_bind(); });
  14475. auto se = detail::scope_exit([&] {
  14476. svr.stop();
  14477. t.join();
  14478. });
  14479. svr.wait_until_ready();
  14480. SSLClient cli(HOST, port);
  14481. cli.enable_server_certificate_verification(false);
  14482. std::promise<void> entered;
  14483. std::promise<void> replaced;
  14484. auto replaced_future = replaced.get_future();
  14485. auto first_call = true;
  14486. // Long enough to live on the heap
  14487. std::string expected(64, 'v');
  14488. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14489. if (first_call) {
  14490. first_call = false;
  14491. entered.set_value();
  14492. replaced_future.wait();
  14493. }
  14494. return expected == std::string(64, 'v');
  14495. });
  14496. thread request([&]() {
  14497. auto res = cli.Get("/test");
  14498. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14499. });
  14500. entered.get_future().wait();
  14501. cli.set_server_certificate_verifier(
  14502. [](const VerifyContext &) { return true; });
  14503. replaced.set_value();
  14504. request.join();
  14505. }
  14506. // VerifyContext::session is the same handle the other tls:: functions take.
  14507. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14508. using namespace httplib::tls;
  14509. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14510. ASSERT_TRUE(svr.is_valid());
  14511. svr.Get("/test", [](const Request &, Response &res) {
  14512. res.set_content("ok", "text/plain");
  14513. });
  14514. auto port = svr.bind_to_any_port(HOST);
  14515. thread t([&]() { svr.listen_after_bind(); });
  14516. auto se = detail::scope_exit([&] {
  14517. svr.stop();
  14518. t.join();
  14519. });
  14520. svr.wait_until_ready();
  14521. SSLClient cli(HOST, port);
  14522. cli.enable_server_certificate_verification(false);
  14523. session_t verifier_session = nullptr;
  14524. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14525. verifier_session = ctx.session;
  14526. return true;
  14527. });
  14528. session_t session_verifier_session = nullptr;
  14529. cli.set_session_verifier([&](session_t session) {
  14530. session_verifier_session = session;
  14531. return SSLVerifierResponse::NoDecisionMade;
  14532. });
  14533. auto res = cli.Get("/test");
  14534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14535. EXPECT_NE(nullptr, verifier_session);
  14536. EXPECT_EQ(session_verifier_session, verifier_session);
  14537. }
  14538. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14539. using httplib::tls::TlsError;
  14540. // Test that verify_error_to_string returns empty for success
  14541. std::string success_str = TlsError::verify_error_to_string(0);
  14542. EXPECT_TRUE(success_str.empty());
  14543. // Test that verify_error_to_string returns non-empty for error codes
  14544. // Using a common error code (certificate expired)
  14545. std::string error_str =
  14546. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14547. EXPECT_FALSE(error_str.empty());
  14548. }
  14549. TEST(SessionVerifierTest, CertificateAccepted) {
  14550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14551. ASSERT_TRUE(svr.is_valid());
  14552. svr.Get("/test", [](const Request &, Response &res) {
  14553. res.set_content("ok", "text/plain");
  14554. });
  14555. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14556. auto se = detail::scope_exit([&] {
  14557. svr.stop();
  14558. t.join();
  14559. });
  14560. svr.wait_until_ready();
  14561. SSLClient cli(HOST, PORT);
  14562. cli.enable_server_certificate_verification(false);
  14563. cli.set_connection_timeout(30);
  14564. bool callback_called = false;
  14565. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14566. EXPECT_NE(session, nullptr);
  14567. callback_called = true;
  14568. return SSLVerifierResponse::CertificateAccepted;
  14569. });
  14570. auto res = cli.Get("/test");
  14571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14572. EXPECT_EQ(200, res->status);
  14573. EXPECT_TRUE(callback_called);
  14574. }
  14575. TEST(SessionVerifierTest, CertificateRejected) {
  14576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14577. ASSERT_TRUE(svr.is_valid());
  14578. svr.Get("/test", [](const Request &, Response &res) {
  14579. res.set_content("ok", "text/plain");
  14580. });
  14581. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14582. auto se = detail::scope_exit([&] {
  14583. svr.stop();
  14584. t.join();
  14585. });
  14586. svr.wait_until_ready();
  14587. SSLClient cli(HOST, PORT);
  14588. cli.enable_server_certificate_verification(false);
  14589. cli.set_connection_timeout(30);
  14590. bool callback_called = false;
  14591. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14592. EXPECT_NE(session, nullptr);
  14593. callback_called = true;
  14594. return SSLVerifierResponse::CertificateRejected;
  14595. });
  14596. auto res = cli.Get("/test");
  14597. EXPECT_FALSE(res);
  14598. EXPECT_TRUE(callback_called);
  14599. }
  14600. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14602. ASSERT_TRUE(svr.is_valid());
  14603. svr.Get("/test", [](const Request &, Response &res) {
  14604. res.set_content("ok", "text/plain");
  14605. });
  14606. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14607. auto se = detail::scope_exit([&] {
  14608. svr.stop();
  14609. t.join();
  14610. });
  14611. svr.wait_until_ready();
  14612. // NoDecisionMade with verification disabled should succeed (no default check)
  14613. SSLClient cli(HOST, PORT);
  14614. cli.enable_server_certificate_verification(false);
  14615. cli.set_connection_timeout(30);
  14616. bool callback_called = false;
  14617. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14618. EXPECT_NE(session, nullptr);
  14619. callback_called = true;
  14620. return SSLVerifierResponse::NoDecisionMade;
  14621. });
  14622. auto res = cli.Get("/test");
  14623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14624. EXPECT_EQ(200, res->status);
  14625. EXPECT_TRUE(callback_called);
  14626. }
  14627. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14629. ASSERT_TRUE(svr.is_valid());
  14630. svr.Get("/test", [](const Request &, Response &res) {
  14631. res.set_content("ok", "text/plain");
  14632. });
  14633. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14634. auto se = detail::scope_exit([&] {
  14635. svr.stop();
  14636. t.join();
  14637. });
  14638. svr.wait_until_ready();
  14639. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14640. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14641. // so we only check that the request fails, not whether the callback was
  14642. // called.
  14643. SSLClient cli(HOST, PORT);
  14644. cli.enable_server_certificate_verification(true);
  14645. cli.set_connection_timeout(30);
  14646. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14647. EXPECT_NE(session, nullptr);
  14648. return SSLVerifierResponse::NoDecisionMade;
  14649. });
  14650. auto res = cli.Get("/test");
  14651. EXPECT_FALSE(res);
  14652. }
  14653. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14654. // Test SSL server using PemMemory constructor with client CA certificates
  14655. // Read PEM files
  14656. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14657. read_file(SERVER_CERT_FILE, server_cert_pem);
  14658. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14659. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14660. // Create SSLServer with PemMemory constructor including client CA
  14661. SSLServer::PemMemory server_pem = {
  14662. server_cert_pem.c_str(),
  14663. server_cert_pem.size(),
  14664. server_key_pem.c_str(),
  14665. server_key_pem.size(),
  14666. client_ca_pem.c_str(),
  14667. client_ca_pem.size(),
  14668. nullptr // no password for server key
  14669. };
  14670. SSLServer svr(server_pem);
  14671. ASSERT_TRUE(svr.is_valid());
  14672. // No SSL error should be recorded for valid setup
  14673. EXPECT_EQ(0, svr.ssl_last_error());
  14674. // Set up server endpoints
  14675. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14676. res.set_content("ok", "text/plain");
  14677. });
  14678. // Start server in a thread
  14679. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14680. svr.wait_until_ready();
  14681. // Connect with client certificate (using constructor with paths)
  14682. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14683. cli.enable_server_certificate_verification(false);
  14684. auto res = cli.Get("/test-pem-ca");
  14685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14686. EXPECT_EQ(200, res->status);
  14687. EXPECT_EQ("ok", res->body);
  14688. svr.stop();
  14689. server_thread.join();
  14690. }
  14691. #endif
  14692. #ifdef _WIN32
  14693. TEST(CleanupTest, WSACleanup) {
  14694. int ret = WSACleanup();
  14695. ASSERT_EQ(0, ret);
  14696. }
  14697. #endif
  14698. #ifndef CPPHTTPLIB_SSL_ENABLED
  14699. TEST(NoSSLSupport, SimpleInterface) {
  14700. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14701. }
  14702. #endif
  14703. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14704. TEST(InvalidScheme, SimpleInterface) {
  14705. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14706. }
  14707. #endif
  14708. TEST(NoScheme, SimpleInterface) {
  14709. Client cli("yahoo.com:80");
  14710. ASSERT_TRUE(cli.is_valid());
  14711. }
  14712. TEST(SendAPI, SimpleInterface_Online) {
  14713. Client cli("http://yahoo.com");
  14714. Request req;
  14715. req.method = "GET";
  14716. req.path = "/";
  14717. auto res = cli.send(req);
  14718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14719. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14720. }
  14721. TEST(SendAPI, WithParamsInRequest) {
  14722. Server svr;
  14723. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14724. EXPECT_TRUE(req.has_param("test"));
  14725. EXPECT_EQ("test_value", req.get_param_value("test"));
  14726. });
  14727. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14728. auto se = detail::scope_exit([&] {
  14729. svr.stop();
  14730. t.join();
  14731. ASSERT_FALSE(svr.is_running());
  14732. });
  14733. svr.wait_until_ready();
  14734. Client cli(HOST, PORT);
  14735. {
  14736. Request req;
  14737. req.method = "GET";
  14738. req.path = "/";
  14739. req.params.emplace("test", "test_value");
  14740. auto res = cli.send(req);
  14741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14742. }
  14743. {
  14744. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14746. }
  14747. }
  14748. TEST(ClientImplMethods, GetSocketTest) {
  14749. httplib::Server svr;
  14750. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14751. res.status = StatusCode::OK_200;
  14752. });
  14753. auto port = svr.bind_to_any_port("127.0.0.1");
  14754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14755. auto se = detail::scope_exit([&] {
  14756. svr.stop();
  14757. thread.join();
  14758. ASSERT_FALSE(svr.is_running());
  14759. });
  14760. svr.wait_until_ready();
  14761. {
  14762. httplib::Client cli("127.0.0.1", port);
  14763. cli.set_keep_alive(true);
  14764. // Use the behavior of cpp-httplib of opening the connection
  14765. // only when the first request happens. If that changes,
  14766. // this test would be obsolete.
  14767. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14768. // This also implicitly tests the server. But other tests would fail much
  14769. // earlier than this one to be considered.
  14770. auto res = cli.Get("/");
  14771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14772. EXPECT_EQ(StatusCode::OK_200, res->status);
  14773. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14774. }
  14775. }
  14776. #ifdef CPPHTTPLIB_SSL_ENABLED
  14777. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14778. Client cli("http://yahoo.com");
  14779. auto res = cli.Get("/");
  14780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14781. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14782. cli.set_follow_location(true);
  14783. res = cli.Get("/");
  14784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14785. EXPECT_EQ(StatusCode::OK_200, res->status);
  14786. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14787. }
  14788. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14789. Client cli("https://yahoo.com");
  14790. auto res = cli.Get("/");
  14791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14792. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14793. cli.set_follow_location(true);
  14794. res = cli.Get("/");
  14795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14796. EXPECT_EQ(StatusCode::OK_200, res->status);
  14797. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14798. }
  14799. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14800. Client cli("https://yahoo.com");
  14801. auto res = cli.Get("/");
  14802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14803. ASSERT_FALSE(!res);
  14804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14805. ASSERT_FALSE(res == nullptr);
  14806. ASSERT_TRUE(res != nullptr);
  14807. EXPECT_EQ(Error::Success, res.error());
  14808. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14809. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14810. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14811. cli.set_follow_location(true);
  14812. res = cli.Get("/");
  14813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14814. EXPECT_EQ(Error::Success, res.error());
  14815. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14816. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14817. EXPECT_EQ(StatusCode::OK_200, res->status);
  14818. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14819. }
  14820. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14821. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14822. Client cli("https://cdnjs.cloudflare.com");
  14823. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14824. Headers{{"Accept-Encoding", "br"}});
  14825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14826. EXPECT_EQ(StatusCode::OK_200, res->status);
  14827. EXPECT_EQ(287630U, res->body.size());
  14828. EXPECT_EQ("application/javascript; charset=utf-8",
  14829. res->get_header_value("Content-Type"));
  14830. }
  14831. #endif
  14832. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14833. #undef REDIR_HOST // Silence compiler warning
  14834. #define REDIR_HOST "https://httpbingo.org"
  14835. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14836. Client cli(REDIR_HOST);
  14837. cli.set_follow_location(true);
  14838. auto res =
  14839. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14841. EXPECT_EQ(StatusCode::OK_200, res->status);
  14842. }
  14843. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14844. Client cli(REDIR_HOST);
  14845. cli.set_follow_location(true);
  14846. Params params;
  14847. params.emplace("url", "http://example.com");
  14848. params.emplace("status_code", "302");
  14849. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14851. EXPECT_EQ(StatusCode::OK_200, res->status);
  14852. }
  14853. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14854. Client cli(REDIR_HOST);
  14855. cli.set_follow_location(true);
  14856. Params params;
  14857. params.emplace("url", "http://example.com");
  14858. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14860. EXPECT_EQ(StatusCode::OK_200, res->status);
  14861. }
  14862. TEST(HttpToHttpsRedirectTest, CertFile) {
  14863. auto ssl_port = PORT + 1;
  14864. Server svr;
  14865. ASSERT_TRUE(svr.is_valid());
  14866. svr.Get("/index", [&](const Request &, Response &res) {
  14867. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14868. "/index");
  14869. svr.stop();
  14870. });
  14871. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14872. ASSERT_TRUE(ssl_svr.is_valid());
  14873. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14874. res.set_content("test", "text/plain");
  14875. ssl_svr.stop();
  14876. });
  14877. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14878. thread t2 =
  14879. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14880. auto se = detail::scope_exit([&] {
  14881. t2.join();
  14882. t.join();
  14883. ASSERT_FALSE(svr.is_running());
  14884. });
  14885. svr.wait_until_ready();
  14886. ssl_svr.wait_until_ready();
  14887. Client cli("127.0.0.1", PORT);
  14888. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14889. cli.enable_server_certificate_verification(true);
  14890. cli.set_follow_location(true);
  14891. cli.set_connection_timeout(30);
  14892. auto res = cli.Get("/index");
  14893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14894. ASSERT_EQ(StatusCode::OK_200, res->status);
  14895. }
  14896. TEST(SSLClientRedirectTest, CertFile) {
  14897. auto ssl_port = PORT + 1;
  14898. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14899. ASSERT_TRUE(ssl_svr1.is_valid());
  14900. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14901. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14902. "/index");
  14903. ssl_svr1.stop();
  14904. });
  14905. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14906. ASSERT_TRUE(ssl_svr2.is_valid());
  14907. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14908. res.set_content("test", "text/plain");
  14909. ssl_svr2.stop();
  14910. });
  14911. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14912. thread t2 =
  14913. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14914. auto se = detail::scope_exit([&] {
  14915. t2.join();
  14916. t.join();
  14917. ASSERT_FALSE(ssl_svr1.is_running());
  14918. });
  14919. ssl_svr1.wait_until_ready();
  14920. ssl_svr2.wait_until_ready();
  14921. SSLClient cli("127.0.0.1", PORT);
  14922. std::string cert;
  14923. read_file(SERVER_CERT2_FILE, cert);
  14924. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14925. cli.enable_server_certificate_verification(true);
  14926. cli.set_follow_location(true);
  14927. cli.set_connection_timeout(30);
  14928. auto res = cli.Get("/index");
  14929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14930. ASSERT_EQ(StatusCode::OK_200, res->status);
  14931. }
  14932. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14933. // another port, so the client follows it with a new client.
  14934. static Result GetThroughTlsRedirectToDifferentPort(
  14935. const std::function<void(SSLClient &)> &setup,
  14936. const char *target_cert = SERVER_CERT2_FILE,
  14937. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14938. auto ssl_port = PORT + 1;
  14939. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14940. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14941. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14942. "/index");
  14943. });
  14944. SSLServer ssl_svr2(target_cert, target_key);
  14945. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14946. res.set_content("test", "text/plain");
  14947. });
  14948. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14949. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14950. auto se = detail::scope_exit([&] {
  14951. ssl_svr2.stop();
  14952. ssl_svr1.stop();
  14953. t2.join();
  14954. t.join();
  14955. });
  14956. ssl_svr1.wait_until_ready();
  14957. ssl_svr2.wait_until_ready();
  14958. SSLClient cli("127.0.0.1", PORT);
  14959. cli.set_follow_location(true);
  14960. cli.set_connection_timeout(30);
  14961. setup(cli);
  14962. return cli.Get("/index");
  14963. }
  14964. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14965. auto calls = 0;
  14966. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14967. cli.enable_server_certificate_verification(false);
  14968. // Accept the first server only.
  14969. cli.set_session_verifier([&](tls::session_t) {
  14970. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14971. : SSLVerifierResponse::CertificateRejected;
  14972. });
  14973. });
  14974. ASSERT_FALSE(res);
  14975. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14976. EXPECT_EQ(2, calls);
  14977. }
  14978. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14979. std::string pinned;
  14980. auto res = GetThroughTlsRedirectToDifferentPort(
  14981. [&](SSLClient &cli) {
  14982. cli.enable_server_certificate_verification(false);
  14983. // Pin the first certificate seen.
  14984. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14985. if (pinned.empty()) { pinned = ctx.serial(); }
  14986. return ctx.serial() == pinned;
  14987. });
  14988. },
  14989. // A certificate other than the first server's.
  14990. SERVER_CERT_FILE);
  14991. EXPECT_FALSE(res);
  14992. EXPECT_FALSE(pinned.empty());
  14993. }
  14994. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14995. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14996. std::string cert;
  14997. read_file(SERVER_CERT2_FILE, cert);
  14998. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14999. });
  15000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15001. EXPECT_EQ(StatusCode::OK_200, res->status);
  15002. }
  15003. // The target's certificate is signed by the root CA, which the first server's
  15004. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15005. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15006. auto res = GetThroughTlsRedirectToDifferentPort(
  15007. [](SSLClient &cli) {
  15008. std::string root_ca, cert;
  15009. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15010. read_file(SERVER_CERT2_FILE, cert);
  15011. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15012. cli.load_ca_cert_store(cert.data(), cert.size());
  15013. cli.enable_server_hostname_verification(false);
  15014. },
  15015. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15017. EXPECT_EQ(StatusCode::OK_200, res->status);
  15018. }
  15019. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15020. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15021. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15022. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15023. auto res = GetThroughTlsRedirectToDifferentPort(
  15024. [](SSLClient &cli) {
  15025. std::string root_ca, cert;
  15026. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15027. read_file(SERVER_CERT2_FILE, cert);
  15028. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15029. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15030. cli.enable_server_hostname_verification(false);
  15031. },
  15032. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15033. ASSERT_FALSE(res);
  15034. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15035. }
  15036. #endif
  15037. #endif
  15038. #ifdef CPPHTTPLIB_SSL_ENABLED
  15039. // Test that set_ca_cert_store() skips system certs (consistent with
  15040. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15041. // should be trusted - system certs should NOT be loaded.
  15042. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15043. // Load a specific cert that is NOT a system CA cert
  15044. std::string cert;
  15045. read_file(SERVER_CERT2_FILE, cert);
  15046. SSLClient cli("google.com");
  15047. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15048. cli.enable_server_certificate_verification(true);
  15049. // This should FAIL because:
  15050. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15051. // 2. System certs should NOT be loaded when custom store is set
  15052. // If system certs WERE loaded, this would succeed
  15053. auto res = cli.Get("/");
  15054. ASSERT_FALSE(res);
  15055. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15056. }
  15057. // Same as above, but through the native store handle path. Regression test:
  15058. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15059. // merged system certs into the user-provided store.
  15060. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15061. std::string cert;
  15062. read_file(SERVER_CERT2_FILE, cert);
  15063. SSLClient cli("google.com");
  15064. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15065. cli.enable_server_certificate_verification(true);
  15066. auto res = cli.Get("/");
  15067. ASSERT_FALSE(res);
  15068. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15069. }
  15070. // A custom store set via the native handle must still verify a server whose
  15071. // cert it does contain.
  15072. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15073. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15074. ASSERT_TRUE(svr.is_valid());
  15075. svr.Get("/test", [&](const Request &, Response &res) {
  15076. res.set_content("test", "text/plain");
  15077. });
  15078. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15079. auto se = detail::scope_exit([&] {
  15080. svr.stop();
  15081. t.join();
  15082. ASSERT_FALSE(svr.is_running());
  15083. });
  15084. svr.wait_until_ready();
  15085. SSLClient cli("127.0.0.1", PORT);
  15086. std::string cert;
  15087. read_file(SERVER_CERT2_FILE, cert);
  15088. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15089. cli.enable_server_certificate_verification(true);
  15090. cli.set_connection_timeout(30);
  15091. auto res = cli.Get("/test");
  15092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15093. ASSERT_EQ(StatusCode::OK_200, res->status);
  15094. }
  15095. // CA certs loaded through the universal Client must be transferred to the
  15096. // client created internally for following an HTTPS redirect. Regression test:
  15097. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15098. // the CA data for redirect transfer.
  15099. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15100. auto ssl_port = PORT + 1;
  15101. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15102. ASSERT_TRUE(ssl_svr1.is_valid());
  15103. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15104. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15105. "/index");
  15106. });
  15107. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15108. ASSERT_TRUE(ssl_svr2.is_valid());
  15109. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15110. res.set_content("test", "text/plain");
  15111. });
  15112. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15113. thread t2 =
  15114. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15115. auto se = detail::scope_exit([&] {
  15116. ssl_svr2.stop();
  15117. ssl_svr1.stop();
  15118. t2.join();
  15119. t.join();
  15120. ASSERT_FALSE(ssl_svr1.is_running());
  15121. });
  15122. ssl_svr1.wait_until_ready();
  15123. ssl_svr2.wait_until_ready();
  15124. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15125. std::string cert;
  15126. read_file(SERVER_CERT2_FILE, cert);
  15127. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15128. cli.enable_server_certificate_verification(true);
  15129. cli.set_follow_location(true);
  15130. cli.set_connection_timeout(30);
  15131. auto res = cli.Get("/index");
  15132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15133. ASSERT_EQ(StatusCode::OK_200, res->status);
  15134. }
  15135. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15136. // so a host signed by a system CA verifies even though a custom CA is set
  15137. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15138. std::string cert;
  15139. read_file(SERVER_CERT2_FILE, cert);
  15140. SSLClient cli("google.com");
  15141. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15142. cli.enable_system_ca(true);
  15143. cli.enable_server_certificate_verification(true);
  15144. auto res = cli.Get("/");
  15145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15146. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15147. }
  15148. // The custom CA remains effective when combined with the system CA
  15149. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15150. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15151. ASSERT_TRUE(svr.is_valid());
  15152. svr.Get("/test", [&](const Request &, Response &res) {
  15153. res.set_content("test", "text/plain");
  15154. });
  15155. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15156. auto se = detail::scope_exit([&] {
  15157. svr.stop();
  15158. t.join();
  15159. ASSERT_FALSE(svr.is_running());
  15160. });
  15161. svr.wait_until_ready();
  15162. SSLClient cli("127.0.0.1", PORT);
  15163. std::string cert;
  15164. read_file(SERVER_CERT2_FILE, cert);
  15165. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15166. cli.enable_system_ca(true);
  15167. cli.enable_server_certificate_verification(true);
  15168. cli.set_connection_timeout(30);
  15169. auto res = cli.Get("/test");
  15170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15171. ASSERT_EQ(StatusCode::OK_200, res->status);
  15172. }
  15173. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15174. // skip chain verification entirely (only the certificate identity was
  15175. // checked), so a server presenting an untrusted certificate with a matching
  15176. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15177. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15178. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15179. ASSERT_TRUE(svr.is_valid());
  15180. svr.Get("/test", [&](const Request &, Response &res) {
  15181. res.set_content("test", "text/plain");
  15182. });
  15183. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15184. auto se = detail::scope_exit([&] {
  15185. svr.stop();
  15186. t.join();
  15187. ASSERT_FALSE(svr.is_running());
  15188. });
  15189. svr.wait_until_ready();
  15190. SSLClient cli("127.0.0.1", PORT);
  15191. std::string cert;
  15192. // A trusted CA that did not sign the server certificate. The server cert
  15193. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15194. // this connection.
  15195. read_file(CLIENT_CA_CERT_FILE, cert);
  15196. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15197. cli.enable_server_certificate_verification(true);
  15198. cli.set_connection_timeout(30);
  15199. auto res = cli.Get("/test");
  15200. ASSERT_FALSE(res);
  15201. }
  15202. // enable_system_ca(false) prevents system CA loading entirely
  15203. TEST(SSLClientTest, DisableSystemCa_Online) {
  15204. SSLClient cli("google.com");
  15205. cli.enable_system_ca(false);
  15206. cli.enable_server_certificate_verification(true);
  15207. auto res = cli.Get("/");
  15208. ASSERT_FALSE(res);
  15209. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15210. // itself when the CA chain is empty
  15211. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15212. res.error() == Error::SSLConnection);
  15213. }
  15214. // The universal Client forwards enable_system_ca()
  15215. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15216. std::string cert;
  15217. read_file(SERVER_CERT2_FILE, cert);
  15218. Client cli("https://google.com");
  15219. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15220. cli.enable_system_ca(true);
  15221. cli.enable_server_certificate_verification(true);
  15222. auto res = cli.Get("/");
  15223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15224. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15225. }
  15226. // The system CA policy must carry over to the client created internally for
  15227. // following a cross-host HTTPS redirect
  15228. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15229. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15230. ASSERT_TRUE(svr.is_valid());
  15231. svr.Get("/index", [&](const Request &, Response &res) {
  15232. res.set_redirect("https://www.google.com/");
  15233. });
  15234. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15235. auto se = detail::scope_exit([&] {
  15236. svr.stop();
  15237. t.join();
  15238. ASSERT_FALSE(svr.is_running());
  15239. });
  15240. svr.wait_until_ready();
  15241. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15242. std::string cert;
  15243. read_file(SERVER_CERT2_FILE, cert);
  15244. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15245. cli.enable_system_ca(true);
  15246. cli.enable_server_certificate_verification(true);
  15247. cli.set_follow_location(true);
  15248. cli.set_connection_timeout(30);
  15249. // Receiving any response proves the redirect client completed the TLS
  15250. // handshake with a system-CA-signed host
  15251. auto res = cli.Get("/index");
  15252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15253. }
  15254. TEST(MultipartFormDataTest, LargeData) {
  15255. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15256. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15257. const ContentReader &content_reader) {
  15258. if (req.is_multipart_form_data()) {
  15259. std::vector<FormData> items;
  15260. content_reader(
  15261. [&](const FormData &file) {
  15262. items.push_back(file);
  15263. return true;
  15264. },
  15265. [&](const char *data, size_t data_length) {
  15266. items.back().content.append(data, data_length);
  15267. return true;
  15268. });
  15269. EXPECT_TRUE(std::string(items[0].name) == "document");
  15270. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15271. EXPECT_TRUE(items[0].filename == "2MB_data");
  15272. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15273. EXPECT_TRUE(items[1].name == "hello");
  15274. EXPECT_TRUE(items[1].content == "world");
  15275. EXPECT_TRUE(items[1].filename == "");
  15276. EXPECT_TRUE(items[1].content_type == "");
  15277. } else {
  15278. std::string body;
  15279. content_reader([&](const char *data, size_t data_length) {
  15280. body.append(data, data_length);
  15281. return true;
  15282. });
  15283. }
  15284. });
  15285. auto port = svr.bind_to_any_port(HOST);
  15286. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15287. auto se = detail::scope_exit([&] {
  15288. svr.stop();
  15289. t.join();
  15290. ASSERT_FALSE(svr.is_running());
  15291. });
  15292. svr.wait_until_ready();
  15293. {
  15294. std::string data(1024 * 1024 * 2, '.');
  15295. std::stringstream buffer;
  15296. buffer << data;
  15297. SSLClient cli(HOST, port);
  15298. cli.enable_server_certificate_verification(false);
  15299. UploadFormDataItems items{
  15300. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15301. {"hello", "world", "", ""},
  15302. };
  15303. auto res = cli.Post("/post", items);
  15304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15305. ASSERT_EQ(StatusCode::OK_200, res->status);
  15306. }
  15307. }
  15308. TEST(MultipartFormDataTest, DataProviderItems) {
  15309. std::random_device seed_gen;
  15310. std::mt19937 random(seed_gen());
  15311. std::string rand1;
  15312. rand1.resize(1000);
  15313. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15314. std::string rand2;
  15315. rand2.resize(3000);
  15316. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15317. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15318. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15319. const ContentReader &content_reader) {
  15320. ASSERT_FALSE(req.is_multipart_form_data());
  15321. std::string body;
  15322. content_reader([&](const char *data, size_t data_length) {
  15323. body.append(data, data_length);
  15324. return true;
  15325. });
  15326. EXPECT_EQ(body, "");
  15327. });
  15328. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15329. const ContentReader &content_reader) {
  15330. ASSERT_TRUE(req.is_multipart_form_data());
  15331. std::vector<FormData> items;
  15332. content_reader(
  15333. [&](const FormData &file) {
  15334. items.push_back(file);
  15335. return true;
  15336. },
  15337. [&](const char *data, size_t data_length) {
  15338. items.back().content.append(data, data_length);
  15339. return true;
  15340. });
  15341. ASSERT_TRUE(items.size() == 2);
  15342. EXPECT_EQ(std::string(items[0].name), "name1");
  15343. EXPECT_EQ(items[0].content, "Testing123");
  15344. EXPECT_EQ(items[0].filename, "filename1");
  15345. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15346. EXPECT_EQ(items[1].name, "name2");
  15347. EXPECT_EQ(items[1].content, "Testing456");
  15348. EXPECT_EQ(items[1].filename, "");
  15349. EXPECT_EQ(items[1].content_type, "");
  15350. });
  15351. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15352. const ContentReader &content_reader) {
  15353. ASSERT_TRUE(req.is_multipart_form_data());
  15354. std::vector<FormData> items;
  15355. content_reader(
  15356. [&](const FormData &file) {
  15357. items.push_back(file);
  15358. return true;
  15359. },
  15360. [&](const char *data, size_t data_length) {
  15361. items.back().content.append(data, data_length);
  15362. return true;
  15363. });
  15364. ASSERT_TRUE(items.size() == 2);
  15365. EXPECT_EQ(items[0].name, "name3");
  15366. EXPECT_EQ(items[0].content, rand1);
  15367. EXPECT_EQ(items[0].filename, "filename3");
  15368. EXPECT_EQ(items[0].content_type, "");
  15369. EXPECT_EQ(items[1].name, "name4");
  15370. EXPECT_EQ(items[1].content, rand2);
  15371. EXPECT_EQ(items[1].filename, "filename4");
  15372. EXPECT_EQ(items[1].content_type, "");
  15373. });
  15374. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15375. const ContentReader &content_reader) {
  15376. ASSERT_TRUE(req.is_multipart_form_data());
  15377. std::vector<FormData> items;
  15378. content_reader(
  15379. [&](const FormData &file) {
  15380. items.push_back(file);
  15381. return true;
  15382. },
  15383. [&](const char *data, size_t data_length) {
  15384. items.back().content.append(data, data_length);
  15385. return true;
  15386. });
  15387. ASSERT_TRUE(items.size() == 4);
  15388. EXPECT_EQ(std::string(items[0].name), "name1");
  15389. EXPECT_EQ(items[0].content, "Testing123");
  15390. EXPECT_EQ(items[0].filename, "filename1");
  15391. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15392. EXPECT_EQ(items[1].name, "name2");
  15393. EXPECT_EQ(items[1].content, "Testing456");
  15394. EXPECT_EQ(items[1].filename, "");
  15395. EXPECT_EQ(items[1].content_type, "");
  15396. EXPECT_EQ(items[2].name, "name3");
  15397. EXPECT_EQ(items[2].content, rand1);
  15398. EXPECT_EQ(items[2].filename, "filename3");
  15399. EXPECT_EQ(items[2].content_type, "");
  15400. EXPECT_EQ(items[3].name, "name4");
  15401. EXPECT_EQ(items[3].content, rand2);
  15402. EXPECT_EQ(items[3].filename, "filename4");
  15403. EXPECT_EQ(items[3].content_type, "");
  15404. });
  15405. auto port = svr.bind_to_any_port("localhost");
  15406. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15407. auto se = detail::scope_exit([&] {
  15408. svr.stop();
  15409. t.join();
  15410. ASSERT_FALSE(svr.is_running());
  15411. });
  15412. svr.wait_until_ready();
  15413. {
  15414. SSLClient cli("localhost", port);
  15415. cli.enable_server_certificate_verification(false);
  15416. UploadFormDataItems items{
  15417. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15418. {"name2", "Testing456", "", ""}, // not a file
  15419. };
  15420. {
  15421. auto res = cli.Post("/post-none", {}, {}, {});
  15422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15423. ASSERT_EQ(StatusCode::OK_200, res->status);
  15424. }
  15425. FormDataProviderItems providers;
  15426. {
  15427. auto res =
  15428. cli.Post("/post-items", {}, items, providers); // empty providers
  15429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15430. ASSERT_EQ(StatusCode::OK_200, res->status);
  15431. }
  15432. providers.push_back({"name3",
  15433. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15434. // test the offset is given correctly at each step
  15435. if (!offset)
  15436. sink.os.write(rand1.data(), 30);
  15437. else if (offset == 30)
  15438. sink.os.write(rand1.data() + 30, 300);
  15439. else if (offset == 330)
  15440. sink.os.write(rand1.data() + 330, 670);
  15441. else if (offset == rand1.size())
  15442. sink.done();
  15443. return true;
  15444. },
  15445. "filename3",
  15446. {}});
  15447. providers.push_back({"name4",
  15448. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15449. // test the offset is given correctly at each step
  15450. if (!offset)
  15451. sink.os.write(rand2.data(), 2000);
  15452. else if (offset == 2000)
  15453. sink.os.write(rand2.data() + 2000, 1);
  15454. else if (offset == 2001)
  15455. sink.os.write(rand2.data() + 2001, 999);
  15456. else if (offset == rand2.size())
  15457. sink.done();
  15458. return true;
  15459. },
  15460. "filename4",
  15461. {}});
  15462. {
  15463. auto res = cli.Post("/post-providers", {}, {}, providers);
  15464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15465. ASSERT_EQ(StatusCode::OK_200, res->status);
  15466. }
  15467. {
  15468. auto res = cli.Post("/post-both", {}, items, providers);
  15469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15470. ASSERT_EQ(StatusCode::OK_200, res->status);
  15471. }
  15472. }
  15473. }
  15474. TEST(MultipartFormDataTest, BadHeader) {
  15475. Server svr;
  15476. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15477. res.set_content("ok", "text/plain");
  15478. });
  15479. thread t = thread([&] { svr.listen(HOST, PORT); });
  15480. auto se = detail::scope_exit([&] {
  15481. svr.stop();
  15482. t.join();
  15483. ASSERT_FALSE(svr.is_running());
  15484. });
  15485. svr.wait_until_ready();
  15486. const std::string body =
  15487. "This is the preamble. It is to be ignored, though it\r\n"
  15488. "is a handy place for composition agents to include an\r\n"
  15489. "explanatory note to non-MIME conformant readers.\r\n"
  15490. "\r\n"
  15491. "\r\n"
  15492. "--simple boundary\r\n"
  15493. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15494. ": BAD...\r\n"
  15495. "\r\n"
  15496. "value1\r\n"
  15497. "--simple boundary\r\n"
  15498. "Content-Disposition: form-data; name=\"field2\"; "
  15499. "filename=\"example.txt\"\r\n"
  15500. "\r\n"
  15501. "value2\r\n"
  15502. "--simple boundary--\r\n"
  15503. "This is the epilogue. It is also to be ignored.\r\n";
  15504. std::string content_type =
  15505. R"(multipart/form-data; boundary="simple boundary")";
  15506. Client cli(HOST, PORT);
  15507. auto res = cli.Post("/post", body, content_type.c_str());
  15508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15509. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15510. }
  15511. TEST(MultipartFormDataTest, WithPreamble) {
  15512. Server svr;
  15513. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15514. res.set_content("ok", "text/plain");
  15515. });
  15516. thread t = thread([&] { svr.listen(HOST, PORT); });
  15517. auto se = detail::scope_exit([&] {
  15518. svr.stop();
  15519. t.join();
  15520. ASSERT_FALSE(svr.is_running());
  15521. });
  15522. svr.wait_until_ready();
  15523. const std::string body =
  15524. "This is the preamble. It is to be ignored, though it\r\n"
  15525. "is a handy place for composition agents to include an\r\n"
  15526. "explanatory note to non-MIME conformant readers.\r\n"
  15527. "\r\n"
  15528. "\r\n"
  15529. "--simple boundary\r\n"
  15530. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15531. "\r\n"
  15532. "value1\r\n"
  15533. "--simple boundary\r\n"
  15534. "Content-Disposition: form-data; name=\"field2\"; "
  15535. "filename=\"example.txt\"\r\n"
  15536. "\r\n"
  15537. "value2\r\n"
  15538. "--simple boundary--\r\n"
  15539. "This is the epilogue. It is also to be ignored.\r\n";
  15540. std::string content_type =
  15541. R"(multipart/form-data; boundary="simple boundary")";
  15542. Client cli(HOST, PORT);
  15543. auto res = cli.Post("/post", body, content_type.c_str());
  15544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15545. EXPECT_EQ(StatusCode::OK_200, res->status);
  15546. }
  15547. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15549. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15550. const ContentReader &content_reader) {
  15551. if (req.is_multipart_form_data()) {
  15552. std::vector<FormData> items;
  15553. content_reader(
  15554. [&](const FormData &file) {
  15555. items.push_back(file);
  15556. return true;
  15557. },
  15558. [&](const char *data, size_t data_length) {
  15559. items.back().content.append(data, data_length);
  15560. return true;
  15561. });
  15562. EXPECT_TRUE(std::string(items[0].name) == "document");
  15563. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15564. EXPECT_TRUE(items[0].filename == "2MB_data");
  15565. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15566. EXPECT_TRUE(items[1].name == "hello");
  15567. EXPECT_TRUE(items[1].content == "world");
  15568. EXPECT_TRUE(items[1].filename == "");
  15569. EXPECT_TRUE(items[1].content_type == "");
  15570. } else {
  15571. std::string body;
  15572. content_reader([&](const char *data, size_t data_length) {
  15573. body.append(data, data_length);
  15574. return true;
  15575. });
  15576. }
  15577. });
  15578. auto port = svr.bind_to_any_port("localhost");
  15579. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15580. auto se = detail::scope_exit([&] {
  15581. svr.stop();
  15582. t.join();
  15583. ASSERT_FALSE(svr.is_running());
  15584. });
  15585. svr.wait_until_ready();
  15586. {
  15587. std::string data(1024 * 1024 * 2, '.');
  15588. std::stringstream buffer;
  15589. buffer << data;
  15590. SSLClient cli("localhost", port);
  15591. cli.enable_server_certificate_verification(false);
  15592. UploadFormDataItems items{
  15593. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15594. {"hello", "world", "", ""},
  15595. };
  15596. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15598. ASSERT_EQ(StatusCode::OK_200, res->status);
  15599. }
  15600. }
  15601. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15602. std::string data(1024 * 1024 * 2, '&');
  15603. std::stringstream buffer;
  15604. buffer << data;
  15605. Client cli("https://localhost:8080");
  15606. UploadFormDataItems items{
  15607. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15608. {"hello", "world", "", ""},
  15609. };
  15610. for (const char &c : " \t\r\n") {
  15611. auto res =
  15612. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15613. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15614. ASSERT_FALSE(res);
  15615. }
  15616. }
  15617. TEST(MultipartFormDataTest, PutFormData) {
  15618. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15619. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15620. const ContentReader &content_reader) {
  15621. if (req.is_multipart_form_data()) {
  15622. std::vector<FormData> items;
  15623. content_reader(
  15624. [&](const FormData &file) {
  15625. items.push_back(file);
  15626. return true;
  15627. },
  15628. [&](const char *data, size_t data_length) {
  15629. items.back().content.append(data, data_length);
  15630. return true;
  15631. });
  15632. EXPECT_TRUE(std::string(items[0].name) == "document");
  15633. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15634. EXPECT_TRUE(items[0].filename == "2MB_data");
  15635. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15636. EXPECT_TRUE(items[1].name == "hello");
  15637. EXPECT_TRUE(items[1].content == "world");
  15638. EXPECT_TRUE(items[1].filename == "");
  15639. EXPECT_TRUE(items[1].content_type == "");
  15640. } else {
  15641. std::string body;
  15642. content_reader([&](const char *data, size_t data_length) {
  15643. body.append(data, data_length);
  15644. return true;
  15645. });
  15646. }
  15647. });
  15648. auto port = svr.bind_to_any_port("localhost");
  15649. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15650. auto se = detail::scope_exit([&] {
  15651. svr.stop();
  15652. t.join();
  15653. ASSERT_FALSE(svr.is_running());
  15654. });
  15655. svr.wait_until_ready();
  15656. {
  15657. std::string data(1024 * 1024 * 2, '&');
  15658. std::stringstream buffer;
  15659. buffer << data;
  15660. SSLClient cli("localhost", port);
  15661. cli.enable_server_certificate_verification(false);
  15662. UploadFormDataItems items{
  15663. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15664. {"hello", "world", "", ""},
  15665. };
  15666. auto res = cli.Put("/put", items);
  15667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15668. ASSERT_EQ(StatusCode::OK_200, res->status);
  15669. }
  15670. }
  15671. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15673. svr.Put("/put_customboundary",
  15674. [&](const Request &req, const Response & /*res*/,
  15675. const ContentReader &content_reader) {
  15676. if (req.is_multipart_form_data()) {
  15677. std::vector<FormData> items;
  15678. content_reader(
  15679. [&](const FormData &file) {
  15680. items.push_back(file);
  15681. return true;
  15682. },
  15683. [&](const char *data, size_t data_length) {
  15684. items.back().content.append(data, data_length);
  15685. return true;
  15686. });
  15687. EXPECT_TRUE(std::string(items[0].name) == "document");
  15688. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15689. EXPECT_TRUE(items[0].filename == "2MB_data");
  15690. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15691. EXPECT_TRUE(items[1].name == "hello");
  15692. EXPECT_TRUE(items[1].content == "world");
  15693. EXPECT_TRUE(items[1].filename == "");
  15694. EXPECT_TRUE(items[1].content_type == "");
  15695. } else {
  15696. std::string body;
  15697. content_reader([&](const char *data, size_t data_length) {
  15698. body.append(data, data_length);
  15699. return true;
  15700. });
  15701. }
  15702. });
  15703. auto port = svr.bind_to_any_port("localhost");
  15704. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15705. auto se = detail::scope_exit([&] {
  15706. svr.stop();
  15707. t.join();
  15708. ASSERT_FALSE(svr.is_running());
  15709. });
  15710. svr.wait_until_ready();
  15711. {
  15712. std::string data(1024 * 1024 * 2, '&');
  15713. std::stringstream buffer;
  15714. buffer << data;
  15715. SSLClient cli("localhost", port);
  15716. cli.enable_server_certificate_verification(false);
  15717. UploadFormDataItems items{
  15718. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15719. {"hello", "world", "", ""},
  15720. };
  15721. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15723. ASSERT_EQ(StatusCode::OK_200, res->status);
  15724. }
  15725. }
  15726. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15727. std::string data(1024 * 1024 * 2, '&');
  15728. std::stringstream buffer;
  15729. buffer << data;
  15730. Client cli("https://localhost:8080");
  15731. cli.enable_server_certificate_verification(false);
  15732. UploadFormDataItems items{
  15733. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15734. {"hello", "world", "", ""},
  15735. };
  15736. for (const char &c : " \t\r\n") {
  15737. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15738. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15739. ASSERT_FALSE(res);
  15740. }
  15741. }
  15742. TEST(MultipartFormDataTest, AlternateFilename) {
  15743. auto handled = false;
  15744. Server svr;
  15745. svr.Post("/test", [&](const Request &req, Response &res) {
  15746. ASSERT_EQ(2u, req.form.files.size());
  15747. ASSERT_EQ(1u, req.form.fields.size());
  15748. // Test files
  15749. const auto &file1 = req.form.get_file("file1");
  15750. ASSERT_EQ("file1", file1.name);
  15751. ASSERT_EQ("A.txt", file1.filename);
  15752. ASSERT_EQ("text/plain", file1.content_type);
  15753. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15754. const auto &file2 = req.form.get_file("file2");
  15755. ASSERT_EQ("file2", file2.name);
  15756. ASSERT_EQ("a.html", file2.filename);
  15757. ASSERT_EQ("text/html", file2.content_type);
  15758. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15759. file2.content);
  15760. // Test text field
  15761. const auto &text = req.form.get_field("text");
  15762. ASSERT_EQ("text default", text);
  15763. res.set_content("ok", "text/plain");
  15764. handled = true;
  15765. });
  15766. thread t = thread([&] { svr.listen(HOST, PORT); });
  15767. auto se = detail::scope_exit([&] {
  15768. svr.stop();
  15769. t.join();
  15770. ASSERT_FALSE(svr.is_running());
  15771. ASSERT_TRUE(handled);
  15772. });
  15773. svr.wait_until_ready();
  15774. auto req = "POST /test HTTP/1.1\r\n"
  15775. "Host: localhost\r\n"
  15776. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15777. "Content-Length: 399\r\n"
  15778. "\r\n"
  15779. "----------\r\n"
  15780. "Content-Disposition: form-data; name=\"text\"\r\n"
  15781. "\r\n"
  15782. "text default\r\n"
  15783. "----------\r\n"
  15784. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15785. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15786. "Content-Type: text/plain\r\n"
  15787. "\r\n"
  15788. "Content of a.txt.\r\n"
  15789. "\r\n"
  15790. "----------\r\n"
  15791. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15792. "\"a.html\"\r\n"
  15793. "Content-Type: text/html\r\n"
  15794. "\r\n"
  15795. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15796. "\r\n"
  15797. "------------\r\n";
  15798. ASSERT_TRUE(send_request(1, req));
  15799. }
  15800. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15801. auto handled = false;
  15802. Server svr;
  15803. svr.Post("/test", [&](const Request &req, Response &res) {
  15804. // Case-insensitive "utf-8''" prefix with a long value
  15805. const auto &file = req.form.get_file("file1");
  15806. ASSERT_EQ("file1", file.name);
  15807. // 8000 chars exercises both the Content-Disposition parser and the
  15808. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15809. // Prior to the fix, std::regex_match on this header would cause O(N)
  15810. // stack recursion in libstdc++, leading to SIGSEGV.
  15811. std::string expected_filename(8000, 'A');
  15812. ASSERT_EQ(expected_filename, file.filename);
  15813. res.set_content("ok", "text/plain");
  15814. handled = true;
  15815. });
  15816. thread t = thread([&] { svr.listen(HOST, PORT); });
  15817. auto se = detail::scope_exit([&] {
  15818. svr.stop();
  15819. t.join();
  15820. ASSERT_FALSE(svr.is_running());
  15821. ASSERT_TRUE(handled);
  15822. });
  15823. svr.wait_until_ready();
  15824. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15825. // Regression test for GHSA-qq6v-r583-3h69
  15826. std::string long_filename(8000, 'A');
  15827. std::string body = "----------\r\n"
  15828. "Content-Disposition: form-data; name=\"file1\"; "
  15829. "filename*=\"Utf-8''" +
  15830. long_filename +
  15831. "\"\r\n"
  15832. "\r\n"
  15833. "hello\r\n"
  15834. "------------\r\n";
  15835. auto req = "POST /test HTTP/1.1\r\n"
  15836. "Host: localhost\r\n"
  15837. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15838. "Content-Length: " +
  15839. std::to_string(body.size()) + "\r\n\r\n" + body;
  15840. ASSERT_TRUE(send_request(1, req));
  15841. }
  15842. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15843. auto handled = false;
  15844. Server svr;
  15845. svr.Post("/test", [&](const Request &req, Response &) {
  15846. ASSERT_EQ(2u, req.form.fields.size());
  15847. const auto &text1 = req.form.get_field("text1");
  15848. ASSERT_EQ("text1", text1);
  15849. const auto &text2 = req.form.get_field("text2");
  15850. ASSERT_EQ("text2", text2);
  15851. handled = true;
  15852. });
  15853. thread t = thread([&] { svr.listen(HOST, PORT); });
  15854. auto se = detail::scope_exit([&] {
  15855. svr.stop();
  15856. t.join();
  15857. ASSERT_FALSE(svr.is_running());
  15858. ASSERT_TRUE(handled);
  15859. });
  15860. svr.wait_until_ready();
  15861. auto req = "POST /test HTTP/1.1\r\n"
  15862. "Host: localhost\r\n"
  15863. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15864. "Content-Length: 146\r\n"
  15865. "\r\n----------\r\n"
  15866. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15867. "\r\n"
  15868. "text1"
  15869. "\r\n----------\r\n"
  15870. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15871. "\r\n"
  15872. "text2"
  15873. "\r\n------------";
  15874. std::string response;
  15875. ASSERT_TRUE(send_request(1, req, &response));
  15876. ASSERT_EQ("200", response.substr(9, 3));
  15877. }
  15878. TEST(MultipartFormDataTest, ContentLength) {
  15879. auto handled = false;
  15880. Server svr;
  15881. svr.Post("/test", [&](const Request &req, Response &) {
  15882. ASSERT_EQ(2u, req.form.fields.size());
  15883. const auto &text1 = req.form.get_field("text1");
  15884. ASSERT_EQ("text1", text1);
  15885. const auto &text2 = req.form.get_field("text2");
  15886. ASSERT_EQ("text2", text2);
  15887. handled = true;
  15888. });
  15889. thread t = thread([&] { svr.listen(HOST, PORT); });
  15890. auto se = detail::scope_exit([&] {
  15891. svr.stop();
  15892. t.join();
  15893. ASSERT_FALSE(svr.is_running());
  15894. ASSERT_TRUE(handled);
  15895. });
  15896. svr.wait_until_ready();
  15897. auto req = "POST /test HTTP/1.1\r\n"
  15898. "Host: localhost\r\n"
  15899. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15900. "Content-Length: 167\r\n"
  15901. "\r\n----------\r\n"
  15902. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15903. "Content-Length: 5\r\n"
  15904. "\r\n"
  15905. "text1"
  15906. "\r\n----------\r\n"
  15907. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15908. "\r\n"
  15909. "text2"
  15910. "\r\n------------\r\n";
  15911. std::string response;
  15912. ASSERT_TRUE(send_request(1, req, &response));
  15913. ASSERT_EQ("200", response.substr(9, 3));
  15914. }
  15915. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15916. auto handled = false;
  15917. Server svr;
  15918. svr.Post("/test", [&](const Request &req, Response &) {
  15919. ASSERT_EQ(2u, req.form.fields.size());
  15920. const auto &text1 = req.form.get_field("text1");
  15921. ASSERT_EQ("text1", text1);
  15922. // TODO: Add header access for text fields if needed
  15923. const auto &text2 = req.form.get_field("text2");
  15924. ASSERT_EQ("text2", text2);
  15925. // TODO: Header access for text fields needs to be implemented
  15926. // auto &headers = it->second.headers;
  15927. // ASSERT_EQ(3U, headers.size());
  15928. // auto custom_header = headers.find("x-whatever");
  15929. // ASSERT_TRUE(custom_header != headers.end());
  15930. // ASSERT_NE("customvalue", custom_header->second);
  15931. // ASSERT_EQ("CustomValue", custom_header->second);
  15932. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15933. handled = true;
  15934. });
  15935. thread t = thread([&] { svr.listen(HOST, PORT); });
  15936. auto se = detail::scope_exit([&] {
  15937. svr.stop();
  15938. t.join();
  15939. ASSERT_FALSE(svr.is_running());
  15940. ASSERT_TRUE(handled);
  15941. });
  15942. svr.wait_until_ready();
  15943. auto req = "POST /test HTTP/1.1\r\n"
  15944. "Host: localhost\r\n"
  15945. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15946. "Content-Length: 232\r\n"
  15947. "\r\n----------\r\n"
  15948. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15949. "Content-Length: 5\r\n"
  15950. "X-Test: 1\r\n"
  15951. "\r\n"
  15952. "text1"
  15953. "\r\n----------\r\n"
  15954. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15955. "Content-Type: text/plain\r\n"
  15956. "X-Whatever: CustomValue\r\n"
  15957. "\r\n"
  15958. "text2"
  15959. "\r\n------------\r\n"
  15960. "That should be disregarded. Not even read";
  15961. std::string response;
  15962. ASSERT_TRUE(send_request(1, req, &response));
  15963. ASSERT_EQ("200", response.substr(9, 3));
  15964. }
  15965. TEST(MultipartFormDataTest, LargeHeader) {
  15966. auto handled = false;
  15967. Server svr;
  15968. svr.Post("/test", [&](const Request &req, Response &) {
  15969. ASSERT_EQ(1u, req.form.fields.size());
  15970. const auto &text = req.form.get_field("name1");
  15971. ASSERT_EQ("text1", text);
  15972. handled = true;
  15973. });
  15974. thread t = thread([&] { svr.listen(HOST, PORT); });
  15975. auto se = detail::scope_exit([&] {
  15976. svr.stop();
  15977. t.join();
  15978. ASSERT_FALSE(svr.is_running());
  15979. ASSERT_TRUE(handled);
  15980. });
  15981. svr.wait_until_ready();
  15982. auto boundary = std::string("cpp-httplib-multipart-data");
  15983. std::string content = "--" + boundary +
  15984. "\r\n"
  15985. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15986. "\r\n"
  15987. "text1\r\n"
  15988. "--" +
  15989. boundary + "--\r\n";
  15990. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15991. "Host: localhost\r\n"
  15992. "Content-Type: multipart/form-data;boundary=" +
  15993. boundary +
  15994. "\r\n"
  15995. "Content-Length: " +
  15996. std::to_string(content.size()) +
  15997. "\r\n"
  15998. "Dummy-Header: ";
  15999. std::string header_suffix = "\r\n"
  16000. "\r\n";
  16001. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16002. size_t header_dummy_size =
  16003. read_buff_size -
  16004. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16005. auto header_dummy = std::string(header_dummy_size, '@');
  16006. auto req = header_prefix + header_dummy + header_suffix + content;
  16007. std::string response;
  16008. ASSERT_TRUE(send_request(1, req, &response));
  16009. ASSERT_EQ("200", response.substr(9, 3));
  16010. }
  16011. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16012. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16013. // (not chunked Transfer-Encoding) after the streaming refactor.
  16014. auto handled = false;
  16015. Server svr;
  16016. svr.Post("/upload", [&](const Request &req, Response &res) {
  16017. auto cl_it = req.headers.find("Content-Length");
  16018. EXPECT_TRUE(cl_it != req.headers.end());
  16019. auto te_it = req.headers.find("Transfer-Encoding");
  16020. EXPECT_TRUE(te_it == req.headers.end());
  16021. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16022. res.set_content("ok", "text/plain");
  16023. handled = true;
  16024. });
  16025. auto port = svr.bind_to_any_port(HOST);
  16026. auto t = thread([&] { svr.listen_after_bind(); });
  16027. auto se = detail::scope_exit([&] {
  16028. svr.stop();
  16029. t.join();
  16030. ASSERT_FALSE(svr.is_running());
  16031. ASSERT_TRUE(handled);
  16032. });
  16033. svr.wait_until_ready();
  16034. UploadFormDataItems items = {
  16035. {"field1", "hello", "", "text/plain"},
  16036. {"file1", "world", "test.txt", "application/octet-stream"},
  16037. };
  16038. Client cli(HOST, port);
  16039. auto res = cli.Post("/upload", {}, items);
  16040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16041. EXPECT_EQ(StatusCode::OK_200, res->status);
  16042. }
  16043. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16044. // Verify that make_multipart_content_provider coalesces many small segments
  16045. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16046. constexpr size_t kItemCount = 1000;
  16047. UploadFormDataItems items;
  16048. items.reserve(kItemCount);
  16049. for (size_t i = 0; i < kItemCount; i++) {
  16050. items.push_back(
  16051. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16052. }
  16053. const std::string boundary = "----test-boundary";
  16054. auto content_length = detail::get_multipart_content_length(items, boundary);
  16055. auto provider = detail::make_multipart_content_provider(items, boundary);
  16056. // Drive the provider the same way write_content_with_progress does
  16057. size_t write_count = 0;
  16058. size_t total_bytes = 0;
  16059. DataSink sink;
  16060. size_t offset = 0;
  16061. sink.write = [&](const char *d, size_t l) -> bool {
  16062. (void)d;
  16063. write_count++;
  16064. total_bytes += l;
  16065. offset += l;
  16066. return true;
  16067. };
  16068. sink.is_writable = []() -> bool { return true; };
  16069. while (offset < content_length) {
  16070. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16071. }
  16072. EXPECT_EQ(content_length, total_bytes);
  16073. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16074. // With buffering into 64KB blocks, write_count should be much smaller.
  16075. auto segment_count = 3 * kItemCount + 1;
  16076. EXPECT_LT(write_count, segment_count / 10);
  16077. }
  16078. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16079. // Integration test: send many UploadFormDataItems and verify the server
  16080. // receives all of them correctly (#2410).
  16081. constexpr size_t kItemCount = 500;
  16082. auto handled = false;
  16083. Server svr;
  16084. svr.Post("/upload", [&](const Request &req, Response &res) {
  16085. EXPECT_EQ(kItemCount, req.form.fields.size());
  16086. for (size_t i = 0; i < kItemCount; i++) {
  16087. auto key = "field" + std::to_string(i);
  16088. auto val = "value" + std::to_string(i);
  16089. auto it = req.form.fields.find(key);
  16090. if (it != req.form.fields.end()) {
  16091. EXPECT_EQ(val, it->second.content);
  16092. } else {
  16093. ADD_FAILURE() << "Missing field: " << key;
  16094. }
  16095. }
  16096. res.set_content("ok", "text/plain");
  16097. handled = true;
  16098. });
  16099. auto port = svr.bind_to_any_port(HOST);
  16100. auto t = thread([&] { svr.listen_after_bind(); });
  16101. auto se = detail::scope_exit([&] {
  16102. svr.stop();
  16103. t.join();
  16104. ASSERT_FALSE(svr.is_running());
  16105. ASSERT_TRUE(handled);
  16106. });
  16107. svr.wait_until_ready();
  16108. UploadFormDataItems items;
  16109. items.reserve(kItemCount);
  16110. for (size_t i = 0; i < kItemCount; i++) {
  16111. items.push_back(
  16112. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16113. }
  16114. Client cli(HOST, port);
  16115. auto res = cli.Post("/upload", items);
  16116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16117. EXPECT_EQ(StatusCode::OK_200, res->status);
  16118. }
  16119. TEST(MultipartFormDataTest, MakeFileProvider) {
  16120. // Verify make_file_provider sends a file's contents correctly.
  16121. const std::string file_content(4096, 'Z');
  16122. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16123. {
  16124. std::ofstream ofs(tmp_path, std::ios::binary);
  16125. ofs.write(file_content.data(),
  16126. static_cast<std::streamsize>(file_content.size()));
  16127. }
  16128. auto handled = false;
  16129. Server svr;
  16130. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16131. const ContentReader &content_reader) {
  16132. ASSERT_TRUE(req.is_multipart_form_data());
  16133. std::vector<FormData> items;
  16134. content_reader(
  16135. [&](const FormData &file) {
  16136. items.push_back(file);
  16137. return true;
  16138. },
  16139. [&](const char *data, size_t data_length) {
  16140. items.back().content.append(data, data_length);
  16141. return true;
  16142. });
  16143. ASSERT_EQ(1u, items.size());
  16144. EXPECT_EQ("myfile", items[0].name);
  16145. EXPECT_EQ("data.bin", items[0].filename);
  16146. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16147. EXPECT_EQ(file_content, items[0].content);
  16148. handled = true;
  16149. });
  16150. auto port = svr.bind_to_any_port(HOST);
  16151. auto t = thread([&] { svr.listen_after_bind(); });
  16152. auto se = detail::scope_exit([&] {
  16153. svr.stop();
  16154. t.join();
  16155. ASSERT_FALSE(svr.is_running());
  16156. ASSERT_TRUE(handled);
  16157. std::remove(tmp_path.c_str());
  16158. });
  16159. svr.wait_until_ready();
  16160. FormDataProviderItems providers;
  16161. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16162. "application/octet-stream"));
  16163. Client cli(HOST, port);
  16164. auto res = cli.Post("/upload", {}, {}, providers);
  16165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16166. EXPECT_EQ(StatusCode::OK_200, res->status);
  16167. }
  16168. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16169. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16170. // (100) headers is rejected with a 400 Bad Request response.
  16171. Server svr;
  16172. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16173. res.set_content("ok", "text/plain");
  16174. });
  16175. thread t = thread([&] { svr.listen(HOST, PORT); });
  16176. auto se = detail::scope_exit([&] {
  16177. svr.stop();
  16178. t.join();
  16179. ASSERT_FALSE(svr.is_running());
  16180. });
  16181. svr.wait_until_ready();
  16182. // Build a multipart part with 101 custom headers (exceeding
  16183. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16184. std::stringstream body;
  16185. body << "--simpleboundary\r\n"
  16186. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16187. for (int i = 0; i < 101; i++) {
  16188. body << "X-Custom-Header-" << i << ": value\r\n";
  16189. }
  16190. body << "\r\n"
  16191. << "value1\r\n"
  16192. << "--simpleboundary--\r\n";
  16193. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16194. Client cli(HOST, PORT);
  16195. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16197. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16198. }
  16199. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16200. // A body that never contains the declared boundary must not be accumulated
  16201. // while the parser waits for it. Buffering it would also make every read
  16202. // rescan everything seen so far, which is quadratic in the body size.
  16203. Server svr;
  16204. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16205. res.set_content("ok", "text/plain");
  16206. });
  16207. auto port = svr.bind_to_any_port(HOST);
  16208. thread t = thread([&] { svr.listen_after_bind(); });
  16209. auto se = detail::scope_exit([&] {
  16210. svr.stop();
  16211. t.join();
  16212. ASSERT_FALSE(svr.is_running());
  16213. });
  16214. svr.wait_until_ready();
  16215. Client cli(HOST, port);
  16216. cli.set_read_timeout(60, 0);
  16217. cli.set_write_timeout(60, 0);
  16218. // '-' is the worst case: it matches the first character of the boundary, so
  16219. // every position has to be checked against it.
  16220. auto post_dashes = [&](size_t size) {
  16221. const std::string body(size, '-');
  16222. auto start = std::chrono::steady_clock::now();
  16223. auto res =
  16224. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16225. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16226. std::chrono::steady_clock::now() - start)
  16227. .count();
  16228. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16229. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16230. return ms;
  16231. };
  16232. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16233. // Windows.
  16234. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16235. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16236. // Comparing the two sizes rather than checking an absolute duration keeps
  16237. // this meaningful across build types and CI load, both of which move the
  16238. // absolute numbers by more than an order of magnitude. Four times the bytes
  16239. // costs about four times the time when parsing is linear, and about sixteen
  16240. // times when the body is buffered and rescanned.
  16241. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16242. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16243. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16244. << "ms, which suggests the body is being buffered and rescanned";
  16245. }
  16246. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16247. // A boundary can only be followed by CRLF or by "--", so anything else is
  16248. // malformed no matter what comes next. The parser must say so right away
  16249. // instead of buffering the rest of the declared body.
  16250. Server svr;
  16251. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16252. res.set_content("ok", "text/plain");
  16253. });
  16254. auto port = svr.bind_to_any_port(HOST);
  16255. thread t = thread([&] { svr.listen_after_bind(); });
  16256. auto se = detail::scope_exit([&] {
  16257. svr.stop();
  16258. t.join();
  16259. ASSERT_FALSE(svr.is_running());
  16260. });
  16261. svr.wait_until_ready();
  16262. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16263. // buffers instead of failing would still be waiting for the remaining bytes.
  16264. const std::string body = "--zzzz\r\n"
  16265. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16266. "\r\n"
  16267. "text1"
  16268. "\r\n--zzzzXX";
  16269. const std::string req = "POST /post HTTP/1.1\r\n"
  16270. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16271. "Content-Length: 1048576\r\n"
  16272. "\r\n" +
  16273. body;
  16274. std::string response;
  16275. ASSERT_TRUE(send_request(3, req, &response, port));
  16276. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16277. EXPECT_EQ("400", response.substr(9, 3));
  16278. }
  16279. // Posts a multipart body split into two writes, so that the server sees the
  16280. // split at whatever offset the caller chose, and expects the single "text1"
  16281. // field to come through.
  16282. static void expect_split_multipart_ok(const std::string &body1,
  16283. const std::string &body2) {
  16284. auto handled = false;
  16285. Server svr;
  16286. svr.Post("/post", [&](const Request &req, Response &) {
  16287. EXPECT_EQ(1u, req.form.fields.size());
  16288. EXPECT_EQ("text1", req.form.get_field("text1"));
  16289. handled = true;
  16290. });
  16291. auto port = svr.bind_to_any_port(HOST);
  16292. thread t = thread([&] { svr.listen_after_bind(); });
  16293. auto se = detail::scope_exit([&] {
  16294. svr.stop();
  16295. t.join();
  16296. ASSERT_FALSE(svr.is_running());
  16297. ASSERT_TRUE(handled);
  16298. });
  16299. svr.wait_until_ready();
  16300. // "Connection: close" makes the server close once it has answered, so the
  16301. // response drain ends immediately instead of idling until the read timeout.
  16302. const std::string head =
  16303. "POST /post HTTP/1.1\r\n"
  16304. "Host: localhost\r\n"
  16305. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16306. "Connection: close\r\n"
  16307. "Content-Length: " +
  16308. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16309. std::string response;
  16310. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16311. ASSERT_GE(response.size(), 12u) << "no response";
  16312. EXPECT_EQ("200", response.substr(9, 3));
  16313. }
  16314. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16315. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16316. // ignored, including when it does not arrive in the same read as the
  16317. // close-delimiter itself.
  16318. expect_split_multipart_ok("--zzzz\r\n"
  16319. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16320. "\r\n"
  16321. "text1"
  16322. "\r\n--zzzz--",
  16323. "\r\nthis epilogue must be ignored\r\n");
  16324. }
  16325. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16326. // The initial boundary may be preceded by a preamble of any length and may
  16327. // straddle a read boundary. Discarding data while waiting for it must not
  16328. // throw away a partial boundary sitting at the end of the buffer.
  16329. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16330. "zz\r\n"
  16331. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16332. "\r\n"
  16333. "text1"
  16334. "\r\n--zzzz--\r\n");
  16335. }
  16336. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16337. // The received boundary was only checked for being non-empty, so it could be
  16338. // as long as a header is allowed to be. The parser scans the body for
  16339. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16340. // costs a nearly full comparison at nearly every position, making the
  16341. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16342. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16343. Server svr;
  16344. svr.Post("/post", [](const Request &req, Response &res) {
  16345. EXPECT_EQ(1u, req.form.fields.size());
  16346. EXPECT_EQ("text1", req.form.get_field("text1"));
  16347. res.set_content("ok", "text/plain");
  16348. });
  16349. auto port = svr.bind_to_any_port(HOST);
  16350. thread t = thread([&] { svr.listen_after_bind(); });
  16351. auto se = detail::scope_exit([&] {
  16352. svr.stop();
  16353. t.join();
  16354. ASSERT_FALSE(svr.is_running());
  16355. });
  16356. svr.wait_until_ready();
  16357. Client cli(HOST, port);
  16358. auto post_with_boundary_of_length = [&](size_t len) {
  16359. const std::string boundary(len, 'a');
  16360. const std::string body =
  16361. "--" + boundary +
  16362. "\r\n"
  16363. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16364. "\r\n"
  16365. "text1"
  16366. "\r\n--" +
  16367. boundary + "--\r\n";
  16368. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16369. };
  16370. auto res = post_with_boundary_of_length(70);
  16371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16372. EXPECT_EQ(StatusCode::OK_200, res->status);
  16373. res = post_with_boundary_of_length(71);
  16374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16375. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16376. }
  16377. TEST(MakeFileBodyTest, Basic) {
  16378. const std::string file_content(4096, 'Z');
  16379. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16380. {
  16381. std::ofstream ofs(tmp_path, std::ios::binary);
  16382. ofs.write(file_content.data(),
  16383. static_cast<std::streamsize>(file_content.size()));
  16384. }
  16385. auto handled = false;
  16386. Server svr;
  16387. svr.Post("/upload", [&](const Request &req, Response &res) {
  16388. EXPECT_EQ(file_content, req.body);
  16389. handled = true;
  16390. res.status = StatusCode::OK_200;
  16391. });
  16392. auto port = svr.bind_to_any_port(HOST);
  16393. auto t = thread([&] { svr.listen_after_bind(); });
  16394. auto se = detail::scope_exit([&] {
  16395. svr.stop();
  16396. t.join();
  16397. ASSERT_FALSE(svr.is_running());
  16398. ASSERT_TRUE(handled);
  16399. std::remove(tmp_path.c_str());
  16400. });
  16401. svr.wait_until_ready();
  16402. auto fb = make_file_body(tmp_path);
  16403. ASSERT_GT(fb.first, 0u);
  16404. Client cli(HOST, port);
  16405. auto res =
  16406. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16408. EXPECT_EQ(StatusCode::OK_200, res->status);
  16409. }
  16410. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16411. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16412. {
  16413. std::ofstream ofs(path, std::ios::binary);
  16414. const std::string content(100, 'A');
  16415. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16416. }
  16417. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16418. auto body = make_file_body(path);
  16419. ASSERT_EQ(100u, body.first);
  16420. ASSERT_TRUE(static_cast<bool>(body.second));
  16421. // Rewritten shorter after its length was measured - and, on a server, after
  16422. // that length has already gone out as Content-Length.
  16423. {
  16424. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16425. const std::string content(10, 'A');
  16426. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16427. }
  16428. std::string written;
  16429. DataSink sink;
  16430. sink.write = [&](const char *d, size_t l) {
  16431. written.append(d, l);
  16432. return true;
  16433. };
  16434. // The provider has to report failure. write_content_with_progress() advances
  16435. // its offset only by what was written, so a provider that returns true
  16436. // without completing the length it promised is called again straight away,
  16437. // and again.
  16438. EXPECT_FALSE(body.second(0, body.first, sink));
  16439. EXPECT_EQ(std::string(10, 'A'), written);
  16440. }
  16441. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16442. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16443. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16444. {
  16445. std::ofstream ofs(path, std::ios::binary);
  16446. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16447. }
  16448. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16449. auto body = make_file_body(path);
  16450. ASSERT_EQ(content.size(), body.first);
  16451. ASSERT_TRUE(static_cast<bool>(body.second));
  16452. std::string written;
  16453. DataSink sink;
  16454. sink.write = [&](const char *d, size_t l) {
  16455. written.append(d, l);
  16456. return true;
  16457. };
  16458. EXPECT_TRUE(body.second(0, body.first, sink));
  16459. EXPECT_EQ(content, written);
  16460. }
  16461. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16462. static constexpr unsigned int number_of_tasks{1000000};
  16463. std::atomic_uint count{0};
  16464. std::unique_ptr<TaskQueue> task_queue{
  16465. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16466. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16467. auto queued = task_queue->enqueue(
  16468. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16469. EXPECT_TRUE(queued);
  16470. }
  16471. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16472. task_queue->shutdown();
  16473. #else
  16474. EXPECT_NO_THROW(task_queue->shutdown());
  16475. #endif
  16476. EXPECT_EQ(number_of_tasks, count.load());
  16477. }
  16478. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16479. static constexpr unsigned int number_of_tasks{1000000};
  16480. static constexpr unsigned int qlimit{2};
  16481. unsigned int queued_count{0};
  16482. std::atomic_uint count{0};
  16483. std::unique_ptr<TaskQueue> task_queue{
  16484. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16485. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16486. if (task_queue->enqueue(
  16487. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16488. queued_count++;
  16489. }
  16490. }
  16491. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16492. task_queue->shutdown();
  16493. #else
  16494. EXPECT_NO_THROW(task_queue->shutdown());
  16495. #endif
  16496. EXPECT_EQ(queued_count, count.load());
  16497. EXPECT_TRUE(queued_count <= number_of_tasks);
  16498. EXPECT_TRUE(queued_count >= qlimit);
  16499. }
  16500. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16501. // Use a short idle timeout so a dynamic thread spawns, times out and
  16502. // exits during the test, and the pool keeps working afterwards.
  16503. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16504. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16505. /*idle_timeout_sec=*/1}};
  16506. std::atomic_uint count{0};
  16507. std::condition_variable cv;
  16508. std::mutex mtx;
  16509. bool release = false;
  16510. // Block the base thread so the second task spawns a dynamic thread.
  16511. EXPECT_TRUE(task_queue->enqueue([&] {
  16512. std::unique_lock<std::mutex> lock(mtx);
  16513. while (!release) {
  16514. cv.wait(lock);
  16515. }
  16516. count++;
  16517. }));
  16518. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16519. // Let the dynamic thread finish its task and exceed the idle timeout.
  16520. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16521. {
  16522. std::unique_lock<std::mutex> lock(mtx);
  16523. release = true;
  16524. }
  16525. cv.notify_all();
  16526. // The pool must still accept and run tasks after the dynamic thread exited.
  16527. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16528. task_queue->shutdown();
  16529. EXPECT_EQ(3u, count.load());
  16530. }
  16531. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16532. static constexpr size_t number_of_tasks{32};
  16533. std::unique_ptr<TaskQueue> task_queue{
  16534. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16535. // Let the base threads go idle so the burst below finds them waiting.
  16536. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16537. std::mutex mtx;
  16538. std::condition_variable cv;
  16539. size_t running = 0;
  16540. bool release = false;
  16541. for (size_t i = 0; i < number_of_tasks; i++) {
  16542. EXPECT_TRUE(task_queue->enqueue([&] {
  16543. std::unique_lock<std::mutex> lock(mtx);
  16544. running++;
  16545. cv.notify_all();
  16546. cv.wait(lock, [&] { return release; });
  16547. }));
  16548. }
  16549. {
  16550. std::unique_lock<std::mutex> lock(mtx);
  16551. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16552. [&] { return running == number_of_tasks; }));
  16553. release = true;
  16554. }
  16555. cv.notify_all();
  16556. task_queue->shutdown();
  16557. }
  16558. TEST(TaskQueueTest, MaxQueuedRequests) {
  16559. static constexpr unsigned int qlimit{3};
  16560. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16561. std::condition_variable sem_cv;
  16562. std::mutex sem_mtx;
  16563. int credits = 0;
  16564. bool queued;
  16565. /* Fill up the queue with tasks that will block until we give them credits to
  16566. * complete. */
  16567. for (unsigned int n = 0; n <= qlimit;) {
  16568. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16569. std::unique_lock<std::mutex> lock(sem_mtx);
  16570. while (credits <= 0) {
  16571. sem_cv.wait(lock);
  16572. }
  16573. /* Consume the credit and signal the test code if they are all gone. */
  16574. if (--credits == 0) { sem_cv.notify_one(); }
  16575. });
  16576. if (n < qlimit) {
  16577. /* The first qlimit enqueues must succeed. */
  16578. EXPECT_TRUE(queued);
  16579. } else {
  16580. /* The last one will succeed only when the worker thread
  16581. * starts and dequeues the first blocking task. Although
  16582. * not necessary for the correctness of this test, we sleep for
  16583. * a short while to avoid busy waiting. */
  16584. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16585. }
  16586. if (queued) { n++; }
  16587. }
  16588. /* Further enqueues must fail since the queue is full. */
  16589. for (auto i = 0; i < 4; i++) {
  16590. queued = task_queue->enqueue([] {});
  16591. EXPECT_FALSE(queued);
  16592. }
  16593. /* Give the credits to allow the previous tasks to complete. */
  16594. {
  16595. std::unique_lock<std::mutex> lock(sem_mtx);
  16596. credits += qlimit + 1;
  16597. }
  16598. sem_cv.notify_all();
  16599. /* Wait for all the credits to be consumed. */
  16600. {
  16601. std::unique_lock<std::mutex> lock(sem_mtx);
  16602. while (credits > 0) {
  16603. sem_cv.wait(lock);
  16604. }
  16605. }
  16606. /* Check that we are able again to enqueue at least qlimit tasks. */
  16607. for (unsigned int i = 0; i < qlimit; i++) {
  16608. queued = task_queue->enqueue([] {});
  16609. EXPECT_TRUE(queued);
  16610. }
  16611. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16612. task_queue->shutdown();
  16613. #else
  16614. EXPECT_NO_THROW(task_queue->shutdown());
  16615. #endif
  16616. }
  16617. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16618. Server svr;
  16619. std::string method;
  16620. std::string body;
  16621. auto has_content_length = false;
  16622. auto has_transfer_encoding = false;
  16623. std::atomic<int> bad_requests{0};
  16624. // Leftover body bytes get parsed as a malformed request and answered with
  16625. // 400
  16626. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16627. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16628. });
  16629. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16630. res.set_redirect("/down", StatusCode::SeeOther_303);
  16631. });
  16632. svr.Get("/down", [&](const Request &req, Response &res) {
  16633. method = req.method;
  16634. body = req.body;
  16635. has_content_length = req.has_header("Content-Length");
  16636. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16637. res.set_content("ok", "text/plain");
  16638. });
  16639. auto port = svr.bind_to_any_port(HOST);
  16640. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16641. auto se = detail::scope_exit([&] {
  16642. svr.stop();
  16643. thread.join();
  16644. ASSERT_FALSE(svr.is_running());
  16645. });
  16646. svr.wait_until_ready();
  16647. const std::string payload = "SECRET-BODY";
  16648. auto check = [&](Client &cli, const Result &res) {
  16649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16650. EXPECT_EQ(StatusCode::OK_200, res->status);
  16651. EXPECT_EQ("ok", res->body);
  16652. EXPECT_EQ("GET", method);
  16653. EXPECT_TRUE(body.empty());
  16654. EXPECT_FALSE(has_content_length);
  16655. EXPECT_FALSE(has_transfer_encoding);
  16656. // Nothing of the original body may be left on the connection
  16657. auto res2 = cli.Get("/down");
  16658. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16659. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16660. EXPECT_EQ("ok", res2->body);
  16661. EXPECT_EQ(0, bad_requests);
  16662. };
  16663. // With content length
  16664. {
  16665. Client cli(HOST, port);
  16666. cli.set_keep_alive(true);
  16667. cli.set_follow_location(true);
  16668. auto res = cli.Post(
  16669. "/up", payload.size(),
  16670. [&](size_t offset, size_t length, DataSink &sink) {
  16671. return sink.write(payload.data() + offset, length);
  16672. },
  16673. "text/plain");
  16674. check(cli, res);
  16675. }
  16676. // Without content length (chunked)
  16677. {
  16678. Client cli(HOST, port);
  16679. cli.set_keep_alive(true);
  16680. cli.set_follow_location(true);
  16681. auto res = cli.Post(
  16682. "/up",
  16683. [&](size_t /*offset*/, DataSink &sink) {
  16684. sink.write(payload.data(), payload.size());
  16685. sink.done();
  16686. return true;
  16687. },
  16688. "text/plain");
  16689. check(cli, res);
  16690. }
  16691. }
  16692. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16693. Server svr;
  16694. std::string target;
  16695. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16696. // Echo the still-encoded name back in the Location
  16697. const std::string prefix = "/start/";
  16698. res.status = StatusCode::Found_302;
  16699. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16700. });
  16701. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16702. target = req.target;
  16703. res.set_content("ok", "text/plain");
  16704. });
  16705. auto port = svr.bind_to_any_port(HOST);
  16706. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16707. auto se = detail::scope_exit([&] {
  16708. svr.stop();
  16709. thread.join();
  16710. ASSERT_FALSE(svr.is_running());
  16711. });
  16712. svr.wait_until_ready();
  16713. // Decoding the Location path would turn the first four into a path
  16714. // separator, a query delimiter, a fragment delimiter and a different
  16715. // percent-encoded octet. The rest must keep reaching the server as they are.
  16716. const std::vector<std::string> names = {
  16717. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16718. };
  16719. for (auto path_encode : {true, false}) {
  16720. Client cli(HOST, port);
  16721. cli.set_follow_location(true);
  16722. cli.set_path_encode(path_encode);
  16723. for (const auto &name : names) {
  16724. target.clear();
  16725. auto res = cli.Get("/start/" + name);
  16726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16727. EXPECT_EQ(StatusCode::OK_200, res->status);
  16728. EXPECT_EQ("/dest/" + name, target);
  16729. }
  16730. }
  16731. }
  16732. TEST(RedirectTest, NotModifiedIsReturned) {
  16733. Server svr;
  16734. svr.Get("/cached", [](const Request &, Response &res) {
  16735. res.status = StatusCode::NotModified_304;
  16736. });
  16737. auto port = svr.bind_to_any_port(HOST);
  16738. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16739. auto se = detail::scope_exit([&] {
  16740. svr.stop();
  16741. thread.join();
  16742. ASSERT_FALSE(svr.is_running());
  16743. });
  16744. svr.wait_until_ready();
  16745. Client cli(HOST, port);
  16746. cli.set_follow_location(true);
  16747. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16749. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16750. }
  16751. TEST(RedirectTest, NoLocationIsReturned) {
  16752. Server svr;
  16753. svr.Get("/no-location", [](const Request &, Response &res) {
  16754. res.status = StatusCode::Found_302;
  16755. res.set_content("no location", "text/plain");
  16756. });
  16757. auto port = svr.bind_to_any_port(HOST);
  16758. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16759. auto se = detail::scope_exit([&] {
  16760. svr.stop();
  16761. thread.join();
  16762. ASSERT_FALSE(svr.is_running());
  16763. });
  16764. svr.wait_until_ready();
  16765. Client cli(HOST, port);
  16766. cli.set_follow_location(true);
  16767. auto res = cli.Get("/no-location");
  16768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16769. EXPECT_EQ(StatusCode::Found_302, res->status);
  16770. EXPECT_EQ("no location", res->body);
  16771. // The callbacks see the body of the response that is returned
  16772. auto handler_called = false;
  16773. auto progress_called = false;
  16774. std::string body;
  16775. auto res2 = cli.Get(
  16776. "/no-location",
  16777. [&](const Response &) {
  16778. handler_called = true;
  16779. return true;
  16780. },
  16781. [&](const char *data, size_t data_length) {
  16782. body.append(data, data_length);
  16783. return true;
  16784. },
  16785. [&](size_t, size_t) {
  16786. progress_called = true;
  16787. return true;
  16788. });
  16789. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16790. EXPECT_EQ(StatusCode::Found_302, res2->status);
  16791. EXPECT_TRUE(handler_called);
  16792. EXPECT_TRUE(progress_called);
  16793. EXPECT_EQ("no location", body);
  16794. }
  16795. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16796. Server svr;
  16797. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16798. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16799. });
  16800. svr.Get("/hello", [](const Request &req, Response &res) {
  16801. res.set_content(req.get_param_value("key"), "text/plain");
  16802. });
  16803. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16804. auto se = detail::scope_exit([&] {
  16805. svr.stop();
  16806. thread.join();
  16807. ASSERT_FALSE(svr.is_running());
  16808. });
  16809. svr.wait_until_ready();
  16810. {
  16811. Client cli(HOST, PORT);
  16812. cli.set_follow_location(true);
  16813. auto res = cli.Get("/");
  16814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16815. EXPECT_EQ(StatusCode::OK_200, res->status);
  16816. EXPECT_EQ("val&key2=val2", res->body);
  16817. }
  16818. }
  16819. #endif
  16820. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16821. Server svr;
  16822. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16823. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16824. });
  16825. svr.Get("/hello", [](const Request &req, Response &res) {
  16826. res.set_content(req.get_param_value("key"), "text/plain");
  16827. });
  16828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16829. auto se = detail::scope_exit([&] {
  16830. svr.stop();
  16831. thread.join();
  16832. ASSERT_FALSE(svr.is_running());
  16833. });
  16834. svr.wait_until_ready();
  16835. {
  16836. Client cli(HOST, PORT);
  16837. cli.set_follow_location(true);
  16838. auto res = cli.Get("/");
  16839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16840. EXPECT_EQ(StatusCode::OK_200, res->status);
  16841. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16842. }
  16843. }
  16844. TEST(RedirectTest, RedirectWithPlusInPath) {
  16845. Server svr;
  16846. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16847. res.set_redirect("/a+b");
  16848. });
  16849. // Route pattern uses regex; escape + as \\+
  16850. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16851. res.set_content(req.path, "text/plain");
  16852. });
  16853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16854. auto se = detail::scope_exit([&] {
  16855. svr.stop();
  16856. thread.join();
  16857. ASSERT_FALSE(svr.is_running());
  16858. });
  16859. svr.wait_until_ready();
  16860. {
  16861. Client cli(HOST, PORT);
  16862. cli.set_follow_location(true);
  16863. auto res = cli.Get("/");
  16864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16865. EXPECT_EQ(StatusCode::OK_200, res->status);
  16866. EXPECT_EQ("/a+b", res->body);
  16867. }
  16868. }
  16869. TEST(RedirectTest, ResolveRelativeLocation) {
  16870. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16871. const std::vector<std::pair<std::string, std::string>> cases = {
  16872. {"g", "/b/c/g"},
  16873. {"./g", "/b/c/g"},
  16874. {"g/", "/b/c/g/"},
  16875. {"?y", "/b/c/d;p?y"},
  16876. {"g?y", "/b/c/g?y"},
  16877. {"#s", "/b/c/d;p?q#s"},
  16878. {"g#s", "/b/c/g#s"},
  16879. {"g?y#s", "/b/c/g?y#s"},
  16880. {";x", "/b/c/;x"},
  16881. {"g;x", "/b/c/g;x"},
  16882. {".", "/b/c/"},
  16883. {"./", "/b/c/"},
  16884. {"..", "/b/"},
  16885. {"../", "/b/"},
  16886. {"../g", "/b/g"},
  16887. {"../..", "/"},
  16888. {"../../", "/"},
  16889. {"../../g", "/g"},
  16890. {"../../../g", "/g"},
  16891. {"g.", "/b/c/g."},
  16892. {".g", "/b/c/.g"},
  16893. {"g..", "/b/c/g.."},
  16894. {"..g", "/b/c/..g"},
  16895. {"./../g", "/b/g"},
  16896. {"./g/.", "/b/c/g/"},
  16897. {"g/./h", "/b/c/g/h"},
  16898. {"g/../h", "/b/c/h"},
  16899. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16900. {"g;x=1/../y", "/b/c/y"},
  16901. {"g?y/./x", "/b/c/g?y/./x"},
  16902. {"g#s/../x", "/b/c/g#s/../x"},
  16903. // Not relative-path references, so left for parse_url.
  16904. {"/g", "/g"},
  16905. {"//g", "//g"},
  16906. {"http://g/x", "http://g/x"},
  16907. {"g:h", "g:h"},
  16908. };
  16909. for (const auto &c : cases) {
  16910. EXPECT_EQ(c.second,
  16911. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16912. << c.first;
  16913. }
  16914. }
  16915. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16916. Server svr;
  16917. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16918. res.set_redirect(req.get_param_value("to"));
  16919. });
  16920. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16921. res.set_content(req.target, "text/plain");
  16922. });
  16923. svr.Get("/other", [](const Request &req, Response &res) {
  16924. res.set_content(req.target, "text/plain");
  16925. });
  16926. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16927. auto se = detail::scope_exit([&] {
  16928. svr.stop();
  16929. thread.join();
  16930. ASSERT_FALSE(svr.is_running());
  16931. });
  16932. svr.wait_until_ready();
  16933. const std::vector<std::pair<std::string, std::string>> cases = {
  16934. {"next", "/dir/next"},
  16935. {"./next?x=1", "/dir/next?x=1"},
  16936. {"../other", "/other"},
  16937. };
  16938. for (const auto &c : cases) {
  16939. Client cli(HOST, PORT);
  16940. cli.set_follow_location(true);
  16941. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16942. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16943. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16944. EXPECT_EQ(c.second, res->body) << c.first;
  16945. }
  16946. }
  16947. #ifdef CPPHTTPLIB_SSL_ENABLED
  16948. TEST(RedirectTest, Issue2185_Online) {
  16949. SSLClient client("github.com");
  16950. client.set_follow_location(true);
  16951. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16952. "Coollab-Windows.zip");
  16953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16954. EXPECT_EQ(StatusCode::OK_200, res->status);
  16955. EXPECT_EQ(9920427U, res->body.size());
  16956. }
  16957. #endif
  16958. TEST(VulnerabilityTest, CRLFInjection) {
  16959. Server svr;
  16960. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16961. res.set_content("Hello 1", "text/plain");
  16962. });
  16963. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16964. res.set_content("Hello 2", "text/plain");
  16965. });
  16966. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16967. res.set_content("Hello 3", "text/plain");
  16968. });
  16969. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16970. res.set_content("Hello 4", "text/plain");
  16971. });
  16972. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16973. for (const auto &x : req.headers) {
  16974. auto key = x.first;
  16975. EXPECT_STRNE("evil", key.c_str());
  16976. }
  16977. });
  16978. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16979. auto se = detail::scope_exit([&] {
  16980. svr.stop();
  16981. thread.join();
  16982. ASSERT_FALSE(svr.is_running());
  16983. });
  16984. svr.wait_until_ready();
  16985. {
  16986. Client cli(HOST, PORT);
  16987. cli.Post("/test1", "A=B",
  16988. "application/x-www-form-urlencoded\r\nevil: hello1");
  16989. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16990. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16991. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16992. }
  16993. }
  16994. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16995. auto server_thread = std::thread([] {
  16996. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16997. default_socket_options(srv);
  16998. sockaddr_in addr{};
  16999. addr.sin_family = AF_INET;
  17000. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17001. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17002. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17003. ::listen(srv, 1);
  17004. sockaddr_in cli_addr{};
  17005. socklen_t cli_len = sizeof(cli_addr);
  17006. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17007. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17008. std::string buf_all;
  17009. char buf[2048];
  17010. ssize_t n;
  17011. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17012. buf_all.append(buf, static_cast<size_t>(n));
  17013. size_t pos;
  17014. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17015. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17016. auto e = request_block.find("\r\n");
  17017. if (e != std::string::npos) {
  17018. auto request_line = request_block.substr(0, e);
  17019. std::string msg =
  17020. "CRLF injection detected in request line: '" + request_line + "'";
  17021. EXPECT_FALSE(true) << msg;
  17022. }
  17023. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17024. ::send(cli,
  17025. #ifdef _WIN32
  17026. static_cast<const char *>(resp.c_str()),
  17027. static_cast<int>(resp.size()),
  17028. #else
  17029. resp.c_str(), resp.size(),
  17030. #endif
  17031. 0);
  17032. buf_all.erase(0, pos + 4);
  17033. }
  17034. }
  17035. detail::close_socket(cli);
  17036. detail::close_socket(srv);
  17037. });
  17038. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17039. auto cli = Client("127.0.0.1", PORT + 1);
  17040. auto headers = Headers{
  17041. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17042. {"Connection", "keep-alive"}};
  17043. auto res = cli.Get("/hi", headers);
  17044. EXPECT_FALSE(res);
  17045. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17046. server_thread.join();
  17047. }
  17048. // A request rejected before any byte reaches the socket must fail right away
  17049. // instead of waiting for a response the server will never send.
  17050. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17051. // The kernel completes the TCP handshake from the listen backlog, so the
  17052. // client connects, but nothing ever reads, responds or closes.
  17053. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17054. default_socket_options(srv);
  17055. sockaddr_in addr{};
  17056. addr.sin_family = AF_INET;
  17057. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17058. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17059. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17060. ASSERT_EQ(0, ::listen(srv, 8));
  17061. auto cli = Client("127.0.0.1", PORT + 1);
  17062. cli.set_read_timeout(10, 0);
  17063. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17064. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17065. std::chrono::steady_clock::now() - start)
  17066. .count();
  17067. };
  17068. {
  17069. Request req;
  17070. req.method = "GE T";
  17071. req.path = "/";
  17072. auto start = std::chrono::steady_clock::now();
  17073. auto res = cli.send(req);
  17074. EXPECT_FALSE(res);
  17075. EXPECT_EQ(Error::Write, res.error());
  17076. EXPECT_LT(elapsed_ms(start), 1000);
  17077. }
  17078. {
  17079. auto start = std::chrono::steady_clock::now();
  17080. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17081. EXPECT_FALSE(res);
  17082. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17083. EXPECT_LT(elapsed_ms(start), 1000);
  17084. }
  17085. EXPECT_FALSE(cli.is_socket_open());
  17086. detail::close_socket(srv);
  17087. }
  17088. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17089. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17090. default_socket_options(srv);
  17091. sockaddr_in addr{};
  17092. addr.sin_family = AF_INET;
  17093. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17094. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17095. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17096. ASSERT_EQ(0, ::listen(srv, 1));
  17097. std::string received;
  17098. auto server_thread = std::thread([&] {
  17099. auto sock = ::accept(srv, nullptr, nullptr);
  17100. if (sock == INVALID_SOCKET) { return; }
  17101. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17102. char buf[2048];
  17103. ssize_t n;
  17104. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17105. received.append(buf, static_cast<size_t>(n));
  17106. }
  17107. detail::close_socket(sock);
  17108. });
  17109. {
  17110. auto cli = Client("127.0.0.1", PORT + 1);
  17111. // "Z" sorts after the default headers, so writing straight to the socket
  17112. // would have sent the request line and those headers before the rejection.
  17113. auto handle =
  17114. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17115. EXPECT_FALSE(handle.is_valid());
  17116. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17117. }
  17118. server_thread.join();
  17119. detail::close_socket(srv);
  17120. EXPECT_TRUE(received.empty()) << received;
  17121. }
  17122. TEST(PathParamsTest, StaticMatch) {
  17123. const auto pattern = "/users/all";
  17124. detail::PathParamsMatcher matcher(pattern);
  17125. Request request;
  17126. request.path = "/users/all";
  17127. ASSERT_TRUE(matcher.match(request));
  17128. std::unordered_map<std::string, std::string> expected_params = {};
  17129. EXPECT_EQ(request.path_params, expected_params);
  17130. }
  17131. TEST(PathParamsTest, StaticMismatch) {
  17132. const auto pattern = "/users/all";
  17133. detail::PathParamsMatcher matcher(pattern);
  17134. Request request;
  17135. request.path = "/users/1";
  17136. ASSERT_FALSE(matcher.match(request));
  17137. }
  17138. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17139. const auto pattern = "/users/:id/subscriptions";
  17140. detail::PathParamsMatcher matcher(pattern);
  17141. Request request;
  17142. request.path = "/users/42/subscriptions";
  17143. ASSERT_TRUE(matcher.match(request));
  17144. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17145. EXPECT_EQ(request.path_params, expected_params);
  17146. }
  17147. TEST(PathParamsTest, SingleParamInTheEnd) {
  17148. const auto pattern = "/users/:id";
  17149. detail::PathParamsMatcher matcher(pattern);
  17150. Request request;
  17151. request.path = "/users/24";
  17152. ASSERT_TRUE(matcher.match(request));
  17153. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17154. EXPECT_EQ(request.path_params, expected_params);
  17155. }
  17156. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17157. const auto pattern = "/users/:id/";
  17158. detail::PathParamsMatcher matcher(pattern);
  17159. Request request;
  17160. request.path = "/users/42/";
  17161. ASSERT_TRUE(matcher.match(request));
  17162. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17163. EXPECT_EQ(request.path_params, expected_params);
  17164. }
  17165. TEST(PathParamsTest, EmptyParam) {
  17166. const auto pattern = "/users/:id/";
  17167. detail::PathParamsMatcher matcher(pattern);
  17168. Request request;
  17169. request.path = "/users//";
  17170. ASSERT_TRUE(matcher.match(request));
  17171. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17172. EXPECT_EQ(request.path_params, expected_params);
  17173. }
  17174. TEST(PathParamsTest, FragmentMismatch) {
  17175. const auto pattern = "/users/:id/";
  17176. detail::PathParamsMatcher matcher(pattern);
  17177. Request request;
  17178. request.path = "/admins/24/";
  17179. ASSERT_FALSE(matcher.match(request));
  17180. }
  17181. TEST(PathParamsTest, ExtraFragments) {
  17182. const auto pattern = "/users/:id";
  17183. detail::PathParamsMatcher matcher(pattern);
  17184. Request request;
  17185. request.path = "/users/42/subscriptions";
  17186. ASSERT_FALSE(matcher.match(request));
  17187. }
  17188. TEST(PathParamsTest, MissingTrailingParam) {
  17189. const auto pattern = "/users/:id";
  17190. detail::PathParamsMatcher matcher(pattern);
  17191. Request request;
  17192. request.path = "/users";
  17193. ASSERT_FALSE(matcher.match(request));
  17194. }
  17195. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17196. const auto pattern = "/users/:id/subscriptions";
  17197. detail::PathParamsMatcher matcher(pattern);
  17198. Request request;
  17199. request.path = "/users/subscriptions";
  17200. ASSERT_FALSE(matcher.match(request));
  17201. }
  17202. TEST(PathParamsTest, MultipleParams) {
  17203. const auto pattern = "/users/:userid/subscriptions/:subid";
  17204. detail::PathParamsMatcher matcher(pattern);
  17205. Request request;
  17206. request.path = "/users/42/subscriptions/2";
  17207. ASSERT_TRUE(matcher.match(request));
  17208. std::unordered_map<std::string, std::string> expected_params = {
  17209. {"userid", "42"}, {"subid", "2"}};
  17210. EXPECT_EQ(request.path_params, expected_params);
  17211. }
  17212. TEST(PathParamsTest, SequenceOfParams) {
  17213. const auto pattern = "/values/:x/:y/:z";
  17214. detail::PathParamsMatcher matcher(pattern);
  17215. Request request;
  17216. request.path = "/values/1/2/3";
  17217. ASSERT_TRUE(matcher.match(request));
  17218. std::unordered_map<std::string, std::string> expected_params = {
  17219. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17220. EXPECT_EQ(request.path_params, expected_params);
  17221. }
  17222. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17223. const auto pattern = "/prefix:suffix";
  17224. detail::PathParamsMatcher matcher(pattern);
  17225. Request request;
  17226. request.path = "/prefix:suffix";
  17227. ASSERT_TRUE(matcher.match(request));
  17228. const std::unordered_map<std::string, std::string> expected_params = {};
  17229. EXPECT_EQ(request.path_params, expected_params);
  17230. }
  17231. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17232. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17233. // calling thread's stack on a long enough path for a quantified pattern;
  17234. // RegexMatcher must refuse to run regex matching on paths beyond
  17235. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17236. detail::RegexMatcher matcher("/files/(.*)");
  17237. Request within_limit;
  17238. within_limit.path = "/files/" + std::string(10, 'A');
  17239. EXPECT_TRUE(matcher.match(within_limit));
  17240. Request over_limit;
  17241. over_limit.path =
  17242. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17243. EXPECT_FALSE(matcher.match(over_limit));
  17244. }
  17245. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17246. Server svr;
  17247. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17248. res.set_content("ok", "text/plain");
  17249. });
  17250. auto port = svr.bind_to_any_port(HOST);
  17251. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17252. auto se = detail::scope_exit([&] {
  17253. svr.stop();
  17254. thread.join();
  17255. ASSERT_FALSE(svr.is_running());
  17256. });
  17257. svr.wait_until_ready();
  17258. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17259. // request URI limit; this used to be able to crash the process.
  17260. std::string path =
  17261. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17262. std::string req = "GET " + path +
  17263. " HTTP/1.1\r\n"
  17264. "Host: " +
  17265. std::string(HOST) + ":" + std::to_string(port) +
  17266. "\r\n"
  17267. "Connection: close\r\n"
  17268. "\r\n";
  17269. std::string response;
  17270. ASSERT_TRUE(send_request(5, req, &response, port));
  17271. EXPECT_NE(std::string::npos, response.find("404"));
  17272. }
  17273. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17274. Server svr;
  17275. auto handler = [](const Request & /*req*/, Response &res) {
  17276. res.set_content("hit", "text/plain");
  17277. };
  17278. // No regex metacharacter, so this one is compared literally
  17279. svr.Get("/literal/route", handler);
  17280. // '.' is a regex metacharacter, so this one must keep regex semantics
  17281. svr.Get("/a.c", handler);
  17282. auto port = svr.bind_to_any_port(HOST);
  17283. std::thread t([&]() { svr.listen_after_bind(); });
  17284. auto se = detail::scope_exit([&] {
  17285. svr.stop();
  17286. t.join();
  17287. ASSERT_FALSE(svr.is_running());
  17288. });
  17289. svr.wait_until_ready();
  17290. Client cli(HOST, port);
  17291. struct {
  17292. const char *path;
  17293. int status;
  17294. } cases[] = {
  17295. {"/literal/route", StatusCode::OK_200},
  17296. {"/literal/routes", StatusCode::NotFound_404},
  17297. {"/literal/rout", StatusCode::NotFound_404},
  17298. {"/abc", StatusCode::OK_200},
  17299. {"/a.c", StatusCode::OK_200},
  17300. };
  17301. for (const auto &x : cases) {
  17302. auto res = cli.Get(x.path);
  17303. ASSERT_TRUE(res) << x.path;
  17304. EXPECT_EQ(x.status, res->status) << x.path;
  17305. }
  17306. }
  17307. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17308. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17309. // from exhausting the stack, so it must only constrain routes that actually
  17310. // run a regular expression. A literal route is matched by comparison and
  17311. // stays usable at any length.
  17312. Server svr;
  17313. const std::string pattern =
  17314. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17315. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17316. res.set_content("hit", "text/plain");
  17317. });
  17318. auto port = svr.bind_to_any_port(HOST);
  17319. std::thread t([&]() { svr.listen_after_bind(); });
  17320. auto se = detail::scope_exit([&] {
  17321. svr.stop();
  17322. t.join();
  17323. ASSERT_FALSE(svr.is_running());
  17324. });
  17325. svr.wait_until_ready();
  17326. Client cli(HOST, port);
  17327. auto res = cli.Get(pattern);
  17328. ASSERT_TRUE(res);
  17329. EXPECT_EQ(StatusCode::OK_200, res->status);
  17330. }
  17331. TEST(ParseUrlTest, VariousPatterns) {
  17332. {
  17333. detail::UrlComponents uc;
  17334. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17335. EXPECT_EQ("http", uc.scheme);
  17336. EXPECT_EQ("example.com", uc.host);
  17337. EXPECT_EQ("8080", uc.port);
  17338. EXPECT_EQ("/path", uc.path);
  17339. EXPECT_EQ("?q=1", uc.query);
  17340. }
  17341. {
  17342. detail::UrlComponents uc;
  17343. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17344. EXPECT_EQ("https", uc.scheme);
  17345. EXPECT_EQ("example.com", uc.host);
  17346. EXPECT_TRUE(uc.port.empty());
  17347. EXPECT_EQ("/path", uc.path);
  17348. }
  17349. {
  17350. detail::UrlComponents uc;
  17351. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17352. EXPECT_EQ("::1", uc.host);
  17353. EXPECT_EQ("8080", uc.port);
  17354. EXPECT_EQ("/path", uc.path);
  17355. }
  17356. {
  17357. detail::UrlComponents uc;
  17358. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17359. }
  17360. {
  17361. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17362. // the path while the connection still targets the bracketed host.
  17363. detail::UrlComponents uc;
  17364. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17365. }
  17366. {
  17367. detail::UrlComponents uc;
  17368. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17369. }
  17370. {
  17371. detail::UrlComponents uc;
  17372. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17373. EXPECT_EQ("::1", uc.host);
  17374. EXPECT_TRUE(uc.port.empty());
  17375. EXPECT_EQ("/path", uc.path);
  17376. }
  17377. {
  17378. detail::UrlComponents uc;
  17379. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17380. EXPECT_TRUE(uc.scheme.empty());
  17381. EXPECT_EQ("example.com", uc.host);
  17382. EXPECT_EQ("/path", uc.path);
  17383. EXPECT_EQ("?q=1", uc.query);
  17384. }
  17385. {
  17386. detail::UrlComponents uc;
  17387. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17388. EXPECT_TRUE(uc.host.empty());
  17389. EXPECT_EQ("/path", uc.path);
  17390. EXPECT_EQ("?q=1", uc.query);
  17391. }
  17392. {
  17393. detail::UrlComponents uc;
  17394. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17395. EXPECT_EQ("example.com", uc.host);
  17396. EXPECT_EQ("8080", uc.port);
  17397. }
  17398. {
  17399. // Unix socket path — must not be parsed as host
  17400. detail::UrlComponents uc;
  17401. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17402. EXPECT_TRUE(uc.host.empty());
  17403. }
  17404. {
  17405. detail::UrlComponents uc;
  17406. ASSERT_TRUE(detail::parse_url("", uc));
  17407. EXPECT_TRUE(uc.host.empty());
  17408. EXPECT_TRUE(uc.path.empty());
  17409. }
  17410. {
  17411. detail::UrlComponents uc;
  17412. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17413. }
  17414. {
  17415. detail::UrlComponents uc;
  17416. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17417. }
  17418. {
  17419. // Accepted by parse_url; callers restrict to http/https
  17420. detail::UrlComponents uc;
  17421. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17422. EXPECT_EQ("ftp", uc.scheme);
  17423. }
  17424. {
  17425. detail::UrlComponents uc;
  17426. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17427. }
  17428. {
  17429. detail::UrlComponents uc;
  17430. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17431. }
  17432. }
  17433. TEST(ParseUrlTest, FragmentHandling) {
  17434. {
  17435. detail::UrlComponents uc;
  17436. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17437. EXPECT_EQ("/path", uc.path);
  17438. EXPECT_TRUE(uc.query.empty());
  17439. }
  17440. {
  17441. detail::UrlComponents uc;
  17442. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17443. EXPECT_TRUE(uc.path.empty());
  17444. EXPECT_TRUE(uc.query.empty());
  17445. }
  17446. }
  17447. TEST(ParseUrlTest, UserinfoHandling) {
  17448. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17449. // parsers would see evil.com as the host.
  17450. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17451. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17452. for (auto url : urls) {
  17453. detail::UrlComponents uc;
  17454. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17455. }
  17456. }
  17457. TEST(ParseUrlTest, IPv6EdgeCases) {
  17458. {
  17459. detail::UrlComponents uc;
  17460. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17461. EXPECT_TRUE(uc.scheme.empty());
  17462. EXPECT_EQ("::1", uc.host);
  17463. EXPECT_EQ("8080", uc.port);
  17464. }
  17465. {
  17466. // Zone ID '%25' is not in [a-fA-F0-9:]
  17467. detail::UrlComponents uc;
  17468. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17469. }
  17470. }
  17471. TEST(ParseUrlTest, SchemeEdgeCases) {
  17472. {
  17473. detail::UrlComponents uc;
  17474. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17475. }
  17476. {
  17477. detail::UrlComponents uc;
  17478. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17479. }
  17480. {
  17481. detail::UrlComponents uc;
  17482. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17483. }
  17484. }
  17485. TEST(ParseUrlTest, PortEdgeCases) {
  17486. {
  17487. detail::UrlComponents uc;
  17488. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17489. EXPECT_TRUE(uc.port.empty());
  17490. EXPECT_EQ("/path", uc.path);
  17491. }
  17492. {
  17493. // parse_url accepts any port string; validation is done by parse_port
  17494. detail::UrlComponents uc;
  17495. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17496. EXPECT_EQ("abc", uc.port);
  17497. }
  17498. }
  17499. TEST(ParseUrlTest, WebSocketPatterns) {
  17500. {
  17501. detail::UrlComponents uc;
  17502. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17503. EXPECT_EQ("ws", uc.scheme);
  17504. EXPECT_EQ("echo.example.com", uc.host);
  17505. EXPECT_EQ("8080", uc.port);
  17506. EXPECT_EQ("/ws", uc.path);
  17507. }
  17508. {
  17509. detail::UrlComponents uc;
  17510. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17511. EXPECT_EQ("wss", uc.scheme);
  17512. EXPECT_EQ("echo.example.com", uc.host);
  17513. EXPECT_TRUE(uc.port.empty());
  17514. EXPECT_EQ("/ws", uc.path);
  17515. }
  17516. }
  17517. TEST(ParseUrlTest, QueryOnly) {
  17518. detail::UrlComponents uc;
  17519. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17520. EXPECT_TRUE(uc.host.empty());
  17521. EXPECT_TRUE(uc.path.empty());
  17522. EXPECT_EQ("?q=1&r=2", uc.query);
  17523. }
  17524. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17525. detail::UrlComponents uc;
  17526. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17527. EXPECT_TRUE(uc.scheme.empty());
  17528. EXPECT_EQ("example.com", uc.host);
  17529. EXPECT_EQ("443", uc.port);
  17530. EXPECT_EQ("/path", uc.path);
  17531. }
  17532. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17533. // If ipv6 regex working, regex match codepath is taken.
  17534. // else port will default to 80 in Client impl
  17535. int clientImplMagicPort = 80;
  17536. int port = 4321;
  17537. // above ports must be different to avoid false negative
  17538. EXPECT_NE(clientImplMagicPort, port);
  17539. std::string ipV6TestURL = "http://[ff06::c3]";
  17540. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17541. CLIENT_PRIVATE_KEY_FILE);
  17542. EXPECT_EQ(cli.port(), port);
  17543. }
  17544. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17545. auto file_path = "./www/dir/index.html";
  17546. auto dir_path = "./www/dir";
  17547. detail::FileStat stat_file(file_path);
  17548. EXPECT_TRUE(stat_file.is_file());
  17549. EXPECT_FALSE(stat_file.is_dir());
  17550. detail::FileStat stat_dir(dir_path);
  17551. EXPECT_FALSE(stat_dir.is_file());
  17552. EXPECT_TRUE(stat_dir.is_dir());
  17553. }
  17554. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17555. // IPv4 with default HTTP port (80)
  17556. EXPECT_EQ("example.com",
  17557. detail::make_host_and_port_string("example.com", 80, false));
  17558. // IPv4 with default HTTPS port (443)
  17559. EXPECT_EQ("example.com",
  17560. detail::make_host_and_port_string("example.com", 443, true));
  17561. // IPv4 with non-default HTTP port
  17562. EXPECT_EQ("example.com:8080",
  17563. detail::make_host_and_port_string("example.com", 8080, false));
  17564. // IPv4 with non-default HTTPS port
  17565. EXPECT_EQ("example.com:8443",
  17566. detail::make_host_and_port_string("example.com", 8443, true));
  17567. // IPv6 with default HTTP port (80)
  17568. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17569. // IPv6 with default HTTPS port (443)
  17570. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17571. // IPv6 with non-default HTTP port
  17572. EXPECT_EQ("[::1]:8080",
  17573. detail::make_host_and_port_string("::1", 8080, false));
  17574. // IPv6 with non-default HTTPS port
  17575. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17576. // IPv6 full address with default port
  17577. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17578. detail::make_host_and_port_string(
  17579. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17580. // IPv6 full address with non-default port
  17581. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17582. detail::make_host_and_port_string(
  17583. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17584. // IPv6 localhost with non-default port
  17585. EXPECT_EQ("[::1]:3000",
  17586. detail::make_host_and_port_string("::1", 3000, false));
  17587. // IPv6 with zone ID (link-local address) with default port
  17588. EXPECT_EQ("[fe80::1%eth0]",
  17589. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17590. // IPv6 with zone ID (link-local address) with non-default port
  17591. EXPECT_EQ("[fe80::1%eth0]:8080",
  17592. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17593. // Edge case: Port 443 with is_ssl=false (should add port)
  17594. EXPECT_EQ("example.com:443",
  17595. detail::make_host_and_port_string("example.com", 443, false));
  17596. // Edge case: Port 80 with is_ssl=true (should add port)
  17597. EXPECT_EQ("example.com:80",
  17598. detail::make_host_and_port_string("example.com", 80, true));
  17599. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17600. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17601. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17602. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17603. // Security fix: Already bracketed IPv6 should not get double brackets
  17604. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17605. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17606. EXPECT_EQ("[::1]:8080",
  17607. detail::make_host_and_port_string("[::1]", 8080, false));
  17608. EXPECT_EQ("[2001:db8::1]:8080",
  17609. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17610. EXPECT_EQ("[fe80::1%eth0]",
  17611. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17612. EXPECT_EQ("[fe80::1%eth0]:8080",
  17613. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17614. // Edge case: Empty host (should return as-is)
  17615. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17616. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17617. // This is a known limitation but shouldn't crash
  17618. EXPECT_EQ("[host:name]",
  17619. detail::make_host_and_port_string("host:name", 80, false));
  17620. // Port number edge cases (no validation, but should not crash)
  17621. EXPECT_EQ("example.com:0",
  17622. detail::make_host_and_port_string("example.com", 0, false));
  17623. EXPECT_EQ("example.com:-1",
  17624. detail::make_host_and_port_string("example.com", -1, false));
  17625. EXPECT_EQ("example.com:65535",
  17626. detail::make_host_and_port_string("example.com", 65535, false));
  17627. EXPECT_EQ("example.com:65536",
  17628. detail::make_host_and_port_string("example.com", 65536, false));
  17629. }
  17630. #ifdef CPPHTTPLIB_SSL_ENABLED
  17631. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17632. httplib::SSLClient cli("roblox.com", 443);
  17633. cli.set_follow_location(true);
  17634. auto res = cli.Get("/");
  17635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17636. EXPECT_EQ(StatusCode::OK_200, res->status);
  17637. }
  17638. #endif
  17639. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17640. Server svr;
  17641. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17642. EXPECT_EQ(res.status, 400);
  17643. });
  17644. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17645. auto se = detail::scope_exit([&] {
  17646. svr.stop();
  17647. thread.join();
  17648. ASSERT_FALSE(svr.is_running());
  17649. });
  17650. svr.wait_until_ready();
  17651. Client cli(HOST, PORT);
  17652. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17653. }
  17654. TEST(InvalidHeaderCharsTest, is_field_name) {
  17655. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17656. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17657. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17658. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17659. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17660. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17661. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17662. EXPECT_FALSE(detail::fields::is_field_name(""));
  17663. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17664. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17665. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17666. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17667. }
  17668. TEST(InvalidHeaderCharsTest, is_field_value) {
  17669. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17670. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17671. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17672. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17673. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17674. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17675. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17676. EXPECT_TRUE(detail::fields::is_field_value(""));
  17677. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17678. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17679. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17680. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17681. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17682. }
  17683. TEST(InvalidHeaderCharsTest, OnServer) {
  17684. Server svr;
  17685. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17686. std::string header = "Not Set";
  17687. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17688. res.set_header(header, "value");
  17689. res.set_content("Page Content Page Content", "text/plain");
  17690. });
  17691. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17692. std::string header = "Not Set";
  17693. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17694. res.set_header("X-Test", header);
  17695. res.set_content("Page Content Page Content", "text/plain");
  17696. });
  17697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17698. auto se = detail::scope_exit([&] {
  17699. svr.stop();
  17700. thread.join();
  17701. ASSERT_FALSE(svr.is_running());
  17702. });
  17703. svr.wait_until_ready();
  17704. Client cli(HOST, PORT);
  17705. {
  17706. auto res = cli.Get(
  17707. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17709. EXPECT_EQ("Page Content Page Content", res->body);
  17710. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17711. }
  17712. {
  17713. auto res = cli.Get(
  17714. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17716. EXPECT_EQ("Page Content Page Content", res->body);
  17717. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17718. }
  17719. }
  17720. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17721. auto handled = false;
  17722. Server svr;
  17723. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17724. thread t = thread([&] { svr.listen(HOST, PORT); });
  17725. auto se = detail::scope_exit([&] {
  17726. svr.stop();
  17727. t.join();
  17728. ASSERT_FALSE(svr.is_running());
  17729. ASSERT_FALSE(handled);
  17730. });
  17731. svr.wait_until_ready();
  17732. auto req = "POST /test HTTP/1.1\r\n"
  17733. "Content-Length: x\r\n"
  17734. "\r\n";
  17735. std::string response;
  17736. ASSERT_TRUE(send_request(1, req, &response));
  17737. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17738. response.substr(0, response.find("\r\n")));
  17739. }
  17740. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17741. // case-insensitive, and a server that receives a 100-continue expectation in
  17742. // an HTTP/1.0 request MUST ignore it.
  17743. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17744. std::string response;
  17745. ASSERT_TRUE(send_request(1, req, &response, port));
  17746. *got_100 = response.find("100 Continue") != std::string::npos;
  17747. }
  17748. class ExpectTokenTest : public ::testing::Test {
  17749. protected:
  17750. void SetUp() override {
  17751. svr_.Post("/p", [](const Request &, Response &res) {
  17752. res.set_content("ok", "text/plain");
  17753. });
  17754. port_ = svr_.bind_to_any_port(HOST);
  17755. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17756. svr_.wait_until_ready();
  17757. }
  17758. void TearDown() override {
  17759. svr_.stop();
  17760. if (thread_.joinable()) { thread_.join(); }
  17761. }
  17762. std::string request(const char *version, const char *expect_value) const {
  17763. return std::string("POST /p ") + version +
  17764. "\r\n"
  17765. "Host: localhost\r\n"
  17766. "Content-Length: 2\r\n"
  17767. "Connection: close\r\n"
  17768. "Expect: " +
  17769. expect_value +
  17770. "\r\n"
  17771. "\r\n"
  17772. "hi";
  17773. }
  17774. Server svr_;
  17775. int port_ = 0;
  17776. thread thread_;
  17777. };
  17778. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17779. bool got_100 = false;
  17780. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17781. EXPECT_TRUE(got_100);
  17782. }
  17783. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17784. bool got_100 = true;
  17785. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17786. EXPECT_FALSE(got_100);
  17787. }
  17788. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17789. bool got_100 = false;
  17790. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17791. EXPECT_TRUE(got_100);
  17792. }
  17793. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17794. bool got_100 = false;
  17795. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17796. EXPECT_TRUE(got_100);
  17797. }
  17798. // `100 Continue` is sent only when the server starts reading the body, so a
  17799. // request rejected before that never invites the client to send it. The
  17800. // requests below carry the expectation but withhold the body, as a client
  17801. // waiting for `100 Continue` would.
  17802. // A POST that expects `100 Continue` and withholds its two-byte body.
  17803. static std::string expect_headers_only(const std::string &path) {
  17804. return "POST " + path +
  17805. " HTTP/1.1\r\n"
  17806. "Host: localhost\r\n"
  17807. "Content-Length: 2\r\n"
  17808. "Expect: 100-continue\r\n"
  17809. "\r\n";
  17810. }
  17811. class ExpectLazyContinueTest : public ::testing::Test {
  17812. protected:
  17813. void SetUp() override {
  17814. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17815. if (req.path == "/pre-routing") {
  17816. res.status = StatusCode::Unauthorized_401;
  17817. return Server::HandlerResponse::Handled;
  17818. }
  17819. return Server::HandlerResponse::Unhandled;
  17820. });
  17821. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17822. if (req.matched_route == "/pre-request") {
  17823. res.status = StatusCode::Forbidden_403;
  17824. return Server::HandlerResponse::Handled;
  17825. }
  17826. return Server::HandlerResponse::Unhandled;
  17827. });
  17828. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17829. res.set_content("ok", "text/plain");
  17830. });
  17831. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17832. res.set_content("ok", "text/plain");
  17833. });
  17834. svr_.Post("/reader-used", [](const Request &, Response &res,
  17835. const ContentReader &content_reader) {
  17836. std::string body;
  17837. content_reader([&](const char *data, size_t len) {
  17838. body.append(data, len);
  17839. return true;
  17840. });
  17841. res.set_content(body, "text/plain");
  17842. });
  17843. svr_.Post("/reader-unused",
  17844. [](const Request &, Response &res, const ContentReader &) {
  17845. res.set_content("ignored", "text/plain");
  17846. });
  17847. port_ = svr_.bind_to_any_port(HOST);
  17848. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17849. svr_.wait_until_ready();
  17850. }
  17851. void TearDown() override {
  17852. svr_.stop();
  17853. if (thread_.joinable()) { thread_.join(); }
  17854. }
  17855. // Sends `req` and reads until the server closes the connection. Returns
  17856. // false if the read had to wait for the client-side timeout instead.
  17857. bool send_until_closed(const std::string &req, std::string *resp) const {
  17858. auto start = std::chrono::steady_clock::now();
  17859. if (!send_request(3, req, resp, port_)) { return false; }
  17860. auto elapsed = std::chrono::steady_clock::now() - start;
  17861. return elapsed < std::chrono::seconds(2);
  17862. }
  17863. // The final response comes without `100 Continue`, and the server closes
  17864. // the connection since the body may or may not follow.
  17865. void expect_final_without_interim(const std::string &path,
  17866. const char *status_line) const {
  17867. std::string resp;
  17868. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17869. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17870. EXPECT_EQ(0u, resp.find(status_line));
  17871. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17872. }
  17873. Server svr_;
  17874. int port_ = 0;
  17875. thread thread_;
  17876. };
  17877. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17878. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17879. }
  17880. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17881. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17882. }
  17883. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17884. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17885. }
  17886. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17887. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17888. }
  17889. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17890. // The body follows once `100 Continue` has had time to arrive.
  17891. auto req = expect_headers_only("/reader-used");
  17892. req.insert(req.size() - 2, "Connection: close\r\n");
  17893. std::string resp;
  17894. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17895. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17896. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17897. EXPECT_NE(std::string::npos, resp.find("hi"));
  17898. }
  17899. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17900. // Large enough for the client to add `Expect: 100-continue` itself.
  17901. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17902. std::atomic<bool> body_sent{false};
  17903. Client cli(HOST, port_);
  17904. auto res = cli.Post(
  17905. "/pre-request", length,
  17906. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17907. body_sent = true;
  17908. std::string chunk(len, 'x');
  17909. sink.write(chunk.data(), chunk.size());
  17910. return true;
  17911. },
  17912. "application/octet-stream");
  17913. ASSERT_TRUE(res);
  17914. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17915. EXPECT_FALSE(body_sent);
  17916. }
  17917. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17918. Server svr;
  17919. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17920. return StatusCode::ExpectationFailed_417;
  17921. });
  17922. svr.Post("/p", [](const Request &, Response &res) {
  17923. res.set_content("ok", "text/plain");
  17924. });
  17925. auto port = svr.bind_to_any_port(HOST);
  17926. thread t = thread([&] { svr.listen_after_bind(); });
  17927. auto se = detail::scope_exit([&] {
  17928. svr.stop();
  17929. t.join();
  17930. });
  17931. svr.wait_until_ready();
  17932. std::string resp;
  17933. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17934. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17935. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17936. // Exactly one response: the route handler must not run after the 417.
  17937. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17938. }
  17939. #ifndef _WIN32
  17940. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17941. static constexpr char reject[] = "Unauthorized";
  17942. static constexpr char accept[] = "Upload accepted";
  17943. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17944. Server svr;
  17945. svr.set_expect_100_continue_handler(
  17946. [](const Request & /*req*/, Response &res) {
  17947. res.status = StatusCode::Unauthorized_401;
  17948. res.set_content(reject, "text/plain");
  17949. return res.status;
  17950. });
  17951. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17952. res.set_content(accept, "text/plain");
  17953. });
  17954. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17955. auto se = detail::scope_exit([&] {
  17956. svr.stop();
  17957. thread.join();
  17958. ASSERT_FALSE(svr.is_running());
  17959. });
  17960. svr.wait_until_ready();
  17961. {
  17962. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17963. curl_easy_init(), &curl_easy_cleanup};
  17964. ASSERT_NE(curl, nullptr);
  17965. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17966. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17967. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17968. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17969. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17970. &curl_slist_free_all};
  17971. ASSERT_NE(list, nullptr);
  17972. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17973. struct read_data {
  17974. uint64_t read_size;
  17975. uint64_t total_size;
  17976. } data = {0, total_size};
  17977. using read_callback_t =
  17978. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17979. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17980. void *userdata) -> size_t {
  17981. read_data *d = (read_data *)userdata;
  17982. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17983. std::fill_n(ptr, size * nmemb, 'A');
  17984. d->read_size += size * nmemb;
  17985. return size * nmemb;
  17986. };
  17987. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  17988. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17989. std::vector<char> buffer;
  17990. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17991. using write_callback_t =
  17992. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17993. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17994. void *userdata) -> size_t {
  17995. std::vector<char> *buf = (std::vector<char> *)userdata;
  17996. buf->reserve(buf->size() + size * nmemb + 1);
  17997. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17998. return size * nmemb;
  17999. };
  18000. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18001. {
  18002. const auto res = curl_easy_perform(curl.get());
  18003. ASSERT_EQ(res, CURLE_OK);
  18004. }
  18005. {
  18006. auto response_code = long{};
  18007. const auto res =
  18008. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18009. ASSERT_EQ(res, CURLE_OK);
  18010. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18011. }
  18012. {
  18013. auto dl = curl_off_t{};
  18014. const auto res =
  18015. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18016. ASSERT_EQ(res, CURLE_OK);
  18017. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18018. }
  18019. {
  18020. buffer.push_back('\0');
  18021. ASSERT_STRCASEEQ(buffer.data(), reject);
  18022. }
  18023. }
  18024. }
  18025. #endif
  18026. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18027. // Regression test for #2458.
  18028. //
  18029. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18030. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18031. // ticket can make the client socket spuriously readable during the
  18032. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18033. // the client withholds the body and then blocks reading a response that never
  18034. // comes, failing with `Failed to read connection`.
  18035. //
  18036. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18037. // within the timeout. This raw OpenSSL server deliberately never sends
  18038. // `100 Continue`; the client must still deliver the body and receive 200.
  18039. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18040. signal(SIGPIPE, SIG_IGN);
  18041. const auto port = PORT + 4;
  18042. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18043. ASSERT_NE(srv, INVALID_SOCKET);
  18044. int opt = 1;
  18045. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18046. sockaddr_in addr{};
  18047. addr.sin_family = AF_INET;
  18048. addr.sin_port = htons(static_cast<uint16_t>(port));
  18049. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18050. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18051. ASSERT_EQ(0, ::listen(srv, 1));
  18052. std::atomic<size_t> server_body_bytes{0};
  18053. auto server_thread = std::thread([&] {
  18054. sockaddr_in cli_addr{};
  18055. socklen_t cli_len = sizeof(cli_addr);
  18056. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18057. if (cli == INVALID_SOCKET) { return; }
  18058. // Bound the lifetime of the server side so a buggy client (which never
  18059. // sends the body) cannot make this thread block forever on join.
  18060. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18061. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18062. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18063. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18064. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18065. SSL *ssl = SSL_new(ctx);
  18066. SSL_set_fd(ssl, static_cast<int>(cli));
  18067. if (SSL_accept(ssl) > 0) {
  18068. // Read the request headers. Reading here also flushes the TLS 1.3
  18069. // session tickets to the client. Deliberately do NOT send
  18070. // `100 Continue`.
  18071. std::string buf;
  18072. char tmp[1024];
  18073. while (buf.find("\r\n\r\n") == std::string::npos) {
  18074. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18075. if (n <= 0) { break; }
  18076. buf.append(tmp, static_cast<size_t>(n));
  18077. }
  18078. // A correct client sends the body now; count what arrives.
  18079. auto pos = buf.find("\r\n\r\n");
  18080. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18081. while (body < 4096) {
  18082. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18083. if (n <= 0) { break; }
  18084. body += static_cast<size_t>(n);
  18085. }
  18086. server_body_bytes = body;
  18087. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18088. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18089. SSL_shutdown(ssl);
  18090. }
  18091. SSL_free(ssl);
  18092. detail::close_socket(cli);
  18093. SSL_CTX_free(ctx);
  18094. });
  18095. auto se = detail::scope_exit([&] {
  18096. server_thread.join();
  18097. detail::close_socket(srv);
  18098. });
  18099. SSLClient cli("127.0.0.1", port);
  18100. cli.enable_server_certificate_verification(false);
  18101. cli.set_connection_timeout(5, 0);
  18102. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18103. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18104. std::string body(4096, 'A');
  18105. auto res = cli.Put("/api/test", body, "application/json");
  18106. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18107. EXPECT_EQ(StatusCode::OK_200, res->status);
  18108. EXPECT_EQ(body.size(), server_body_bytes.load());
  18109. }
  18110. #endif
  18111. template <typename S, typename C>
  18112. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18113. svr.Get("/stream", [&](const Request &, Response &res) {
  18114. auto data = new std::string("01234567890123456789");
  18115. res.set_content_provider(
  18116. data->size(), "text/plain",
  18117. [&, data](size_t offset, size_t length, DataSink &sink) {
  18118. const size_t DATA_CHUNK_SIZE = 4;
  18119. const auto &d = *data;
  18120. std::this_thread::sleep_for(std::chrono::seconds(1));
  18121. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18122. return true;
  18123. },
  18124. [data](bool success) {
  18125. EXPECT_FALSE(success);
  18126. delete data;
  18127. });
  18128. });
  18129. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18130. auto i = new size_t(0);
  18131. res.set_content_provider(
  18132. "text/plain",
  18133. [i](size_t, DataSink &sink) {
  18134. if (*i < 5) {
  18135. std::this_thread::sleep_for(std::chrono::seconds(1));
  18136. sink.write("abcd", 4);
  18137. (*i)++;
  18138. } else {
  18139. sink.done();
  18140. }
  18141. return true;
  18142. },
  18143. [i](bool success) {
  18144. EXPECT_FALSE(success);
  18145. delete i;
  18146. });
  18147. });
  18148. svr.Get("/chunked", [&](const Request &, Response &res) {
  18149. auto i = new size_t(0);
  18150. res.set_chunked_content_provider(
  18151. "text/plain",
  18152. [i](size_t, DataSink &sink) {
  18153. if (*i < 5) {
  18154. std::this_thread::sleep_for(std::chrono::seconds(1));
  18155. sink.os << "abcd";
  18156. (*i)++;
  18157. } else {
  18158. sink.done();
  18159. }
  18160. return true;
  18161. },
  18162. [i](bool success) {
  18163. EXPECT_FALSE(success);
  18164. delete i;
  18165. });
  18166. });
  18167. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18168. auto se = detail::scope_exit([&] {
  18169. svr.stop();
  18170. listen_thread.join();
  18171. ASSERT_FALSE(svr.is_running());
  18172. });
  18173. svr.wait_until_ready();
  18174. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18175. {
  18176. auto start = std::chrono::steady_clock::now();
  18177. auto res = cli.Get("/stream");
  18178. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18179. std::chrono::steady_clock::now() - start)
  18180. .count();
  18181. ASSERT_FALSE(res);
  18182. EXPECT_EQ(Error::Read, res.error());
  18183. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18184. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18185. }
  18186. {
  18187. auto start = std::chrono::steady_clock::now();
  18188. auto res = cli.Get("/stream_without_length");
  18189. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18190. std::chrono::steady_clock::now() - start)
  18191. .count();
  18192. ASSERT_FALSE(res);
  18193. EXPECT_EQ(Error::Read, res.error());
  18194. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18195. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18196. }
  18197. {
  18198. auto start = std::chrono::steady_clock::now();
  18199. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18200. EXPECT_EQ("abcd", string(data, data_length));
  18201. return true;
  18202. });
  18203. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18204. std::chrono::steady_clock::now() - start)
  18205. .count();
  18206. ASSERT_FALSE(res);
  18207. EXPECT_EQ(Error::Read, res.error());
  18208. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18209. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18210. }
  18211. }
  18212. TEST(MaxTimeoutTest, ContentStream) {
  18213. time_t timeout = 2000;
  18214. time_t threshold = 200;
  18215. Server svr;
  18216. Client cli("localhost", PORT);
  18217. max_timeout_test(svr, cli, timeout, threshold);
  18218. }
  18219. #ifdef CPPHTTPLIB_SSL_ENABLED
  18220. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18221. time_t timeout = 2000;
  18222. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18224. SSLClient cli("localhost", PORT);
  18225. cli.enable_server_certificate_verification(false);
  18226. max_timeout_test(svr, cli, timeout, threshold);
  18227. }
  18228. #endif
  18229. class EventDispatcher {
  18230. public:
  18231. EventDispatcher() {}
  18232. bool wait_event(DataSink *sink) {
  18233. unique_lock<mutex> lk(m_);
  18234. int id = id_;
  18235. // Wait with timeout to prevent hanging if client disconnects
  18236. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18237. [&] { return cid_ == id; })) {
  18238. return false; // Timeout occurred
  18239. }
  18240. sink->write(message_.data(), message_.size());
  18241. return true;
  18242. }
  18243. void send_event(const string &message) {
  18244. lock_guard<mutex> lk(m_);
  18245. cid_ = id_++;
  18246. message_ = message;
  18247. cv_.notify_all();
  18248. }
  18249. private:
  18250. mutex m_;
  18251. condition_variable cv_;
  18252. atomic_int id_{0};
  18253. atomic_int cid_{-1};
  18254. string message_;
  18255. };
  18256. TEST(ClientInThreadTest, Issue2068) {
  18257. EventDispatcher ed;
  18258. Server svr;
  18259. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18260. res.set_chunked_content_provider("text/event-stream",
  18261. [&](size_t /*offset*/, DataSink &sink) {
  18262. return ed.wait_event(&sink);
  18263. });
  18264. });
  18265. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18266. svr.wait_until_ready();
  18267. thread event_thread([&] {
  18268. int id = 0;
  18269. while (svr.is_running()) {
  18270. this_thread::sleep_for(chrono::milliseconds(500));
  18271. std::stringstream ss;
  18272. ss << "data: " << id << "\n\n";
  18273. ed.send_event(ss.str());
  18274. id++;
  18275. }
  18276. });
  18277. auto se = detail::scope_exit([&] {
  18278. svr.stop();
  18279. listen_thread.join();
  18280. event_thread.join();
  18281. ASSERT_FALSE(svr.is_running());
  18282. });
  18283. {
  18284. auto client = detail::make_unique<Client>(HOST, PORT);
  18285. client->set_read_timeout(std::chrono::minutes(10));
  18286. std::atomic<bool> stop{false};
  18287. std::thread t([&] {
  18288. client->Get("/event1",
  18289. [&](const char *, size_t) -> bool { return !stop; });
  18290. });
  18291. std::this_thread::sleep_for(std::chrono::seconds(2));
  18292. stop = true;
  18293. client->stop();
  18294. t.join();
  18295. // Reset client after thread has finished
  18296. client.reset();
  18297. }
  18298. }
  18299. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18300. auto handled = false;
  18301. Server svr;
  18302. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18303. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18304. auto se = detail::scope_exit([&] {
  18305. svr.stop();
  18306. t.join();
  18307. ASSERT_FALSE(svr.is_running());
  18308. ASSERT_FALSE(handled);
  18309. });
  18310. svr.wait_until_ready();
  18311. // Two Content-Length headers with different values — must be rejected
  18312. auto req = "POST /test HTTP/1.1\r\n"
  18313. "Content-Length: 5\r\n"
  18314. "Content-Length: 10\r\n"
  18315. "\r\n"
  18316. "hello";
  18317. std::string response;
  18318. ASSERT_TRUE(send_request(1, req, &response));
  18319. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18320. response.substr(0, response.find("\r\n")));
  18321. }
  18322. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18323. auto handled = false;
  18324. Server svr;
  18325. svr.Post("/test", [&](const Request &, Response &res) {
  18326. handled = true;
  18327. res.set_content("ok", "text/plain");
  18328. });
  18329. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18330. auto se = detail::scope_exit([&] {
  18331. svr.stop();
  18332. t.join();
  18333. ASSERT_FALSE(svr.is_running());
  18334. ASSERT_TRUE(handled);
  18335. });
  18336. svr.wait_until_ready();
  18337. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18338. auto req = "POST /test HTTP/1.1\r\n"
  18339. "Host: localhost\r\n"
  18340. "Content-Length: 5\r\n"
  18341. "Content-Length: 5\r\n"
  18342. "\r\n"
  18343. "hello";
  18344. std::string response;
  18345. ASSERT_TRUE(send_request(1, req, &response));
  18346. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18347. }
  18348. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18349. Server svr;
  18350. svr.Get("/test", [](const Request &, Response &res) {
  18351. res.set_content("ok", "text/plain");
  18352. });
  18353. auto port = svr.bind_to_any_port(HOST);
  18354. thread t = thread([&] { svr.listen_after_bind(); });
  18355. auto se = detail::scope_exit([&] {
  18356. svr.stop();
  18357. t.join();
  18358. ASSERT_FALSE(svr.is_running());
  18359. });
  18360. svr.wait_until_ready();
  18361. auto status_line = [&](const std::string &host_lines) {
  18362. std::string res;
  18363. send_request(
  18364. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18365. &res, port);
  18366. return res.substr(0, res.find("\r\n"));
  18367. };
  18368. const char *accepted[] = {
  18369. "Host: localhost\r\n",
  18370. "Host: a.example:8080\r\n",
  18371. "Host: my_service\r\n",
  18372. "Host: [::1]:8080\r\n",
  18373. "Host: [fe80::1%25eth0]\r\n",
  18374. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18375. };
  18376. for (auto host_lines : accepted) {
  18377. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18378. }
  18379. const char *rejected[] = {
  18380. "Host: a.example\r\nHost: b.example\r\n",
  18381. "Host: a.example\r\nHost: a.example\r\n",
  18382. "Host: a@b.example\r\n",
  18383. "Host: a.example/b\r\n",
  18384. "Host: a.example\\b\r\n",
  18385. "Host: a.example?b\r\n",
  18386. "Host: a.example#b\r\n",
  18387. "Host: a.example b.example\r\n",
  18388. };
  18389. for (auto host_lines : rejected) {
  18390. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18391. << host_lines;
  18392. }
  18393. }
  18394. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18395. Server svr;
  18396. svr.Get("/", [](const Request &req, Response &res) {
  18397. EXPECT_EQ(2U, req.trailers.size());
  18398. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18399. // Denied
  18400. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18401. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18402. // Accepted
  18403. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18404. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18405. EXPECT_TRUE(req.has_trailer("X-World"));
  18406. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18407. res.set_content("ok", "text/plain");
  18408. });
  18409. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18410. auto se = detail::scope_exit([&] {
  18411. svr.stop();
  18412. t.join();
  18413. ASSERT_FALSE(svr.is_running());
  18414. });
  18415. svr.wait_until_ready();
  18416. const std::string req = "GET / HTTP/1.1\r\n"
  18417. "Transfer-Encoding: chunked\r\n"
  18418. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18419. "\r\n"
  18420. "0\r\n"
  18421. "Content-Length: 10\r\n"
  18422. "Host: internal.local\r\n"
  18423. "Content-Type: malicious/content\r\n"
  18424. "Cookie: any\r\n"
  18425. "Set-Cookie: any\r\n"
  18426. "X-Forwarded-For: attacker.com\r\n"
  18427. "X-Real-Ip: 1.1.1.1\r\n"
  18428. "X-Hello: hello\r\n"
  18429. "X-World: world\r\n"
  18430. "\r\n";
  18431. std::string res;
  18432. ASSERT_TRUE(send_request(1, req, &res));
  18433. }
  18434. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18435. // several field lines, and the combined value is what has to be parsed. A
  18436. // Trailer field split across lines therefore declares every name it lists;
  18437. // reading only the first line silently drops the trailers the later lines
  18438. // declare. The prohibited-trailer filter still applies to every line.
  18439. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18440. Server svr;
  18441. size_t observed_trailer_count = 0;
  18442. std::string observed_hello;
  18443. std::string observed_world;
  18444. bool observed_content_length = true;
  18445. svr.Get("/", [&](const Request &req, Response &res) {
  18446. observed_trailer_count = req.trailers.size();
  18447. observed_hello = req.get_trailer_value("X-Hello");
  18448. observed_world = req.get_trailer_value("X-World");
  18449. observed_content_length = req.has_trailer("Content-Length");
  18450. res.set_content("ok", "text/plain");
  18451. });
  18452. auto port = svr.bind_to_any_port(HOST);
  18453. thread t = thread([&]() { svr.listen_after_bind(); });
  18454. auto se = detail::scope_exit([&] {
  18455. svr.stop();
  18456. t.join();
  18457. ASSERT_FALSE(svr.is_running());
  18458. });
  18459. svr.wait_until_ready();
  18460. const std::string req = "GET / HTTP/1.1\r\n"
  18461. "Host: localhost\r\n"
  18462. "Transfer-Encoding: chunked\r\n"
  18463. "Trailer: X-Hello\r\n"
  18464. "Trailer: X-World, Content-Length\r\n"
  18465. "\r\n"
  18466. "0\r\n"
  18467. "X-Hello: hello\r\n"
  18468. "X-World: world\r\n"
  18469. "Content-Length: 10\r\n"
  18470. "\r\n";
  18471. std::string res;
  18472. ASSERT_TRUE(send_request(1, req, &res, port));
  18473. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18474. // Accepted: both field lines contribute to the declared set
  18475. EXPECT_EQ(2U, observed_trailer_count);
  18476. EXPECT_EQ(observed_hello, "hello");
  18477. EXPECT_EQ(observed_world, "world");
  18478. // Denied: a prohibited name stays prohibited on a later field line
  18479. EXPECT_FALSE(observed_content_length);
  18480. }
  18481. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18482. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18483. // unbounded run of fields that are never declared, because the counter would
  18484. // only advance for declared fields.
  18485. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18486. Server svr;
  18487. bool handler_called = false;
  18488. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18489. handler_called = true;
  18490. res.set_content("ok", "text/plain");
  18491. });
  18492. auto port = svr.bind_to_any_port(HOST);
  18493. thread t = thread([&]() { svr.listen_after_bind(); });
  18494. auto se = detail::scope_exit([&] {
  18495. svr.stop();
  18496. t.join();
  18497. ASSERT_FALSE(svr.is_running());
  18498. });
  18499. svr.wait_until_ready();
  18500. // Declare nothing, then send far more undeclared trailer fields than the
  18501. // header-count limit. Parsing must stop and reject the request rather than
  18502. // read every line.
  18503. std::string req = "GET / HTTP/1.1\r\n"
  18504. "Transfer-Encoding: chunked\r\n"
  18505. "\r\n"
  18506. "0\r\n";
  18507. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18508. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18509. }
  18510. req += "\r\n";
  18511. std::string res;
  18512. ASSERT_TRUE(send_request(1, req, &res, port));
  18513. // The request is rejected before the handler runs.
  18514. EXPECT_FALSE(handler_called);
  18515. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18516. }
  18517. // The set of declared trailer names is capped so a peer cannot grow it without
  18518. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18519. // declared past the cap is not honored, even if the field is actually sent.
  18520. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18521. Server svr;
  18522. // One name inside the cap and one past it, so the test tracks the cap rather
  18523. // than a fixed count.
  18524. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18525. const std::string within_cap_name = "X-T-0";
  18526. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18527. bool observed_within_cap = false;
  18528. bool observed_past_cap = false;
  18529. svr.Get("/", [&](const Request &req, Response &res) {
  18530. observed_within_cap = req.has_trailer(within_cap_name);
  18531. observed_past_cap = req.has_trailer(past_cap_name);
  18532. res.set_content("ok", "text/plain");
  18533. });
  18534. auto port = svr.bind_to_any_port(HOST);
  18535. thread t = thread([&]() { svr.listen_after_bind(); });
  18536. auto se = detail::scope_exit([&] {
  18537. svr.stop();
  18538. t.join();
  18539. ASSERT_FALSE(svr.is_running());
  18540. });
  18541. svr.wait_until_ready();
  18542. // Declare more trailer names than the cap in a single Trailer field, then
  18543. // actually send the first (within the cap) and the last (past it).
  18544. std::string trailer_decl = "Trailer: ";
  18545. for (int i = 0; i < declared_count; i++) {
  18546. if (i != 0) { trailer_decl += ", "; }
  18547. trailer_decl += "X-T-" + std::to_string(i);
  18548. }
  18549. trailer_decl += "\r\n";
  18550. const std::string req = "GET / HTTP/1.1\r\n"
  18551. "Host: localhost\r\n"
  18552. "Transfer-Encoding: chunked\r\n" +
  18553. trailer_decl +
  18554. "\r\n"
  18555. "0\r\n" +
  18556. within_cap_name + ": a\r\n" + past_cap_name +
  18557. ": b\r\n"
  18558. "\r\n";
  18559. std::string res;
  18560. ASSERT_TRUE(send_request(1, req, &res, port));
  18561. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18562. // A name within the cap is honored; one declared past the cap is dropped.
  18563. EXPECT_TRUE(observed_within_cap);
  18564. EXPECT_FALSE(observed_past_cap);
  18565. }
  18566. // A direct client that is not listed in trusted_proxies must not be able to
  18567. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18568. // the peer address on the actual TCP connection determines whether the
  18569. // header is honored.
  18570. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18571. Server svr;
  18572. // Deliberately does NOT include the loopback address the test client
  18573. // actually connects from, so the direct connection is not a trusted proxy.
  18574. svr.set_trusted_proxies({"203.0.113.66"});
  18575. std::string observed_remote_addr;
  18576. svr.Get("/ip", [&](const Request &req, Response &res) {
  18577. observed_remote_addr = req.remote_addr;
  18578. res.set_content("ok", "text/plain");
  18579. });
  18580. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18581. auto se = detail::scope_exit([&] {
  18582. svr.stop();
  18583. t.join();
  18584. ASSERT_FALSE(svr.is_running());
  18585. });
  18586. svr.wait_until_ready();
  18587. Client cli(HOST, PORT);
  18588. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18590. EXPECT_EQ(StatusCode::OK_200, res->status);
  18591. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18592. // ignored entirely and the real connection-level address retained.
  18593. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18594. observed_remote_addr == "127.0.0.1");
  18595. }
  18596. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18597. Server svr;
  18598. std::string observed_remote_addr;
  18599. std::string observed_xff;
  18600. svr.Get("/ip", [&](const Request &req, Response &res) {
  18601. observed_remote_addr = req.remote_addr;
  18602. observed_xff = req.get_header_value("X-Forwarded-For");
  18603. res.set_content("ok", "text/plain");
  18604. });
  18605. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18606. auto se = detail::scope_exit([&] {
  18607. svr.stop();
  18608. t.join();
  18609. ASSERT_FALSE(svr.is_running());
  18610. });
  18611. svr.wait_until_ready();
  18612. Client cli(HOST, PORT);
  18613. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18615. EXPECT_EQ(StatusCode::OK_200, res->status);
  18616. EXPECT_EQ(observed_xff, "203.0.113.66");
  18617. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18618. observed_remote_addr == "127.0.0.1");
  18619. }
  18620. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18621. Server svr;
  18622. svr.set_trusted_proxies({"203.0.113.66"});
  18623. std::string observed_remote_addr;
  18624. std::string observed_xff;
  18625. svr.Get("/ip", [&](const Request &req, Response &res) {
  18626. observed_remote_addr = req.remote_addr;
  18627. observed_xff = req.get_header_value("X-Forwarded-For");
  18628. res.set_content("ok", "text/plain");
  18629. });
  18630. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18631. auto se = detail::scope_exit([&] {
  18632. svr.stop();
  18633. t.join();
  18634. ASSERT_FALSE(svr.is_running());
  18635. });
  18636. svr.wait_until_ready();
  18637. Client cli(HOST, PORT);
  18638. auto res = cli.Get("/ip");
  18639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18640. EXPECT_EQ(StatusCode::OK_200, res->status);
  18641. EXPECT_EQ(observed_xff, "");
  18642. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18643. observed_remote_addr == "127.0.0.1");
  18644. }
  18645. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18646. Server svr;
  18647. // Include the loopback address the test client actually connects from, so
  18648. // the direct connection itself is recognized as the trusted proxy hop.
  18649. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18650. std::string observed_remote_addr;
  18651. std::string observed_xff;
  18652. svr.Get("/ip", [&](const Request &req, Response &res) {
  18653. observed_remote_addr = req.remote_addr;
  18654. observed_xff = req.get_header_value("X-Forwarded-For");
  18655. res.set_content("ok", "text/plain");
  18656. });
  18657. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18658. auto se = detail::scope_exit([&] {
  18659. svr.stop();
  18660. t.join();
  18661. ASSERT_FALSE(svr.is_running());
  18662. });
  18663. svr.wait_until_ready();
  18664. Client cli(HOST, PORT);
  18665. auto res = cli.Get(
  18666. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18668. EXPECT_EQ(StatusCode::OK_200, res->status);
  18669. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18670. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18671. }
  18672. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18673. Server svr;
  18674. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18675. std::string observed_remote_addr;
  18676. std::string observed_xff;
  18677. svr.Get("/ip", [&](const Request &req, Response &res) {
  18678. observed_remote_addr = req.remote_addr;
  18679. observed_xff = req.get_header_value("X-Forwarded-For");
  18680. res.set_content("ok", "text/plain");
  18681. });
  18682. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18683. auto se = detail::scope_exit([&] {
  18684. svr.stop();
  18685. t.join();
  18686. ASSERT_FALSE(svr.is_running());
  18687. });
  18688. svr.wait_until_ready();
  18689. Client cli(HOST, PORT);
  18690. auto res = cli.Get(
  18691. "/ip",
  18692. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18694. EXPECT_EQ(StatusCode::OK_200, res->status);
  18695. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18696. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18697. }
  18698. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18699. Server svr;
  18700. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18701. std::string observed_remote_addr;
  18702. std::string observed_xff;
  18703. svr.Get("/ip", [&](const Request &req, Response &res) {
  18704. observed_remote_addr = req.remote_addr;
  18705. observed_xff = req.get_header_value("X-Forwarded-For");
  18706. res.set_content("ok", "text/plain");
  18707. });
  18708. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18709. auto se = detail::scope_exit([&] {
  18710. svr.stop();
  18711. t.join();
  18712. ASSERT_FALSE(svr.is_running());
  18713. });
  18714. svr.wait_until_ready();
  18715. Client cli(HOST, PORT);
  18716. auto res = cli.Get(
  18717. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18719. EXPECT_EQ(StatusCode::OK_200, res->status);
  18720. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18721. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18722. // and must not be selected.
  18723. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18724. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18725. }
  18726. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18727. Server svr;
  18728. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18729. std::string observed_remote_addr;
  18730. svr.Get("/ip", [&](const Request &req, Response &res) {
  18731. observed_remote_addr = req.remote_addr;
  18732. res.set_content("ok", "text/plain");
  18733. });
  18734. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18735. auto se = detail::scope_exit([&] {
  18736. svr.stop();
  18737. t.join();
  18738. ASSERT_FALSE(svr.is_running());
  18739. });
  18740. svr.wait_until_ready();
  18741. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18742. // a forged address and the trusted proxy's own address; the forged value must
  18743. // not win over the address the trusted proxy actually recorded.
  18744. Client cli(HOST, PORT);
  18745. auto res = cli.Get(
  18746. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18748. EXPECT_EQ(StatusCode::OK_200, res->status);
  18749. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18750. }
  18751. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18752. Server svr;
  18753. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18754. std::string observed_remote_addr;
  18755. std::string observed_xff;
  18756. svr.Get("/ip", [&](const Request &req, Response &res) {
  18757. observed_remote_addr = req.remote_addr;
  18758. observed_xff = req.get_header_value("X-Forwarded-For");
  18759. res.set_content("ok", "text/plain");
  18760. });
  18761. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18762. auto se = detail::scope_exit([&] {
  18763. svr.stop();
  18764. t.join();
  18765. ASSERT_FALSE(svr.is_running());
  18766. });
  18767. svr.wait_until_ready();
  18768. Client cli(HOST, PORT);
  18769. auto res = cli.Get(
  18770. "/ip",
  18771. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18773. EXPECT_EQ(StatusCode::OK_200, res->status);
  18774. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18775. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18776. }
  18777. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18778. Server svr;
  18779. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18780. std::string observed_remote_addr;
  18781. std::string observed_xff;
  18782. svr.Get("/ip", [&](const Request &req, Response &res) {
  18783. observed_remote_addr = req.remote_addr;
  18784. observed_xff = req.get_header_value("X-Forwarded-For");
  18785. res.set_content("ok", "text/plain");
  18786. });
  18787. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18788. auto se = detail::scope_exit([&] {
  18789. svr.stop();
  18790. t.join();
  18791. ASSERT_FALSE(svr.is_running());
  18792. });
  18793. svr.wait_until_ready();
  18794. std::string raw_req =
  18795. "GET /ip HTTP/1.1\r\n"
  18796. "Host: localhost\r\n"
  18797. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18798. "Connection: close\r\n"
  18799. "\r\n";
  18800. std::string out;
  18801. ASSERT_TRUE(send_request(5, raw_req, &out));
  18802. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18803. // Header parser trims surrounding whitespace of the header value
  18804. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18805. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18806. }
  18807. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18808. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18809. // their own X-Forwarded-For as a separate field line rather than extending the
  18810. // one the client sent, so every occurrence has to be taken into account.
  18811. // Reading only the first one hands back the address the client chose.
  18812. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18813. Server svr;
  18814. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18815. std::string observed_remote_addr;
  18816. size_t observed_xff_count = 0;
  18817. svr.Get("/ip", [&](const Request &req, Response &res) {
  18818. observed_remote_addr = req.remote_addr;
  18819. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18820. res.set_content("ok", "text/plain");
  18821. });
  18822. auto port = svr.bind_to_any_port(HOST);
  18823. thread t = thread([&]() { svr.listen_after_bind(); });
  18824. auto se = detail::scope_exit([&] {
  18825. svr.stop();
  18826. t.join();
  18827. ASSERT_FALSE(svr.is_running());
  18828. });
  18829. svr.wait_until_ready();
  18830. // The client supplies the first field line; the trusted proxy appends the
  18831. // address it observed as a second one.
  18832. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18833. "Host: localhost\r\n"
  18834. "X-Forwarded-For: 1.2.3.4\r\n"
  18835. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18836. "Connection: close\r\n"
  18837. "\r\n";
  18838. std::string out;
  18839. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18840. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18841. EXPECT_EQ(observed_xff_count, 2U);
  18842. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18843. // The same chain spread over one field line per hop derives the same client
  18844. // address, i.e. the split and the comma-joined representations agree.
  18845. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18846. "Host: localhost\r\n"
  18847. "X-Forwarded-For: 1.2.3.4\r\n"
  18848. "X-Forwarded-For: 198.51.100.23\r\n"
  18849. "X-Forwarded-For: 192.0.2.45\r\n"
  18850. "Connection: close\r\n"
  18851. "\r\n";
  18852. out.clear();
  18853. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18854. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18855. EXPECT_EQ(observed_xff_count, 3U);
  18856. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18857. }
  18858. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18859. // crash the server (it used to call front() on an empty vector inside
  18860. // get_client_ip). The connection-level remote address must be retained instead.
  18861. static void run_malformed_xff_test(const std::string &xff_value) {
  18862. Server svr;
  18863. svr.set_trusted_proxies({"192.0.2.45"});
  18864. std::string observed_remote_addr;
  18865. svr.Get("/ip", [&](const Request &req, Response &res) {
  18866. observed_remote_addr = req.remote_addr;
  18867. res.set_content("ok", "text/plain");
  18868. });
  18869. int port = 0;
  18870. thread t = thread([&]() {
  18871. port = svr.bind_to_any_port(HOST);
  18872. svr.listen_after_bind();
  18873. });
  18874. auto se = detail::scope_exit([&] {
  18875. svr.stop();
  18876. t.join();
  18877. ASSERT_FALSE(svr.is_running());
  18878. });
  18879. svr.wait_until_ready();
  18880. Client cli(HOST, port);
  18881. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18883. EXPECT_EQ(StatusCode::OK_200, res->status);
  18884. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18885. observed_remote_addr == "127.0.0.1");
  18886. }
  18887. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18888. run_malformed_xff_test("");
  18889. }
  18890. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18891. run_malformed_xff_test(",");
  18892. }
  18893. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18894. run_malformed_xff_test(", , ,");
  18895. }
  18896. // The same rule applies to Accept: a request whose acceptable types are spread
  18897. // over several field lines must be negotiated against all of them.
  18898. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18899. // case-insensitive connection options. Comparing the whole field value against
  18900. // one option misses a client that sends several of them, and misses every
  18901. // casing but the one written in the comparison.
  18902. //
  18903. // Sends req, reads the response, then reuses the same socket for a second
  18904. // request to find out whether the server kept the connection.
  18905. static void probe_connection_reuse(int port, const std::string &req,
  18906. bool *announced_close, bool *reusable) {
  18907. auto error = Error::Success;
  18908. auto sock = detail::create_client_socket(
  18909. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18910. /*connection_timeout_sec=*/5, 0,
  18911. /*read_timeout_sec=*/1, 0,
  18912. /*write_timeout_sec=*/5, 0, std::string(), error);
  18913. ASSERT_NE(sock, INVALID_SOCKET);
  18914. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18915. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18916. "Host: localhost\r\n"
  18917. "Connection: close\r\n"
  18918. "\r\n";
  18919. std::string first_response;
  18920. std::string second_response;
  18921. detail::process_client_socket(
  18922. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18923. [&](Stream &strm) {
  18924. if (strm.write(req.data(), req.size()) !=
  18925. static_cast<ssize_t>(req.size())) {
  18926. return false;
  18927. }
  18928. char buf[512];
  18929. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18930. // Headers plus the two-byte body of the handler below
  18931. while (reader.getline()) {
  18932. first_response += reader.ptr();
  18933. if (first_response.find("ok") != std::string::npos) { break; }
  18934. }
  18935. if (strm.write(second.data(), second.size()) !=
  18936. static_cast<ssize_t>(second.size())) {
  18937. return true;
  18938. }
  18939. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18940. while (reader2.getline()) {
  18941. second_response += reader2.ptr();
  18942. if (second_response.find("ok") != std::string::npos) { break; }
  18943. }
  18944. return true;
  18945. });
  18946. *announced_close =
  18947. first_response.find("Connection: close") != std::string::npos;
  18948. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18949. }
  18950. class ConnectionTokenTest : public ::testing::Test {
  18951. protected:
  18952. void SetUp() override {
  18953. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18954. res.set_content("ok", "text/plain");
  18955. });
  18956. port_ = svr_.bind_to_any_port(HOST);
  18957. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18958. svr_.wait_until_ready();
  18959. }
  18960. void TearDown() override {
  18961. svr_.stop();
  18962. if (thread_.joinable()) { thread_.join(); }
  18963. }
  18964. Server svr_;
  18965. int port_ = 0;
  18966. thread thread_;
  18967. };
  18968. // "close" alongside another option still closes the connection, and the
  18969. // response says so rather than leaving the peer to discover it.
  18970. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18971. bool announced_close = false;
  18972. bool reusable = true;
  18973. probe_connection_reuse(port_,
  18974. "GET /keepalive HTTP/1.1\r\n"
  18975. "Host: localhost\r\n"
  18976. "Connection: keep-alive, close\r\n"
  18977. "\r\n",
  18978. &announced_close, &reusable);
  18979. EXPECT_TRUE(announced_close);
  18980. EXPECT_FALSE(reusable);
  18981. }
  18982. // "close" split over two field lines is the same list, so it is honored too.
  18983. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18984. bool announced_close = false;
  18985. bool reusable = true;
  18986. probe_connection_reuse(port_,
  18987. "GET /keepalive HTTP/1.1\r\n"
  18988. "Host: localhost\r\n"
  18989. "Connection: keep-alive\r\n"
  18990. "Connection: close\r\n"
  18991. "\r\n",
  18992. &announced_close, &reusable);
  18993. EXPECT_TRUE(announced_close);
  18994. EXPECT_FALSE(reusable);
  18995. }
  18996. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18997. // keep-alive in the spelling everyone actually sends keeps its connection.
  18998. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18999. bool announced_close = false;
  19000. bool reusable = false;
  19001. probe_connection_reuse(port_,
  19002. "GET /keepalive HTTP/1.0\r\n"
  19003. "Host: localhost\r\n"
  19004. "Connection: keep-alive\r\n"
  19005. "\r\n",
  19006. &announced_close, &reusable);
  19007. EXPECT_FALSE(announced_close);
  19008. EXPECT_TRUE(reusable);
  19009. }
  19010. // A token the value merely contains is not the token itself.
  19011. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19012. bool announced_close = false;
  19013. bool reusable = false;
  19014. probe_connection_reuse(port_,
  19015. "GET /keepalive HTTP/1.1\r\n"
  19016. "Host: localhost\r\n"
  19017. "Connection: notclose\r\n"
  19018. "\r\n",
  19019. &announced_close, &reusable);
  19020. EXPECT_FALSE(announced_close);
  19021. EXPECT_TRUE(reusable);
  19022. }
  19023. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19024. Server svr;
  19025. std::vector<std::string> observed_types;
  19026. svr.Get("/", [&](const Request &req, Response &res) {
  19027. observed_types = req.accept_content_types;
  19028. res.set_content("ok", "text/plain");
  19029. });
  19030. auto port = svr.bind_to_any_port(HOST);
  19031. thread t = thread([&]() { svr.listen_after_bind(); });
  19032. auto se = detail::scope_exit([&] {
  19033. svr.stop();
  19034. t.join();
  19035. ASSERT_FALSE(svr.is_running());
  19036. });
  19037. svr.wait_until_ready();
  19038. Client cli(HOST, port);
  19039. Headers headers;
  19040. headers.emplace("Accept", "text/plain;q=0.5");
  19041. headers.emplace("Accept", "application/json");
  19042. auto res = cli.Get("/", headers);
  19043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19044. EXPECT_EQ(StatusCode::OK_200, res->status);
  19045. // Sorted by q-value, so the second field line's type comes first
  19046. ASSERT_EQ(2U, observed_types.size());
  19047. EXPECT_EQ("application/json", observed_types[0]);
  19048. EXPECT_EQ("text/plain", observed_types[1]);
  19049. }
  19050. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19051. // empty field line must not contribute a bare comma to the combined value.
  19052. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19053. Server svr;
  19054. std::vector<std::string> observed_types;
  19055. svr.Get("/", [&](const Request &req, Response &res) {
  19056. observed_types = req.accept_content_types;
  19057. res.set_content("ok", "text/plain");
  19058. });
  19059. auto port = svr.bind_to_any_port(HOST);
  19060. thread t = thread([&]() { svr.listen_after_bind(); });
  19061. auto se = detail::scope_exit([&] {
  19062. svr.stop();
  19063. t.join();
  19064. ASSERT_FALSE(svr.is_running());
  19065. });
  19066. svr.wait_until_ready();
  19067. // Empty first field line, then a real one
  19068. std::string raw_req = "GET / HTTP/1.1\r\n"
  19069. "Host: localhost\r\n"
  19070. "Accept:\r\n"
  19071. "Accept: application/json\r\n"
  19072. "Connection: close\r\n"
  19073. "\r\n";
  19074. std::string out;
  19075. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19076. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19077. ASSERT_EQ(1U, observed_types.size());
  19078. EXPECT_EQ("application/json", observed_types[0]);
  19079. }
  19080. // The skip in get_combined_header_value() is what keeps an empty field line
  19081. // from contributing a bare comma. Only a trailing empty field line exercises
  19082. // it: a leading one is already covered by the "combined is still empty" check,
  19083. // and parse_accept_header() now ignores the empty element either way, so the
  19084. // request-level test above can no longer tell the two apart.
  19085. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19086. Headers headers;
  19087. headers.emplace("Accept", "text/html");
  19088. headers.emplace("Accept", "");
  19089. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19090. headers.clear();
  19091. headers.emplace("Accept", "");
  19092. headers.emplace("Accept", "application/json");
  19093. EXPECT_EQ("application/json",
  19094. detail::get_combined_header_value(headers, "Accept"));
  19095. }
  19096. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19097. // An encoding offered on a later Accept-Encoding field line is still offered.
  19098. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19099. Server svr;
  19100. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19101. res.set_content(std::string(1024, 'x'), "text/plain");
  19102. });
  19103. auto port = svr.bind_to_any_port(HOST);
  19104. thread t = thread([&]() { svr.listen_after_bind(); });
  19105. auto se = detail::scope_exit([&] {
  19106. svr.stop();
  19107. t.join();
  19108. ASSERT_FALSE(svr.is_running());
  19109. });
  19110. svr.wait_until_ready();
  19111. Client cli(HOST, port);
  19112. cli.set_decompress(false);
  19113. Headers headers;
  19114. headers.emplace("Accept-Encoding", "identity");
  19115. headers.emplace("Accept-Encoding", "gzip");
  19116. auto res = cli.Get("/", headers);
  19117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19118. EXPECT_EQ(StatusCode::OK_200, res->status);
  19119. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19120. }
  19121. #endif
  19122. #ifndef _WIN32
  19123. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19124. Server svr;
  19125. svr.Post("/post", [&](const Request &req, Response &res) {
  19126. res.set_content(req.body, "text/plain");
  19127. });
  19128. svr.Put("/put", [&](const Request &req, Response &res) {
  19129. res.set_content(req.body, "text/plain");
  19130. });
  19131. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19132. res.set_content(req.body, "text/plain");
  19133. });
  19134. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19135. res.set_content(req.body, "text/plain");
  19136. });
  19137. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19138. auto se = detail::scope_exit([&] {
  19139. svr.stop();
  19140. t.join();
  19141. ASSERT_FALSE(svr.is_running());
  19142. });
  19143. svr.wait_until_ready();
  19144. std::string resp;
  19145. // POST without Content-Length
  19146. ASSERT_TRUE(send_request(5,
  19147. "POST /post HTTP/1.1\r\n"
  19148. "Host: localhost\r\n"
  19149. "Connection: close\r\n"
  19150. "\r\n",
  19151. &resp));
  19152. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19153. // PUT without Content-Length
  19154. resp.clear();
  19155. ASSERT_TRUE(send_request(5,
  19156. "PUT /put HTTP/1.1\r\n"
  19157. "Host: localhost\r\n"
  19158. "Connection: close\r\n"
  19159. "\r\n",
  19160. &resp));
  19161. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19162. // PATCH without Content-Length
  19163. resp.clear();
  19164. ASSERT_TRUE(send_request(5,
  19165. "PATCH /patch HTTP/1.1\r\n"
  19166. "Host: localhost\r\n"
  19167. "Connection: close\r\n"
  19168. "\r\n",
  19169. &resp));
  19170. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19171. // DELETE without Content-Length
  19172. resp.clear();
  19173. ASSERT_TRUE(send_request(5,
  19174. "DELETE /delete HTTP/1.1\r\n"
  19175. "Host: localhost\r\n"
  19176. "Connection: close\r\n"
  19177. "\r\n",
  19178. &resp));
  19179. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19180. }
  19181. #endif
  19182. //==============================================================================
  19183. // open_stream() Tests
  19184. //==============================================================================
  19185. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19186. std::string result;
  19187. char buf[8192];
  19188. ssize_t n;
  19189. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19190. result.append(buf, static_cast<size_t>(n));
  19191. }
  19192. return result;
  19193. }
  19194. // Mock stream for unit tests
  19195. class MockStream : public Stream {
  19196. public:
  19197. std::string data;
  19198. size_t pos = 0;
  19199. ssize_t error_after = -1; // -1 = no error
  19200. explicit MockStream(const std::string &d, ssize_t err = -1)
  19201. : data(d), error_after(err) {}
  19202. bool is_readable() const override { return true; }
  19203. bool wait_readable() const override { return true; }
  19204. bool wait_writable() const override { return true; }
  19205. ssize_t read(char *ptr, size_t size) override {
  19206. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19207. if (pos >= data.size()) return 0;
  19208. size_t limit =
  19209. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19210. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19211. std::memcpy(ptr, data.data() + pos, to_read);
  19212. pos += to_read;
  19213. return static_cast<ssize_t>(to_read);
  19214. }
  19215. ssize_t write(const char *, size_t) override { return -1; }
  19216. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19217. ip = "127.0.0.1";
  19218. port = 0;
  19219. }
  19220. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19221. ip = "127.0.0.1";
  19222. port = 0;
  19223. }
  19224. socket_t socket() const override { return INVALID_SOCKET; }
  19225. time_t duration() const override { return 0; }
  19226. };
  19227. TEST(StreamHandleTest, Basic) {
  19228. ClientImpl::StreamHandle handle;
  19229. EXPECT_FALSE(handle.is_valid());
  19230. handle.response = detail::make_unique<Response>();
  19231. handle.error = Error::Connection;
  19232. EXPECT_FALSE(handle.is_valid());
  19233. handle.error = Error::Success;
  19234. EXPECT_TRUE(handle.is_valid());
  19235. }
  19236. TEST(BodyReaderTest, Basic) {
  19237. MockStream stream("Hello, World!");
  19238. detail::BodyReader reader;
  19239. reader.stream = &stream;
  19240. reader.content_length = 13;
  19241. char buf[32];
  19242. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19243. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19244. EXPECT_TRUE(reader.eof);
  19245. }
  19246. TEST(BodyReaderTest, NoStream) {
  19247. detail::BodyReader reader;
  19248. char buf[32];
  19249. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19250. EXPECT_EQ(Error::Connection, reader.last_error);
  19251. }
  19252. TEST(BodyReaderTest, Error) {
  19253. MockStream stream("Hello, World!", 5);
  19254. detail::BodyReader reader;
  19255. reader.stream = &stream;
  19256. reader.content_length = 13;
  19257. char buf[32];
  19258. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19259. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19260. EXPECT_EQ(Error::Read, reader.last_error);
  19261. }
  19262. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19263. // Mock-based StreamHandle tests relying on private internals are removed.
  19264. class OpenStreamTest : public ::testing::Test {
  19265. protected:
  19266. void SetUp() override {
  19267. svr_.Get("/hello", [](const Request &, Response &res) {
  19268. res.set_content("Hello World!", "text/plain");
  19269. });
  19270. svr_.Get("/large", [](const Request &, Response &res) {
  19271. res.set_content(std::string(10000, 'X'), "text/plain");
  19272. });
  19273. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19274. res.set_content("Hello World!", "image/jpeg");
  19275. res.set_header("Content-Encoding", "UTF-8");
  19276. });
  19277. svr_.Get("/chunked", [](const Request &, Response &res) {
  19278. res.set_chunked_content_provider("text/plain",
  19279. [](size_t offset, DataSink &sink) {
  19280. if (offset < 15) {
  19281. sink.write("chunk", 5);
  19282. return true;
  19283. }
  19284. sink.done();
  19285. return true;
  19286. });
  19287. });
  19288. svr_.Get("/compressible", [](const Request &, Response &res) {
  19289. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19290. DataSink &sink) {
  19291. if (offset < 100 * 1024) {
  19292. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19293. sink.write(chunk.data(), chunk.size());
  19294. return true;
  19295. }
  19296. sink.done();
  19297. return true;
  19298. });
  19299. });
  19300. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19301. [](const Request & /*req*/, Response &res) {
  19302. auto i = new int(0);
  19303. res.set_header("Trailer", "Content-Length, X-Allowed");
  19304. res.set_chunked_content_provider(
  19305. "text/plain",
  19306. [i](size_t /*offset*/, DataSink &sink) {
  19307. switch (*i) {
  19308. case 0: sink.os << "123"; break;
  19309. case 1: sink.os << "456"; break;
  19310. case 2: sink.os << "789"; break;
  19311. case 3: {
  19312. sink.done_with_trailer(
  19313. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19314. } break;
  19315. }
  19316. (*i)++;
  19317. return true;
  19318. },
  19319. [i](bool success) {
  19320. EXPECT_TRUE(success);
  19321. delete i;
  19322. });
  19323. });
  19324. // Echo headers endpoint for header-related tests
  19325. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19326. std::string body;
  19327. for (const auto &h : req.headers) {
  19328. body.append(h.first);
  19329. body.push_back(':');
  19330. body.append(h.second);
  19331. body.push_back('\n');
  19332. }
  19333. res.set_content(body, "text/plain");
  19334. });
  19335. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19336. std::string body;
  19337. for (const auto &h : req.headers) {
  19338. body.append(h.first);
  19339. body.push_back(':');
  19340. body.append(h.second);
  19341. body.push_back('\n');
  19342. }
  19343. res.set_content(body, "text/plain");
  19344. });
  19345. port_ = svr_.bind_to_any_port("127.0.0.1");
  19346. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19347. svr_.wait_until_ready();
  19348. }
  19349. void TearDown() override {
  19350. svr_.stop();
  19351. if (thread_.joinable()) thread_.join();
  19352. }
  19353. Server svr_;
  19354. std::thread thread_;
  19355. int port_ = 0;
  19356. };
  19357. TEST_F(OpenStreamTest, Basic) {
  19358. Client cli("127.0.0.1", port_);
  19359. auto handle = cli.open_stream("GET", "/hello");
  19360. EXPECT_TRUE(handle.is_valid());
  19361. EXPECT_EQ("Hello World!", read_all(handle));
  19362. }
  19363. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19364. Client cli("127.0.0.1", port_);
  19365. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19366. ASSERT_TRUE(handle.is_valid());
  19367. EXPECT_EQ("Hello World!", read_all(handle));
  19368. }
  19369. TEST_F(OpenStreamTest, SmallBuffer) {
  19370. Client cli("127.0.0.1", port_);
  19371. auto handle = cli.open_stream("GET", "/hello");
  19372. std::string result;
  19373. char buf[4];
  19374. ssize_t n;
  19375. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19376. result.append(buf, static_cast<size_t>(n));
  19377. EXPECT_EQ("Hello World!", result);
  19378. }
  19379. TEST_F(OpenStreamTest, DefaultHeaders) {
  19380. Client cli("127.0.0.1", port_);
  19381. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19382. {
  19383. auto handle = cli.open_stream("GET", "/echo-headers");
  19384. ASSERT_TRUE(handle.is_valid());
  19385. auto body = read_all(handle);
  19386. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19387. std::string::npos);
  19388. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19389. std::string::npos);
  19390. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19391. }
  19392. // open_stream POST with body and no explicit content_type should NOT add
  19393. // text/plain Content-Type (behavior differs from non-streaming path), but
  19394. // should include Content-Length
  19395. {
  19396. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19397. ASSERT_TRUE(handle.is_valid());
  19398. auto body = read_all(handle);
  19399. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19400. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19401. }
  19402. // open_stream POST with explicit Content-Type should preserve it
  19403. {
  19404. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19405. {{"Content-Type", "application/custom"}},
  19406. "{}", "application/custom");
  19407. ASSERT_TRUE(handle.is_valid());
  19408. auto body = read_all(handle);
  19409. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19410. }
  19411. // User-specified User-Agent must not be overwritten for stream API
  19412. {
  19413. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19414. {{"User-Agent", "MyAgent/1.2"}});
  19415. ASSERT_TRUE(handle.is_valid());
  19416. auto body = read_all(handle);
  19417. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19418. }
  19419. }
  19420. TEST_F(OpenStreamTest, Large) {
  19421. Client cli("127.0.0.1", port_);
  19422. auto handle = cli.open_stream("GET", "/large");
  19423. EXPECT_EQ(10000u, read_all(handle).size());
  19424. }
  19425. TEST_F(OpenStreamTest, ConnectionError) {
  19426. Client cli("127.0.0.1", 9999);
  19427. auto handle = cli.open_stream("GET", "/hello");
  19428. EXPECT_FALSE(handle.is_valid());
  19429. }
  19430. TEST_F(OpenStreamTest, Chunked) {
  19431. Client cli("127.0.0.1", port_);
  19432. auto handle = cli.open_stream("GET", "/chunked");
  19433. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19434. "Transfer-Encoding") == "chunked");
  19435. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19436. }
  19437. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19438. Client cli("127.0.0.1", port_);
  19439. auto handle =
  19440. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19441. ASSERT_TRUE(handle.is_valid());
  19442. // Consume body to allow trailers to be received/parsed
  19443. auto body = read_all(handle);
  19444. // Explicitly parse trailers (ensure trailers are available for assertion)
  19445. handle.parse_trailers_if_needed();
  19446. EXPECT_EQ(std::string("123456789"), body);
  19447. // The response should include a Trailer header declaring both names
  19448. ASSERT_TRUE(handle.response);
  19449. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19450. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19451. handle.response->get_header_value("Trailer"));
  19452. // Prohibited trailer must not be present
  19453. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19454. // Allowed trailer should be present
  19455. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19456. EXPECT_EQ(std::string("yes"),
  19457. handle.response->get_trailer_value("X-Allowed"));
  19458. // Verify trailers are NOT present as regular headers
  19459. EXPECT_EQ(std::string(""),
  19460. handle.response->get_header_value("Content-Length"));
  19461. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19462. }
  19463. // Accepts one connection on an OS-assigned port, which it hands over through
  19464. // port_promise, reads the request head and sends back response. after_send,
  19465. // if given, runs on the connection before it is closed.
  19466. static std::thread
  19467. serve_single_response(std::promise<int> &port_promise,
  19468. const std::string &response,
  19469. std::function<void(socket_t)> after_send = nullptr) {
  19470. return std::thread([&port_promise, response, after_send] {
  19471. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19472. default_socket_options(srv);
  19473. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19474. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19475. sockaddr_in addr{};
  19476. addr.sin_family = AF_INET;
  19477. addr.sin_port = htons(0); // Let OS assign a free port
  19478. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19479. int opt = 1;
  19480. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19481. #ifdef _WIN32
  19482. reinterpret_cast<const char *>(&opt),
  19483. #else
  19484. &opt,
  19485. #endif
  19486. sizeof(opt));
  19487. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19488. ::listen(srv, 1) != 0) {
  19489. port_promise.set_value(-1);
  19490. detail::close_socket(srv);
  19491. return;
  19492. }
  19493. socklen_t addr_len = sizeof(addr);
  19494. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19495. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19496. sockaddr_in cli_addr{};
  19497. socklen_t cli_len = sizeof(cli_addr);
  19498. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19499. if (cli != INVALID_SOCKET) {
  19500. // Read the complete HTTP request (until the blank line that terminates
  19501. // headers) before sending the response. If the server closes the socket
  19502. // while the client's request data is still unread in the kernel receive
  19503. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19504. // connection on both sides: it discards the client's receive buffer
  19505. // (which already holds our response) and causes any in-progress write on
  19506. // the client to fail with ECONNRESET. Reading all request data first
  19507. // ensures close() emits a graceful FIN.
  19508. {
  19509. char rbuf[256];
  19510. std::string req;
  19511. while (req.find("\r\n\r\n") == std::string::npos) {
  19512. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19513. if (n <= 0) { break; }
  19514. req.append(rbuf, static_cast<size_t>(n));
  19515. }
  19516. }
  19517. ::send(cli,
  19518. #ifdef _WIN32
  19519. static_cast<const char *>(response.c_str()),
  19520. static_cast<int>(response.size()),
  19521. #else
  19522. response.c_str(), response.size(),
  19523. #endif
  19524. 0);
  19525. if (after_send) { after_send(cli); }
  19526. detail::close_socket(cli);
  19527. }
  19528. detail::close_socket(srv);
  19529. });
  19530. }
  19531. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19532. #ifndef _WIN32
  19533. signal(SIGPIPE, SIG_IGN);
  19534. #endif
  19535. std::promise<int> port_promise;
  19536. auto port_future = port_promise.get_future();
  19537. auto server_thread =
  19538. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19539. "Content-Type: text/plain\r\n"
  19540. "Content-Length: not-a-number\r\n"
  19541. "Connection: close\r\n"
  19542. "\r\n"
  19543. "hello");
  19544. auto port = port_future.get();
  19545. ASSERT_GT(port, 0);
  19546. Client cli("127.0.0.1", port);
  19547. auto handle = cli.open_stream("GET", "/");
  19548. EXPECT_FALSE(handle.is_valid());
  19549. server_thread.join();
  19550. }
  19551. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19552. #ifndef _WIN32
  19553. signal(SIGPIPE, SIG_IGN);
  19554. #endif
  19555. std::promise<int> port_promise;
  19556. auto port_future = port_promise.get_future();
  19557. auto server_thread = serve_single_response(
  19558. port_promise, "HTTP/1.1 200 OK\r\n"
  19559. "Content-Type: text/plain\r\n"
  19560. "Content-Length: 99999999999999999999999999\r\n"
  19561. "Connection: close\r\n"
  19562. "\r\n"
  19563. "hello");
  19564. auto port = port_future.get();
  19565. ASSERT_GT(port, 0);
  19566. // Historically std::stoull would throw std::out_of_range here and crash
  19567. // the process, then parsing silently clamped to a bogus framing length and
  19568. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19569. // so the stream fails to open, matching the not-a-number case above. The
  19570. // process still must NOT terminate.
  19571. Client cli("127.0.0.1", port);
  19572. auto handle = cli.open_stream("GET", "/");
  19573. EXPECT_FALSE(handle.is_valid());
  19574. server_thread.join();
  19575. }
  19576. // Serves `response` to the single request `fn` makes with a fresh client.
  19577. template <typename Fn>
  19578. static void with_single_response(const std::string &response, Fn fn) {
  19579. #ifndef _WIN32
  19580. signal(SIGPIPE, SIG_IGN);
  19581. #endif
  19582. std::promise<int> port_promise;
  19583. auto port_future = port_promise.get_future();
  19584. auto server_thread = serve_single_response(port_promise, response);
  19585. auto se = detail::scope_exit([&] { server_thread.join(); });
  19586. auto port = port_future.get();
  19587. ASSERT_GT(port, 0);
  19588. Client cli("127.0.0.1", port);
  19589. fn(cli);
  19590. }
  19591. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19592. // Neither Content-Length nor chunked: the body ends at the close
  19593. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19594. "Connection: close\r\n"
  19595. "\r\n"
  19596. "hello";
  19597. with_single_response(close_delimited, [](Client &cli) {
  19598. auto handle = cli.open_stream("GET", "/");
  19599. ASSERT_TRUE(handle.is_valid());
  19600. EXPECT_EQ("hello", read_all(handle));
  19601. EXPECT_FALSE(handle.has_read_error());
  19602. });
  19603. // A close before the end of the Content-Length is still an error
  19604. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19605. "Content-Length: 10\r\n"
  19606. "\r\n"
  19607. "hello";
  19608. with_single_response(short_content_length, [](Client &cli) {
  19609. auto handle = cli.open_stream("GET", "/");
  19610. ASSERT_TRUE(handle.is_valid());
  19611. read_all(handle);
  19612. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19613. });
  19614. // So is a close before the last chunk
  19615. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19616. "Transfer-Encoding: chunked\r\n"
  19617. "\r\n"
  19618. "5\r\nhello\r\n";
  19619. with_single_response(short_chunked, [](Client &cli) {
  19620. auto handle = cli.open_stream("GET", "/");
  19621. ASSERT_TRUE(handle.is_valid());
  19622. read_all(handle);
  19623. EXPECT_TRUE(handle.has_read_error());
  19624. });
  19625. }
  19626. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19627. const char *responses[] = {
  19628. "HTTP/1.1 103 Early Hints\r\n"
  19629. "Link: </style.css>; rel=preload\r\n"
  19630. "\r\n"
  19631. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19632. "HTTP/1.1 100 Continue\r\n"
  19633. "X-Note: interim\r\n"
  19634. "\r\n"
  19635. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19636. };
  19637. for (auto response : responses) {
  19638. with_single_response(response, [](Client &cli) {
  19639. auto res = cli.Get("/");
  19640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19641. EXPECT_EQ(StatusCode::OK_200, res->status);
  19642. EXPECT_EQ("ok", res->body);
  19643. });
  19644. }
  19645. }
  19646. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19647. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19648. const std::string final_response =
  19649. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19650. std::string interims;
  19651. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19652. interims += interim;
  19653. }
  19654. with_single_response(interims + final_response, [](Client &cli) {
  19655. auto res = cli.Get("/");
  19656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19657. EXPECT_EQ("ok", res->body);
  19658. });
  19659. with_single_response(interims + interim + final_response, [](Client &cli) {
  19660. auto res = cli.Get("/");
  19661. ASSERT_FALSE(res);
  19662. EXPECT_EQ(Error::Read, res.error());
  19663. });
  19664. }
  19665. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19666. #ifndef _WIN32
  19667. signal(SIGPIPE, SIG_IGN);
  19668. #endif
  19669. // The server answers the head without asking for the body. Bytes it then
  19670. // reads on the connection would be taken for the body the request declared.
  19671. auto closed_by_client = false;
  19672. std::promise<int> port_promise;
  19673. auto server_thread = serve_single_response(
  19674. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19675. [&](socket_t sock) {
  19676. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19677. char buf[256];
  19678. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19679. });
  19680. Client cli("127.0.0.1", port_promise.get_future().get());
  19681. cli.set_keep_alive(true);
  19682. cli.set_read_timeout(1, 0);
  19683. // Long enough for the client to send Expect: 100-continue.
  19684. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19686. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19687. cli.Get("/second");
  19688. server_thread.join();
  19689. EXPECT_TRUE(closed_by_client);
  19690. }
  19691. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19692. // Long enough for the client to send Expect: 100-continue
  19693. with_single_response(
  19694. "HTTP/1.1 103 Early Hints\r\n"
  19695. "Link: </style.css>; rel=preload\r\n"
  19696. "\r\n"
  19697. "HTTP/1.1 401 Unauthorized\r\n"
  19698. "Content-Length: 0\r\n\r\n",
  19699. [](Client &cli) {
  19700. cli.set_read_timeout(2, 0);
  19701. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19704. });
  19705. }
  19706. #ifdef CPPHTTPLIB_SSL_ENABLED
  19707. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19708. #ifndef _WIN32
  19709. signal(SIGPIPE, SIG_IGN);
  19710. #endif
  19711. auto reused = false;
  19712. std::promise<int> port_promise;
  19713. auto server_thread = serve_single_response(
  19714. port_promise,
  19715. "HTTP/1.1 401 Unauthorized\r\n"
  19716. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19717. "Content-Length: 0\r\n\r\n",
  19718. [&](socket_t sock) {
  19719. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19720. char buf[256];
  19721. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19722. });
  19723. Client cli("127.0.0.1", port_promise.get_future().get());
  19724. cli.set_keep_alive(true);
  19725. cli.set_digest_auth("user", "pass");
  19726. cli.set_read_timeout(1, 0);
  19727. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19728. server_thread.join();
  19729. EXPECT_FALSE(reused);
  19730. }
  19731. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19732. // Any other answer to CONNECT would read as the origin's response.
  19733. struct {
  19734. const char *response;
  19735. bool passed_on;
  19736. } cases[] = {
  19737. {"HTTP/1.1 201 Created\r\n"
  19738. "Set-Cookie: session=from-proxy\r\n"
  19739. "Content-Length: 0\r\n\r\n",
  19740. false},
  19741. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19742. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19743. "Content-Length: 0\r\n\r\n",
  19744. true},
  19745. };
  19746. for (const auto &c : cases) {
  19747. std::promise<int> port_promise;
  19748. auto server_thread = serve_single_response(port_promise, c.response);
  19749. SSLClient cli("example.com", 443);
  19750. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19751. auto res = cli.Get("/");
  19752. server_thread.join();
  19753. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19754. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19755. if (res) {
  19756. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19757. }
  19758. }
  19759. }
  19760. #endif
  19761. // Records the client's error logger calls as "error METHOD path", or
  19762. // "error null" for a call without a request
  19763. static ErrorLogger record_errors(std::vector<std::string> &log) {
  19764. return [&log](const Error &err, const Request *req) {
  19765. log.push_back(to_string(err) + " " +
  19766. (req ? req->method + " " + req->path : "null"));
  19767. };
  19768. }
  19769. // A failed request is reported once, with the request the caller made
  19770. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  19771. Server svr;
  19772. svr.Get("/big", [](const Request &, Response &res) {
  19773. res.set_content(std::string(100000, 'b'), "text/plain");
  19774. });
  19775. auto port = svr.bind_to_any_port(HOST);
  19776. std::thread t([&]() { svr.listen_after_bind(); });
  19777. auto se = detail::scope_exit([&] {
  19778. svr.stop();
  19779. t.join();
  19780. });
  19781. svr.wait_until_ready();
  19782. Client cli(HOST, port);
  19783. std::vector<std::string> log;
  19784. cli.set_error_logger(record_errors(log));
  19785. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  19786. cli.Get("/big", [](const char *, size_t) { return false; });
  19787. EXPECT_EQ(expected, log);
  19788. log.clear();
  19789. cli.Get("/big", [](size_t, size_t) { return false; });
  19790. EXPECT_EQ(expected, log);
  19791. }
  19792. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  19793. // Fails while the body is read
  19794. auto broken = [](const Request &, Response &res) {
  19795. res.set_content_provider(10, "text/plain",
  19796. [](size_t, size_t, DataSink &) { return false; });
  19797. };
  19798. Server other;
  19799. other.Get("/broken", broken);
  19800. auto other_port = other.bind_to_any_port(HOST);
  19801. std::thread other_t([&]() { other.listen_after_bind(); });
  19802. auto other_se = detail::scope_exit([&] {
  19803. other.stop();
  19804. other_t.join();
  19805. });
  19806. other.wait_until_ready();
  19807. Server svr;
  19808. svr.Get("/broken", broken);
  19809. svr.Get("/same-origin",
  19810. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  19811. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  19812. res.set_redirect("http://" + std::string(HOST) + ":" +
  19813. std::to_string(other_port) + "/broken");
  19814. });
  19815. auto port = svr.bind_to_any_port(HOST);
  19816. std::thread t([&]() { svr.listen_after_bind(); });
  19817. auto se = detail::scope_exit([&] {
  19818. svr.stop();
  19819. t.join();
  19820. });
  19821. svr.wait_until_ready();
  19822. Client cli(HOST, port);
  19823. cli.set_follow_location(true);
  19824. std::vector<std::string> log;
  19825. cli.set_error_logger(record_errors(log));
  19826. for (auto path : {"/same-origin", "/cross-origin"}) {
  19827. log.clear();
  19828. auto res = cli.Get(path);
  19829. ASSERT_FALSE(res);
  19830. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  19831. log);
  19832. }
  19833. }
  19834. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  19835. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  19836. std::vector<std::string> log;
  19837. cli.set_error_logger(record_errors(log));
  19838. auto handle = cli.open_stream("GET", "/x");
  19839. EXPECT_FALSE(handle.is_valid());
  19840. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  19841. log);
  19842. });
  19843. }
  19844. #ifdef CPPHTTPLIB_SSL_ENABLED
  19845. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  19846. // Not a TLS server, so the handshake fails. It waits for a request line in
  19847. // the handshake bytes, so a short read timeout lets it close quickly.
  19848. Server svr;
  19849. svr.set_read_timeout(0, 100000);
  19850. svr.Get("/x", [](const Request &, Response &res) {
  19851. res.set_content("x", "text/plain");
  19852. });
  19853. auto port = svr.bind_to_any_port(HOST);
  19854. std::thread t([&]() { svr.listen_after_bind(); });
  19855. auto se = detail::scope_exit([&] {
  19856. svr.stop();
  19857. t.join();
  19858. });
  19859. svr.wait_until_ready();
  19860. std::vector<std::string> log;
  19861. SSLClient cli(HOST, port);
  19862. cli.enable_server_certificate_verification(false);
  19863. cli.set_error_logger(record_errors(log));
  19864. auto res = cli.Get("/x");
  19865. ASSERT_FALSE(res);
  19866. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  19867. log.clear();
  19868. auto handle = cli.open_stream("GET", "/x");
  19869. EXPECT_FALSE(handle.is_valid());
  19870. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  19871. log.clear();
  19872. SSLClient no_ca(HOST, port);
  19873. no_ca.set_ca_cert_path("./no-such-ca.pem");
  19874. no_ca.set_error_logger(record_errors(log));
  19875. res = no_ca.Get("/x");
  19876. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  19877. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  19878. }
  19879. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  19880. #ifndef _WIN32
  19881. signal(SIGPIPE, SIG_IGN);
  19882. #endif
  19883. // Refused, answered with a challenge, or closed without an answer
  19884. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  19885. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  19886. "Content-Length: 0\r\n\r\n",
  19887. ""}) {
  19888. std::promise<int> port_promise;
  19889. auto server_thread = serve_single_response(port_promise, response);
  19890. SSLClient cli("example.com", 443);
  19891. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19892. std::vector<std::string> log;
  19893. cli.set_error_logger(record_errors(log));
  19894. auto res = cli.Get("/");
  19895. server_thread.join();
  19896. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  19897. << response;
  19898. }
  19899. }
  19900. #endif
  19901. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19902. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19903. // the chunked coding and drop Content-Length, so a front-end that trusts
  19904. // Content-Length would disagree about where the body ends (response
  19905. // smuggling). The client must reject such a response.
  19906. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19907. for (const char *te : {"chunked", "gzip, chunked"}) {
  19908. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19909. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19910. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19911. "5\r\nhello\r\n0\r\n\r\n";
  19912. with_single_response(response, [&](Client &cli) {
  19913. auto res = cli.Get("/");
  19914. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19915. EXPECT_EQ(Error::Read, res.error()) << te;
  19916. });
  19917. with_single_response(response, [&](Client &cli) {
  19918. auto handle = cli.open_stream("GET", "/");
  19919. EXPECT_FALSE(handle.is_valid()) << te;
  19920. EXPECT_EQ(Error::Read, handle.error) << te;
  19921. });
  19922. }
  19923. }
  19924. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19925. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19926. // closing the connection (unlike a request, which must be rejected).
  19927. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19928. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19929. "Transfer-Encoding: chunked\r\n"
  19930. "Connection: close\r\n"
  19931. "\r\n"
  19932. "5\r\nhello\r\n0\r\n\r\n",
  19933. "HTTP/1.1 200 OK\r\n"
  19934. "Transfer-Encoding: gzip\r\n"
  19935. "Connection: close\r\n"
  19936. "\r\n"
  19937. "hello"}) {
  19938. with_single_response(response, [&](Client &cli) {
  19939. auto res = cli.Get("/");
  19940. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19941. EXPECT_EQ("hello", res->body);
  19942. });
  19943. with_single_response(response, [&](Client &cli) {
  19944. auto handle = cli.open_stream("GET", "/");
  19945. ASSERT_TRUE(handle.is_valid()) << response;
  19946. EXPECT_EQ("hello", read_all(handle));
  19947. });
  19948. }
  19949. }
  19950. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19951. // framing headers describe nothing to read and must not be rejected.
  19952. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19953. const std::string framing = "Content-Length: 5\r\n"
  19954. "Transfer-Encoding: chunked\r\n"
  19955. "Connection: close\r\n"
  19956. "\r\n";
  19957. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19958. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19959. });
  19960. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19961. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19962. });
  19963. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19964. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19965. with_single_response(response, [&](Client &cli) {
  19966. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19967. });
  19968. with_single_response(response, [&](Client &cli) {
  19969. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19970. });
  19971. }
  19972. }
  19973. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19974. // response, is faulty framing, so the connection is not reused after it.
  19975. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19976. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19977. "Content-Length: 0\r\n"
  19978. "Transfer-Encoding: chunked\r\n"
  19979. "\r\n"
  19980. "5\r\nhello\r\n0\r\n\r\n",
  19981. "HTTP/1.0 200 Connection established\r\n"
  19982. "Connection: keep-alive\r\n"
  19983. "Transfer-Encoding: chunked\r\n"
  19984. "\r\n"
  19985. "5\r\nhello\r\n0\r\n\r\n"}) {
  19986. with_single_response(response, [&](Client &cli) {
  19987. cli.set_keep_alive(true);
  19988. auto res = cli.Get("/");
  19989. ASSERT_TRUE(res) << response;
  19990. EXPECT_EQ("hello", res->body);
  19991. EXPECT_FALSE(cli.is_socket_open()) << response;
  19992. });
  19993. }
  19994. }
  19995. // A payload max length of 0 means no limit, however the body is framed.
  19996. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19997. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19998. "Transfer-Encoding: chunked\r\n"
  19999. "\r\n"
  20000. "5\r\nhello\r\n0\r\n\r\n",
  20001. "HTTP/1.1 200 OK\r\n"
  20002. "Connection: close\r\n"
  20003. "\r\n"
  20004. "hello"}) {
  20005. with_single_response(response, [&](Client &cli) {
  20006. cli.set_payload_max_length(0);
  20007. auto res = cli.Get("/");
  20008. ASSERT_TRUE(res) << response;
  20009. EXPECT_EQ("hello", res->body) << response;
  20010. });
  20011. }
  20012. }
  20013. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20014. Server svr;
  20015. svr.set_payload_max_length(0);
  20016. svr.Post("/echo", [](const Request &req, Response &res) {
  20017. res.set_content(req.body, "text/plain");
  20018. });
  20019. auto port = svr.bind_to_any_port(HOST);
  20020. thread t = thread([&] { svr.listen_after_bind(); });
  20021. auto se = detail::scope_exit([&] {
  20022. svr.stop();
  20023. t.join();
  20024. ASSERT_FALSE(svr.is_running());
  20025. });
  20026. svr.wait_until_ready();
  20027. Client cli(HOST, port);
  20028. auto res = cli.Post(
  20029. "/echo",
  20030. [](size_t /*offset*/, DataSink &sink) {
  20031. sink.write("hello", 5);
  20032. sink.done();
  20033. return true;
  20034. },
  20035. "text/plain");
  20036. ASSERT_TRUE(res);
  20037. EXPECT_EQ(StatusCode::OK_200, res->status);
  20038. EXPECT_EQ("hello", res->body);
  20039. }
  20040. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20041. TEST_F(OpenStreamTest, Gzip) {
  20042. Client cli("127.0.0.1", port_);
  20043. auto handle = cli.open_stream("GET", "/compressible", {},
  20044. {{"Accept-Encoding", "gzip"}});
  20045. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20046. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20047. }
  20048. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20049. Client cli("127.0.0.1", port_);
  20050. auto handle =
  20051. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20052. {{"Accept-Encoding", "gzip"}});
  20053. ASSERT_TRUE(handle.is_valid());
  20054. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20055. EXPECT_EQ("123456789", read_all(handle));
  20056. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20057. }
  20058. #endif
  20059. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20060. TEST_F(OpenStreamTest, Brotli) {
  20061. Client cli("127.0.0.1", port_);
  20062. auto handle =
  20063. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20064. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20065. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20066. }
  20067. #endif
  20068. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20069. TEST_F(OpenStreamTest, Zstd) {
  20070. Client cli("127.0.0.1", port_);
  20071. auto handle = cli.open_stream("GET", "/compressible", {},
  20072. {{"Accept-Encoding", "zstd"}});
  20073. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20074. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20075. }
  20076. #endif
  20077. #ifdef CPPHTTPLIB_SSL_ENABLED
  20078. class SSLOpenStreamTest : public ::testing::Test {
  20079. protected:
  20080. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20081. void SetUp() override {
  20082. svr_.Get("/hello", [](const Request &, Response &res) {
  20083. res.set_content("Hello SSL World!", "text/plain");
  20084. });
  20085. svr_.Get("/chunked", [](const Request &, Response &res) {
  20086. res.set_chunked_content_provider("text/plain",
  20087. [](size_t offset, DataSink &sink) {
  20088. if (offset < 15) {
  20089. sink.write("chunk", 5);
  20090. return true;
  20091. }
  20092. sink.done();
  20093. return true;
  20094. });
  20095. });
  20096. svr_.Post("/echo", [](const Request &req, Response &res) {
  20097. res.set_content(req.body, req.get_header_value("Content-Type"));
  20098. });
  20099. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20100. std::string body = req.body;
  20101. res.set_chunked_content_provider(
  20102. "text/plain", [body](size_t offset, DataSink &sink) {
  20103. if (offset < body.size()) {
  20104. sink.write(body.data() + offset, body.size() - offset);
  20105. }
  20106. sink.done();
  20107. return true;
  20108. });
  20109. });
  20110. port_ = svr_.bind_to_any_port("127.0.0.1");
  20111. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20112. svr_.wait_until_ready();
  20113. }
  20114. void TearDown() override {
  20115. svr_.stop();
  20116. if (thread_.joinable()) thread_.join();
  20117. }
  20118. SSLServer svr_;
  20119. std::thread thread_;
  20120. int port_ = 0;
  20121. };
  20122. TEST_F(SSLOpenStreamTest, Basic) {
  20123. SSLClient cli("127.0.0.1", port_);
  20124. cli.enable_server_certificate_verification(false);
  20125. auto handle = cli.open_stream("GET", "/hello");
  20126. ASSERT_TRUE(handle.is_valid());
  20127. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20128. }
  20129. TEST_F(SSLOpenStreamTest, Chunked) {
  20130. SSLClient cli("127.0.0.1", port_);
  20131. cli.enable_server_certificate_verification(false);
  20132. auto handle = cli.open_stream("GET", "/chunked");
  20133. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20134. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20135. "Transfer-Encoding") == "chunked");
  20136. auto body = read_all(handle);
  20137. EXPECT_EQ("chunkchunkchunk", body);
  20138. }
  20139. TEST_F(SSLOpenStreamTest, Post) {
  20140. SSLClient cli("127.0.0.1", port_);
  20141. cli.enable_server_certificate_verification(false);
  20142. auto handle =
  20143. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20144. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20145. EXPECT_EQ(200, handle.response->status);
  20146. auto body = read_all(handle);
  20147. EXPECT_EQ("Hello SSL POST", body);
  20148. }
  20149. TEST_F(SSLOpenStreamTest, PostChunked) {
  20150. SSLClient cli("127.0.0.1", port_);
  20151. cli.enable_server_certificate_verification(false);
  20152. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20153. "Chunked SSL Data", "text/plain");
  20154. ASSERT_TRUE(handle.is_valid());
  20155. EXPECT_EQ(200, handle.response->status);
  20156. auto body = read_all(handle);
  20157. EXPECT_EQ("Chunked SSL Data", body);
  20158. }
  20159. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20160. // Content-Length is terminated by the server closing the connection. When the
  20161. // SSL peer sends a close_notify after the body, the client must treat it as a
  20162. // clean EOF and return a successful response rather than an error.
  20163. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20164. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20165. ASSERT_TRUE(svr.is_valid());
  20166. svr.set_keep_alive_max_count(1);
  20167. const std::string expected_body = "Hello from connection-close response!";
  20168. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20169. res.set_content_provider("text/plain",
  20170. [&](size_t offset, DataSink &sink) -> bool {
  20171. if (offset < expected_body.size()) {
  20172. sink.write(expected_body.data() + offset,
  20173. expected_body.size() - offset);
  20174. }
  20175. sink.done();
  20176. return true;
  20177. });
  20178. });
  20179. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20180. auto se = detail::scope_exit([&] {
  20181. svr.stop();
  20182. listen_thread.join();
  20183. ASSERT_FALSE(svr.is_running());
  20184. });
  20185. svr.wait_until_ready();
  20186. SSLClient cli(HOST, PORT);
  20187. cli.enable_server_certificate_verification(false);
  20188. auto res = cli.Get("/no-content-length");
  20189. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20190. EXPECT_EQ(StatusCode::OK_200, res->status);
  20191. EXPECT_EQ(expected_body, res->body);
  20192. }
  20193. #endif // CPPHTTPLIB_SSL_ENABLED
  20194. //==============================================================================
  20195. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20196. // results for various scenarios.
  20197. //==============================================================================
  20198. TEST(ParityTest, GetVsOpenStream) {
  20199. Server svr;
  20200. const std::string path = "/parity";
  20201. const std::string content = "Parity test content: hello world";
  20202. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20203. res.set_content(content, "text/plain");
  20204. });
  20205. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20206. auto se = detail::scope_exit([&] {
  20207. svr.stop();
  20208. t.join();
  20209. ASSERT_FALSE(svr.is_running());
  20210. });
  20211. svr.wait_until_ready();
  20212. Client cli(HOST, PORT);
  20213. // Non-stream path
  20214. auto r1 = cli.Get(path);
  20215. ASSERT_TRUE(r1);
  20216. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20217. // Stream path
  20218. auto h = cli.open_stream("GET", path);
  20219. ASSERT_TRUE(h.is_valid());
  20220. EXPECT_EQ(r1->body, read_all(h));
  20221. }
  20222. // Helper to compress data with provided compressor type T
  20223. template <typename Compressor>
  20224. static std::string compress_payload_for_parity(const std::string &in) {
  20225. std::string out;
  20226. Compressor compressor;
  20227. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20228. [&](const char *data, size_t n) {
  20229. out.append(data, n);
  20230. return true;
  20231. });
  20232. EXPECT_TRUE(ok);
  20233. return out;
  20234. }
  20235. // Helper function for compression parity tests
  20236. template <typename Compressor>
  20237. static void test_compression_parity(const std::string &original,
  20238. const std::string &path,
  20239. const std::string &encoding) {
  20240. const std::string compressed =
  20241. compress_payload_for_parity<Compressor>(original);
  20242. Server svr;
  20243. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20244. res.set_content(compressed, "application/octet-stream");
  20245. res.set_header("Content-Encoding", encoding);
  20246. });
  20247. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20248. auto se = detail::scope_exit([&] {
  20249. svr.stop();
  20250. t.join();
  20251. ASSERT_FALSE(svr.is_running());
  20252. });
  20253. svr.wait_until_ready();
  20254. Client cli(HOST, PORT);
  20255. // Non-streaming
  20256. {
  20257. auto res = cli.Get(path);
  20258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20259. EXPECT_EQ(StatusCode::OK_200, res->status);
  20260. EXPECT_EQ(original, res->body);
  20261. }
  20262. // Streaming
  20263. {
  20264. auto h = cli.open_stream("GET", path);
  20265. ASSERT_TRUE(h.is_valid());
  20266. EXPECT_EQ(original, read_all(h));
  20267. }
  20268. }
  20269. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20270. TEST(ParityTest, Gzip) {
  20271. test_compression_parity<detail::gzip_compressor>(
  20272. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20273. }
  20274. #endif
  20275. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20276. TEST(ParityTest, Brotli) {
  20277. test_compression_parity<detail::brotli_compressor>(
  20278. "Hello, brotli parity test payload", "/parity-br", "br");
  20279. }
  20280. #endif
  20281. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20282. TEST(ParityTest, Zstd) {
  20283. test_compression_parity<detail::zstd_compressor>(
  20284. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20285. }
  20286. #endif
  20287. //==============================================================================
  20288. // New Stream API Tests
  20289. //==============================================================================
  20290. inline std::string read_body(httplib::stream::Result &result) {
  20291. std::string body;
  20292. while (result.next()) {
  20293. body.append(result.data(), result.size());
  20294. }
  20295. return body;
  20296. }
  20297. TEST(ClientConnectionTest, Basic) {
  20298. httplib::ClientConnection conn;
  20299. EXPECT_FALSE(conn.is_open());
  20300. conn.sock = 1;
  20301. EXPECT_TRUE(conn.is_open());
  20302. httplib::ClientConnection conn2(std::move(conn));
  20303. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20304. conn2.sock = INVALID_SOCKET;
  20305. }
  20306. // Unified test server for all stream::* tests
  20307. class StreamApiTest : public ::testing::Test {
  20308. protected:
  20309. void SetUp() override {
  20310. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20311. res.set_content("Hello World!", "text/plain");
  20312. });
  20313. svr_.Get("/echo-params",
  20314. [](const httplib::Request &req, httplib::Response &res) {
  20315. std::string r;
  20316. for (const auto &p : req.params) {
  20317. if (!r.empty()) r += "&";
  20318. r += p.first + "=" + p.second;
  20319. }
  20320. res.set_content(r, "text/plain");
  20321. });
  20322. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20323. res.set_content(req.body, req.get_header_value("Content-Type"));
  20324. });
  20325. svr_.Post("/echo-headers",
  20326. [](const httplib::Request &req, httplib::Response &res) {
  20327. std::string r;
  20328. for (const auto &h : req.headers)
  20329. r += h.first + ": " + h.second + "\n";
  20330. res.set_content(r, "text/plain");
  20331. });
  20332. svr_.Post("/echo-params",
  20333. [](const httplib::Request &req, httplib::Response &res) {
  20334. std::string r = "params:";
  20335. for (const auto &p : req.params)
  20336. r += p.first + "=" + p.second + ";";
  20337. res.set_content(r + " body:" + req.body, "text/plain");
  20338. });
  20339. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20340. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20341. });
  20342. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20343. res.set_content("PUT:" + req.body, "text/plain");
  20344. });
  20345. svr_.Patch("/echo",
  20346. [](const httplib::Request &req, httplib::Response &res) {
  20347. res.set_content("PATCH:" + req.body, "text/plain");
  20348. });
  20349. svr_.Delete(
  20350. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20351. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20352. "text/plain");
  20353. });
  20354. svr_.Get("/head-test",
  20355. [](const httplib::Request &, httplib::Response &res) {
  20356. res.set_content("body for HEAD", "text/plain");
  20357. });
  20358. svr_.Options("/options",
  20359. [](const httplib::Request &, httplib::Response &res) {
  20360. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20361. });
  20362. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20363. svr_.wait_until_ready();
  20364. }
  20365. void TearDown() override {
  20366. svr_.stop();
  20367. if (thread_.joinable()) thread_.join();
  20368. }
  20369. httplib::Server svr_;
  20370. std::thread thread_;
  20371. };
  20372. // stream::Get tests
  20373. TEST_F(StreamApiTest, GetBasic) {
  20374. httplib::Client cli(HOST, PORT);
  20375. auto result = httplib::stream::Get(cli, "/hello");
  20376. ASSERT_TRUE(result.is_valid());
  20377. EXPECT_EQ(200, result.status());
  20378. EXPECT_EQ("Hello World!", read_body(result));
  20379. }
  20380. TEST_F(StreamApiTest, GetWithParams) {
  20381. httplib::Client cli(HOST, PORT);
  20382. httplib::Params params{{"foo", "bar"}};
  20383. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20384. ASSERT_TRUE(result.is_valid());
  20385. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20386. }
  20387. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20388. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20389. httplib::Client cli(HOST, PORT);
  20390. cli.set_payload_max_length(0);
  20391. auto result = httplib::stream::Get(cli, "/hello");
  20392. ASSERT_TRUE(result.is_valid());
  20393. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20394. EXPECT_EQ("Hello World!", read_body(result));
  20395. }
  20396. #endif
  20397. TEST_F(StreamApiTest, GetConnectionError) {
  20398. httplib::Client cli(HOST, 9999);
  20399. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20400. }
  20401. TEST_F(StreamApiTest, Get404) {
  20402. httplib::Client cli(HOST, PORT);
  20403. auto result = httplib::stream::Get(cli, "/nonexistent");
  20404. EXPECT_TRUE(result.is_valid());
  20405. EXPECT_EQ(404, result.status());
  20406. }
  20407. // stream::Post tests
  20408. TEST_F(StreamApiTest, PostBasic) {
  20409. httplib::Client cli(HOST, PORT);
  20410. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20411. "application/json");
  20412. ASSERT_TRUE(result.is_valid());
  20413. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20414. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20415. }
  20416. TEST_F(StreamApiTest, PostWithHeaders) {
  20417. httplib::Client cli(HOST, PORT);
  20418. httplib::Headers headers{{"X-Custom", "value"}};
  20419. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20420. "text/plain");
  20421. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20422. }
  20423. TEST_F(StreamApiTest, PostWithParams) {
  20424. httplib::Client cli(HOST, PORT);
  20425. httplib::Params params{{"k", "v"}};
  20426. auto result =
  20427. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20428. auto body = read_body(result);
  20429. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20430. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20431. }
  20432. TEST_F(StreamApiTest, PostLarge) {
  20433. httplib::Client cli(HOST, PORT);
  20434. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20435. size_t total = 0;
  20436. while (result.next()) {
  20437. total += result.size();
  20438. }
  20439. EXPECT_EQ(100u * 1024u, total);
  20440. }
  20441. // stream::Put/Patch tests
  20442. TEST_F(StreamApiTest, PutAndPatch) {
  20443. httplib::Client cli(HOST, PORT);
  20444. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20445. EXPECT_EQ("PUT:test", read_body(put));
  20446. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20447. EXPECT_EQ("PATCH:test", read_body(patch));
  20448. }
  20449. // stream::Delete tests
  20450. TEST_F(StreamApiTest, Delete) {
  20451. httplib::Client cli(HOST, PORT);
  20452. auto del1 = httplib::stream::Delete(cli, "/resource");
  20453. EXPECT_EQ("Deleted", read_body(del1));
  20454. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20455. EXPECT_EQ("Deleted:data", read_body(del2));
  20456. }
  20457. // stream::Head/Options tests
  20458. TEST_F(StreamApiTest, HeadAndOptions) {
  20459. httplib::Client cli(HOST, PORT);
  20460. auto head = httplib::stream::Head(cli, "/head-test");
  20461. EXPECT_TRUE(head.is_valid());
  20462. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20463. auto opts = httplib::stream::Options(cli, "/options");
  20464. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20465. }
  20466. // SSL stream::* tests
  20467. #ifdef CPPHTTPLIB_SSL_ENABLED
  20468. class SSLStreamApiTest : public ::testing::Test {
  20469. protected:
  20470. void SetUp() override {
  20471. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20472. res.set_content("Hello SSL!", "text/plain");
  20473. });
  20474. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20475. res.set_content(req.body, "text/plain");
  20476. });
  20477. port_ = svr_.bind_to_any_port("127.0.0.1");
  20478. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20479. svr_.wait_until_ready();
  20480. }
  20481. void TearDown() override {
  20482. svr_.stop();
  20483. if (thread_.joinable()) thread_.join();
  20484. }
  20485. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20486. std::thread thread_;
  20487. int port_ = 0;
  20488. };
  20489. TEST_F(SSLStreamApiTest, GetAndPost) {
  20490. httplib::SSLClient cli("127.0.0.1", port_);
  20491. cli.enable_server_certificate_verification(false);
  20492. auto get = httplib::stream::Get(cli, "/hello");
  20493. EXPECT_EQ("Hello SSL!", read_body(get));
  20494. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20495. EXPECT_EQ("test", read_body(post));
  20496. }
  20497. #endif
  20498. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20499. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20500. // BodyReader
  20501. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20502. // Test that read timeout during streaming is detected
  20503. // Use a large content-length response where server delays mid-stream
  20504. Server svr;
  20505. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20506. // Send a large response with delay in the middle
  20507. res.set_content_provider(
  20508. 1000, // content_length
  20509. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20510. if (offset < 100) {
  20511. // Send first 100 bytes immediately
  20512. std::string data(100, 'A');
  20513. sink.write(data.c_str(), data.size());
  20514. return true;
  20515. }
  20516. // Then delay longer than client timeout
  20517. std::this_thread::sleep_for(std::chrono::seconds(3));
  20518. std::string data(900, 'B');
  20519. sink.write(data.c_str(), data.size());
  20520. return true;
  20521. });
  20522. });
  20523. auto port = 8091;
  20524. std::thread t([&]() { svr.listen("localhost", port); });
  20525. svr.wait_until_ready();
  20526. Client cli("localhost", port);
  20527. cli.set_read_timeout(1, 0); // 1 second timeout
  20528. auto handle = cli.open_stream("GET", "/slow-stream");
  20529. ASSERT_TRUE(handle.is_valid());
  20530. char buf[256];
  20531. ssize_t total = 0;
  20532. ssize_t n;
  20533. bool got_error = false;
  20534. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20535. total += n;
  20536. }
  20537. if (n < 0) {
  20538. got_error = true;
  20539. // Should be timeout or read error
  20540. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20541. handle.get_read_error() == Error::Read)
  20542. << "Actual error: " << to_string(handle.get_read_error());
  20543. }
  20544. // Either we got an error, or we got less data than expected
  20545. EXPECT_TRUE(got_error || total < 1000)
  20546. << "Expected timeout but got all " << total << " bytes";
  20547. svr.stop();
  20548. t.join();
  20549. }
  20550. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20551. // Test connection closed detection via BodyReader
  20552. Server svr;
  20553. std::atomic<bool> close_now{false};
  20554. svr.Get("/will-close", [&](const Request &, Response &res) {
  20555. res.set_content_provider(
  20556. 10000, // Large content_length that we won't fully send
  20557. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20558. if (offset < 100) {
  20559. std::string data(100, 'X');
  20560. sink.write(data.c_str(), data.size());
  20561. return true;
  20562. }
  20563. // Wait for signal then abort
  20564. while (!close_now) {
  20565. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20566. }
  20567. return false; // Abort - server will close connection
  20568. });
  20569. });
  20570. auto port = 8092;
  20571. std::thread t([&]() { svr.listen("localhost", port); });
  20572. svr.wait_until_ready();
  20573. Client cli("localhost", port);
  20574. auto handle = cli.open_stream("GET", "/will-close");
  20575. ASSERT_TRUE(handle.is_valid());
  20576. char buf[256];
  20577. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20578. EXPECT_GT(n, 0) << "First read should succeed";
  20579. // Signal server to close
  20580. close_now = true;
  20581. // Keep reading until error or EOF
  20582. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20583. // Keep reading
  20584. }
  20585. // Should get an error since content_length wasn't satisfied
  20586. if (n < 0) {
  20587. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20588. handle.get_read_error() == Error::Read)
  20589. << "Actual error: " << to_string(handle.get_read_error());
  20590. }
  20591. svr.stop();
  20592. t.join();
  20593. }
  20594. #ifdef CPPHTTPLIB_SSL_ENABLED
  20595. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20596. // Test that read timeout during SSL streaming is detected
  20597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20598. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20599. res.set_content_provider(
  20600. 1000, "text/plain",
  20601. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20602. if (offset < 100) {
  20603. std::string data(100, 'A');
  20604. sink.write(data.c_str(), data.size());
  20605. return true;
  20606. }
  20607. std::this_thread::sleep_for(std::chrono::seconds(3));
  20608. std::string data(900, 'B');
  20609. sink.write(data.c_str(), data.size());
  20610. return true;
  20611. });
  20612. });
  20613. auto port = 8093;
  20614. std::thread t([&]() { svr.listen("localhost", port); });
  20615. svr.wait_until_ready();
  20616. SSLClient cli("localhost", port);
  20617. cli.enable_server_certificate_verification(false);
  20618. cli.set_read_timeout(1, 0); // 1 second timeout
  20619. auto handle = cli.open_stream("GET", "/slow-stream");
  20620. ASSERT_TRUE(handle.is_valid());
  20621. char buf[256];
  20622. ssize_t total = 0;
  20623. ssize_t n;
  20624. bool got_error = false;
  20625. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20626. total += n;
  20627. }
  20628. if (n < 0) {
  20629. got_error = true;
  20630. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20631. handle.get_read_error() == Error::Read)
  20632. << "Actual error: " << to_string(handle.get_read_error());
  20633. }
  20634. EXPECT_TRUE(got_error || total < 1000)
  20635. << "Expected timeout but got all " << total << " bytes";
  20636. svr.stop();
  20637. t.join();
  20638. }
  20639. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20640. // Test SSL connection closed detection
  20641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20642. std::atomic<bool> close_now{false};
  20643. svr.Get("/will-close", [&](const Request &, Response &res) {
  20644. res.set_content_provider(
  20645. 10000, "text/plain",
  20646. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20647. if (offset < 100) {
  20648. std::string data(100, 'X');
  20649. sink.write(data.c_str(), data.size());
  20650. return true;
  20651. }
  20652. while (!close_now) {
  20653. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20654. }
  20655. return false;
  20656. });
  20657. });
  20658. auto port = 8094;
  20659. std::thread t([&]() { svr.listen("localhost", port); });
  20660. svr.wait_until_ready();
  20661. SSLClient cli("localhost", port);
  20662. cli.enable_server_certificate_verification(false);
  20663. auto handle = cli.open_stream("GET", "/will-close");
  20664. ASSERT_TRUE(handle.is_valid());
  20665. char buf[256];
  20666. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20667. EXPECT_GT(n, 0);
  20668. // Signal server to close
  20669. close_now = true;
  20670. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20671. // Keep reading
  20672. }
  20673. if (n < 0) {
  20674. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20675. handle.get_read_error() == Error::Read)
  20676. << "Actual error: " << to_string(handle.get_read_error());
  20677. }
  20678. svr.stop();
  20679. t.join();
  20680. }
  20681. #endif
  20682. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20683. using namespace httplib;
  20684. // Create a test file
  20685. const char *fname = "etag_testfile.txt";
  20686. const char *content = "etag-content";
  20687. {
  20688. std::ofstream ofs(fname);
  20689. ofs << content;
  20690. ASSERT_TRUE(ofs.good());
  20691. }
  20692. Server svr;
  20693. svr.set_mount_point("/static", ".");
  20694. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20695. svr.wait_until_ready();
  20696. Client cli(HOST, PORT);
  20697. // First request: should get 200 with ETag header
  20698. auto res1 = cli.Get("/static/etag_testfile.txt");
  20699. ASSERT_TRUE(res1);
  20700. ASSERT_EQ(200, res1->status);
  20701. ASSERT_TRUE(res1->has_header("ETag"));
  20702. std::string etag = res1->get_header_value("ETag");
  20703. EXPECT_FALSE(etag.empty());
  20704. // Verify ETag format: W/"hex-hex"
  20705. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20706. EXPECT_EQ('W', etag[0]);
  20707. EXPECT_EQ('/', etag[1]);
  20708. EXPECT_EQ('"', etag[2]);
  20709. EXPECT_EQ('"', etag.back());
  20710. // Exact match: expect 304 Not Modified
  20711. Headers h2 = {{"If-None-Match", etag}};
  20712. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20713. ASSERT_TRUE(res2);
  20714. EXPECT_EQ(304, res2->status);
  20715. // Wildcard match: expect 304 Not Modified
  20716. Headers h3 = {{"If-None-Match", "*"}};
  20717. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20718. ASSERT_TRUE(res3);
  20719. EXPECT_EQ(304, res3->status);
  20720. // Non-matching ETag: expect 200
  20721. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20722. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20723. ASSERT_TRUE(res4);
  20724. EXPECT_EQ(200, res4->status);
  20725. // Multiple ETags with one matching: expect 304
  20726. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20727. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20728. ASSERT_TRUE(res5);
  20729. EXPECT_EQ(304, res5->status);
  20730. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20731. // that equivalent to the single comma-separated list above, so the match on
  20732. // the second line must still be found.
  20733. Headers h6;
  20734. h6.emplace("If-None-Match", "W/\"other\"");
  20735. h6.emplace("If-None-Match", etag);
  20736. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20737. ASSERT_TRUE(res6);
  20738. EXPECT_EQ(304, res6->status);
  20739. svr.stop();
  20740. t.join();
  20741. std::remove(fname);
  20742. }
  20743. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20744. using namespace httplib;
  20745. Server svr;
  20746. svr.set_mount_point("/static", ".");
  20747. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20748. svr.wait_until_ready();
  20749. Client cli(HOST, PORT);
  20750. // Send If-None-Match: * to a non-existent file
  20751. Headers h = {{"If-None-Match", "*"}};
  20752. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20754. EXPECT_EQ(404, res->status);
  20755. svr.stop();
  20756. t.join();
  20757. }
  20758. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20759. using namespace httplib;
  20760. // Create a test file
  20761. const char *fname = "etag_boundary_testfile.txt";
  20762. const char *content = "boundary-test";
  20763. {
  20764. std::ofstream ofs(fname);
  20765. ofs << content;
  20766. ASSERT_TRUE(ofs.good());
  20767. }
  20768. Server svr;
  20769. svr.set_mount_point("/static", ".");
  20770. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20771. svr.wait_until_ready();
  20772. Client cli(HOST, PORT);
  20773. // Get the actual ETag
  20774. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20775. ASSERT_TRUE(res1);
  20776. ASSERT_EQ(200, res1->status);
  20777. ASSERT_TRUE(res1->has_header("ETag"));
  20778. std::string etag = res1->get_header_value("ETag");
  20779. // Test 1: Very long ETag value (longer than actual ETag)
  20780. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20781. Headers h1 = {{"If-None-Match", "W/"
  20782. "\"very-long-etag-value-that-is-much-longer-"
  20783. "than-the-actual-etag-value\""}};
  20784. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20785. ASSERT_TRUE(res2);
  20786. EXPECT_EQ(200, res2->status); // Should not match
  20787. // Test 2: Long string followed by wildcard
  20788. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20789. // string)
  20790. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20791. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20792. ASSERT_TRUE(res3);
  20793. EXPECT_EQ(304, res3->status); // Should match on "*"
  20794. // Test 3: Wildcard followed by long string
  20795. // Should match on "*" immediately and return 304
  20796. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20797. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20798. ASSERT_TRUE(res4);
  20799. EXPECT_EQ(304, res4->status); // Should match on "*"
  20800. // Test 4: Multiple long non-matching values
  20801. // Should NOT match and return 200 (test that all comparisons are safe)
  20802. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20803. "W/\"second-long-non-matching-value\", "
  20804. "W/\"third-long-non-matching-value\""}};
  20805. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20806. ASSERT_TRUE(res5);
  20807. EXPECT_EQ(200, res5->status); // Should not match
  20808. // Test 5: Single character that is not "*" (edge case)
  20809. Headers h5 = {{"If-None-Match", "X"}};
  20810. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20811. ASSERT_TRUE(res6);
  20812. EXPECT_EQ(200, res6->status); // Should not match
  20813. svr.stop();
  20814. t.join();
  20815. std::remove(fname);
  20816. }
  20817. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20818. using namespace httplib;
  20819. // Create a test file
  20820. const char *fname = "ims_testfile.txt";
  20821. const char *content = "if-modified-since-test";
  20822. {
  20823. std::ofstream ofs(fname);
  20824. ofs << content;
  20825. ASSERT_TRUE(ofs.good());
  20826. }
  20827. Server svr;
  20828. svr.set_mount_point("/static", ".");
  20829. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20830. svr.wait_until_ready();
  20831. Client cli(HOST, PORT);
  20832. // First request: should get 200 with Last-Modified header
  20833. auto res1 = cli.Get("/static/ims_testfile.txt");
  20834. ASSERT_TRUE(res1);
  20835. ASSERT_EQ(200, res1->status);
  20836. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20837. std::string last_modified = res1->get_header_value("Last-Modified");
  20838. EXPECT_FALSE(last_modified.empty());
  20839. // If-Modified-Since with same time: expect 304
  20840. Headers h2 = {{"If-Modified-Since", last_modified}};
  20841. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20842. ASSERT_TRUE(res2);
  20843. EXPECT_EQ(304, res2->status);
  20844. // If-Modified-Since with future time: expect 304
  20845. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20846. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20847. ASSERT_TRUE(res3);
  20848. EXPECT_EQ(304, res3->status);
  20849. // If-Modified-Since with past time: expect 200
  20850. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20851. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20852. ASSERT_TRUE(res4);
  20853. EXPECT_EQ(200, res4->status);
  20854. // If-None-Match takes precedence over If-Modified-Since
  20855. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20856. ASSERT_TRUE(res1->has_header("ETag"));
  20857. std::string etag = res1->get_header_value("ETag");
  20858. Headers h5 = {{"If-None-Match", etag},
  20859. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20860. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20861. ASSERT_TRUE(res5);
  20862. EXPECT_EQ(304, res5->status);
  20863. svr.stop();
  20864. t.join();
  20865. std::remove(fname);
  20866. }
  20867. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20868. using namespace httplib;
  20869. Server svr;
  20870. // Endpoint that returns compressible content
  20871. svr.Get("/compressible", [](const Request &, Response &res) {
  20872. // Return a large enough body to trigger compression
  20873. std::string body(1000, 'a');
  20874. res.set_content(body, "text/plain");
  20875. });
  20876. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20877. svr.wait_until_ready();
  20878. Client cli(HOST, PORT);
  20879. // Request with gzip support: should get Vary header when compressed
  20880. cli.set_compress(true);
  20881. auto res1 = cli.Get("/compressible");
  20882. ASSERT_TRUE(res1);
  20883. EXPECT_EQ(200, res1->status);
  20884. // If Content-Encoding is set, Vary should also be set
  20885. if (res1->has_header("Content-Encoding")) {
  20886. EXPECT_TRUE(res1->has_header("Vary"));
  20887. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20888. }
  20889. // Request without Accept-Encoding header: should not have compression
  20890. Headers h_no_compress;
  20891. auto res2 = cli.Get("/compressible", h_no_compress);
  20892. ASSERT_TRUE(res2);
  20893. EXPECT_EQ(200, res2->status);
  20894. // Verify Vary header is present when compression is applied
  20895. // (the exact behavior depends on server configuration)
  20896. svr.stop();
  20897. t.join();
  20898. }
  20899. TEST(ETagTest, IfRangeWithETag) {
  20900. using namespace httplib;
  20901. // Create a test file with known content
  20902. const char *fname = "if_range_testfile.txt";
  20903. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20904. {
  20905. std::ofstream ofs(fname);
  20906. ofs << content;
  20907. ASSERT_TRUE(ofs.good());
  20908. }
  20909. Server svr;
  20910. svr.set_mount_point("/static", ".");
  20911. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20912. svr.wait_until_ready();
  20913. Client cli(HOST, PORT);
  20914. // First request: get ETag
  20915. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20916. ASSERT_TRUE(res1);
  20917. ASSERT_EQ(200, res1->status);
  20918. ASSERT_TRUE(res1->has_header("ETag"));
  20919. std::string etag = res1->get_header_value("ETag");
  20920. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20921. // Since our server generates weak ETags (W/"..."), If-Range with our
  20922. // ETag should NOT result in partial content - it should return full content.
  20923. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20924. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20925. ASSERT_TRUE(res2);
  20926. // Weak ETag in If-Range -> full content (200), not partial (206)
  20927. EXPECT_EQ(200, res2->status);
  20928. EXPECT_EQ(content, res2->body);
  20929. EXPECT_FALSE(res2->has_header("Content-Range"));
  20930. // Range request with non-matching If-Range (ETag): should get 200 (full
  20931. // content)
  20932. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20933. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20934. ASSERT_TRUE(res3);
  20935. EXPECT_EQ(200, res3->status);
  20936. EXPECT_EQ(content, res3->body);
  20937. EXPECT_FALSE(res3->has_header("Content-Range"));
  20938. // Range request with strong ETag (hypothetical - our server doesn't generate
  20939. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20940. // should return full content)
  20941. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20942. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20943. ASSERT_TRUE(res4);
  20944. EXPECT_EQ(200, res4->status);
  20945. EXPECT_EQ(content, res4->body);
  20946. EXPECT_FALSE(res4->has_header("Content-Range"));
  20947. svr.stop();
  20948. t.join();
  20949. std::remove(fname);
  20950. }
  20951. TEST(ETagTest, IfRangeWithDate) {
  20952. using namespace httplib;
  20953. // Create a test file
  20954. const char *fname = "if_range_date_testfile.txt";
  20955. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20956. {
  20957. std::ofstream ofs(fname);
  20958. ofs << content;
  20959. ASSERT_TRUE(ofs.good());
  20960. }
  20961. Server svr;
  20962. svr.set_mount_point("/static", ".");
  20963. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20964. svr.wait_until_ready();
  20965. Client cli(HOST, PORT);
  20966. // First request: get Last-Modified
  20967. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20968. ASSERT_TRUE(res1);
  20969. ASSERT_EQ(200, res1->status);
  20970. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20971. std::string last_modified = res1->get_header_value("Last-Modified");
  20972. // Range request with matching If-Range (date): should get 206
  20973. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20974. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20975. ASSERT_TRUE(res2);
  20976. EXPECT_EQ(206, res2->status);
  20977. EXPECT_EQ("FGHIJ", res2->body);
  20978. // Range request with old If-Range date: should get 200 (full content)
  20979. Headers h3 = {{"Range", "bytes=5-9"},
  20980. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20981. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20982. ASSERT_TRUE(res3);
  20983. EXPECT_EQ(200, res3->status);
  20984. EXPECT_EQ(content, res3->body);
  20985. // Range request with future If-Range date: should get 206
  20986. Headers h4 = {{"Range", "bytes=0-4"},
  20987. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20988. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20989. ASSERT_TRUE(res4);
  20990. EXPECT_EQ(206, res4->status);
  20991. EXPECT_EQ("ABCDE", res4->body);
  20992. svr.stop();
  20993. t.join();
  20994. std::remove(fname);
  20995. }
  20996. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20997. using namespace httplib;
  20998. const char *fname = "etag_malformed.txt";
  20999. const char *content = "malformed-etag";
  21000. {
  21001. std::ofstream ofs(fname);
  21002. ofs << content;
  21003. ASSERT_TRUE(ofs.good());
  21004. }
  21005. Server svr;
  21006. svr.set_mount_point("/static", ".");
  21007. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21008. svr.wait_until_ready();
  21009. Client cli(HOST, PORT);
  21010. // baseline: should get 200 and an ETag
  21011. auto res1 = cli.Get("/static/etag_malformed.txt");
  21012. ASSERT_TRUE(res1);
  21013. ASSERT_EQ(200, res1->status);
  21014. ASSERT_TRUE(res1->has_header("ETag"));
  21015. // Malformed ETag value (missing quotes) should be treated as non-matching
  21016. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21017. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21018. ASSERT_TRUE(res_bad);
  21019. EXPECT_EQ(200, res_bad->status);
  21020. // Whitespace-only header value should be considered invalid / non-matching
  21021. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21022. "Host: localhost\r\n"
  21023. "If-None-Match: \r\n"
  21024. "Connection: close\r\n"
  21025. "\r\n";
  21026. std::string out;
  21027. ASSERT_TRUE(send_request(5, raw_req, &out));
  21028. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21029. svr.stop();
  21030. t.join();
  21031. std::remove(fname);
  21032. }
  21033. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21034. using namespace httplib;
  21035. const char *fname = "ims_invalid_format.txt";
  21036. const char *content = "ims-bad-format";
  21037. {
  21038. std::ofstream ofs(fname);
  21039. ofs << content;
  21040. ASSERT_TRUE(ofs.good());
  21041. }
  21042. Server svr;
  21043. svr.set_mount_point("/static", ".");
  21044. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21045. svr.wait_until_ready();
  21046. Client cli(HOST, PORT);
  21047. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21048. ASSERT_TRUE(res1);
  21049. ASSERT_EQ(200, res1->status);
  21050. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21051. // If-Modified-Since with invalid format should not result in 304
  21052. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21053. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21054. ASSERT_TRUE(res_bad);
  21055. EXPECT_EQ(200, res_bad->status);
  21056. // If-Range with invalid date format should be treated as mismatch -> full
  21057. // content (200)
  21058. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21059. {"If-Range", "invalid-date"}};
  21060. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21061. ASSERT_TRUE(res_ifrange);
  21062. EXPECT_EQ(200, res_ifrange->status);
  21063. svr.stop();
  21064. t.join();
  21065. std::remove(fname);
  21066. }
  21067. TEST(ETagTest, IfRangeWithMalformedETag) {
  21068. using namespace httplib;
  21069. const char *fname = "ifrange_malformed.txt";
  21070. const std::string content = "0123456789";
  21071. {
  21072. std::ofstream ofs(fname);
  21073. ofs << content;
  21074. ASSERT_TRUE(ofs.good());
  21075. }
  21076. Server svr;
  21077. svr.set_mount_point("/static", ".");
  21078. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21079. svr.wait_until_ready();
  21080. Client cli(HOST, PORT);
  21081. // First request: get ETag
  21082. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21083. ASSERT_TRUE(res1);
  21084. ASSERT_EQ(200, res1->status);
  21085. ASSERT_TRUE(res1->has_header("ETag"));
  21086. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21087. // full content (200)
  21088. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21089. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21090. ASSERT_TRUE(res2);
  21091. EXPECT_EQ(200, res2->status);
  21092. EXPECT_EQ(content, res2->body);
  21093. svr.stop();
  21094. t.join();
  21095. std::remove(fname);
  21096. }
  21097. TEST(ETagTest, ExtremeLargeDateValues) {
  21098. using namespace httplib;
  21099. const char *fname = "ims_extreme_date.txt";
  21100. const char *content = "ims-extreme-date";
  21101. {
  21102. std::ofstream ofs(fname);
  21103. ofs << content;
  21104. ASSERT_TRUE(ofs.good());
  21105. }
  21106. Server svr;
  21107. svr.set_mount_point("/static", ".");
  21108. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21109. svr.wait_until_ready();
  21110. Client cli(HOST, PORT);
  21111. auto res1 = cli.Get(std::string("/static/") + fname);
  21112. ASSERT_TRUE(res1);
  21113. ASSERT_EQ(200, res1->status);
  21114. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21115. // Extremely large year that may overflow date parsing routines.
  21116. Headers h_large_date = {
  21117. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21118. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21119. ASSERT_TRUE(res_bad);
  21120. // Expect server to treat this as invalid/mismatch and return full content
  21121. EXPECT_EQ(200, res_bad->status);
  21122. // If-Range with extremely large date should be treated as mismatch -> full
  21123. // content (200)
  21124. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21125. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21126. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21127. ASSERT_TRUE(res_ifrange);
  21128. EXPECT_EQ(200, res_ifrange->status);
  21129. svr.stop();
  21130. t.join();
  21131. std::remove(fname);
  21132. }
  21133. TEST(ETagTest, NegativeFileModificationTime) {
  21134. using namespace httplib;
  21135. const char *fname = "ims_negative_mtime.txt";
  21136. const std::string content = "negative-mtime";
  21137. {
  21138. std::ofstream ofs(fname);
  21139. ofs << content;
  21140. ASSERT_TRUE(ofs.good());
  21141. }
  21142. // Try to set file mtime to a negative value. This may fail on some
  21143. // platforms/filesystems; if it fails, the test will still verify server
  21144. // behaves safely by performing a regular conditional request.
  21145. #if defined(__APPLE__) || defined(__linux__)
  21146. bool set_negative = false;
  21147. do {
  21148. struct timeval times[2];
  21149. // access time: now
  21150. times[0].tv_sec = time(nullptr);
  21151. times[0].tv_usec = 0;
  21152. // modification time: negative (e.g., -1)
  21153. times[1].tv_sec = -1;
  21154. times[1].tv_usec = 0;
  21155. if (utimes(fname, times) == 0) { set_negative = true; }
  21156. } while (0);
  21157. #else
  21158. bool set_negative = false;
  21159. #endif
  21160. Server svr;
  21161. svr.set_mount_point("/static", ".");
  21162. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21163. svr.wait_until_ready();
  21164. Client cli(HOST, PORT);
  21165. auto res1 = cli.Get(std::string("/static/") + fname);
  21166. ASSERT_TRUE(res1);
  21167. ASSERT_EQ(200, res1->status);
  21168. bool has_last_modified = res1->has_header("Last-Modified");
  21169. std::string last_modified;
  21170. if (has_last_modified) {
  21171. last_modified = res1->get_header_value("Last-Modified");
  21172. }
  21173. if (set_negative) {
  21174. // If we successfully set a negative mtime, ensure server returns a
  21175. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21176. // with an old date and ensure server handles it without crash.
  21177. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21178. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21179. ASSERT_TRUE(res2);
  21180. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21181. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21182. } else {
  21183. // Could not set negative mtime on this platform; fall back to verifying
  21184. // that normal invalid/malformed dates are treated safely (non-304).
  21185. Headers h_bad_date = {
  21186. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21187. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21188. ASSERT_TRUE(res_bad);
  21189. EXPECT_EQ(200, res_bad->status);
  21190. }
  21191. svr.stop();
  21192. t.join();
  21193. std::remove(fname);
  21194. }
  21195. //==============================================================================
  21196. // Integration Tests with Server
  21197. //==============================================================================
  21198. class SSEIntegrationTest : public ::testing::Test {
  21199. protected:
  21200. void SetUp() override {
  21201. stop_server_.store(false);
  21202. events_.clear();
  21203. server_ = httplib::detail::make_unique<Server>();
  21204. setup_server();
  21205. start_server();
  21206. }
  21207. void TearDown() override {
  21208. stop_server_.store(true);
  21209. event_cv_.notify_all();
  21210. server_->stop();
  21211. if (server_thread_.joinable()) { server_thread_.join(); }
  21212. }
  21213. void setup_server() {
  21214. // Simple SSE endpoint
  21215. server_->Get("/events", [this](const Request &req, Response &res) {
  21216. auto last_id = req.get_header_value("Last-Event-ID");
  21217. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21218. res.set_chunked_content_provider(
  21219. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21220. std::unique_lock<std::mutex> lock(event_mutex_);
  21221. if (event_cv_.wait_for(
  21222. lock, std::chrono::milliseconds(200), [this] {
  21223. return !events_.empty() || stop_server_.load();
  21224. })) {
  21225. if (stop_server_.load()) { return false; }
  21226. if (!events_.empty()) {
  21227. std::string event = events_.front();
  21228. events_.erase(events_.begin());
  21229. sink.write(event.data(), event.size());
  21230. return true;
  21231. }
  21232. }
  21233. return !stop_server_.load();
  21234. });
  21235. });
  21236. // Endpoint that returns error
  21237. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21238. res.status = 500;
  21239. res.set_content("Internal Server Error", "text/plain");
  21240. });
  21241. // Endpoint for custom event types
  21242. server_->Get("/custom-events", [](const Request &, Response &res) {
  21243. res.set_chunked_content_provider(
  21244. "text/event-stream", [](size_t offset, DataSink &sink) {
  21245. if (offset == 0) {
  21246. std::string event = "event: update\ndata: updated\n\n"
  21247. "event: delete\ndata: deleted\n\n";
  21248. sink.write(event.data(), event.size());
  21249. }
  21250. return false; // End stream after sending
  21251. });
  21252. });
  21253. }
  21254. void start_server() {
  21255. port_ = server_->bind_to_any_port(HOST);
  21256. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21257. // Wait for server to start
  21258. while (!server_->is_running()) {
  21259. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21260. }
  21261. }
  21262. int get_port() const { return port_; }
  21263. void send_event(const std::string &event) {
  21264. std::lock_guard<std::mutex> lock(event_mutex_);
  21265. events_.push_back(event);
  21266. event_cv_.notify_all();
  21267. }
  21268. std::unique_ptr<Server> server_;
  21269. std::thread server_thread_;
  21270. std::mutex event_mutex_;
  21271. std::condition_variable event_cv_;
  21272. std::vector<std::string> events_;
  21273. std::atomic<bool> stop_server_{false};
  21274. std::string last_received_event_id_;
  21275. int port_ = 0;
  21276. };
  21277. //==============================================================================
  21278. // SSE Parsing Tests
  21279. //==============================================================================
  21280. class SSEParsingTest : public SSEIntegrationTest {
  21281. protected:
  21282. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21283. // A trailing sentinel event tells when the whole stream has been parsed.
  21284. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21285. auto body = stream + "event: end\ndata: end\n\n";
  21286. server_->Get("/parse", [body](const Request &, Response &res) {
  21287. res.set_content(body, "text/event-stream");
  21288. });
  21289. return collect("/parse");
  21290. }
  21291. // Runs SSEClient against path until an "end" event arrives and returns the
  21292. // messages dispatched before it
  21293. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21294. Client client(HOST, get_port());
  21295. sse::SSEClient sse(client, path);
  21296. std::mutex mutex;
  21297. std::condition_variable cv;
  21298. std::vector<sse::SSEMessage> messages;
  21299. auto done = false;
  21300. sse.on_message([&](const sse::SSEMessage &msg) {
  21301. std::lock_guard<std::mutex> lock(mutex);
  21302. // Ignore a replay from a reconnect that races with stop()
  21303. if (!done) { messages.push_back(msg); }
  21304. });
  21305. sse.on_event("end", [&](const sse::SSEMessage &) {
  21306. std::lock_guard<std::mutex> lock(mutex);
  21307. done = true;
  21308. cv.notify_all();
  21309. });
  21310. sse.set_reconnect_interval(100);
  21311. sse.start_async();
  21312. {
  21313. std::unique_lock<std::mutex> lock(mutex);
  21314. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21315. }
  21316. sse.stop();
  21317. EXPECT_TRUE(done);
  21318. return messages;
  21319. }
  21320. };
  21321. TEST_F(SSEParsingTest, SingleLineData) {
  21322. auto msgs = parse("data: hello\n\n");
  21323. ASSERT_EQ(msgs.size(), 1u);
  21324. EXPECT_EQ(msgs[0].data, "hello");
  21325. EXPECT_EQ(msgs[0].event, "message");
  21326. }
  21327. TEST_F(SSEParsingTest, MultiLineData) {
  21328. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21329. ASSERT_EQ(msgs.size(), 1u);
  21330. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21331. }
  21332. TEST_F(SSEParsingTest, CustomEventType) {
  21333. auto msgs = parse("event: update\ndata: payload\n\n");
  21334. ASSERT_EQ(msgs.size(), 1u);
  21335. EXPECT_EQ(msgs[0].event, "update");
  21336. EXPECT_EQ(msgs[0].data, "payload");
  21337. }
  21338. TEST_F(SSEParsingTest, EventIdHandling) {
  21339. auto msgs = parse("id: 12345\ndata: test\n\n");
  21340. ASSERT_EQ(msgs.size(), 1u);
  21341. EXPECT_EQ(msgs[0].id, "12345");
  21342. }
  21343. TEST_F(SSEParsingTest, EmptyEventId) {
  21344. auto msgs = parse("id:\ndata: test\n\n");
  21345. ASSERT_EQ(msgs.size(), 1u);
  21346. EXPECT_EQ(msgs[0].id, "");
  21347. }
  21348. TEST_F(SSEParsingTest, CommentsIgnored) {
  21349. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21350. ASSERT_EQ(msgs.size(), 1u);
  21351. EXPECT_EQ(msgs[0].data, "hello");
  21352. EXPECT_EQ(msgs[0].event, "message");
  21353. }
  21354. TEST_F(SSEParsingTest, ColonInValue) {
  21355. auto msgs = parse("data: hello:world:test\n\n");
  21356. ASSERT_EQ(msgs.size(), 1u);
  21357. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21358. }
  21359. TEST_F(SSEParsingTest, FieldNameOnly) {
  21360. // A line without a colon is a field name with an empty value
  21361. auto msgs = parse("data\n\n");
  21362. ASSERT_EQ(msgs.size(), 1u);
  21363. EXPECT_EQ(msgs[0].data, "");
  21364. }
  21365. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21366. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21367. ASSERT_EQ(msgs.size(), 1u);
  21368. EXPECT_EQ(msgs[0].event, "update");
  21369. EXPECT_EQ(msgs[0].data, "hello");
  21370. }
  21371. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21372. auto msgs = parse("data\r\n\r\n");
  21373. ASSERT_EQ(msgs.size(), 1u);
  21374. EXPECT_EQ(msgs[0].data, "");
  21375. }
  21376. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21377. auto msgs = parse("event: update\rdata: hello\r\r");
  21378. ASSERT_EQ(msgs.size(), 1u);
  21379. EXPECT_EQ(msgs[0].event, "update");
  21380. EXPECT_EQ(msgs[0].data, "hello");
  21381. }
  21382. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21383. // Chunk boundaries fall inside every \r\n and right before the first one
  21384. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21385. "\n\r", "\nevent: end\ndata: end\n\n"};
  21386. server_->Get("/split", [chunks](const Request &, Response &res) {
  21387. auto i = std::make_shared<size_t>(0);
  21388. res.set_chunked_content_provider(
  21389. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21390. if (*i == chunks.size()) {
  21391. sink.done();
  21392. } else {
  21393. sink.write(chunks[*i].data(), chunks[*i].size());
  21394. (*i)++;
  21395. }
  21396. return true;
  21397. });
  21398. });
  21399. auto msgs = collect("/split");
  21400. ASSERT_EQ(msgs.size(), 1u);
  21401. EXPECT_EQ(msgs[0].event, "update");
  21402. EXPECT_EQ(msgs[0].data, "hello");
  21403. }
  21404. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21405. // Only a BOM at the start of the stream is ignored
  21406. auto msgs = parse("\xEF\xBB\xBF"
  21407. "data: first\n\n"
  21408. "\xEF\xBB\xBF"
  21409. "data: second\n\n");
  21410. ASSERT_EQ(msgs.size(), 1u);
  21411. EXPECT_EQ(msgs[0].data, "first");
  21412. }
  21413. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21414. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21415. ASSERT_EQ(msgs.size(), 1u);
  21416. EXPECT_EQ(msgs[0].data, "hello");
  21417. EXPECT_EQ(msgs[0].event, "message");
  21418. }
  21419. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21420. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21421. ASSERT_EQ(msgs.size(), 2u);
  21422. EXPECT_EQ(msgs[0].data, "hello");
  21423. EXPECT_EQ(msgs[1].data, "hello");
  21424. }
  21425. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21426. // An event without data is not dispatched, and its type must not leak
  21427. // into the next event
  21428. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21429. ASSERT_EQ(msgs.size(), 1u);
  21430. EXPECT_EQ(msgs[0].event, "message");
  21431. EXPECT_EQ(msgs[0].data, "hello");
  21432. }
  21433. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21434. // Also when the empty field replaces an earlier type
  21435. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21436. ASSERT_EQ(msgs.size(), 2u);
  21437. EXPECT_EQ(msgs[0].event, "message");
  21438. EXPECT_EQ(msgs[1].event, "message");
  21439. }
  21440. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21441. // The first connection sends only an id; the second echoes back the
  21442. // Last-Event-ID it was reconnected with
  21443. std::atomic<int> connection_count{0};
  21444. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21445. if (connection_count++ == 0) {
  21446. res.set_content("id: 42\n\n", "text/event-stream");
  21447. } else {
  21448. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21449. "\n\nevent: end\ndata: end\n\n",
  21450. "text/event-stream");
  21451. }
  21452. });
  21453. auto msgs = collect("/id-only");
  21454. ASSERT_EQ(msgs.size(), 1u);
  21455. EXPECT_EQ(msgs[0].data, "42");
  21456. }
  21457. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21458. // The first connection sets an id and then clears it with an empty one; the
  21459. // second reports whether it was reconnected with a Last-Event-ID
  21460. std::atomic<int> connection_count{0};
  21461. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21462. if (connection_count++ == 0) {
  21463. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21464. "text/event-stream");
  21465. } else {
  21466. res.set_content(
  21467. std::string("data: ") +
  21468. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21469. "\n\nevent: end\ndata: end\n\n",
  21470. "text/event-stream");
  21471. }
  21472. });
  21473. auto msgs = collect("/id-clear");
  21474. ASSERT_EQ(msgs.size(), 3u);
  21475. EXPECT_EQ(msgs[0].id, "1");
  21476. EXPECT_EQ(msgs[1].id, "");
  21477. EXPECT_EQ(msgs[2].data, "not sent");
  21478. }
  21479. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21480. // The first connection sets an id and then sends ids that cannot be carried
  21481. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21482. // with
  21483. std::atomic<int> connection_count{0};
  21484. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21485. if (connection_count++ == 0) {
  21486. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21487. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21488. "text/event-stream");
  21489. } else {
  21490. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21491. "\n\nevent: end\ndata: end\n\n",
  21492. "text/event-stream");
  21493. }
  21494. });
  21495. auto msgs = collect("/id-unsendable");
  21496. ASSERT_EQ(msgs.size(), 1u);
  21497. EXPECT_EQ(msgs[0].data, "42");
  21498. }
  21499. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21500. auto msgs = parse("event: notification\nid: evt-42\n"
  21501. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21502. ASSERT_EQ(msgs.size(), 1u);
  21503. EXPECT_EQ(msgs[0].event, "notification");
  21504. EXPECT_EQ(msgs[0].id, "evt-42");
  21505. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21506. }
  21507. TEST(SSEMessageTest, Clear) {
  21508. sse::SSEMessage msg;
  21509. msg.event = "custom";
  21510. msg.data = "some data";
  21511. msg.id = "123";
  21512. msg.clear();
  21513. EXPECT_EQ(msg.event, "message");
  21514. EXPECT_EQ(msg.data, "");
  21515. EXPECT_EQ(msg.id, "");
  21516. }
  21517. //==============================================================================
  21518. // SSE Integration Tests
  21519. //==============================================================================
  21520. // Test: Successful connection and on_open callback
  21521. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21522. // Add a simple endpoint that sends one event and closes
  21523. server_->Get("/simple-event", [](const Request &, Response &res) {
  21524. res.set_chunked_content_provider(
  21525. "text/event-stream", [](size_t offset, DataSink &sink) {
  21526. if (offset == 0) {
  21527. std::string event = "data: hello\n\n";
  21528. sink.write(event.data(), event.size());
  21529. }
  21530. return false; // Close stream after sending
  21531. });
  21532. });
  21533. Client client("localhost", get_port());
  21534. sse::SSEClient sse(client, "/simple-event");
  21535. std::atomic<bool> open_called{false};
  21536. std::atomic<bool> message_received{false};
  21537. sse.on_open([&open_called]() { open_called.store(true); });
  21538. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21539. if (msg.data == "hello") { message_received.store(true); }
  21540. });
  21541. sse.set_reconnect_interval(100);
  21542. sse.set_max_reconnect_attempts(1);
  21543. // Start async
  21544. sse.start_async();
  21545. // Wait for message to be processed
  21546. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21547. sse.stop();
  21548. EXPECT_TRUE(open_called.load());
  21549. EXPECT_TRUE(message_received.load());
  21550. }
  21551. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21552. // A data line that never ends.
  21553. server_->Get("/endless-line", [](const Request &, Response &res) {
  21554. res.set_chunked_content_provider(
  21555. "text/event-stream", [](size_t offset, DataSink &sink) {
  21556. if (offset == 0) { sink.write("data: ", 6); }
  21557. std::string chunk(64 * 1024, 'A');
  21558. return sink.write(chunk.data(), chunk.size());
  21559. });
  21560. });
  21561. Client client("localhost", get_port());
  21562. sse::SSEClient sse(client, "/endless-line");
  21563. std::atomic<bool> too_long{false};
  21564. sse.on_error([&](Error err) {
  21565. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21566. });
  21567. sse.set_max_reconnect_attempts(1);
  21568. sse.start_async();
  21569. for (int i = 0; i < 500 && !too_long; i++) {
  21570. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21571. }
  21572. sse.stop();
  21573. EXPECT_TRUE(too_long);
  21574. }
  21575. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21576. // Far more in all than the client's payload limit below.
  21577. server_->Get("/many-events", [](const Request &, Response &res) {
  21578. res.set_chunked_content_provider(
  21579. "text/event-stream", [](size_t offset, DataSink &sink) {
  21580. if (offset == 0) {
  21581. std::string events;
  21582. for (int i = 0; i < 1000; i++) {
  21583. events += "data: message\n\n";
  21584. }
  21585. sink.write(events.data(), events.size());
  21586. }
  21587. return false;
  21588. });
  21589. });
  21590. Client client("localhost", get_port());
  21591. client.set_payload_max_length(1024);
  21592. sse::SSEClient sse(client, "/many-events");
  21593. std::atomic<int> messages{0};
  21594. std::atomic<bool> too_large{false};
  21595. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21596. sse.on_error([&](Error err) {
  21597. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21598. });
  21599. sse.set_max_reconnect_attempts(1);
  21600. sse.start_async();
  21601. for (int i = 0; i < 500 && messages < 1000; i++) {
  21602. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21603. }
  21604. sse.stop();
  21605. EXPECT_GE(messages.load(), 1000);
  21606. EXPECT_FALSE(too_large);
  21607. }
  21608. // Test: on_message callback
  21609. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21610. // Endpoint that sends multiple events then closes
  21611. server_->Get("/multi-event", [](const Request &, Response &res) {
  21612. res.set_chunked_content_provider(
  21613. "text/event-stream", [](size_t offset, DataSink &sink) {
  21614. if (offset == 0) {
  21615. std::string events = "data: message1\n\ndata: message2\n\n";
  21616. sink.write(events.data(), events.size());
  21617. }
  21618. return false;
  21619. });
  21620. });
  21621. Client client("localhost", get_port());
  21622. sse::SSEClient sse(client, "/multi-event");
  21623. std::vector<std::string> received_messages;
  21624. std::mutex messages_mutex;
  21625. sse.on_message([&](const sse::SSEMessage &msg) {
  21626. std::lock_guard<std::mutex> lock(messages_mutex);
  21627. received_messages.push_back(msg.data);
  21628. });
  21629. sse.set_reconnect_interval(100);
  21630. sse.set_max_reconnect_attempts(1);
  21631. sse.start_async();
  21632. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21633. sse.stop();
  21634. std::lock_guard<std::mutex> lock(messages_mutex);
  21635. EXPECT_GE(received_messages.size(), 2u);
  21636. if (received_messages.size() >= 2) {
  21637. EXPECT_EQ(received_messages[0], "message1");
  21638. EXPECT_EQ(received_messages[1], "message2");
  21639. }
  21640. }
  21641. // Test: on_event for specific types
  21642. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21643. Client client("localhost", get_port());
  21644. sse::SSEClient sse(client, "/custom-events");
  21645. std::atomic<bool> update_received{false};
  21646. std::atomic<bool> delete_received{false};
  21647. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21648. if (msg.data == "updated") { update_received.store(true); }
  21649. });
  21650. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21651. if (msg.data == "deleted") { delete_received.store(true); }
  21652. });
  21653. sse.set_max_reconnect_attempts(1);
  21654. sse.start_async();
  21655. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21656. sse.stop();
  21657. EXPECT_TRUE(update_received.load());
  21658. EXPECT_TRUE(delete_received.load());
  21659. }
  21660. // Test: on_error callback on connection failure
  21661. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21662. // Connect to a non-existent port
  21663. Client client("localhost", 59999);
  21664. sse::SSEClient sse(client, "/events");
  21665. std::atomic<bool> error_called{false};
  21666. Error received_error = Error::Success;
  21667. sse.on_error([&](Error err) {
  21668. error_called.store(true);
  21669. received_error = err;
  21670. });
  21671. sse.set_reconnect_interval(50);
  21672. sse.set_max_reconnect_attempts(1);
  21673. sse.start_async();
  21674. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21675. sse.stop();
  21676. EXPECT_TRUE(error_called.load());
  21677. EXPECT_NE(received_error, Error::Success);
  21678. }
  21679. // Test: Last-Event-ID header sent on reconnect
  21680. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21681. // Endpoint that sends event with ID
  21682. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21683. res.set_chunked_content_provider(
  21684. "text/event-stream", [](size_t offset, DataSink &sink) {
  21685. if (offset == 0) {
  21686. std::string event = "id: evt-123\ndata: test\n\n";
  21687. sink.write(event.data(), event.size());
  21688. }
  21689. return false;
  21690. });
  21691. });
  21692. Client client("localhost", get_port());
  21693. sse::SSEClient sse(client, "/event-with-id");
  21694. std::atomic<bool> id_received{false};
  21695. sse.on_message([&](const sse::SSEMessage &msg) {
  21696. if (!msg.id.empty()) { id_received.store(true); }
  21697. });
  21698. sse.set_reconnect_interval(100);
  21699. sse.set_max_reconnect_attempts(1);
  21700. sse.start_async();
  21701. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21702. sse.stop();
  21703. EXPECT_TRUE(id_received.load());
  21704. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21705. }
  21706. // Test: Manual stop
  21707. TEST_F(SSEIntegrationTest, ManualStop) {
  21708. // Endpoint that sends one event and stays open briefly. The server outlives
  21709. // this test body, so the provider uses the fixture's flag, not a local.
  21710. server_->Get("/stay-open", [this](const Request &, Response &res) {
  21711. res.set_chunked_content_provider(
  21712. "text/event-stream", [this](size_t offset, DataSink &sink) {
  21713. if (offset == 0) {
  21714. std::string event = "data: connected\n\n";
  21715. sink.write(event.data(), event.size());
  21716. }
  21717. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  21718. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21719. }
  21720. return false;
  21721. });
  21722. });
  21723. Client client("localhost", get_port());
  21724. sse::SSEClient sse(client, "/stay-open");
  21725. std::atomic<bool> connected{false};
  21726. sse.on_open([&connected]() { connected.store(true); });
  21727. sse.set_reconnect_interval(100);
  21728. sse.set_max_reconnect_attempts(1);
  21729. sse.start_async();
  21730. // Wait for connection to establish
  21731. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21732. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21733. }
  21734. EXPECT_TRUE(connected.load());
  21735. EXPECT_TRUE(sse.is_connected());
  21736. // Signal handler to stop
  21737. stop_server_.store(true);
  21738. // Stop SSE client
  21739. sse.stop();
  21740. EXPECT_FALSE(sse.is_connected());
  21741. }
  21742. // Sends one event, then nothing until stop is set
  21743. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  21744. return [&stop](const Request &, Response &res) {
  21745. res.set_chunked_content_provider(
  21746. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  21747. if (offset == 0) {
  21748. std::string event = "data: hello\n\n";
  21749. sink.write(event.data(), event.size());
  21750. }
  21751. while (!stop.load()) {
  21752. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21753. }
  21754. return false;
  21755. });
  21756. };
  21757. }
  21758. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  21759. static void check_stop_interrupts_blocked_read(Client &client) {
  21760. client.set_read_timeout(30, 0);
  21761. for (auto by_destructor : {false, true}) {
  21762. std::atomic<bool> received{false};
  21763. std::chrono::steady_clock::time_point start;
  21764. {
  21765. sse::SSEClient sse(client, "/idle-stream");
  21766. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  21767. sse.start_async();
  21768. for (int i = 0; i < 500 && !received.load(); ++i) {
  21769. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21770. }
  21771. ASSERT_TRUE(received.load());
  21772. // Let the client block in the next read
  21773. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  21774. start = std::chrono::steady_clock::now();
  21775. if (!by_destructor) { sse.stop(); }
  21776. }
  21777. EXPECT_LT(std::chrono::steady_clock::now() - start,
  21778. std::chrono::seconds(2));
  21779. }
  21780. }
  21781. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  21782. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  21783. Client client("localhost", get_port());
  21784. check_stop_interrupts_blocked_read(client);
  21785. }
  21786. #ifdef CPPHTTPLIB_SSL_ENABLED
  21787. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  21788. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21789. std::atomic<bool> done{false};
  21790. svr.Get("/idle-stream", idle_event_stream(done));
  21791. auto port = svr.bind_to_any_port(HOST);
  21792. std::thread t([&] { svr.listen_after_bind(); });
  21793. auto se = detail::scope_exit([&] {
  21794. done.store(true);
  21795. svr.stop();
  21796. t.join();
  21797. });
  21798. svr.wait_until_ready();
  21799. Client client("https://localhost:" + std::to_string(port));
  21800. client.enable_server_certificate_verification(false);
  21801. check_stop_interrupts_blocked_read(client);
  21802. }
  21803. #endif
  21804. // Test: SSEClient with custom headers
  21805. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21806. // Setup a server endpoint that checks for custom header
  21807. std::atomic<bool> header_received{false};
  21808. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21809. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21810. header_received.store(true);
  21811. }
  21812. res.set_chunked_content_provider("text/event-stream",
  21813. [](size_t, DataSink &) { return false; });
  21814. });
  21815. Client client("localhost", get_port());
  21816. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21817. sse::SSEClient sse(client, "/header-check", headers);
  21818. sse.set_max_reconnect_attempts(1);
  21819. sse.start_async();
  21820. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21821. sse.stop();
  21822. EXPECT_TRUE(header_received.load());
  21823. }
  21824. // Test: Reconnect interval configuration
  21825. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21826. Client client("localhost", get_port());
  21827. sse::SSEClient sse(client, "/events");
  21828. auto &result = sse.set_reconnect_interval(500);
  21829. // Builder pattern should return reference to self
  21830. EXPECT_EQ(&result, &sse);
  21831. }
  21832. // Test: Max reconnect attempts
  21833. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21834. // Connect to non-existent port to force reconnects
  21835. Client client("localhost", 59998);
  21836. sse::SSEClient sse(client, "/events");
  21837. std::atomic<int> error_count{0};
  21838. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21839. sse.set_reconnect_interval(50);
  21840. sse.set_max_reconnect_attempts(2);
  21841. auto start = std::chrono::steady_clock::now();
  21842. sse.start(); // Blocking call
  21843. auto end = std::chrono::steady_clock::now();
  21844. // Should have stopped after 2 failed attempts
  21845. EXPECT_GE(error_count.load(), 2);
  21846. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21847. auto duration =
  21848. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21849. #ifdef _WIN32
  21850. // Windows is much slower for socket connection failures
  21851. EXPECT_LT(duration.count(), 7000);
  21852. #else
  21853. EXPECT_LT(duration.count(), 1000);
  21854. #endif
  21855. }
  21856. // Test: Multi-line data in integration
  21857. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21858. // Endpoint with multi-line data
  21859. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21860. res.set_chunked_content_provider(
  21861. "text/event-stream", [](size_t offset, DataSink &sink) {
  21862. if (offset == 0) {
  21863. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21864. sink.write(event.data(), event.size());
  21865. }
  21866. return false;
  21867. });
  21868. });
  21869. Client client("localhost", get_port());
  21870. sse::SSEClient sse(client, "/multiline-data");
  21871. std::string received_data;
  21872. std::mutex data_mutex;
  21873. sse.on_message([&](const sse::SSEMessage &msg) {
  21874. std::lock_guard<std::mutex> lock(data_mutex);
  21875. received_data = msg.data;
  21876. });
  21877. sse.set_reconnect_interval(100);
  21878. sse.set_max_reconnect_attempts(1);
  21879. sse.start_async();
  21880. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21881. sse.stop();
  21882. std::lock_guard<std::mutex> lock(data_mutex);
  21883. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21884. }
  21885. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21886. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21887. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21888. DataSink &sink) {
  21889. if (offset == 0) {
  21890. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21891. sink.write(events.data(), events.size());
  21892. }
  21893. return false;
  21894. });
  21895. });
  21896. Client client("localhost", get_port());
  21897. sse::SSEClient sse(client, "/empty-data-lines");
  21898. std::mutex mutex;
  21899. std::condition_variable cv;
  21900. std::vector<std::string> received;
  21901. sse.on_message([&](const sse::SSEMessage &msg) {
  21902. std::lock_guard<std::mutex> lock(mutex);
  21903. received.push_back(msg.data);
  21904. cv.notify_all();
  21905. });
  21906. sse.set_max_reconnect_attempts(1);
  21907. sse.start_async();
  21908. {
  21909. std::unique_lock<std::mutex> lock(mutex);
  21910. cv.wait_for(lock, std::chrono::seconds(2),
  21911. [&] { return received.size() >= 3; });
  21912. }
  21913. sse.stop();
  21914. ASSERT_GE(received.size(), 3u);
  21915. EXPECT_EQ(received[0], "");
  21916. EXPECT_EQ(received[1], "\nhello");
  21917. EXPECT_EQ(received[2], "");
  21918. }
  21919. // Test: Auto-reconnect after server disconnection
  21920. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21921. std::atomic<int> connection_count{0};
  21922. std::atomic<int> message_count{0};
  21923. // Endpoint that sends one event and closes, forcing reconnect
  21924. server_->Get("/reconnect-test",
  21925. [&connection_count](const Request &, Response &res) {
  21926. connection_count.fetch_add(1);
  21927. res.set_chunked_content_provider(
  21928. "text/event-stream", [](size_t offset, DataSink &sink) {
  21929. if (offset == 0) {
  21930. std::string event = "data: hello\n\n";
  21931. sink.write(event.data(), event.size());
  21932. }
  21933. return false; // Close connection after sending
  21934. });
  21935. });
  21936. Client client("localhost", get_port());
  21937. sse::SSEClient sse(client, "/reconnect-test");
  21938. sse.on_message([&message_count](const sse::SSEMessage &) {
  21939. message_count.fetch_add(1);
  21940. });
  21941. sse.set_reconnect_interval(100);
  21942. sse.set_max_reconnect_attempts(3);
  21943. sse.start_async();
  21944. // Wait long enough for multiple reconnects
  21945. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21946. sse.stop();
  21947. // Should have connected multiple times (initial + reconnects)
  21948. EXPECT_GE(connection_count.load(), 2);
  21949. // Should have received messages from multiple connections
  21950. EXPECT_GE(message_count.load(), 2);
  21951. }
  21952. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  21953. std::atomic<int> connection_count{0};
  21954. // Neither Content-Length nor chunked: the close ends the stream
  21955. server_->Get("/close-delimited",
  21956. [&connection_count](const Request &, Response &res) {
  21957. connection_count.fetch_add(1);
  21958. res.set_content_provider(
  21959. "text/event-stream", [](size_t offset, DataSink &sink) {
  21960. if (offset == 0) {
  21961. std::string event = "data: hello\n\n";
  21962. sink.write(event.data(), event.size());
  21963. } else {
  21964. sink.done();
  21965. }
  21966. return true;
  21967. });
  21968. });
  21969. Client client("localhost", get_port());
  21970. sse::SSEClient sse(client, "/close-delimited");
  21971. std::atomic<int> error_count{0};
  21972. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  21973. sse.set_reconnect_interval(100);
  21974. sse.start_async();
  21975. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  21976. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21977. }
  21978. sse.stop();
  21979. // Reconnects as after any end of the stream, but reports no error
  21980. EXPECT_GE(connection_count.load(), 2);
  21981. EXPECT_EQ(0, error_count.load());
  21982. }
  21983. // Test: A retry field that is not all ASCII digits is ignored
  21984. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21985. std::atomic<int> connection_count{0};
  21986. server_->Get("/bad-retry",
  21987. [&connection_count](const Request &, Response &res) {
  21988. connection_count.fetch_add(1);
  21989. res.set_chunked_content_provider(
  21990. "text/event-stream", [](size_t offset, DataSink &sink) {
  21991. if (offset == 0) {
  21992. std::string event = "retry: -1\ndata: hello\n\n";
  21993. sink.write(event.data(), event.size());
  21994. }
  21995. return false;
  21996. });
  21997. });
  21998. Client client("localhost", get_port());
  21999. sse::SSEClient sse(client, "/bad-retry");
  22000. sse.set_reconnect_interval(10000);
  22001. sse.start_async();
  22002. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22003. sse.stop();
  22004. EXPECT_EQ(connection_count.load(), 1);
  22005. }
  22006. // Test: A retry field of all ASCII digits sets the reconnection time
  22007. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22008. std::mutex mutex;
  22009. std::condition_variable cv;
  22010. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22011. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22012. {
  22013. std::lock_guard<std::mutex> lock(mutex);
  22014. connected_at.push_back(std::chrono::steady_clock::now());
  22015. cv.notify_all();
  22016. }
  22017. res.set_chunked_content_provider(
  22018. "text/event-stream", [](size_t offset, DataSink &sink) {
  22019. if (offset == 0) {
  22020. std::string event = "retry: 0\ndata: hello\n\n";
  22021. sink.write(event.data(), event.size());
  22022. }
  22023. return false;
  22024. });
  22025. });
  22026. Client client("localhost", get_port());
  22027. sse::SSEClient sse(client, "/zero-retry");
  22028. sse.set_reconnect_interval(10000);
  22029. sse.start_async();
  22030. {
  22031. std::unique_lock<std::mutex> lock(mutex);
  22032. cv.wait_for(lock, std::chrono::seconds(5),
  22033. [&] { return connected_at.size() >= 2; });
  22034. }
  22035. sse.stop();
  22036. // The server-supplied interval is applied, but never below 100ms, so
  22037. // "retry: 0" does not cause a busy reconnect loop
  22038. std::lock_guard<std::mutex> lock(mutex);
  22039. ASSERT_GE(connected_at.size(), 2u);
  22040. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22041. connected_at[1] - connected_at[0])
  22042. .count();
  22043. EXPECT_GE(interval_ms, 100);
  22044. }
  22045. // Test: Last-Event-ID sent on reconnect
  22046. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22047. std::atomic<int> connection_count{0};
  22048. std::vector<std::string> received_last_event_ids;
  22049. std::mutex id_mutex;
  22050. // Endpoint that checks Last-Event-ID header and sends event with ID
  22051. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22052. int conn = connection_count.fetch_add(1);
  22053. // Capture the Last-Event-ID header from each connection
  22054. {
  22055. std::lock_guard<std::mutex> lock(id_mutex);
  22056. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22057. }
  22058. res.set_chunked_content_provider(
  22059. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22060. if (offset == 0) {
  22061. std::string event =
  22062. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22063. sink.write(event.data(), event.size());
  22064. }
  22065. return false;
  22066. });
  22067. });
  22068. Client client("localhost", get_port());
  22069. sse::SSEClient sse(client, "/reconnect-with-id");
  22070. sse.set_reconnect_interval(100);
  22071. sse.set_max_reconnect_attempts(3);
  22072. sse.start_async();
  22073. // Wait for at least 2 connections
  22074. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22075. sse.stop();
  22076. // Verify behavior
  22077. std::lock_guard<std::mutex> lock(id_mutex);
  22078. EXPECT_GE(received_last_event_ids.size(), 2u);
  22079. // First connection should have no Last-Event-ID
  22080. if (!received_last_event_ids.empty()) {
  22081. EXPECT_EQ(received_last_event_ids[0], "");
  22082. }
  22083. // Second connection should have Last-Event-ID from first connection
  22084. if (received_last_event_ids.size() >= 2) {
  22085. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22086. }
  22087. }
  22088. // Test: set_headers updates headers used on reconnect
  22089. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22090. std::vector<std::string> received_tokens;
  22091. std::mutex token_mutex;
  22092. // Endpoint that captures Authorization header
  22093. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22094. {
  22095. std::lock_guard<std::mutex> lock(token_mutex);
  22096. received_tokens.push_back(req.get_header_value("Authorization"));
  22097. }
  22098. res.set_chunked_content_provider(
  22099. "text/event-stream", [](size_t offset, DataSink &sink) {
  22100. if (offset == 0) {
  22101. std::string event = "data: hello\n\n";
  22102. sink.write(event.data(), event.size());
  22103. }
  22104. return false; // Close connection to trigger reconnect
  22105. });
  22106. });
  22107. Client client("localhost", get_port());
  22108. Headers headers = {{"Authorization", "Bearer old-token"}};
  22109. sse::SSEClient sse(client, "/auth-check", headers);
  22110. // Update headers on each successful connection
  22111. sse.on_open(
  22112. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22113. sse.set_reconnect_interval(100);
  22114. sse.set_max_reconnect_attempts(3);
  22115. sse.start_async();
  22116. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22117. sse.stop();
  22118. std::lock_guard<std::mutex> lock(token_mutex);
  22119. ASSERT_GE(received_tokens.size(), 2u);
  22120. // First connection uses original header
  22121. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22122. // Second connection uses updated header from set_headers
  22123. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22124. }
  22125. // Test: 401 allows reconnection (so on_error can refresh headers)
  22126. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22127. std::atomic<int> connection_count{0};
  22128. // Endpoint: returns 401 on first attempt, 200 on second
  22129. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22130. int conn = connection_count.fetch_add(1);
  22131. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22132. res.status = StatusCode::Unauthorized_401;
  22133. res.set_content("Unauthorized", "text/plain");
  22134. return;
  22135. }
  22136. res.set_chunked_content_provider(
  22137. "text/event-stream", [](size_t offset, DataSink &sink) {
  22138. if (offset == 0) {
  22139. std::string event = "data: authenticated\n\n";
  22140. sink.write(event.data(), event.size());
  22141. }
  22142. return false;
  22143. });
  22144. });
  22145. Client client("localhost", get_port());
  22146. Headers headers = {{"Authorization", "Bearer expired"}};
  22147. sse::SSEClient sse(client, "/auth-retry", headers);
  22148. std::atomic<bool> message_received{false};
  22149. // Refresh token on error
  22150. sse.on_error(
  22151. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22152. sse.on_message([&](const sse::SSEMessage &msg) {
  22153. if (msg.data == "authenticated") { message_received.store(true); }
  22154. });
  22155. sse.set_reconnect_interval(100);
  22156. sse.set_max_reconnect_attempts(3);
  22157. sse.start_async();
  22158. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22159. sse.stop();
  22160. // Should have reconnected after 401 and succeeded with new token
  22161. EXPECT_GE(connection_count.load(), 2);
  22162. EXPECT_TRUE(message_received.load());
  22163. }
  22164. TEST(Issue2318Test, EmptyHostString) {
  22165. {
  22166. httplib::Client cli_empty("", PORT);
  22167. auto res = cli_empty.Get("/");
  22168. ASSERT_FALSE(res);
  22169. EXPECT_EQ(httplib::Error::Connection, res.error());
  22170. }
  22171. {
  22172. httplib::Client cli(" ", PORT);
  22173. auto res = cli.Get("/");
  22174. ASSERT_FALSE(res);
  22175. EXPECT_EQ(httplib::Error::Connection, res.error());
  22176. }
  22177. }
  22178. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22179. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22180. Server svr;
  22181. // Set a small payload limit (1KB)
  22182. svr.set_payload_max_length(1024);
  22183. svr.Post("/test", [&](const Request &req, Response &res) {
  22184. res.set_content("Body size: " + std::to_string(req.body.size()),
  22185. "text/plain");
  22186. });
  22187. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22188. auto se = detail::scope_exit([&] {
  22189. svr.stop();
  22190. listen_thread.join();
  22191. });
  22192. svr.wait_until_ready();
  22193. // Create data that compresses well but exceeds limit when decompressed
  22194. // 8KB of repeated null bytes compresses to a very small size
  22195. std::string original_data(8 * 1024, '\0');
  22196. // Compress the data using gzip
  22197. std::string compressed_data;
  22198. detail::gzip_compressor compressor;
  22199. compressor.compress(original_data.data(), original_data.size(), true,
  22200. [&](const char *data, size_t size) {
  22201. compressed_data.append(data, size);
  22202. return true;
  22203. });
  22204. // Verify compression worked (compressed should be much smaller)
  22205. ASSERT_LT(compressed_data.size(), original_data.size());
  22206. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22207. // Send compressed data with Content-Encoding: gzip
  22208. Client cli(HOST, PORT);
  22209. Headers headers = {{"Content-Encoding", "gzip"}};
  22210. auto res =
  22211. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22212. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22214. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22215. }
  22216. #endif
  22217. // ============================================================================
  22218. // OpenSSL-Specific Tests
  22219. // ============================================================================
  22220. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22221. X509 *readCertificate(const std::string &strFileName) {
  22222. std::ifstream inStream(strFileName);
  22223. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22224. std::istreambuf_iterator<char>());
  22225. if (strCertPEM.empty()) return (nullptr);
  22226. BIO *pbCert = BIO_new(BIO_s_mem());
  22227. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22228. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22229. BIO_free(pbCert);
  22230. return (pCert);
  22231. }
  22232. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22233. std::ifstream inStream(strFileName);
  22234. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22235. std::istreambuf_iterator<char>());
  22236. if (strPrivateKeyPEM.empty()) return (nullptr);
  22237. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22238. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22239. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22240. BIO_free(pbPrivKey);
  22241. return (pPrivateKey);
  22242. }
  22243. TEST(BindServerTest, UpdateCerts) {
  22244. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22245. int port = svr.bind_to_any_port("0.0.0.0");
  22246. ASSERT_TRUE(svr.is_valid());
  22247. ASSERT_TRUE(port > 0);
  22248. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22249. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22250. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22251. ASSERT_TRUE(cert != nullptr);
  22252. ASSERT_TRUE(ca_cert != nullptr);
  22253. ASSERT_TRUE(key != nullptr);
  22254. X509_STORE *cert_store = X509_STORE_new();
  22255. X509_STORE_add_cert(cert_store, ca_cert);
  22256. // svr.update_certs(cert, key, cert_store); // deprecated
  22257. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22258. CLIENT_CA_CERT_FILE);
  22259. ASSERT_TRUE(svr.is_valid());
  22260. svr.stop();
  22261. X509_STORE_free(cert_store);
  22262. X509_free(cert);
  22263. X509_free(ca_cert);
  22264. EVP_PKEY_free(key);
  22265. }
  22266. // Test that update_certs() updates client CA list correctly
  22267. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22268. // Start with file-based constructor
  22269. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22270. ASSERT_TRUE(svr.is_valid());
  22271. // Initially no client CA list should be set
  22272. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22273. ASSERT_TRUE(ssl_ctx != nullptr);
  22274. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22275. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22276. // Now update with client CA (PEM string)
  22277. std::string cert_pem, key_pem, ca_pem;
  22278. read_file(SERVER_CERT_FILE, cert_pem);
  22279. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22280. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22281. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22282. ASSERT_TRUE(svr.is_valid());
  22283. // Now client CA list should be set
  22284. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22285. ASSERT_TRUE(ca_list_after != nullptr);
  22286. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22287. }
  22288. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22289. // Test that the file-path SSLServer constructor properly sets the client CA
  22290. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22292. ASSERT_TRUE(svr.is_valid());
  22293. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22294. ASSERT_TRUE(ssl_ctx != nullptr);
  22295. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22296. ASSERT_TRUE(ca_list != nullptr);
  22297. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22298. }
  22299. #endif
  22300. // ============================================================================
  22301. // MbedTLS-Specific Tests
  22302. // ============================================================================
  22303. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22304. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22305. using namespace httplib::tls;
  22306. // Track if callback was invoked
  22307. bool callback_invoked = false;
  22308. // The callback receives void* ctx which is actually MbedTlsContext*
  22309. // We can access the mbedtls_ssl_config via the context
  22310. auto setup_callback = [&callback_invoked](void *ctx) {
  22311. callback_invoked = true;
  22312. // Cast to MbedTlsContext* to access the ssl config
  22313. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22314. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22315. // Use static variables to hold certificate data (simplified for test)
  22316. static mbedtls_x509_crt own_cert;
  22317. static mbedtls_pk_context own_key;
  22318. static mbedtls_x509_crt ca_chain;
  22319. static bool initialized = false;
  22320. if (!initialized) {
  22321. mbedtls_x509_crt_init(&own_cert);
  22322. mbedtls_pk_init(&own_key);
  22323. mbedtls_x509_crt_init(&ca_chain);
  22324. // Load server certificate
  22325. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22326. return false;
  22327. }
  22328. // Load server private key.
  22329. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22330. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22331. #if MBEDTLS_VERSION_MAJOR == 3
  22332. ,
  22333. mbedtls_ctr_drbg_random, nullptr
  22334. #endif
  22335. ) != 0) {
  22336. return false;
  22337. }
  22338. // Load CA chain for client verification
  22339. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22340. return false;
  22341. }
  22342. initialized = true;
  22343. }
  22344. // Configure the SSL config
  22345. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22346. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22347. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22348. // Set minimum TLS version using mbedTLS native API
  22349. #if MBEDTLS_VERSION_MAJOR >= 3
  22350. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22351. #else
  22352. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22353. MBEDTLS_SSL_MINOR_VERSION_3);
  22354. #endif
  22355. return true;
  22356. };
  22357. SSLServer svr(setup_callback);
  22358. ASSERT_TRUE(svr.is_valid());
  22359. ASSERT_TRUE(callback_invoked);
  22360. svr.Get("/test", [&](const Request &req, Response &res) {
  22361. res.set_content("test", "text/plain");
  22362. auto cert = req.peer_cert();
  22363. ASSERT_TRUE(static_cast<bool>(cert));
  22364. auto common_name = cert.subject_cn();
  22365. EXPECT_EQ("Common Name", common_name);
  22366. });
  22367. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22368. auto se = detail::scope_exit([&] {
  22369. svr.stop();
  22370. t.join();
  22371. ASSERT_FALSE(svr.is_running());
  22372. });
  22373. svr.wait_until_ready();
  22374. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22375. cli.enable_server_certificate_verification(false);
  22376. cli.set_connection_timeout(30);
  22377. auto res = cli.Get("/test");
  22378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22379. ASSERT_EQ(StatusCode::OK_200, res->status);
  22380. }
  22381. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22382. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22383. // keep-alive SSL session, which reads through that config in
  22384. // mbedtls_ssl_close_notify.
  22385. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22387. ASSERT_TRUE(svr.is_valid());
  22388. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22389. res.set_content("test", "text/plain");
  22390. });
  22391. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22392. auto se = detail::scope_exit([&] {
  22393. svr.stop();
  22394. t.join();
  22395. ASSERT_FALSE(svr.is_running());
  22396. });
  22397. svr.wait_until_ready();
  22398. {
  22399. SSLClient cli(HOST, PORT);
  22400. cli.enable_server_certificate_verification(false);
  22401. cli.set_keep_alive(true);
  22402. auto res = cli.Get("/test");
  22403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22404. ASSERT_EQ(StatusCode::OK_200, res->status);
  22405. // cli is destructed here with the keep-alive SSL session still open.
  22406. }
  22407. }
  22408. #endif
  22409. // WebSocket Tests
  22410. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22411. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22412. // defining the meaning of these bits has been negotiated.
  22413. auto make_frame = [](uint8_t first_byte) {
  22414. std::string frame;
  22415. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22416. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22417. frame += "Hello";
  22418. return frame;
  22419. };
  22420. // RSV1 set (0x40)
  22421. {
  22422. detail::BufferStream strm;
  22423. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22424. ws::Opcode opcode;
  22425. std::string payload;
  22426. bool fin;
  22427. EXPECT_EQ(
  22428. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22429. ws::impl::FrameRead::Fail);
  22430. }
  22431. // RSV2 set (0x20)
  22432. {
  22433. detail::BufferStream strm;
  22434. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22435. ws::Opcode opcode;
  22436. std::string payload;
  22437. bool fin;
  22438. EXPECT_EQ(
  22439. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22440. ws::impl::FrameRead::Fail);
  22441. }
  22442. // RSV3 set (0x10)
  22443. {
  22444. detail::BufferStream strm;
  22445. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22446. ws::Opcode opcode;
  22447. std::string payload;
  22448. bool fin;
  22449. EXPECT_EQ(
  22450. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22451. ws::impl::FrameRead::Fail);
  22452. }
  22453. // No RSV bits set - should succeed
  22454. {
  22455. detail::BufferStream strm;
  22456. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22457. ws::Opcode opcode;
  22458. std::string payload;
  22459. bool fin;
  22460. EXPECT_EQ(
  22461. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22462. ws::impl::FrameRead::Ok);
  22463. EXPECT_EQ(ws::Opcode::Text, opcode);
  22464. EXPECT_EQ("Hello", payload);
  22465. EXPECT_TRUE(fin);
  22466. }
  22467. }
  22468. TEST(WebSocketTest, ControlFrameValidation) {
  22469. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22470. // payload length <= 125.
  22471. // Ping with FIN=0 - must be rejected
  22472. {
  22473. detail::BufferStream strm;
  22474. std::string frame;
  22475. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22476. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22477. strm.write(frame.data(), frame.size());
  22478. ws::Opcode opcode;
  22479. std::string payload;
  22480. bool fin;
  22481. EXPECT_EQ(
  22482. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22483. ws::impl::FrameRead::Fail);
  22484. }
  22485. // Close with FIN=0 - must be rejected
  22486. {
  22487. detail::BufferStream strm;
  22488. std::string frame;
  22489. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22490. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22491. strm.write(frame.data(), frame.size());
  22492. ws::Opcode opcode;
  22493. std::string payload;
  22494. bool fin;
  22495. EXPECT_EQ(
  22496. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22497. ws::impl::FrameRead::Fail);
  22498. }
  22499. // Ping with payload_len=126 (extended length) - must be rejected
  22500. {
  22501. detail::BufferStream strm;
  22502. std::string frame;
  22503. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22504. frame += static_cast<char>(126); // payload_len=126 (>125)
  22505. frame += static_cast<char>(0x00); // extended length high byte
  22506. frame += static_cast<char>(126); // extended length low byte
  22507. frame += std::string(126, 'x');
  22508. strm.write(frame.data(), frame.size());
  22509. ws::Opcode opcode;
  22510. std::string payload;
  22511. bool fin;
  22512. EXPECT_EQ(
  22513. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22514. ws::impl::FrameRead::Fail);
  22515. }
  22516. // Ping with FIN=1 and payload_len=125 - should succeed
  22517. {
  22518. detail::BufferStream strm;
  22519. std::string frame;
  22520. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22521. frame += static_cast<char>(125); // payload_len=125
  22522. frame += std::string(125, 'x');
  22523. strm.write(frame.data(), frame.size());
  22524. ws::Opcode opcode;
  22525. std::string payload;
  22526. bool fin;
  22527. EXPECT_EQ(
  22528. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22529. ws::impl::FrameRead::Ok);
  22530. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22531. EXPECT_EQ(125u, payload.size());
  22532. EXPECT_TRUE(fin);
  22533. }
  22534. }
  22535. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22536. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22537. // length MUST be 0.
  22538. // MSB set - must be rejected
  22539. {
  22540. detail::BufferStream strm;
  22541. std::string frame;
  22542. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22543. frame += static_cast<char>(127); // 64-bit extended length
  22544. frame += static_cast<char>(0x80); // MSB set (invalid)
  22545. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22546. strm.write(frame.data(), frame.size());
  22547. ws::Opcode opcode;
  22548. std::string payload;
  22549. bool fin;
  22550. EXPECT_EQ(
  22551. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22552. ws::impl::FrameRead::Fail);
  22553. }
  22554. // MSB clear - should pass length parsing (will be rejected by max_len,
  22555. // but that's a different check; use a small length to verify)
  22556. {
  22557. detail::BufferStream strm;
  22558. std::string frame;
  22559. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22560. frame += static_cast<char>(127); // 64-bit extended length
  22561. frame += std::string(7, '\0'); // high bytes = 0
  22562. frame += static_cast<char>(0x03); // length = 3
  22563. frame += "abc";
  22564. strm.write(frame.data(), frame.size());
  22565. ws::Opcode opcode;
  22566. std::string payload;
  22567. bool fin;
  22568. EXPECT_EQ(
  22569. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22570. ws::impl::FrameRead::Ok);
  22571. EXPECT_EQ(ws::Opcode::Text, opcode);
  22572. EXPECT_EQ("abc", payload);
  22573. }
  22574. }
  22575. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22576. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22577. // Valid UTF-8
  22578. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22579. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22580. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22581. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22582. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22583. // Invalid UTF-8
  22584. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22585. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22586. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22587. EXPECT_FALSE(
  22588. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22589. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22590. }
  22591. TEST(WebSocketTest, ConnectAndDisconnect) {
  22592. Server svr;
  22593. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22594. std::string msg;
  22595. while (ws.read(msg)) {}
  22596. });
  22597. auto port = svr.bind_to_any_port(HOST);
  22598. std::thread t([&]() { svr.listen_after_bind(); });
  22599. svr.wait_until_ready();
  22600. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22601. auto res = client.connect();
  22602. ASSERT_TRUE(res);
  22603. EXPECT_EQ(Error::Success, res.error());
  22604. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22605. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22606. EXPECT_TRUE(client.is_open());
  22607. client.close();
  22608. EXPECT_FALSE(client.is_open());
  22609. svr.stop();
  22610. t.join();
  22611. }
  22612. TEST(WebSocketTest, ValidURL) {
  22613. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22614. EXPECT_TRUE(ws1.is_valid());
  22615. ws::WebSocketClient ws2("ws://example.com/path");
  22616. EXPECT_TRUE(ws2.is_valid());
  22617. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22618. EXPECT_TRUE(ws3.is_valid());
  22619. #ifdef CPPHTTPLIB_SSL_ENABLED
  22620. ws::WebSocketClient wss1("wss://example.com/path");
  22621. EXPECT_TRUE(wss1.is_valid());
  22622. ws::WebSocketClient wss2("wss://example.com:443/path");
  22623. EXPECT_TRUE(wss2.is_valid());
  22624. #endif
  22625. }
  22626. TEST(WebSocketTest, InvalidURL) {
  22627. // No scheme
  22628. ws::WebSocketClient ws1("localhost:8080/path");
  22629. EXPECT_FALSE(ws1.is_valid());
  22630. // No path
  22631. ws::WebSocketClient ws2("ws://localhost:8080");
  22632. EXPECT_FALSE(ws2.is_valid());
  22633. // Empty string
  22634. ws::WebSocketClient ws3("");
  22635. EXPECT_FALSE(ws3.is_valid());
  22636. // Missing host
  22637. ws::WebSocketClient ws4("ws://:8080/path");
  22638. EXPECT_FALSE(ws4.is_valid());
  22639. // Port number overflow — should not crash
  22640. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22641. EXPECT_FALSE(ws5.is_valid());
  22642. // Port out of range
  22643. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22644. EXPECT_FALSE(ws6.is_valid());
  22645. }
  22646. TEST(WebSocketTest, UnsupportedScheme) {
  22647. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22648. ws::WebSocketClient ws1("http://localhost:8080/path");
  22649. EXPECT_FALSE(ws1.is_valid());
  22650. ws::WebSocketClient ws2("https://localhost:8080/path");
  22651. EXPECT_FALSE(ws2.is_valid());
  22652. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22653. EXPECT_FALSE(ws3.is_valid());
  22654. #else
  22655. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22656. std::invalid_argument);
  22657. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22658. std::invalid_argument);
  22659. #endif
  22660. }
  22661. TEST(WebSocketTest, ConnectWhenInvalid) {
  22662. ws::WebSocketClient ws("not a valid url");
  22663. EXPECT_FALSE(ws.is_valid());
  22664. auto res = ws.connect();
  22665. EXPECT_FALSE(res);
  22666. EXPECT_EQ(Error::Connection, res.error());
  22667. EXPECT_EQ(-1, res.status());
  22668. }
  22669. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22670. // Grab a port that is free, then close it again so nothing listens there
  22671. Server svr;
  22672. auto port = svr.bind_to_any_port(HOST);
  22673. svr.stop();
  22674. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22675. auto res = client.connect();
  22676. ASSERT_FALSE(res);
  22677. EXPECT_EQ(Error::Connection, res.error());
  22678. EXPECT_EQ(-1, res.status());
  22679. }
  22680. TEST(WebSocketTest, DefaultPort) {
  22681. ws::WebSocketClient ws1("ws://example.com/path");
  22682. EXPECT_TRUE(ws1.is_valid());
  22683. // ws:// defaults to port 80 (verified by successful parse)
  22684. #ifdef CPPHTTPLIB_SSL_ENABLED
  22685. ws::WebSocketClient ws2("wss://example.com/path");
  22686. EXPECT_TRUE(ws2.is_valid());
  22687. // wss:// defaults to port 443 (verified by successful parse)
  22688. #endif
  22689. }
  22690. TEST(WebSocketTest, IPv6LiteralAddress) {
  22691. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22692. EXPECT_TRUE(ws1.is_valid());
  22693. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22694. EXPECT_TRUE(ws2.is_valid());
  22695. }
  22696. TEST(WebSocketTest, ComplexPath) {
  22697. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22698. EXPECT_TRUE(ws1.is_valid());
  22699. ws::WebSocketClient ws2("ws://localhost:8080/");
  22700. EXPECT_TRUE(ws2.is_valid());
  22701. }
  22702. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22703. Server svr;
  22704. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22705. std::string msg;
  22706. while (ws.read(msg)) {}
  22707. });
  22708. auto port = svr.bind_to_any_port(HOST);
  22709. std::thread t([&]() { svr.listen_after_bind(); });
  22710. svr.wait_until_ready();
  22711. auto another_host = "example.com";
  22712. auto wrong_ip = "192.0.2.1";
  22713. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22714. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22715. ASSERT_TRUE(client.connect());
  22716. EXPECT_TRUE(client.is_open());
  22717. client.close();
  22718. svr.stop();
  22719. t.join();
  22720. }
  22721. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22722. Server svr;
  22723. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22724. std::string msg;
  22725. while (ws.read(msg)) {}
  22726. });
  22727. auto port = svr.bind_to_any_port(HOST);
  22728. std::thread t([&]() { svr.listen_after_bind(); });
  22729. svr.wait_until_ready();
  22730. auto wrong_ip = "192.0.2.1";
  22731. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22732. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22733. client.set_connection_timeout(1);
  22734. client.set_read_timeout(1);
  22735. client.set_write_timeout(1);
  22736. EXPECT_FALSE(client.connect());
  22737. EXPECT_FALSE(client.is_open());
  22738. svr.stop();
  22739. t.join();
  22740. }
  22741. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22742. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22743. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22744. // (RFC 6761) is only a map key and the Host header value.
  22745. auto host = "target.invalid";
  22746. Server svr;
  22747. std::string received_host;
  22748. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22749. received_host = req.get_header_value("Host");
  22750. std::string msg;
  22751. while (ws.read(msg)) {}
  22752. });
  22753. auto port = svr.bind_to_any_port(HOST);
  22754. std::thread t([&]() { svr.listen_after_bind(); });
  22755. // ASSERT_* below returns from the test body, which would leave t joinable
  22756. // and make ~thread call std::terminate.
  22757. auto se = detail::scope_exit([&] {
  22758. svr.stop();
  22759. if (t.joinable()) { t.join(); }
  22760. });
  22761. svr.wait_until_ready();
  22762. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22763. std::to_string(port) + "/ws");
  22764. client.set_hostname_addr_map({{host, HOST}});
  22765. ASSERT_TRUE(client.connect());
  22766. EXPECT_TRUE(client.is_open());
  22767. client.close();
  22768. svr.stop();
  22769. t.join();
  22770. // The mapping only redirects the connection; the identity stays host_.
  22771. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22772. }
  22773. class WebSocketIntegrationTest : public ::testing::Test {
  22774. protected:
  22775. void SetUp() override {
  22776. server_ = httplib::detail::make_unique<Server>();
  22777. setup_server();
  22778. start_server();
  22779. }
  22780. void TearDown() override {
  22781. server_->stop();
  22782. if (server_thread_.joinable()) { server_thread_.join(); }
  22783. }
  22784. void setup_server() {
  22785. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22786. std::string msg;
  22787. ws::ReadResult ret;
  22788. while ((ret = ws.read(msg))) {
  22789. if (ret == ws::Binary) {
  22790. ws.send(msg.data(), msg.size());
  22791. } else {
  22792. ws.send(msg);
  22793. }
  22794. }
  22795. });
  22796. server_->WebSocket("/ws-echo-string",
  22797. [](const Request &, ws::WebSocket &ws) {
  22798. std::string msg;
  22799. while (ws.read(msg)) {
  22800. ws.send("echo: " + msg);
  22801. }
  22802. });
  22803. server_->WebSocket(
  22804. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22805. // Echo back request metadata
  22806. ws.send("path:" + req.path);
  22807. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22808. std::string msg;
  22809. while (ws.read(msg)) {}
  22810. });
  22811. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22812. std::string msg;
  22813. ws.read(msg); // wait for a message
  22814. ws.close();
  22815. });
  22816. server_->WebSocket("/ws-close-status",
  22817. [](const Request &, ws::WebSocket &ws) {
  22818. std::string msg;
  22819. ws.read(msg); // wait for a message
  22820. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22821. });
  22822. server_->WebSocket(
  22823. "/ws-subprotocol",
  22824. [](const Request &, ws::WebSocket &ws) {
  22825. std::string msg;
  22826. while (ws.read(msg)) {
  22827. ws.send(msg);
  22828. }
  22829. },
  22830. [](const std::vector<std::string> &protocols) -> std::string {
  22831. for (const auto &p : protocols) {
  22832. if (p == "graphql-ws") { return p; }
  22833. }
  22834. return "";
  22835. });
  22836. server_->WebSocket(
  22837. "/ws-subprotocol-unoffered",
  22838. [](const Request &, ws::WebSocket &ws) {
  22839. std::string msg;
  22840. while (ws.read(msg)) {
  22841. ws.send(msg);
  22842. }
  22843. },
  22844. [](const std::vector<std::string> &) -> std::string {
  22845. return "admin";
  22846. });
  22847. }
  22848. void start_server() {
  22849. port_ = server_->bind_to_any_port(HOST);
  22850. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22851. server_->wait_until_ready();
  22852. }
  22853. std::unique_ptr<Server> server_;
  22854. std::thread server_thread_;
  22855. int port_ = 0;
  22856. };
  22857. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22858. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22859. "/ws-echo");
  22860. ASSERT_TRUE(client.connect());
  22861. ASSERT_TRUE(client.is_open());
  22862. ASSERT_TRUE(client.send("Hello WebSocket"));
  22863. std::string msg;
  22864. EXPECT_EQ(ws::Text, client.read(msg));
  22865. EXPECT_EQ("Hello WebSocket", msg);
  22866. client.close();
  22867. }
  22868. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22869. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22870. "/ws-echo");
  22871. ASSERT_TRUE(client.connect());
  22872. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22873. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22874. std::string msg;
  22875. EXPECT_EQ(ws::Binary, client.read(msg));
  22876. EXPECT_EQ(binary_data, msg);
  22877. client.close();
  22878. }
  22879. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22880. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22881. "/ws-echo");
  22882. ASSERT_TRUE(client.connect());
  22883. for (int i = 0; i < 10; i++) {
  22884. auto text = "message " + std::to_string(i);
  22885. ASSERT_TRUE(client.send(text));
  22886. std::string msg;
  22887. ASSERT_TRUE(client.read(msg));
  22888. EXPECT_EQ(text, msg);
  22889. }
  22890. client.close();
  22891. }
  22892. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22893. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22894. "/ws-close");
  22895. ASSERT_TRUE(client.connect());
  22896. // Send a message to trigger the server to close
  22897. ASSERT_TRUE(client.send("trigger close"));
  22898. // The server will close, so read should return false
  22899. std::string msg;
  22900. EXPECT_FALSE(client.read(msg));
  22901. EXPECT_FALSE(client.is_open());
  22902. }
  22903. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22905. "/ws-echo");
  22906. ASSERT_TRUE(client.connect());
  22907. // 128KB message
  22908. std::string large_data(128 * 1024, 'X');
  22909. ASSERT_TRUE(client.send(large_data));
  22910. std::string msg;
  22911. ASSERT_TRUE(client.read(msg));
  22912. EXPECT_EQ(large_data, msg);
  22913. client.close();
  22914. }
  22915. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22916. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22917. "/ws-echo");
  22918. ASSERT_TRUE(client.connect());
  22919. const int num_threads = 4;
  22920. std::vector<std::thread> threads;
  22921. std::atomic<int> send_count{0};
  22922. for (int t = 0; t < num_threads; t++) {
  22923. threads.emplace_back([&client, &send_count, t]() {
  22924. for (int i = 0; i < 5; i++) {
  22925. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22926. if (client.send(text)) { send_count++; }
  22927. }
  22928. });
  22929. }
  22930. for (auto &th : threads) {
  22931. th.join();
  22932. }
  22933. int received = 0;
  22934. std::string msg;
  22935. while (received < send_count.load()) {
  22936. if (!client.read(msg)) { break; }
  22937. received++;
  22938. }
  22939. EXPECT_EQ(send_count.load(), received);
  22940. client.close();
  22941. }
  22942. TEST_F(WebSocketIntegrationTest, ReadString) {
  22943. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22944. "/ws-echo-string");
  22945. ASSERT_TRUE(client.connect());
  22946. ASSERT_TRUE(client.send("hello"));
  22947. std::string msg;
  22948. ASSERT_TRUE(client.read(msg));
  22949. EXPECT_EQ("echo: hello", msg);
  22950. ASSERT_TRUE(client.send("world"));
  22951. ASSERT_TRUE(client.read(msg));
  22952. EXPECT_EQ("echo: world", msg);
  22953. client.close();
  22954. }
  22955. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22956. Headers headers = {{"X-Test-Header", "test-value"}};
  22957. ws::WebSocketClient client(
  22958. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22959. ASSERT_TRUE(client.connect());
  22960. std::string msg;
  22961. ASSERT_TRUE(client.read(msg));
  22962. EXPECT_EQ("path:/ws-request-info", msg);
  22963. ASSERT_TRUE(client.read(msg));
  22964. EXPECT_EQ("header:test-value", msg);
  22965. client.close();
  22966. }
  22967. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22968. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22969. "/ws-echo");
  22970. client.set_read_timeout(1, 0); // 1 second
  22971. ASSERT_TRUE(client.connect());
  22972. // Don't send anything — server echo handler waits for a message, so read()
  22973. // should time out. The connection survives it: nothing was consumed.
  22974. std::string msg;
  22975. EXPECT_EQ(client.read(msg), ws::Timeout);
  22976. EXPECT_TRUE(client.is_open());
  22977. // And it is still usable afterwards.
  22978. EXPECT_TRUE(client.send("after timeout"));
  22979. EXPECT_EQ(client.read(msg), ws::Text);
  22980. EXPECT_EQ(msg, "after timeout");
  22981. }
  22982. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22983. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22984. "/ws-echo");
  22985. client.set_read_timeout(1, 0);
  22986. ASSERT_TRUE(client.connect());
  22987. ASSERT_TRUE(client.send("first"));
  22988. std::string msg;
  22989. ASSERT_EQ(client.read(msg), ws::Text);
  22990. ASSERT_EQ(msg, "first");
  22991. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22992. // not be used with a read timeout: it would reprocess the previous message.
  22993. EXPECT_EQ(client.read(msg), ws::Timeout);
  22994. EXPECT_EQ(msg, "first");
  22995. }
  22996. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22997. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22998. "/ws-echo");
  22999. ASSERT_TRUE(client.connect());
  23000. // Setting it once the connection is open reaches the live stream, not just
  23001. // the seed for the next connect().
  23002. client.set_read_timeout(1, 0);
  23003. std::string msg;
  23004. EXPECT_EQ(client.read(msg), ws::Timeout);
  23005. EXPECT_TRUE(client.is_open());
  23006. }
  23007. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23009. "/ws-echo");
  23010. client.set_read_timeout(5, 0);
  23011. ASSERT_TRUE(client.connect());
  23012. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23013. // The server should reject it and close the connection.
  23014. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23015. client.send(oversized);
  23016. // The server's read() should have failed due to payload limit,
  23017. // so our read() should return false (connection closed).
  23018. std::string msg;
  23019. EXPECT_FALSE(client.read(msg));
  23020. }
  23021. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23023. "/ws-echo");
  23024. client.set_read_timeout(10, 0);
  23025. ASSERT_TRUE(client.connect());
  23026. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23027. // This should succeed.
  23028. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23029. ASSERT_TRUE(client.send(at_limit));
  23030. std::string msg;
  23031. ASSERT_TRUE(client.read(msg));
  23032. EXPECT_EQ(at_limit.size(), msg.size());
  23033. client.close();
  23034. }
  23035. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23036. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23037. "/nonexistent");
  23038. auto res = client.connect();
  23039. EXPECT_FALSE(res);
  23040. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23041. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23042. EXPECT_FALSE(client.is_open());
  23043. }
  23044. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23045. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23046. "/ws-echo");
  23047. ASSERT_TRUE(client.connect());
  23048. ASSERT_TRUE(client.send(""));
  23049. std::string msg;
  23050. EXPECT_EQ(ws::Text, client.read(msg));
  23051. EXPECT_EQ("", msg);
  23052. client.close();
  23053. }
  23054. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23055. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23056. "/ws-echo");
  23057. // First connection
  23058. ASSERT_TRUE(client.connect());
  23059. ASSERT_TRUE(client.send("first"));
  23060. std::string msg;
  23061. ASSERT_TRUE(client.read(msg));
  23062. EXPECT_EQ("first", msg);
  23063. client.close();
  23064. EXPECT_FALSE(client.is_open());
  23065. // Reconnect using the same client object
  23066. ASSERT_TRUE(client.connect());
  23067. ASSERT_TRUE(client.is_open());
  23068. ASSERT_TRUE(client.send("second"));
  23069. ASSERT_TRUE(client.read(msg));
  23070. EXPECT_EQ("second", msg);
  23071. client.close();
  23072. }
  23073. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23074. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23075. "/ws-close-status");
  23076. ASSERT_TRUE(client.connect());
  23077. // Trigger the server to close with GoingAway status
  23078. ASSERT_TRUE(client.send("trigger"));
  23079. // read() should return false after receiving the close frame
  23080. std::string msg;
  23081. EXPECT_FALSE(client.read(msg));
  23082. EXPECT_FALSE(client.is_open());
  23083. }
  23084. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23085. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23086. "/ws-echo");
  23087. ASSERT_TRUE(client.connect());
  23088. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23089. EXPECT_FALSE(client.is_open());
  23090. }
  23091. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23092. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23093. ws::WebSocketClient client(
  23094. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23095. ASSERT_TRUE(client.connect());
  23096. // Server should have selected graphql-ws
  23097. EXPECT_EQ("graphql-ws", client.subprotocol());
  23098. client.close();
  23099. }
  23100. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23101. Headers headers;
  23102. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23103. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23104. ws::WebSocketClient client(
  23105. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23106. ASSERT_TRUE(client.connect());
  23107. // The offer on the second field line counts too, so graphql-ws is selected
  23108. EXPECT_EQ("graphql-ws", client.subprotocol());
  23109. client.close();
  23110. }
  23111. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23112. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23113. ws::WebSocketClient client(
  23114. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23115. ASSERT_TRUE(client.connect());
  23116. // Server should not have selected any subprotocol
  23117. EXPECT_TRUE(client.subprotocol().empty());
  23118. client.close();
  23119. }
  23120. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23121. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23122. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23123. "/ws-subprotocol-unoffered",
  23124. headers);
  23125. ASSERT_TRUE(client.connect());
  23126. EXPECT_TRUE(client.subprotocol().empty());
  23127. client.close();
  23128. }
  23129. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23130. // Connect without requesting any subprotocol
  23131. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23132. "/ws-subprotocol");
  23133. ASSERT_TRUE(client.connect());
  23134. EXPECT_TRUE(client.subprotocol().empty());
  23135. client.close();
  23136. }
  23137. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23138. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23139. "/ws-echo");
  23140. client.set_tcp_nodelay(true);
  23141. client.set_connection_timeout(3, 0);
  23142. bool socket_options_called = false;
  23143. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23144. ASSERT_TRUE(client.connect());
  23145. ASSERT_TRUE(client.is_open());
  23146. EXPECT_TRUE(socket_options_called);
  23147. ASSERT_TRUE(client.send("hello"));
  23148. std::string msg;
  23149. auto result = client.read(msg);
  23150. EXPECT_EQ(result, ws::ReadResult::Text);
  23151. EXPECT_EQ(msg, "hello");
  23152. client.close();
  23153. }
  23154. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23155. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23156. "/ws-echo");
  23157. client.set_connection_timeout(std::chrono::seconds(3));
  23158. client.set_write_timeout(std::chrono::seconds(3));
  23159. // A sub-second remainder exercises the seconds/microseconds split.
  23160. client.set_read_timeout(std::chrono::milliseconds(1500));
  23161. ASSERT_TRUE(client.connect());
  23162. auto start = std::chrono::steady_clock::now();
  23163. std::string msg;
  23164. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23165. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23166. std::chrono::steady_clock::now() - start)
  23167. .count();
  23168. // Above 1s so that dropping the microseconds half of the split fails here.
  23169. // Ignoring the setter altogether would not reach this line at all: a client
  23170. // waits forever by default.
  23171. EXPECT_GE(elapsed, 1400);
  23172. EXPECT_LT(elapsed, 30000);
  23173. }
  23174. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23175. Server svr;
  23176. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23177. if (!req.has_header("Authorization")) {
  23178. res.status = StatusCode::Unauthorized_401;
  23179. res.set_content("Unauthorized", "text/plain");
  23180. return Server::HandlerResponse::Handled;
  23181. }
  23182. return Server::HandlerResponse::Unhandled;
  23183. });
  23184. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23185. std::string msg;
  23186. while (ws.read(msg)) {
  23187. ws.send(msg);
  23188. }
  23189. });
  23190. auto port = svr.bind_to_any_port("localhost");
  23191. std::thread t([&]() { svr.listen_after_bind(); });
  23192. svr.wait_until_ready();
  23193. // Without Authorization header - should be rejected before upgrade
  23194. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23195. EXPECT_FALSE(client1.connect());
  23196. // The rejection is framed like any other HTTP response
  23197. {
  23198. Client cli("localhost", port);
  23199. Headers headers = {{"Upgrade", "websocket"},
  23200. {"Connection", "Upgrade"},
  23201. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23202. {"Sec-WebSocket-Version", "13"}};
  23203. auto res = cli.Get("/ws", headers);
  23204. ASSERT_TRUE(res);
  23205. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23206. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23207. EXPECT_EQ("Unauthorized", res->body);
  23208. }
  23209. // With Authorization header - should succeed
  23210. Headers headers = {{"Authorization", "Bearer token123"}};
  23211. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23212. headers);
  23213. ASSERT_TRUE(client2.connect());
  23214. ASSERT_TRUE(client2.send("hello"));
  23215. std::string msg;
  23216. ASSERT_TRUE(client2.read(msg));
  23217. EXPECT_EQ("hello", msg);
  23218. client2.close();
  23219. svr.stop();
  23220. t.join();
  23221. }
  23222. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23223. Server svr;
  23224. std::atomic<int> pre_routing_calls{0};
  23225. std::atomic<int> pre_request_calls{0};
  23226. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23227. pre_routing_calls++;
  23228. if (req.path == "/handled") {
  23229. res.set_content("handled", "text/plain");
  23230. return Server::HandlerResponse::Handled;
  23231. }
  23232. return Server::HandlerResponse::Unhandled;
  23233. });
  23234. svr.set_pre_request_handler([&](const Request &, Response &) {
  23235. pre_request_calls++;
  23236. return Server::HandlerResponse::Unhandled;
  23237. });
  23238. svr.Get("/http", [](const Request &, Response &res) {
  23239. res.set_content("http", "text/plain");
  23240. });
  23241. svr.WebSocket("/ws",
  23242. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23243. auto port = svr.bind_to_any_port("localhost");
  23244. std::thread t([&]() { svr.listen_after_bind(); });
  23245. auto se = detail::scope_exit([&] {
  23246. svr.stop();
  23247. t.join();
  23248. });
  23249. svr.wait_until_ready();
  23250. Headers upgrade = {{"Upgrade", "websocket"},
  23251. {"Connection", "Upgrade"},
  23252. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23253. {"Sec-WebSocket-Version", "13"}};
  23254. auto get = [&](const char *path) {
  23255. pre_routing_calls = 0;
  23256. return Client("localhost", port).Get(path, upgrade);
  23257. };
  23258. // No WebSocket route, but an HTTP one
  23259. auto res = get("/http");
  23260. ASSERT_TRUE(res);
  23261. EXPECT_EQ(StatusCode::OK_200, res->status);
  23262. EXPECT_EQ("http", res->body);
  23263. EXPECT_EQ(1, pre_routing_calls);
  23264. EXPECT_EQ(1, pre_request_calls);
  23265. // No route at all
  23266. res = get("/none");
  23267. ASSERT_TRUE(res);
  23268. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23269. EXPECT_EQ(1, pre_routing_calls);
  23270. // Answered by the pre-routing handler
  23271. res = get("/handled");
  23272. ASSERT_TRUE(res);
  23273. EXPECT_EQ(StatusCode::OK_200, res->status);
  23274. EXPECT_EQ("handled", res->body);
  23275. EXPECT_EQ(1, pre_routing_calls);
  23276. // A WebSocket route
  23277. pre_routing_calls = 0;
  23278. pre_request_calls = 0;
  23279. {
  23280. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23281. "/ws");
  23282. ASSERT_TRUE(client.connect());
  23283. std::string msg;
  23284. ASSERT_TRUE(client.read(msg));
  23285. EXPECT_EQ("ws", msg);
  23286. client.close();
  23287. }
  23288. EXPECT_EQ(1, pre_routing_calls);
  23289. EXPECT_EQ(1, pre_request_calls);
  23290. }
  23291. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23292. Server svr;
  23293. std::atomic<int> pre_request_calls{0};
  23294. std::atomic<bool> route_matched{false};
  23295. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23296. pre_request_calls++;
  23297. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23298. if (req.get_header_value("Authorization") != "Bearer token123") {
  23299. res.status = StatusCode::Unauthorized_401;
  23300. res.set_content("Unauthorized", "text/plain");
  23301. return Server::HandlerResponse::Handled;
  23302. }
  23303. return Server::HandlerResponse::Unhandled;
  23304. });
  23305. std::atomic<bool> handler_called{false};
  23306. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23307. handler_called = true;
  23308. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23309. });
  23310. auto port = svr.bind_to_any_port("localhost");
  23311. std::thread t([&]() { svr.listen_after_bind(); });
  23312. svr.wait_until_ready();
  23313. // Without Authorization header - should be rejected before upgrade
  23314. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23315. "/ws/1");
  23316. EXPECT_FALSE(client1.connect());
  23317. EXPECT_FALSE(handler_called);
  23318. EXPECT_EQ(1, pre_request_calls);
  23319. EXPECT_TRUE(route_matched);
  23320. // The rejection is an ordinary HTTP response, not a protocol switch
  23321. {
  23322. Client cli("localhost", port);
  23323. Headers headers = {{"Upgrade", "websocket"},
  23324. {"Connection", "Upgrade"},
  23325. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23326. {"Sec-WebSocket-Version", "13"}};
  23327. auto res = cli.Get("/ws/1", headers);
  23328. ASSERT_TRUE(res);
  23329. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23330. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23331. EXPECT_EQ("Unauthorized", res->body);
  23332. }
  23333. EXPECT_FALSE(handler_called);
  23334. // With Authorization header - should succeed
  23335. Headers headers = {{"Authorization", "Bearer token123"}};
  23336. ws::WebSocketClient client2(
  23337. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23338. ASSERT_TRUE(client2.connect());
  23339. std::string msg;
  23340. ASSERT_TRUE(client2.read(msg));
  23341. EXPECT_EQ("/ws/:id 2", msg);
  23342. EXPECT_TRUE(handler_called);
  23343. client2.close();
  23344. svr.stop();
  23345. t.join();
  23346. }
  23347. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23348. Server svr;
  23349. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23350. // A read timeout is how a handler gets control back. Without it, a handler
  23351. // parked in read() can never write on the connection it is reading.
  23352. ws.set_read_timeout(std::chrono::milliseconds(100));
  23353. std::string msg;
  23354. while (ws.is_open()) {
  23355. auto r = ws.read(msg);
  23356. if (r == httplib::ws::Timeout) {
  23357. ws.send("tick");
  23358. continue;
  23359. }
  23360. if (r == httplib::ws::Fail) { break; }
  23361. ws.send(msg);
  23362. }
  23363. });
  23364. auto port = svr.bind_to_any_port("localhost");
  23365. std::thread t([&]() { svr.listen_after_bind(); });
  23366. svr.wait_until_ready();
  23367. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23368. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23369. ASSERT_TRUE(client.connect());
  23370. // The client sends nothing, so anything it receives came out of the
  23371. // handler's timeout path.
  23372. std::string msg;
  23373. ASSERT_EQ(client.read(msg), ws::Text);
  23374. EXPECT_EQ("tick", msg);
  23375. client.close();
  23376. svr.stop();
  23377. t.join();
  23378. }
  23379. // Stream::read may return fewer bytes than asked for. This is that contract at
  23380. // its worst -- one byte per call -- which is what a frame header straddling a
  23381. // read buffer's boundary looks like to the frame parser.
  23382. class WsByteAtATimeStream : public Stream {
  23383. public:
  23384. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23385. bool is_readable() const override { return true; }
  23386. bool wait_readable() const override { return true; }
  23387. bool wait_writable() const override { return true; }
  23388. ssize_t read(char *ptr, size_t size) override {
  23389. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23390. *ptr = data_[pos_++];
  23391. return 1;
  23392. }
  23393. ssize_t write(const char *, size_t size) override {
  23394. return static_cast<ssize_t>(size);
  23395. }
  23396. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23397. ip = "127.0.0.1";
  23398. port = 0;
  23399. }
  23400. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23401. ip = "127.0.0.1";
  23402. port = 0;
  23403. }
  23404. socket_t socket() const override { return INVALID_SOCKET; }
  23405. time_t duration() const override { return 0; }
  23406. private:
  23407. std::string data_;
  23408. size_t pos_ = 0;
  23409. };
  23410. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23411. // The payload uses the 16-bit extended length, so the header, the length
  23412. // and the mask key are all multi-byte fields here. Each used to be read
  23413. // with a single read() call, which fails as soon as one is split. The
  23414. // payload is also a little over one read chunk, so it is read in two.
  23415. std::string body;
  23416. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23417. body += static_cast<char>(i % 251);
  23418. }
  23419. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23420. std::string frame;
  23421. frame += static_cast<char>(0x81); // FIN + Text
  23422. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23423. frame += static_cast<char>(body.size() >> 8);
  23424. frame += static_cast<char>(body.size() & 0xff);
  23425. for (size_t i = 0; i < 4; i++) {
  23426. frame += static_cast<char>(mask[i]);
  23427. }
  23428. for (size_t i = 0; i < body.size(); i++) {
  23429. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23430. }
  23431. WsByteAtATimeStream strm(frame);
  23432. ws::Opcode opcode;
  23433. std::string payload;
  23434. bool fin = false;
  23435. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23436. /*expect_masked=*/true, body.size()),
  23437. ws::impl::FrameRead::Ok);
  23438. EXPECT_TRUE(fin);
  23439. EXPECT_EQ(opcode, ws::Opcode::Text);
  23440. EXPECT_EQ(payload, body);
  23441. }
  23442. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23443. std::string body(2000, 'x');
  23444. std::string frame;
  23445. frame += static_cast<char>(0x82); // FIN + Binary
  23446. frame += static_cast<char>(126); // 16-bit length follows
  23447. frame += static_cast<char>(body.size() >> 8);
  23448. frame += static_cast<char>(body.size() & 0xff);
  23449. frame += body;
  23450. detail::BufferStream strm;
  23451. strm.write(frame.data(), frame.size());
  23452. ws::Opcode opcode;
  23453. std::string payload;
  23454. bool fin;
  23455. EXPECT_EQ(
  23456. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23457. ws::impl::FrameRead::Ok);
  23458. EXPECT_EQ(body, payload);
  23459. }
  23460. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23461. // The header announces the largest payload allowed, and only 3 bytes of it
  23462. // ever arrive.
  23463. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23464. std::string frame;
  23465. frame += static_cast<char>(0x82); // FIN + Binary
  23466. frame += static_cast<char>(127); // 64-bit length follows
  23467. for (int shift = 56; shift >= 0; shift -= 8) {
  23468. frame += static_cast<char>((len >> shift) & 0xff);
  23469. }
  23470. frame += "abc";
  23471. detail::BufferStream strm;
  23472. strm.write(frame.data(), frame.size());
  23473. ws::Opcode opcode;
  23474. std::string payload;
  23475. bool fin;
  23476. EXPECT_EQ(
  23477. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23478. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23479. ws::impl::FrameRead::Fail);
  23480. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23481. }
  23482. TEST(WebSocketTest, QueryStringInHandshake) {
  23483. Server svr;
  23484. std::mutex mtx;
  23485. std::string received_target;
  23486. std::string received_token;
  23487. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23488. {
  23489. std::lock_guard<std::mutex> lock(mtx);
  23490. received_target = req.target;
  23491. if (req.has_param("token")) {
  23492. received_token = req.get_param_value("token");
  23493. }
  23494. }
  23495. std::string msg;
  23496. while (ws.read(msg)) {
  23497. ws.send(msg);
  23498. }
  23499. });
  23500. auto port = svr.bind_to_any_port("localhost");
  23501. std::thread t([&]() { svr.listen_after_bind(); });
  23502. svr.wait_until_ready();
  23503. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23504. "/ws?token=ABC&session=123");
  23505. ASSERT_TRUE(client.connect());
  23506. // Round-trip ensures the handler has run and captured the request.
  23507. ASSERT_TRUE(client.send("hello"));
  23508. std::string msg;
  23509. ASSERT_TRUE(client.read(msg));
  23510. EXPECT_EQ("hello", msg);
  23511. client.close();
  23512. {
  23513. std::lock_guard<std::mutex> lock(mtx);
  23514. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23515. EXPECT_EQ("ABC", received_token);
  23516. }
  23517. svr.stop();
  23518. t.join();
  23519. }
  23520. // Run a handshake against a throwaway server and hand the request the server
  23521. // received back to the caller, so tests can assert on the headers the client
  23522. // actually put on the wire.
  23523. static void capture_websocket_handshake_request(
  23524. const Headers &client_headers,
  23525. std::function<void(const Request &, int port)> verify) {
  23526. Server svr;
  23527. std::mutex mtx;
  23528. Request received;
  23529. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23530. {
  23531. std::lock_guard<std::mutex> lock(mtx);
  23532. received = req;
  23533. }
  23534. std::string msg;
  23535. while (ws.read(msg)) {
  23536. ws.send(msg);
  23537. }
  23538. });
  23539. auto port = svr.bind_to_any_port("localhost");
  23540. std::thread t([&]() { svr.listen_after_bind(); });
  23541. auto se = detail::scope_exit([&] {
  23542. svr.stop();
  23543. t.join();
  23544. });
  23545. svr.wait_until_ready();
  23546. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23547. client_headers);
  23548. ASSERT_TRUE(client.connect());
  23549. ASSERT_TRUE(client.send("hello"));
  23550. std::string msg;
  23551. ASSERT_TRUE(client.read(msg));
  23552. client.close();
  23553. {
  23554. std::lock_guard<std::mutex> lock(mtx);
  23555. verify(received, port);
  23556. }
  23557. }
  23558. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23559. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23560. // Non-default port must be present in the Host header. Default ports
  23561. // (80/443) are omitted; that logic is covered by
  23562. // MakeHostAndPortStringTest.
  23563. EXPECT_EQ("localhost:" + std::to_string(port),
  23564. req.get_header_value("Host"));
  23565. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23566. req.get_header_value("User-Agent"));
  23567. EXPECT_FALSE(req.has_header("Accept"));
  23568. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23569. EXPECT_FALSE(req.has_header("Content-Length"));
  23570. });
  23571. }
  23572. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23573. capture_websocket_handshake_request(
  23574. {{"Host", "example.com"},
  23575. {"User-Agent", "custom-agent"},
  23576. {"X-Custom", "value"}},
  23577. [](const Request &req, int) {
  23578. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23579. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23580. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23581. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23582. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23583. });
  23584. }
  23585. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23586. capture_websocket_handshake_request(
  23587. {{"Upgrade", "bogus"},
  23588. {"Connection", "close"},
  23589. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23590. {"Sec-WebSocket-Version", "8"}},
  23591. [](const Request &req, int) {
  23592. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23593. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23594. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23595. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23596. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23597. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23598. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23599. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23600. req.get_header_value("Sec-WebSocket-Key"));
  23601. });
  23602. }
  23603. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23604. // A header the client refuses to send must abort the handshake before any
  23605. // part of it reaches the wire; a lone request line would otherwise sit in
  23606. // the peer's buffer as a truncated request.
  23607. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23608. ASSERT_NE(INVALID_SOCKET, srv);
  23609. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23610. sockaddr_in addr{};
  23611. addr.sin_family = AF_INET;
  23612. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23613. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23614. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23615. ASSERT_EQ(0, ::listen(srv, 1));
  23616. sockaddr_in bound{};
  23617. socklen_t bound_len = sizeof(bound);
  23618. ASSERT_EQ(
  23619. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23620. auto port = ntohs(bound.sin_port);
  23621. ssize_t received = -1;
  23622. std::thread t([&] {
  23623. // Bound every blocking call so a regression fails the test with a bad
  23624. // value instead of hanging the suite.
  23625. fd_set rfds;
  23626. FD_ZERO(&rfds);
  23627. FD_SET(srv, &rfds);
  23628. timeval tv{5, 0};
  23629. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23630. 0) {
  23631. return;
  23632. }
  23633. sockaddr_in cli_addr{};
  23634. socklen_t cli_len = sizeof(cli_addr);
  23635. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23636. if (cli == INVALID_SOCKET) { return; }
  23637. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23638. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23639. char buf[4096];
  23640. received = ::recv(cli, buf, sizeof(buf), 0);
  23641. });
  23642. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23643. // connect() has already shut the socket down by the time it returns false,
  23644. // so the peer sees EOF without waiting for the client to be destroyed.
  23645. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23646. {{"X-Bad", "a\r\nInjected: 1"}});
  23647. EXPECT_FALSE(client.connect());
  23648. t.join();
  23649. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23650. EXPECT_EQ(0, received);
  23651. }
  23652. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23653. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23654. // contains "upgrade" as a substring is a different token and must not
  23655. // start a WebSocket handshake.
  23656. auto make_request = [](const std::vector<std::string> &connection_values) {
  23657. Request req;
  23658. req.method = "GET";
  23659. req.headers.emplace("Upgrade", "websocket");
  23660. for (const auto &value : connection_values) {
  23661. req.headers.emplace("Connection", value);
  23662. }
  23663. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23664. req.headers.emplace("Sec-WebSocket-Version", "13");
  23665. return req;
  23666. };
  23667. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23668. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23669. EXPECT_TRUE(
  23670. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23671. EXPECT_TRUE(
  23672. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23673. EXPECT_TRUE(
  23674. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23675. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23676. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23677. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23678. EXPECT_FALSE(
  23679. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23680. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23681. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23682. }
  23683. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23684. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23685. // asks recipients to match each protocol-name case-insensitively, and RFC
  23686. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23687. // client naming websocket alongside another protocol, or on a second field
  23688. // line, is offering websocket; a value that merely contains "websocket" as a
  23689. // substring is a different protocol name and is not.
  23690. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23691. Request req;
  23692. req.method = "GET";
  23693. for (const auto &value : upgrade_values) {
  23694. req.headers.emplace("Upgrade", value);
  23695. }
  23696. req.headers.emplace("Connection", "Upgrade");
  23697. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23698. req.headers.emplace("Sec-WebSocket-Version", "13");
  23699. return req;
  23700. };
  23701. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23702. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23703. EXPECT_TRUE(
  23704. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23705. EXPECT_TRUE(
  23706. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23707. EXPECT_TRUE(
  23708. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23709. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23710. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23711. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23712. EXPECT_FALSE(
  23713. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23714. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23715. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23716. }
  23717. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23718. Server svr;
  23719. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23720. auto port = svr.bind_to_any_port("localhost");
  23721. std::thread t([&]() { svr.listen_after_bind(); });
  23722. auto se = detail::scope_exit([&] {
  23723. svr.stop();
  23724. t.join();
  23725. });
  23726. svr.wait_until_ready();
  23727. Headers headers = {{"Upgrade", "websocket"},
  23728. {"Connection", "notupgrade"},
  23729. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23730. {"Sec-WebSocket-Version", "13"}};
  23731. Client cli("localhost", port);
  23732. auto res = cli.Get("/ws", headers);
  23733. // The route exists only as a WebSocket route, so a request that fails the
  23734. // handshake check falls through to ordinary routing.
  23735. ASSERT_TRUE(res);
  23736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23737. }
  23738. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23739. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23740. // Connection value is the only thing left for the client to reject.
  23741. Server svr;
  23742. svr.Get("/ws", [](const Request &req, Response &res) {
  23743. res.status = StatusCode::SwitchingProtocol_101;
  23744. res.set_header("Upgrade", "websocket");
  23745. res.set_header("Connection", "notupgrade");
  23746. res.set_header("Sec-WebSocket-Accept",
  23747. detail::websocket_accept_key(
  23748. req.get_header_value("Sec-WebSocket-Key")));
  23749. });
  23750. auto port = svr.bind_to_any_port("localhost");
  23751. std::thread t([&]() { svr.listen_after_bind(); });
  23752. auto se = detail::scope_exit([&] {
  23753. svr.stop();
  23754. t.join();
  23755. });
  23756. svr.wait_until_ready();
  23757. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23758. auto res = client.connect();
  23759. EXPECT_FALSE(res);
  23760. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23761. EXPECT_FALSE(client.is_open());
  23762. }
  23763. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23764. Server svr;
  23765. svr.Get("/ws", [](const Request &req, Response &res) {
  23766. res.status = StatusCode::SwitchingProtocol_101;
  23767. res.set_header("Upgrade", "websocket");
  23768. res.set_header("Connection", "Upgrade");
  23769. res.set_header("Sec-WebSocket-Accept",
  23770. detail::websocket_accept_key(
  23771. req.get_header_value("Sec-WebSocket-Key")));
  23772. res.set_header("Sec-WebSocket-Protocol", "admin");
  23773. });
  23774. auto port = svr.bind_to_any_port("localhost");
  23775. std::thread t([&]() { svr.listen_after_bind(); });
  23776. auto se = detail::scope_exit([&] {
  23777. svr.stop();
  23778. t.join();
  23779. });
  23780. svr.wait_until_ready();
  23781. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23782. // Server selects a subprotocol the client never offered
  23783. {
  23784. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23785. ws::WebSocketClient client(url, headers);
  23786. auto res = client.connect();
  23787. EXPECT_FALSE(res);
  23788. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23789. EXPECT_FALSE(client.is_open());
  23790. EXPECT_TRUE(client.subprotocol().empty());
  23791. }
  23792. // Client offered none but the server named one anyway
  23793. {
  23794. ws::WebSocketClient client(url);
  23795. auto res = client.connect();
  23796. EXPECT_FALSE(res);
  23797. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23798. EXPECT_FALSE(client.is_open());
  23799. EXPECT_TRUE(client.subprotocol().empty());
  23800. }
  23801. }
  23802. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23803. // The socket path doubles as the URL host, so it must not contain '/'.
  23804. const char *shard = getenv("GTEST_SHARD_INDEX");
  23805. const std::string sock_path =
  23806. shard ? std::string("httplib-ws-") + shard + ".sock"
  23807. : std::string("httplib-ws.sock");
  23808. std::remove(sock_path.c_str());
  23809. Server svr;
  23810. std::mutex mtx;
  23811. std::string received_host;
  23812. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23813. {
  23814. std::lock_guard<std::mutex> lock(mtx);
  23815. received_host = req.get_header_value("Host");
  23816. }
  23817. std::string msg;
  23818. while (ws.read(msg)) {
  23819. ws.send(msg);
  23820. }
  23821. });
  23822. svr.set_address_family(AF_UNIX);
  23823. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23824. auto se = detail::scope_exit([&] {
  23825. svr.stop();
  23826. t.join();
  23827. std::remove(sock_path.c_str());
  23828. });
  23829. svr.wait_until_ready();
  23830. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23831. client.set_address_family(AF_UNIX);
  23832. ASSERT_TRUE(client.connect());
  23833. ASSERT_TRUE(client.send("hello"));
  23834. std::string msg;
  23835. ASSERT_TRUE(client.read(msg));
  23836. client.close();
  23837. {
  23838. std::lock_guard<std::mutex> lock(mtx);
  23839. // There is no host:port for a Unix socket, so the same "localhost"
  23840. // placeholder the HTTP client uses is expected.
  23841. EXPECT_EQ("localhost", received_host);
  23842. }
  23843. }
  23844. // Two threads must never parse WebSocket frames from the same stream.
  23845. // close() used to read the peer's Close reply with its own frame read, so it
  23846. // raced a reader thread that was in the middle of a payload: the payload loop
  23847. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23848. // so bytes taken by close() were replaced with bytes from further along the
  23849. // stream. The message kept its length and silently changed content.
  23850. //
  23851. // The raw peer below sends a frame header plus part of the payload, waits for
  23852. // the handler to call close(), and only then sends the rest. Whichever thread
  23853. // would win the race for those bytes, the message must arrive intact, because
  23854. // close() must not touch the stream while read() owns it.
  23855. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23856. #ifndef _WIN32
  23857. signal(SIGPIPE, SIG_IGN);
  23858. #endif
  23859. const size_t payload_len = 120; // fits the 7-bit length field
  23860. const size_t prefix_len = 8;
  23861. const int attempts = 8;
  23862. std::string expected(payload_len, '\0');
  23863. for (size_t i = 0; i < payload_len; i++) {
  23864. expected[i] = static_cast<char>('a' + i % 26);
  23865. }
  23866. std::atomic<bool> peer_stalled{false};
  23867. std::atomic<bool> handler_done{false};
  23868. std::mutex received_mutex;
  23869. std::vector<std::string> received;
  23870. // Bound every wait, so a regression fails the test instead of hanging the
  23871. // suite.
  23872. auto wait_for = [](const std::atomic<bool> &flag) {
  23873. for (int i = 0; i < 500 && !flag; i++) {
  23874. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23875. }
  23876. };
  23877. Server svr;
  23878. svr.set_websocket_ping_interval(0);
  23879. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23880. std::thread reader([&]() {
  23881. std::string msg;
  23882. while (ws.read(msg)) {
  23883. std::lock_guard<std::mutex> guard(received_mutex);
  23884. received.push_back(msg);
  23885. }
  23886. });
  23887. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23888. // inside read_websocket_frame() when close() runs.
  23889. wait_for(peer_stalled);
  23890. ws.close();
  23891. reader.join();
  23892. handler_done = true;
  23893. });
  23894. auto port = svr.bind_to_any_port("127.0.0.1");
  23895. std::thread t([&]() { svr.listen_after_bind(); });
  23896. auto se = detail::scope_exit([&] {
  23897. svr.stop();
  23898. t.join();
  23899. });
  23900. svr.wait_until_ready();
  23901. auto send_bytes = [](socket_t s, const std::string &data) {
  23902. #ifdef _WIN32
  23903. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23904. #else
  23905. auto n = ::send(s, data.data(), data.size(), 0);
  23906. #endif
  23907. return n == static_cast<decltype(n)>(data.size());
  23908. };
  23909. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23910. // Every length used here fits the 7-bit length field.
  23911. auto masked_header = [](uint8_t first_byte, size_t len) {
  23912. std::string h;
  23913. h += static_cast<char>(first_byte);
  23914. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23915. h.append(4, '\0'); // mask key
  23916. return h;
  23917. };
  23918. for (int attempt = 0; attempt < attempts; attempt++) {
  23919. peer_stalled = false;
  23920. handler_done = false;
  23921. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23922. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23923. auto se_sock = detail::scope_exit([&] {
  23924. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23925. });
  23926. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23927. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23928. sockaddr_in addr{};
  23929. addr.sin_family = AF_INET;
  23930. addr.sin_port = htons(static_cast<uint16_t>(port));
  23931. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23932. ASSERT_EQ(
  23933. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23934. << "attempt " << attempt;
  23935. ASSERT_TRUE(send_bytes(sock,
  23936. "GET /ws HTTP/1.1\r\n"
  23937. "Host: 127.0.0.1\r\n"
  23938. "Upgrade: websocket\r\n"
  23939. "Connection: Upgrade\r\n"
  23940. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23941. "Sec-WebSocket-Version: 13\r\n"
  23942. "\r\n"))
  23943. << "attempt " << attempt;
  23944. std::string response;
  23945. while (response.find("\r\n\r\n") == std::string::npos) {
  23946. char buf[512];
  23947. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23948. if (n <= 0) { break; }
  23949. response.append(buf, static_cast<size_t>(n));
  23950. }
  23951. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23952. << "attempt " << attempt;
  23953. // Send the header of a Binary message but only the first prefix_len bytes
  23954. // of its payload, leaving the reader thread stalled inside the payload.
  23955. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23956. expected.substr(0, prefix_len)))
  23957. << "attempt " << attempt;
  23958. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23959. peer_stalled = true;
  23960. // Let close() send its Close frame and park in its own read before the
  23961. // rest of the payload arrives, so both threads are waiting for it.
  23962. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23963. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23964. close_frame += static_cast<char>(0x03); // status 1000
  23965. close_frame += static_cast<char>(0xE8);
  23966. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23967. << "attempt " << attempt;
  23968. // Closing the peer releases the reader thread even on the buggy path,
  23969. // where it waits for bytes another thread already consumed.
  23970. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23971. detail::close_socket(sock);
  23972. sock = INVALID_SOCKET;
  23973. wait_for(handler_done);
  23974. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23975. }
  23976. std::lock_guard<std::mutex> guard(received_mutex);
  23977. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23978. << "a message in flight when close() ran was dropped";
  23979. for (size_t i = 0; i < received.size(); i++) {
  23980. EXPECT_EQ(expected, received[i]) << "message " << i;
  23981. }
  23982. }
  23983. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23984. // returning the socket, or INVALID_SOCKET.
  23985. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23986. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23987. if (sock == INVALID_SOCKET) { return sock; }
  23988. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23989. sockaddr_in addr{};
  23990. addr.sin_family = AF_INET;
  23991. addr.sin_port = htons(static_cast<uint16_t>(port));
  23992. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23993. std::string req = "GET " + path +
  23994. " HTTP/1.1\r\n"
  23995. "Host: 127.0.0.1\r\n"
  23996. "Upgrade: websocket\r\n"
  23997. "Connection: Upgrade\r\n"
  23998. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23999. "Sec-WebSocket-Version: 13\r\n"
  24000. "\r\n";
  24001. std::string res;
  24002. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24003. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24004. static_cast<ssize_t>(req.size())) {
  24005. char c;
  24006. while (res.find("\r\n\r\n") == std::string::npos &&
  24007. ::recv(sock, &c, 1, 0) == 1) {
  24008. res += c;
  24009. }
  24010. }
  24011. if (res.find(" 101 ") == std::string::npos) {
  24012. detail::close_socket(sock);
  24013. return INVALID_SOCKET;
  24014. }
  24015. return sock;
  24016. }
  24017. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24018. // The payload must fit the 7-bit length field.
  24019. static std::string masked_frame(uint8_t first_byte,
  24020. const std::string &payload) {
  24021. std::string f;
  24022. f += static_cast<char>(first_byte);
  24023. f += static_cast<char>(0x80 | payload.size());
  24024. f.append(4, '\0');
  24025. return f + payload;
  24026. }
  24027. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24028. std::atomic<bool> done{false};
  24029. std::string received;
  24030. Server svr;
  24031. svr.set_websocket_ping_interval(0);
  24032. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24033. std::string msg;
  24034. if (ws.read(msg) == ws::Binary) { received = msg; }
  24035. done = true;
  24036. });
  24037. auto port = svr.bind_to_any_port("127.0.0.1");
  24038. std::thread t([&]() { svr.listen_after_bind(); });
  24039. auto se = detail::scope_exit([&] {
  24040. svr.stop();
  24041. t.join();
  24042. });
  24043. svr.wait_until_ready();
  24044. auto sock = connect_raw_websocket(port, "/ws");
  24045. ASSERT_NE(INVALID_SOCKET, sock);
  24046. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24047. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24048. masked_frame(0x89, "p") + // FIN + Ping
  24049. masked_frame(0x80, "lo"); // FIN + Continuation
  24050. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24051. for (int i = 0; i < 500 && !done; i++) {
  24052. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24053. }
  24054. ASSERT_TRUE(done);
  24055. EXPECT_EQ("Hello", received);
  24056. // The Ping between the fragments is answered with a Pong.
  24057. char pong[3];
  24058. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24059. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24060. }
  24061. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24062. Server svr;
  24063. svr.set_websocket_ping_interval(-1);
  24064. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24065. std::string msg;
  24066. while (ws.read(msg)) {}
  24067. });
  24068. auto port = svr.bind_to_any_port("127.0.0.1");
  24069. std::thread t([&]() { svr.listen_after_bind(); });
  24070. auto se = detail::scope_exit([&] {
  24071. svr.stop();
  24072. t.join();
  24073. });
  24074. svr.wait_until_ready();
  24075. auto sock = connect_raw_websocket(port, "/ws");
  24076. ASSERT_NE(INVALID_SOCKET, sock);
  24077. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24078. // Nothing comes while the client stays quiet.
  24079. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24080. char c;
  24081. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24082. }
  24083. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24084. // and that has to end a read() already waiting on the peer, on every platform.
  24085. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24086. // The peer sends no pings, and its handler never calls read(), which is
  24087. // where pongs are written.
  24088. std::mutex mutex;
  24089. std::condition_variable cv;
  24090. auto release = false;
  24091. svr.set_websocket_ping_interval(0);
  24092. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24093. std::unique_lock<std::mutex> lock(mutex);
  24094. cv.wait(lock, [&] { return release; });
  24095. });
  24096. auto port = svr.bind_to_any_port(HOST);
  24097. std::thread t([&]() { svr.listen_after_bind(); });
  24098. auto se = detail::scope_exit([&] {
  24099. {
  24100. std::lock_guard<std::mutex> lock(mutex);
  24101. release = true;
  24102. }
  24103. cv.notify_all();
  24104. svr.stop();
  24105. t.join();
  24106. });
  24107. svr.wait_until_ready();
  24108. ws::WebSocketClient client(std::string(scheme) +
  24109. "://localhost:" + std::to_string(port) + "/ws");
  24110. #ifdef CPPHTTPLIB_SSL_ENABLED
  24111. client.enable_server_certificate_verification(false);
  24112. #endif
  24113. // A ping a second, given up on after two go unanswered: about 3s
  24114. client.set_websocket_ping_interval(1);
  24115. client.set_websocket_max_missed_pongs(2);
  24116. // Well past that, so that a read the timeout ends instead stands out
  24117. client.set_read_timeout(10);
  24118. ASSERT_TRUE(client.connect());
  24119. auto start = std::chrono::steady_clock::now();
  24120. std::string msg;
  24121. EXPECT_EQ(ws::Fail, client.read(msg));
  24122. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24123. std::chrono::steady_clock::now() - start)
  24124. .count(),
  24125. 6000);
  24126. EXPECT_FALSE(client.is_open());
  24127. }
  24128. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24129. Server svr;
  24130. check_pong_timeout_ends_read(svr, "ws");
  24131. }
  24132. #ifdef CPPHTTPLIB_SSL_ENABLED
  24133. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24135. ASSERT_TRUE(svr.is_valid());
  24136. check_pong_timeout_ends_read(svr, "wss");
  24137. }
  24138. #endif
  24139. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24140. Server svr;
  24141. svr.set_websocket_ping_interval(0);
  24142. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24143. std::string msg;
  24144. while (ws.read(msg)) {}
  24145. });
  24146. auto port = svr.bind_to_any_port("127.0.0.1");
  24147. std::thread t([&]() { svr.listen_after_bind(); });
  24148. auto se = detail::scope_exit([&] {
  24149. svr.stop();
  24150. t.join();
  24151. });
  24152. svr.wait_until_ready();
  24153. // Each Close payload and the reply it should get: an echo when valid, 1002
  24154. // otherwise.
  24155. std::vector<std::pair<std::string, std::string>> cases = {
  24156. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24157. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24158. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24159. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24160. };
  24161. // Also between the fragments of a message.
  24162. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24163. for (const auto &c : cases) {
  24164. auto sock = connect_raw_websocket(port, "/ws");
  24165. ASSERT_NE(INVALID_SOCKET, sock);
  24166. auto frames = prefix + masked_frame(0x88, c.first);
  24167. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24168. std::string reply;
  24169. char buf[256];
  24170. while (reply.size() < 2 + c.second.size()) {
  24171. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24172. if (n <= 0) { break; }
  24173. reply.append(buf, static_cast<size_t>(n));
  24174. }
  24175. detail::close_socket(sock);
  24176. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24177. c.second,
  24178. reply);
  24179. }
  24180. }
  24181. }
  24182. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24183. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24184. protected:
  24185. void SetUp() override {
  24186. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24187. SERVER_PRIVATE_KEY_FILE);
  24188. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24189. std::string msg;
  24190. ws::ReadResult ret;
  24191. while ((ret = ws.read(msg))) {
  24192. if (ret == ws::Binary) {
  24193. ws.send(msg.data(), msg.size());
  24194. } else {
  24195. ws.send(msg);
  24196. }
  24197. }
  24198. });
  24199. port_ = server_->bind_to_any_port(HOST);
  24200. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24201. server_->wait_until_ready();
  24202. }
  24203. void TearDown() override {
  24204. server_->stop();
  24205. if (server_thread_.joinable()) { server_thread_.join(); }
  24206. }
  24207. std::unique_ptr<SSLServer> server_;
  24208. std::thread server_thread_;
  24209. int port_ = 0;
  24210. };
  24211. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24212. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24213. {
  24214. ws::WebSocketClient client(url);
  24215. client.enable_server_certificate_verification(false);
  24216. auto calls = 0;
  24217. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24218. calls++;
  24219. return false;
  24220. });
  24221. EXPECT_FALSE(client.connect());
  24222. EXPECT_GT(calls, 0);
  24223. }
  24224. {
  24225. ws::WebSocketClient client(url);
  24226. client.enable_server_certificate_verification(false);
  24227. client.set_session_verifier([](tls::session_t) {
  24228. return SSLVerifierResponse::CertificateRejected;
  24229. });
  24230. EXPECT_FALSE(client.connect());
  24231. }
  24232. {
  24233. ws::WebSocketClient client(url);
  24234. client.enable_server_certificate_verification(false);
  24235. client.set_session_verifier([](tls::session_t) {
  24236. return SSLVerifierResponse::CertificateAccepted;
  24237. });
  24238. EXPECT_TRUE(client.connect());
  24239. }
  24240. }
  24241. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24242. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24243. "/ws-echo");
  24244. client.enable_server_certificate_verification(false);
  24245. ASSERT_TRUE(client.connect());
  24246. ASSERT_TRUE(client.is_open());
  24247. ASSERT_TRUE(client.send("Hello WSS"));
  24248. std::string msg;
  24249. EXPECT_EQ(ws::Text, client.read(msg));
  24250. EXPECT_EQ("Hello WSS", msg);
  24251. client.close();
  24252. }
  24253. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24254. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24255. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24256. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24257. // client (without calling close() first) is the only path that runs
  24258. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24259. // bug exactly.
  24260. //
  24261. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24262. // when linked against an instrumented libssl; run under Valgrind to catch it
  24263. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24264. // suite (the freed session otherwise stalls on the close handshake) — this test
  24265. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24266. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24267. {
  24268. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24269. "/ws-echo");
  24270. client.enable_server_certificate_verification(false);
  24271. client.set_read_timeout(2, 0);
  24272. client.set_write_timeout(2, 0);
  24273. ASSERT_TRUE(client.connect());
  24274. ASSERT_TRUE(client.is_open());
  24275. ASSERT_TRUE(client.send("still open"));
  24276. // Intentionally do NOT call client.close(): leaving scope runs
  24277. // shutdown_and_close() with the WebSocket still open, which must send the
  24278. // close frame while the TLS session is still alive.
  24279. }
  24280. }
  24281. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24282. // shutdown_and_close() at the start of connect(), reproducing the same
  24283. // use-after-free within the test body rather than at scope exit. The second
  24284. // connect must succeed and echo, proving the close handshake ran over a live
  24285. // session. See the note above about memory-tool requirements.
  24286. TEST_F(WebSocketSSLIntegrationTest,
  24287. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24288. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24289. "/ws-echo");
  24290. client.enable_server_certificate_verification(false);
  24291. client.set_read_timeout(2, 0);
  24292. client.set_write_timeout(2, 0);
  24293. ASSERT_TRUE(client.connect());
  24294. ASSERT_TRUE(client.is_open());
  24295. ASSERT_TRUE(client.send("still open"));
  24296. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24297. // the still-open connection, which must not touch a freed TLS session.
  24298. ASSERT_TRUE(client.connect());
  24299. ASSERT_TRUE(client.is_open());
  24300. ASSERT_TRUE(client.send("after reconnect"));
  24301. std::string msg;
  24302. EXPECT_EQ(ws::Text, client.read(msg));
  24303. EXPECT_EQ("after reconnect", msg);
  24304. client.close();
  24305. }
  24306. #endif
  24307. #ifdef CPPHTTPLIB_SSL_ENABLED
  24308. class WebSocketSSLCATest : public ::testing::Test {
  24309. protected:
  24310. void SetUp() override {
  24311. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24312. SERVER_PRIVATE_KEY_FILE);
  24313. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24314. std::string msg;
  24315. while (ws.read(msg)) {
  24316. ws.send(msg);
  24317. }
  24318. });
  24319. port_ = server_->bind_to_any_port("127.0.0.1");
  24320. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24321. server_->wait_until_ready();
  24322. }
  24323. void TearDown() override {
  24324. server_->stop();
  24325. if (server_thread_.joinable()) { server_thread_.join(); }
  24326. }
  24327. std::string url() const {
  24328. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24329. }
  24330. std::unique_ptr<SSLServer> server_;
  24331. std::thread server_thread_;
  24332. int port_ = 0;
  24333. };
  24334. // A custom CA loaded as PEM verifies the server with full certificate
  24335. // verification enabled
  24336. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24337. ws::WebSocketClient client(url());
  24338. std::string cert;
  24339. read_file(SERVER_CERT2_FILE, cert);
  24340. client.load_ca_cert_store(cert.c_str(), cert.size());
  24341. ASSERT_TRUE(client.connect());
  24342. ASSERT_TRUE(client.send("hello"));
  24343. std::string msg;
  24344. EXPECT_EQ(ws::Text, client.read(msg));
  24345. EXPECT_EQ("hello", msg);
  24346. client.close();
  24347. }
  24348. // A custom CA that does not cover the server must fail verification (the
  24349. // custom CA is exclusive; system certs are not loaded alongside it)
  24350. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24351. ws::WebSocketClient client(url());
  24352. std::string cert;
  24353. read_file(CLIENT_CA_CERT_FILE, cert);
  24354. client.load_ca_cert_store(cert.c_str(), cert.size());
  24355. auto res = client.connect();
  24356. ASSERT_FALSE(res);
  24357. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24358. EXPECT_EQ(-1, res.status());
  24359. EXPECT_NE(0u, res.ssl_backend_error());
  24360. }
  24361. // The same CA as a file path rather than PEM in memory
  24362. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24363. ws::WebSocketClient client(url());
  24364. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24365. ASSERT_TRUE(client.connect());
  24366. ASSERT_TRUE(client.send("hello"));
  24367. std::string msg;
  24368. EXPECT_EQ(ws::Text, client.read(msg));
  24369. EXPECT_EQ("hello", msg);
  24370. client.close();
  24371. }
  24372. // ...and a CA file that does not cover the server still fails, so it is the
  24373. // path above that decides the outcome
  24374. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24375. ws::WebSocketClient client(url());
  24376. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24377. ASSERT_FALSE(client.connect());
  24378. }
  24379. // Regression test: reconnecting with a native custom CA store used to reuse
  24380. // a store handle the previous TLS context had already freed (use-after-free
  24381. // under the OpenSSL backend). The context now lives as long as the client.
  24382. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24383. ws::WebSocketClient client(url());
  24384. std::string cert;
  24385. read_file(SERVER_CERT2_FILE, cert);
  24386. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24387. ASSERT_TRUE(client.connect());
  24388. client.close();
  24389. ASSERT_TRUE(client.connect());
  24390. ASSERT_TRUE(client.send("again"));
  24391. std::string msg;
  24392. EXPECT_EQ(ws::Text, client.read(msg));
  24393. EXPECT_EQ("again", msg);
  24394. client.close();
  24395. }
  24396. // Regression test: a certificate with a trusted chain but no identity match
  24397. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24398. // verification entirely for IP hosts, so this connection succeeded there.
  24399. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24400. // chain verification while the identity check must still fail.
  24401. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24403. ASSERT_TRUE(svr.is_valid());
  24404. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24405. std::string msg;
  24406. while (ws.read(msg)) {
  24407. ws.send(msg);
  24408. }
  24409. });
  24410. auto port = svr.bind_to_any_port("127.0.0.1");
  24411. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24412. auto se = detail::scope_exit([&] {
  24413. svr.stop();
  24414. t.join();
  24415. });
  24416. svr.wait_until_ready();
  24417. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24418. "/echo");
  24419. std::string cert;
  24420. read_file(SERVER_CERT_FILE, cert);
  24421. client.load_ca_cert_store(cert.c_str(), cert.size());
  24422. ASSERT_FALSE(client.connect());
  24423. }
  24424. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24425. // SNI, so nothing binds the host name to the TLS session. These bind the
  24426. // server to "localhost" instead, the only shape that exercises the SNI and
  24427. // hostname-verification path with certificate verification left enabled.
  24428. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24429. protected:
  24430. void Start(const char *cert_file) {
  24431. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24432. SERVER_PRIVATE_KEY_FILE);
  24433. ASSERT_TRUE(server_->is_valid());
  24434. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24435. std::string msg;
  24436. while (ws.read(msg)) {
  24437. ws.send(msg);
  24438. }
  24439. });
  24440. port_ = server_->bind_to_any_port("localhost");
  24441. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24442. server_->wait_until_ready();
  24443. }
  24444. void TearDown() override {
  24445. if (server_) { server_->stop(); }
  24446. if (server_thread_.joinable()) { server_thread_.join(); }
  24447. }
  24448. std::string url() const {
  24449. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24450. }
  24451. std::unique_ptr<SSLServer> server_;
  24452. std::thread server_thread_;
  24453. int port_ = 0;
  24454. };
  24455. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24456. // out and the connection is usable
  24457. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24458. Start(SERVER_CERT2_FILE);
  24459. ws::WebSocketClient client(url());
  24460. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24461. ASSERT_TRUE(client.connect());
  24462. ASSERT_TRUE(client.send("hello"));
  24463. std::string msg;
  24464. EXPECT_EQ(ws::Text, client.read(msg));
  24465. EXPECT_EQ("hello", msg);
  24466. client.close();
  24467. }
  24468. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24469. // while the identity check must still reject "localhost"
  24470. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24471. Start(SERVER_CERT_FILE);
  24472. ws::WebSocketClient client(url());
  24473. client.set_ca_cert_path(SERVER_CERT_FILE);
  24474. auto res = client.connect();
  24475. ASSERT_FALSE(res);
  24476. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24477. EXPECT_EQ(-1, res.status());
  24478. }
  24479. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24480. // disabled: the chain is still checked, only the identity check is skipped
  24481. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24482. Start(SERVER_CERT_FILE);
  24483. ws::WebSocketClient client(url());
  24484. client.set_ca_cert_path(SERVER_CERT_FILE);
  24485. client.enable_server_hostname_verification(false);
  24486. ASSERT_TRUE(client.connect());
  24487. ASSERT_TRUE(client.send("hello"));
  24488. std::string msg;
  24489. EXPECT_EQ(ws::Text, client.read(msg));
  24490. EXPECT_EQ("hello", msg);
  24491. client.close();
  24492. }
  24493. // A CA that did not sign the server certificate fails the chain, even though
  24494. // the name would match
  24495. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24496. Start(SERVER_CERT2_FILE);
  24497. ws::WebSocketClient client(url());
  24498. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24499. ASSERT_FALSE(client.connect());
  24500. }
  24501. // With verification disabled, neither the chain nor the name is checked
  24502. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24503. Start(SERVER_CERT_FILE);
  24504. ws::WebSocketClient client(url());
  24505. client.enable_server_certificate_verification(false);
  24506. ASSERT_TRUE(client.connect());
  24507. ASSERT_TRUE(client.send("hello"));
  24508. std::string msg;
  24509. EXPECT_EQ(ws::Text, client.read(msg));
  24510. EXPECT_EQ("hello", msg);
  24511. client.close();
  24512. }
  24513. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24514. protected:
  24515. void SetUp() override {
  24516. server_ = httplib::detail::make_unique<SSLServer>(
  24517. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24518. ASSERT_TRUE(server_->is_valid());
  24519. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24520. std::string msg;
  24521. while (ws.read(msg)) {
  24522. ws.send(msg);
  24523. }
  24524. });
  24525. port_ = server_->bind_to_any_port("localhost");
  24526. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24527. server_->wait_until_ready();
  24528. }
  24529. void TearDown() override {
  24530. server_->stop();
  24531. if (server_thread_.joinable()) { server_thread_.join(); }
  24532. }
  24533. std::string url() const {
  24534. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24535. }
  24536. void ConnectWithClientCert(const std::string &client_cert_file,
  24537. const std::string &client_private_key_file,
  24538. const char *private_key_password) {
  24539. std::string cert_pem, key_pem;
  24540. read_file(client_cert_file, cert_pem);
  24541. read_file(client_private_key_file, key_pem);
  24542. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24543. key_pem.c_str(), key_pem.size(),
  24544. private_key_password};
  24545. ConnectWithPem(pem);
  24546. }
  24547. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  24548. ws::WebSocketClient client(url(), pem);
  24549. ASSERT_TRUE(client.is_valid());
  24550. client.enable_server_certificate_verification(false);
  24551. ASSERT_TRUE(client.connect());
  24552. ASSERT_TRUE(client.send("hello"));
  24553. std::string msg;
  24554. EXPECT_EQ(ws::Text, client.read(msg));
  24555. EXPECT_EQ("hello", msg);
  24556. client.close();
  24557. }
  24558. std::unique_ptr<SSLServer> server_;
  24559. std::thread server_thread_;
  24560. int port_ = 0;
  24561. };
  24562. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  24563. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  24564. }
  24565. // Control for the tests above: the fixture's server really does require a
  24566. // client certificate, so it is the PEM the constructor installed that decides
  24567. // the outcome.
  24568. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  24569. ws::WebSocketClient client(url());
  24570. ASSERT_TRUE(client.is_valid());
  24571. client.enable_server_certificate_verification(false);
  24572. EXPECT_FALSE(client.connect());
  24573. }
  24574. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  24575. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  24576. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  24577. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  24578. }
  24579. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  24580. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  24581. std::string cert_pem, key_pem;
  24582. read_file(CLIENT_CERT_FILE, cert_pem);
  24583. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  24584. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  24585. std::vector<char> key(key_pem.begin(), key_pem.end());
  24586. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  24587. key.size(), nullptr};
  24588. ConnectWithPem(pem);
  24589. }
  24590. #endif
  24591. #if !defined(_WIN32)
  24592. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  24593. auto secret_dir = std::string("./symlink_test_secret");
  24594. auto served_dir = std::string("./symlink_test_served");
  24595. auto secret_file = secret_dir + "/secret.txt";
  24596. auto symlink_path = served_dir + "/escape";
  24597. // Setup: create directories and files
  24598. mkdir(secret_dir.c_str(), 0755);
  24599. mkdir(served_dir.c_str(), 0755);
  24600. {
  24601. std::ofstream ofs(secret_file);
  24602. ofs << "SECRET_DATA";
  24603. }
  24604. // Create symlink using absolute path so it resolves correctly
  24605. #ifdef PATH_MAX
  24606. char abs_secret[PATH_MAX];
  24607. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24608. #else
  24609. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24610. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24611. ASSERT_NE(nullptr, abs_secret);
  24612. #endif
  24613. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24614. auto se = detail::scope_exit([&] {
  24615. unlink(symlink_path.c_str());
  24616. unlink(secret_file.c_str());
  24617. rmdir(served_dir.c_str());
  24618. rmdir(secret_dir.c_str());
  24619. });
  24620. Server svr;
  24621. svr.set_mount_point("/", served_dir);
  24622. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24623. auto se2 = detail::scope_exit([&] {
  24624. svr.stop();
  24625. listen_thread.join();
  24626. });
  24627. svr.wait_until_ready();
  24628. Client cli("localhost", PORT);
  24629. // Symlink pointing outside base dir should be blocked
  24630. auto res = cli.Get("/escape/secret.txt");
  24631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24632. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24633. }
  24634. #endif
  24635. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24636. // "GET /smuggled" request), reads the first response, and only then sends the
  24637. // embedded request as the body. Returns how many times /smuggled ran.
  24638. //
  24639. // The body is sent AFTER receiving the first response (as in the original
  24640. // PoC) so that the stream_line_reader cannot buffer it together with the
  24641. // headers of the first request.
  24642. static int count_smuggled_requests(const std::string &outer_head,
  24643. std::string &first_response) {
  24644. Server svr;
  24645. svr.set_mount_point("/", "./www");
  24646. std::atomic<int> smuggled_count(0);
  24647. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24648. smuggled_count++;
  24649. res.set_content("oops", "text/plain");
  24650. });
  24651. svr.Post("/post", [&](const Request &req, Response &res) {
  24652. res.set_content(req.body, "text/plain");
  24653. });
  24654. auto port = svr.bind_to_any_port("localhost");
  24655. thread t = thread([&] { svr.listen_after_bind(); });
  24656. auto se = detail::scope_exit([&] {
  24657. svr.stop();
  24658. t.join();
  24659. });
  24660. svr.wait_until_ready();
  24661. auto error = Error::Success;
  24662. auto sock = detail::create_client_socket(
  24663. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24664. /*connection_timeout_sec=*/2, 0,
  24665. /*read_timeout_sec=*/2, 0,
  24666. /*write_timeout_sec=*/2, 0, std::string(), error);
  24667. EXPECT_NE(INVALID_SOCKET, sock);
  24668. if (sock == INVALID_SOCKET) { return -1; }
  24669. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24670. // The "smuggled" request will be sent as the body of the outer request
  24671. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24672. "Host: localhost\r\n"
  24673. "Connection: close\r\n"
  24674. "\r\n";
  24675. auto head = outer_head;
  24676. auto len = std::to_string(smuggled.size());
  24677. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24678. pos = head.find("{len}", pos + len.size())) {
  24679. head.replace(pos, 5, len);
  24680. }
  24681. // Step 1: Send only the outer request headers (no body yet)
  24682. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  24683. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24684. // Step 2: Read the first response
  24685. char buf[4096];
  24686. for (;;) {
  24687. auto n = recv(sock, buf, sizeof(buf), 0);
  24688. if (n <= 0) break;
  24689. first_response.append(buf, static_cast<size_t>(n));
  24690. // Stop once we have a complete response (headers + body)
  24691. auto hdr_end = first_response.find("\r\n\r\n");
  24692. if (hdr_end != std::string::npos) {
  24693. // Check for Content-Length to know when the body is complete
  24694. auto cl_pos = first_response.find("Content-Length:");
  24695. if (cl_pos != std::string::npos) {
  24696. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24697. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24698. auto cl = std::stoul(
  24699. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24700. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24701. } else {
  24702. break; // No Content-Length, assume headers-only response
  24703. }
  24704. }
  24705. }
  24706. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24707. // vulnerable server the keep-alive loop reads this as a second request. The
  24708. // server may already have closed the connection, so the result is ignored.
  24709. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  24710. // Half-close so that a server which drained the body sees EOF and closes,
  24711. // instead of the read below waiting for the read timeout.
  24712. #ifdef _WIN32
  24713. ::shutdown(sock, SD_SEND);
  24714. #else
  24715. ::shutdown(sock, SHUT_WR);
  24716. #endif
  24717. // Step 4: Read until the server closes the connection
  24718. for (;;) {
  24719. auto n = recv(sock, buf, sizeof(buf), 0);
  24720. if (n <= 0) break;
  24721. }
  24722. return smuggled_count.load();
  24723. }
  24724. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24725. // A GET request with Content-Length to a static file handler must have its
  24726. // body drained before the keep-alive connection is reused. Otherwise the
  24727. // unread body bytes are interpreted as the next HTTP request.
  24728. std::string first_response;
  24729. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24730. "Host: localhost\r\n"
  24731. "Content-Length: {len}\r\n"
  24732. "\r\n",
  24733. first_response));
  24734. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24735. }
  24736. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24737. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24738. // be answered with 400 and the connection closed. Treating it as "no body"
  24739. // leaves the body to be parsed as the next request.
  24740. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24741. const char *targets[] = {
  24742. "GET /file", // handler that never reads the body
  24743. "GET /not-found", // no handler matches (404)
  24744. "POST /post", // handler that reads the body
  24745. };
  24746. for (auto target : targets) {
  24747. for (auto value : values) {
  24748. std::string first_response;
  24749. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24750. " HTTP/1.1\r\n"
  24751. "Host: localhost\r\n"
  24752. "Content-Length: " +
  24753. value + "\r\n\r\n",
  24754. first_response))
  24755. << target << " with Content-Length: " << value;
  24756. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24757. << target << " with Content-Length: " << value;
  24758. }
  24759. }
  24760. }
  24761. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24762. // A 400 for an unparseable request line leaves the rest of the message
  24763. // unread, so the connection must be closed rather than reused.
  24764. std::string first_response;
  24765. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24766. "Host: localhost\r\n"
  24767. "Content-Length: {len}\r\n"
  24768. "\r\n",
  24769. first_response));
  24770. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24771. }
  24772. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24773. // Same as above for a header block that fails to parse.
  24774. std::string first_response;
  24775. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24776. "Host: localhost\r\n"
  24777. "Bad Header\r\n"
  24778. "Content-Length: {len}\r\n"
  24779. "\r\n",
  24780. first_response));
  24781. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24782. }
  24783. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24784. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24785. // server must not read another request on that connection, even when the
  24786. // request had no body to drain.
  24787. std::string first_response;
  24788. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24789. "Host: localhost\r\n"
  24790. "\r\n",
  24791. first_response));
  24792. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24793. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24794. }
  24795. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24796. // A content reader that stops early leaves the stream inside the body.
  24797. // Draining the whole Content-Length from there, or reading the body again,
  24798. // reads into the next request, and whatever follows is parsed as a request
  24799. // of its own.
  24800. Server svr;
  24801. std::atomic<int> smuggled_count(0);
  24802. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24803. svr.Post("/upload", [](const Request &req, Response &res,
  24804. const ContentReader &content_reader) {
  24805. // Stop at the last chunk, so the whole body has been read however it
  24806. // arrives.
  24807. auto length = req.get_header_value_u64("Content-Length");
  24808. size_t total = 0;
  24809. auto consumed = content_reader([&](const char *, size_t n) {
  24810. total += n;
  24811. return total < length;
  24812. });
  24813. EXPECT_FALSE(consumed);
  24814. if (req.has_param("retry")) {
  24815. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24816. }
  24817. // Replace the 400 the aborted read set, which would close the connection.
  24818. res.set_redirect("/done");
  24819. });
  24820. auto port = svr.bind_to_any_port(HOST);
  24821. thread t = thread([&] { svr.listen_after_bind(); });
  24822. auto se = detail::scope_exit([&] {
  24823. svr.stop();
  24824. t.join();
  24825. });
  24826. svr.wait_until_ready();
  24827. // A front end sees the second request as a POST whose body is the GET. The
  24828. // first body is as long as the POST's headers, so draining it again reads
  24829. // exactly those and leaves the GET to be parsed next.
  24830. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24831. "Host: localhost\r\n"
  24832. "\r\n";
  24833. std::string second_head = "POST /post HTTP/1.1\r\n"
  24834. "Host: localhost\r\n"
  24835. "Content-Length: " +
  24836. std::to_string(inner.size()) +
  24837. "\r\n"
  24838. "\r\n";
  24839. for (auto target : {"/upload", "/upload?retry"}) {
  24840. smuggled_count = 0;
  24841. std::string request = "POST " + std::string(target) +
  24842. " HTTP/1.1\r\n"
  24843. "Host: localhost\r\n"
  24844. "Content-Length: " +
  24845. std::to_string(second_head.size()) +
  24846. "\r\n"
  24847. "\r\n" +
  24848. std::string(second_head.size(), 'A') + second_head +
  24849. inner;
  24850. std::string response;
  24851. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24852. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24853. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24854. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24855. EXPECT_EQ(0, smuggled_count.load()) << target;
  24856. }
  24857. }
  24858. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24859. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24860. // must be rejected with 400 Bad Request.
  24861. Server svr;
  24862. svr.Post("/test", [&](const Request &, Response &res) {
  24863. res.set_content("ok", "text/plain");
  24864. });
  24865. thread t = thread([&] { svr.listen(HOST, PORT); });
  24866. auto se = detail::scope_exit([&] {
  24867. svr.stop();
  24868. t.join();
  24869. ASSERT_FALSE(svr.is_running());
  24870. });
  24871. svr.wait_until_ready();
  24872. // Exact "chunked"
  24873. {
  24874. auto req = "POST /test HTTP/1.1\r\n"
  24875. "Host: localhost\r\n"
  24876. "Content-Length: 5\r\n"
  24877. "Transfer-Encoding: chunked\r\n"
  24878. "Connection: close\r\n"
  24879. "\r\n"
  24880. "hello";
  24881. std::string response;
  24882. ASSERT_TRUE(send_request(1, req, &response));
  24883. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24884. response.substr(0, response.find("\r\n")));
  24885. }
  24886. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24887. {
  24888. auto req = "POST /test HTTP/1.1\r\n"
  24889. "Host: localhost\r\n"
  24890. "Content-Length: 5\r\n"
  24891. "Transfer-Encoding: gzip, chunked\r\n"
  24892. "Connection: close\r\n"
  24893. "\r\n"
  24894. "hello";
  24895. std::string response;
  24896. ASSERT_TRUE(send_request(1, req, &response));
  24897. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24898. response.substr(0, response.find("\r\n")));
  24899. }
  24900. }
  24901. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24902. Server svr;
  24903. svr.Post("/test", [&](const Request &, Response &res) {
  24904. res.set_content("ok", "text/plain");
  24905. });
  24906. thread t = thread([&] { svr.listen(HOST, PORT); });
  24907. auto se = detail::scope_exit([&] {
  24908. svr.stop();
  24909. t.join();
  24910. ASSERT_FALSE(svr.is_running());
  24911. });
  24912. svr.wait_until_ready();
  24913. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24914. // length cannot be determined, so the server must answer 400 and close
  24915. // rather than treat the request as bodyless and leave the body in the
  24916. // socket for the next request to pick up.
  24917. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24918. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24919. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24920. std::string response;
  24921. ASSERT_TRUE(send_request(1, req, &response));
  24922. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24923. response.substr(0, response.find("\r\n")))
  24924. << transfer_encoding;
  24925. }
  24926. // RFC 9110 5.3: the codings may also be split across several
  24927. // Transfer-Encoding lines, which combine in the order they were received.
  24928. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24929. // just like the single-line "chunked, gzip" above.
  24930. {
  24931. auto req = "POST /test HTTP/1.1\r\n"
  24932. "Host: localhost\r\n"
  24933. "Transfer-Encoding: chunked\r\n"
  24934. "Transfer-Encoding: gzip\r\n"
  24935. "\r\n"
  24936. "0\r\n\r\n";
  24937. std::string response;
  24938. ASSERT_TRUE(send_request(1, req, &response));
  24939. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24940. response.substr(0, response.find("\r\n")));
  24941. }
  24942. // A sequence ending in chunked stays valid.
  24943. auto req = "POST /test HTTP/1.1\r\n"
  24944. "Host: localhost\r\n"
  24945. "Transfer-Encoding: gzip, chunked\r\n"
  24946. "Connection: close\r\n"
  24947. "\r\n"
  24948. "0\r\n\r\n";
  24949. std::string response;
  24950. ASSERT_TRUE(send_request(1, req, &response));
  24951. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24952. // ...including when it is spread over several lines.
  24953. auto split_req = "POST /test HTTP/1.1\r\n"
  24954. "Host: localhost\r\n"
  24955. "Transfer-Encoding: gzip\r\n"
  24956. "Transfer-Encoding: chunked\r\n"
  24957. "Connection: close\r\n"
  24958. "\r\n"
  24959. "0\r\n\r\n";
  24960. std::string split_response;
  24961. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24962. EXPECT_EQ("HTTP/1.1 200 OK",
  24963. split_response.substr(0, split_response.find("\r\n")));
  24964. }
  24965. // Regression for issue #2450: a DELETE without Content-Length on a
  24966. // keep-alive connection must not let the post-response drain consume the
  24967. // next request's bytes.
  24968. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24969. Server svr;
  24970. std::atomic<int> delete_count(0);
  24971. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24972. delete_count++;
  24973. res.status = StatusCode::NoContent_204;
  24974. });
  24975. auto port = svr.bind_to_any_port(HOST);
  24976. thread t = thread([&] { svr.listen_after_bind(); });
  24977. auto se = detail::scope_exit([&] {
  24978. svr.stop();
  24979. t.join();
  24980. });
  24981. svr.wait_until_ready();
  24982. auto error = Error::Success;
  24983. auto sock = detail::create_client_socket(
  24984. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24985. /*connection_timeout_sec=*/2, 0,
  24986. /*read_timeout_sec=*/2, 0,
  24987. /*write_timeout_sec=*/2, 0, std::string(), error);
  24988. ASSERT_NE(INVALID_SOCKET, sock);
  24989. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24990. auto send_request_and_read_response = [&](const std::string &req,
  24991. std::string &out) -> bool {
  24992. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  24993. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24994. char buf[4096];
  24995. for (;;) {
  24996. auto n = recv(sock, buf, sizeof(buf), 0);
  24997. if (n <= 0) { return !out.empty(); }
  24998. out.append(buf, static_cast<size_t>(n));
  24999. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25000. }
  25001. };
  25002. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25003. "Host: localhost\r\n"
  25004. "\r\n";
  25005. std::string resp1;
  25006. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25007. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25008. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25009. "Host: localhost\r\n"
  25010. "Connection: close\r\n"
  25011. "\r\n";
  25012. std::string resp2;
  25013. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25014. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25015. EXPECT_EQ(2, delete_count.load());
  25016. }
  25017. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25018. Server svr;
  25019. svr.Post("/ingest", [&](const Request &, Response &res,
  25020. const ContentReader &content_reader) {
  25021. auto consumed = content_reader([](const char *, size_t) { return false; });
  25022. EXPECT_FALSE(consumed);
  25023. res.status = StatusCode::Conflict_409;
  25024. res.set_header("Connection", "close");
  25025. });
  25026. auto port = svr.bind_to_any_port(HOST);
  25027. thread t = thread([&] { svr.listen_after_bind(); });
  25028. auto se = detail::scope_exit([&] {
  25029. svr.stop();
  25030. t.join();
  25031. });
  25032. svr.wait_until_ready();
  25033. auto error = Error::Success;
  25034. auto sock = detail::create_client_socket(
  25035. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25036. /*connection_timeout_sec=*/2, 0,
  25037. /*read_timeout_sec=*/1, 0,
  25038. /*write_timeout_sec=*/2, 0, std::string(), error);
  25039. ASSERT_NE(INVALID_SOCKET, sock);
  25040. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25041. std::string request = "POST /ingest HTTP/1.1\r\n"
  25042. "Host: localhost\r\n"
  25043. "Transfer-Encoding: chunked\r\n"
  25044. "\r\n"
  25045. "4\r\n"
  25046. "data\r\n";
  25047. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25048. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25049. std::string response;
  25050. ssize_t received = 0;
  25051. do {
  25052. char buf[4096];
  25053. received = recv(sock, buf, sizeof(buf), 0);
  25054. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25055. } while (received > 0);
  25056. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25057. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25058. EXPECT_EQ(0, received);
  25059. }
  25060. namespace no_proxy_test {
  25061. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25062. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25063. // calling listen().
  25064. class ScopedServer {
  25065. public:
  25066. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25067. ~ScopedServer() {
  25068. svr_.stop();
  25069. if (th_.joinable()) { th_.join(); }
  25070. }
  25071. Server &svr() { return svr_; }
  25072. int port() const { return port_; }
  25073. void listen() {
  25074. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25075. svr_.wait_until_ready();
  25076. }
  25077. private:
  25078. Server svr_;
  25079. std::thread th_;
  25080. int port_ = 0;
  25081. };
  25082. class ProxyAndTargetServers {
  25083. public:
  25084. ProxyAndTargetServers() {
  25085. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25086. proxy_hits_++;
  25087. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25088. res.set_content("via-proxy", "text/plain");
  25089. });
  25090. target_.Get(".*", [this](const Request &req, Response &res) {
  25091. target_hits_++;
  25092. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25093. res.set_content("direct", "text/plain");
  25094. });
  25095. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25096. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25097. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25098. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25099. proxy_mock_.wait_until_ready();
  25100. target_.wait_until_ready();
  25101. }
  25102. ~ProxyAndTargetServers() {
  25103. proxy_mock_.stop();
  25104. target_.stop();
  25105. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25106. if (target_thread_.joinable()) { target_thread_.join(); }
  25107. }
  25108. Server &proxy_mock() { return proxy_mock_; }
  25109. Server &target() { return target_; }
  25110. int proxy_port() const { return proxy_port_; }
  25111. int target_port() const { return target_port_; }
  25112. int proxy_hits() const { return proxy_hits_.load(); }
  25113. int target_hits() const { return target_hits_.load(); }
  25114. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25115. void reset_counters() {
  25116. proxy_hits_ = 0;
  25117. target_hits_ = 0;
  25118. last_had_proxy_authz_ = false;
  25119. }
  25120. private:
  25121. Server proxy_mock_;
  25122. Server target_;
  25123. std::thread proxy_thread_;
  25124. std::thread target_thread_;
  25125. int proxy_port_ = 0;
  25126. int target_port_ = 0;
  25127. std::atomic<int> proxy_hits_{0};
  25128. std::atomic<int> target_hits_{0};
  25129. std::atomic<bool> last_had_proxy_authz_{false};
  25130. };
  25131. inline std::unique_ptr<Client> make_client(const std::string &host,
  25132. ProxyAndTargetServers &s) {
  25133. auto cli = detail::make_unique<Client>(host, s.target_port());
  25134. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25135. cli->set_proxy("127.0.0.1", s.proxy_port());
  25136. return cli;
  25137. }
  25138. } // namespace no_proxy_test
  25139. using no_proxy_test::make_client;
  25140. using no_proxy_test::ProxyAndTargetServers;
  25141. TEST(NoProxyTest, ExactHostnameBypasses) {
  25142. ProxyAndTargetServers s;
  25143. auto cli = make_client("example.com", s);
  25144. cli->set_no_proxy({"example.com"});
  25145. auto res = cli->Get("/");
  25146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25147. EXPECT_EQ(0, s.proxy_hits());
  25148. EXPECT_EQ(1, s.target_hits());
  25149. }
  25150. TEST(NoProxyTest, SubdomainBypasses) {
  25151. ProxyAndTargetServers s;
  25152. auto cli = make_client("foo.example.com", s);
  25153. cli->set_no_proxy({"example.com"});
  25154. auto res = cli->Get("/");
  25155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25156. EXPECT_EQ(0, s.proxy_hits());
  25157. EXPECT_EQ(1, s.target_hits());
  25158. }
  25159. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25160. // Regression guard: "evilexample.com" must not be considered a subdomain
  25161. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25162. // check would let traffic bypass the proxy and leak credentials direct
  25163. // to the attacker host.
  25164. ProxyAndTargetServers s;
  25165. auto cli = make_client("evilexample.com", s);
  25166. cli->set_no_proxy({"example.com"});
  25167. auto res = cli->Get("/");
  25168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25169. EXPECT_GE(s.proxy_hits(), 1);
  25170. EXPECT_EQ(0, s.target_hits());
  25171. }
  25172. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25173. ProxyAndTargetServers s;
  25174. auto cli = make_client("example.com.evil.com", s);
  25175. cli->set_no_proxy({"example.com"});
  25176. auto res = cli->Get("/");
  25177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25178. EXPECT_GE(s.proxy_hits(), 1);
  25179. EXPECT_EQ(0, s.target_hits());
  25180. }
  25181. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25182. ProxyAndTargetServers s;
  25183. auto cli = make_client("example.com", s);
  25184. cli->set_no_proxy({".example.com"});
  25185. auto res = cli->Get("/");
  25186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25187. EXPECT_EQ(0, s.proxy_hits());
  25188. EXPECT_EQ(1, s.target_hits());
  25189. }
  25190. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25191. ProxyAndTargetServers s;
  25192. auto cli = make_client("Example.COM", s);
  25193. cli->set_no_proxy({"EXAMPLE.com"});
  25194. auto res = cli->Get("/");
  25195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25196. EXPECT_EQ(0, s.proxy_hits());
  25197. EXPECT_EQ(1, s.target_hits());
  25198. }
  25199. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25200. ProxyAndTargetServers s;
  25201. auto cli = make_client("example.com.", s);
  25202. cli->set_no_proxy({"example.com"});
  25203. auto res = cli->Get("/");
  25204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25205. EXPECT_EQ(0, s.proxy_hits());
  25206. EXPECT_EQ(1, s.target_hits());
  25207. }
  25208. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25209. // Trailing dots must be normalized on BOTH sides — host and entry.
  25210. // An implementation that only strips the host-side trailing dot would
  25211. // fail to match host "example.com" against entry "example.com." because
  25212. // a literal substring search would compare 11 chars against 12.
  25213. ProxyAndTargetServers s;
  25214. auto cli = make_client("example.com", s);
  25215. cli->set_no_proxy({"example.com."});
  25216. auto res = cli->Get("/");
  25217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25218. EXPECT_EQ(0, s.proxy_hits());
  25219. EXPECT_EQ(1, s.target_hits());
  25220. }
  25221. TEST(NoProxyTest, WildcardBypassesEverything) {
  25222. ProxyAndTargetServers s;
  25223. auto cli = make_client("anything.invalid.test", s);
  25224. cli->set_no_proxy({"*"});
  25225. auto res = cli->Get("/");
  25226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25227. EXPECT_EQ(0, s.proxy_hits());
  25228. EXPECT_EQ(1, s.target_hits());
  25229. }
  25230. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25231. ProxyAndTargetServers s;
  25232. Client cli("127.0.0.1", s.target_port());
  25233. cli.set_proxy("127.0.0.1", s.proxy_port());
  25234. cli.set_no_proxy({"127.0.0.1"});
  25235. auto res = cli.Get("/");
  25236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25237. EXPECT_EQ(0, s.proxy_hits());
  25238. EXPECT_EQ(1, s.target_hits());
  25239. }
  25240. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25241. ProxyAndTargetServers s;
  25242. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25243. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25244. cli.set_proxy("127.0.0.1", s.proxy_port());
  25245. cli.set_no_proxy({"::1"});
  25246. auto res = cli.Get("/");
  25247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25248. EXPECT_EQ(0, s.proxy_hits());
  25249. EXPECT_EQ(1, s.target_hits());
  25250. }
  25251. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25252. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25253. // must still be recognized as IPv6 for CIDR matching. Implementations
  25254. // that detect IPv6 only when the host begins with '[' would parse the
  25255. // host as a hostname and miss the match.
  25256. ProxyAndTargetServers s;
  25257. Client cli("fe80::1", s.target_port());
  25258. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25259. cli.set_proxy("127.0.0.1", s.proxy_port());
  25260. cli.set_no_proxy({"fe80::/10"});
  25261. auto res = cli.Get("/");
  25262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25263. EXPECT_EQ(0, s.proxy_hits());
  25264. EXPECT_EQ(1, s.target_hits());
  25265. }
  25266. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25267. ProxyAndTargetServers s;
  25268. Client cli("::1", s.target_port());
  25269. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25270. cli.set_proxy("127.0.0.1", s.proxy_port());
  25271. cli.set_no_proxy({"[::1]"});
  25272. auto res = cli.Get("/");
  25273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25274. EXPECT_EQ(0, s.proxy_hits());
  25275. EXPECT_EQ(1, s.target_hits());
  25276. }
  25277. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25278. ProxyAndTargetServers s;
  25279. Client cli("fe80::1", s.target_port());
  25280. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25281. cli.set_proxy("127.0.0.1", s.proxy_port());
  25282. cli.set_no_proxy({"[fe80::]/10"});
  25283. auto res = cli.Get("/");
  25284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25285. EXPECT_EQ(0, s.proxy_hits());
  25286. EXPECT_EQ(1, s.target_hits());
  25287. }
  25288. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25289. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25290. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25291. // tricks via address-family conversion.
  25292. ProxyAndTargetServers s;
  25293. Client cli("::ffff:127.0.0.1", s.target_port());
  25294. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25295. cli.set_proxy("127.0.0.1", s.proxy_port());
  25296. cli.set_no_proxy({"127.0.0.1"});
  25297. auto res = cli.Get("/");
  25298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25299. EXPECT_GE(s.proxy_hits(), 1);
  25300. EXPECT_EQ(0, s.target_hits());
  25301. }
  25302. TEST(NoProxyTest, IPv4CidrMatch) {
  25303. ProxyAndTargetServers s;
  25304. Client cli("127.0.0.1", s.target_port());
  25305. cli.set_proxy("127.0.0.1", s.proxy_port());
  25306. cli.set_no_proxy({"127.0.0.0/8"});
  25307. auto res = cli.Get("/");
  25308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25309. EXPECT_EQ(0, s.proxy_hits());
  25310. EXPECT_EQ(1, s.target_hits());
  25311. }
  25312. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25313. ProxyAndTargetServers s;
  25314. Client cli("127.0.0.1", s.target_port());
  25315. cli.set_proxy("127.0.0.1", s.proxy_port());
  25316. cli.set_no_proxy({"10.0.0.0/8"});
  25317. auto res = cli.Get("/");
  25318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25319. EXPECT_GE(s.proxy_hits(), 1);
  25320. EXPECT_EQ(0, s.target_hits());
  25321. }
  25322. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25323. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25324. // IPv4 target matches.
  25325. ProxyAndTargetServers s;
  25326. Client cli("127.0.0.1", s.target_port());
  25327. cli.set_proxy("127.0.0.1", s.proxy_port());
  25328. cli.set_no_proxy({"0.0.0.0/0"});
  25329. auto res = cli.Get("/");
  25330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25331. EXPECT_EQ(0, s.proxy_hits());
  25332. EXPECT_EQ(1, s.target_hits());
  25333. }
  25334. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25335. ProxyAndTargetServers s;
  25336. Client cli("127.0.0.1", s.target_port());
  25337. cli.set_proxy("127.0.0.1", s.proxy_port());
  25338. cli.set_no_proxy({"127.0.0.1"});
  25339. auto res = cli.Get("/");
  25340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25341. EXPECT_EQ(0, s.proxy_hits());
  25342. EXPECT_EQ(1, s.target_hits());
  25343. }
  25344. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25345. ProxyAndTargetServers s;
  25346. Client cli("127.0.0.1", s.target_port());
  25347. cli.set_proxy("127.0.0.1", s.proxy_port());
  25348. cli.set_no_proxy({"127.0.0.0/33"});
  25349. auto res = cli.Get("/");
  25350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25351. EXPECT_GE(s.proxy_hits(), 1);
  25352. EXPECT_EQ(0, s.target_hits());
  25353. }
  25354. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25355. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25356. ProxyAndTargetServers s;
  25357. Client cli("127.0.0.1", s.target_port());
  25358. cli.set_proxy("127.0.0.1", s.proxy_port());
  25359. cli.set_no_proxy({"127.0.0.1/"});
  25360. auto res = cli.Get("/");
  25361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25362. EXPECT_GE(s.proxy_hits(), 1);
  25363. EXPECT_EQ(0, s.target_hits());
  25364. }
  25365. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25366. ProxyAndTargetServers s;
  25367. auto cli = make_client("internal.corp", s);
  25368. cli->set_proxy_basic_auth("u", "p");
  25369. cli->set_no_proxy({"internal.corp"});
  25370. auto res = cli->Get("/");
  25371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25372. EXPECT_EQ(1, s.target_hits());
  25373. EXPECT_EQ(0, s.proxy_hits());
  25374. EXPECT_FALSE(s.last_had_proxy_authz())
  25375. << "Proxy-Authorization must not be sent direct to the target";
  25376. }
  25377. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25378. ProxyAndTargetServers s;
  25379. auto cli = make_client("public.example", s);
  25380. cli->set_proxy_basic_auth("u", "p");
  25381. cli->set_no_proxy({"internal.corp"}); // does not match
  25382. auto res = cli->Get("/");
  25383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25384. EXPECT_GE(s.proxy_hits(), 1);
  25385. EXPECT_TRUE(s.last_had_proxy_authz());
  25386. }
  25387. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25388. std::atomic<int> hits{0};
  25389. std::atomic<int> hits_with_authz{0};
  25390. no_proxy_test::ScopedServer proxy_mock;
  25391. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25392. hits++;
  25393. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25394. if (req.target.find("/redir") != std::string::npos) {
  25395. res.set_redirect("http://other.example/landed");
  25396. } else {
  25397. res.set_content("via-proxy", "text/plain");
  25398. }
  25399. });
  25400. proxy_mock.listen();
  25401. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25402. hits = 0;
  25403. hits_with_authz = 0;
  25404. Client cli("public.example", 80);
  25405. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25406. cli.set_proxy_basic_auth(c.first, c.second);
  25407. cli.set_follow_location(true);
  25408. // The redirect to another host goes through the proxy as well
  25409. auto res = cli.Get("/redir");
  25410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25411. EXPECT_EQ(2, hits.load());
  25412. EXPECT_EQ(2, hits_with_authz.load());
  25413. }
  25414. }
  25415. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25416. ProxyAndTargetServers s;
  25417. auto cli = make_client("anything.test", s);
  25418. auto res = cli->Get("/");
  25419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25420. EXPECT_GE(s.proxy_hits(), 1);
  25421. EXPECT_EQ(0, s.target_hits());
  25422. }
  25423. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25424. ProxyAndTargetServers s;
  25425. auto cli = make_client("example.com", s);
  25426. cli->set_no_proxy({"example.com:8080"});
  25427. auto res = cli->Get("/");
  25428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25429. EXPECT_GE(s.proxy_hits(), 1);
  25430. EXPECT_EQ(0, s.target_hits());
  25431. }
  25432. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25433. ProxyAndTargetServers s;
  25434. auto cli = make_client("anything.test", s);
  25435. cli->set_no_proxy({"", " ", "\t"});
  25436. auto res = cli->Get("/");
  25437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25438. EXPECT_GE(s.proxy_hits(), 1);
  25439. EXPECT_EQ(0, s.target_hits());
  25440. }
  25441. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25442. // An entry with leading/trailing whitespace must still match — env-style
  25443. // values are commonly pasted with stray spaces and an implementation
  25444. // that feeds the raw token directly to inet_pton would fail to match
  25445. // valid CIDRs because of the spaces.
  25446. ProxyAndTargetServers s;
  25447. Client cli("127.0.0.1", s.target_port());
  25448. cli.set_proxy("127.0.0.1", s.proxy_port());
  25449. cli.set_no_proxy({" 127.0.0.0/8 "});
  25450. auto res = cli.Get("/");
  25451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25452. EXPECT_EQ(0, s.proxy_hits());
  25453. EXPECT_EQ(1, s.target_hits());
  25454. }
  25455. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  25456. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  25457. // go direct and must NOT carry Proxy-Authorization.
  25458. std::atomic<int> proxy_hits{0};
  25459. std::atomic<int> target_hits{0};
  25460. std::atomic<bool> target_saw_authz{false};
  25461. no_proxy_test::ScopedServer proxy_mock, target;
  25462. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25463. proxy_hits++;
  25464. res.status = 302;
  25465. res.set_header("Location", "http://127.0.0.1:" +
  25466. std::to_string(target.port()) + "/landed");
  25467. });
  25468. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25469. target_hits++;
  25470. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  25471. res.set_content("direct", "text/plain");
  25472. });
  25473. proxy_mock.listen();
  25474. target.listen();
  25475. Client cli("public.example", target.port());
  25476. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25477. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25478. cli.set_proxy_basic_auth("u", "p");
  25479. cli.set_no_proxy({"127.0.0.1"});
  25480. cli.set_follow_location(true);
  25481. auto res = cli.Get("/redir");
  25482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25483. EXPECT_GE(proxy_hits.load(), 1);
  25484. EXPECT_GE(target_hits.load(), 1);
  25485. EXPECT_FALSE(target_saw_authz.load());
  25486. }
  25487. #ifdef CPPHTTPLIB_SSL_ENABLED
  25488. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  25489. // Direct origin replying 407 must not trigger the digest retry; otherwise
  25490. // proxy creds would be sent to the (possibly hostile) origin.
  25491. std::atomic<int> target_hits{0};
  25492. std::atomic<bool> target_saw_proxy_authz{false};
  25493. no_proxy_test::ScopedServer target;
  25494. target.svr().Get(".*", [&](const Request &req, Response &res) {
  25495. target_hits++;
  25496. if (req.has_header("Proxy-Authorization")) {
  25497. target_saw_proxy_authz = true;
  25498. }
  25499. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25500. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  25501. "nonce=\"abc\", algorithm=MD5");
  25502. });
  25503. target.listen();
  25504. // The proxy address is set to the target's port: the bypass MUST kick in;
  25505. // if it doesn't, the test still routes "via proxy" to the same server and
  25506. // the Proxy-Authorization assertion below catches the leak.
  25507. Client cli("evil.example", target.port());
  25508. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  25509. cli.set_proxy("127.0.0.1", target.port());
  25510. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25511. cli.set_no_proxy({"evil.example"});
  25512. auto res = cli.Get("/x");
  25513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25514. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25515. EXPECT_EQ(1, target_hits.load());
  25516. EXPECT_FALSE(target_saw_proxy_authz.load());
  25517. }
  25518. #endif
  25519. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  25520. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  25521. std::atomic<int> proxy_hits{0};
  25522. std::atomic<int> bypass_hits{0};
  25523. std::atomic<bool> proxy_saw_c_url{false};
  25524. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  25525. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25526. proxy_hits++;
  25527. if (req.path.find("/start") != std::string::npos) {
  25528. res.status = 302;
  25529. res.set_header("Location", "http://127.0.0.1:" +
  25530. std::to_string(bypass_server.port()) +
  25531. "/middle");
  25532. return;
  25533. }
  25534. if (req.path.find("/end") != std::string::npos) {
  25535. proxy_saw_c_url = true;
  25536. res.set_content("c-via-proxy", "text/plain");
  25537. return;
  25538. }
  25539. res.set_content("unexpected", "text/plain");
  25540. });
  25541. // public.example's "advertised" port is arbitrary (the request never lands
  25542. // there — it goes through the proxy), but use a dynamic value to stay
  25543. // friendly with sharded parallel runs.
  25544. int public_port = bypass_server.port();
  25545. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  25546. bypass_hits++;
  25547. res.status = 302;
  25548. res.set_header("Location", "http://public.example:" +
  25549. std::to_string(public_port) + "/end");
  25550. });
  25551. proxy_mock.listen();
  25552. bypass_server.listen();
  25553. Client cli("public.example", public_port);
  25554. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25555. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25556. cli.set_no_proxy({"127.0.0.1"});
  25557. cli.set_follow_location(true);
  25558. auto res = cli.Get("/start");
  25559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25560. EXPECT_EQ(StatusCode::OK_200, res->status);
  25561. EXPECT_EQ("c-via-proxy", res->body);
  25562. EXPECT_GE(proxy_hits.load(), 2);
  25563. EXPECT_GE(bypass_hits.load(), 1);
  25564. EXPECT_TRUE(proxy_saw_c_url.load());
  25565. }
  25566. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  25567. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  25568. // request reconnects to the correct endpoint.
  25569. std::atomic<int> proxy_hits{0};
  25570. std::atomic<int> target_hits{0};
  25571. no_proxy_test::ScopedServer proxy_mock, target;
  25572. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  25573. proxy_hits++;
  25574. res.set_content("via-proxy", "text/plain");
  25575. });
  25576. target.svr().Get(".*", [&](const Request &, Response &res) {
  25577. target_hits++;
  25578. res.set_content("direct", "text/plain");
  25579. });
  25580. proxy_mock.listen();
  25581. target.listen();
  25582. Client cli("public.example", target.port());
  25583. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  25584. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25585. cli.set_keep_alive(true);
  25586. auto res1 = cli.Get("/a");
  25587. ASSERT_TRUE(res1);
  25588. EXPECT_EQ("via-proxy", res1->body);
  25589. EXPECT_EQ(1, proxy_hits.load());
  25590. EXPECT_EQ(0, target_hits.load());
  25591. cli.set_no_proxy({"public.example"});
  25592. auto res2 = cli.Get("/b");
  25593. ASSERT_TRUE(res2);
  25594. EXPECT_EQ("direct", res2->body);
  25595. EXPECT_EQ(1, proxy_hits.load());
  25596. EXPECT_EQ(1, target_hits.load());
  25597. }
  25598. // Forward declarations (see the base64_encode note).
  25599. namespace httplib {
  25600. namespace detail {
  25601. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  25602. int shutdown_socket(socket_t sock) noexcept;
  25603. } // namespace detail
  25604. } // namespace httplib
  25605. namespace proxy_tunnel_test {
  25606. const char *const kTunnelEstablished =
  25607. "HTTP/1.1 200 Connection established\r\n\r\n";
  25608. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  25609. using ConnectReply = std::function<std::string(const std::string &head)>;
  25610. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  25611. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  25612. class ScopedConnectProxy {
  25613. public:
  25614. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  25615. : forward_port_(forward_port), reply_(std::move(reply)) {
  25616. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25617. if (listen_sock_ == INVALID_SOCKET) { return; }
  25618. auto a = loopback(0);
  25619. auto addr = reinterpret_cast<sockaddr *>(&a);
  25620. socklen_t alen = sizeof(a);
  25621. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  25622. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  25623. ::listen(listen_sock_, 4) != 0) {
  25624. return;
  25625. }
  25626. port_ = ntohs(a.sin_port);
  25627. th_ = std::thread([this] { run(); });
  25628. }
  25629. ~ScopedConnectProxy() {
  25630. if (th_.joinable()) {
  25631. stop_ = true;
  25632. auto wake = connect_to(port_);
  25633. th_.join();
  25634. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  25635. }
  25636. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  25637. }
  25638. int port() const { return port_; }
  25639. int connect_hits() const { return connect_hits_.load(); }
  25640. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25641. std::string connect_request() const {
  25642. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25643. return connect_request_;
  25644. }
  25645. private:
  25646. static sockaddr_in loopback(int port) {
  25647. sockaddr_in a{};
  25648. a.sin_family = AF_INET;
  25649. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25650. a.sin_port = htons(static_cast<unsigned short>(port));
  25651. return a;
  25652. }
  25653. static socket_t connect_to(int port) {
  25654. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25655. if (sock == INVALID_SOCKET) { return sock; }
  25656. auto a = loopback(port);
  25657. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25658. detail::close_socket(sock);
  25659. return INVALID_SOCKET;
  25660. }
  25661. return sock;
  25662. }
  25663. static bool send_all(socket_t sock, const char *data, size_t size) {
  25664. while (size > 0) {
  25665. auto n = detail::send_socket(sock, data, size, 0);
  25666. if (n <= 0) { return false; }
  25667. data += n;
  25668. size -= static_cast<size_t>(n);
  25669. }
  25670. return true;
  25671. }
  25672. void run() {
  25673. for (;;) {
  25674. auto client = ::accept(listen_sock_, nullptr, nullptr);
  25675. if (stop_) {
  25676. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  25677. return;
  25678. }
  25679. if (client == INVALID_SOCKET) { continue; }
  25680. serve(client);
  25681. detail::close_socket(client);
  25682. }
  25683. }
  25684. void serve(socket_t client) {
  25685. std::string head;
  25686. char buf[2048];
  25687. while (head.find("\r\n\r\n") == std::string::npos) {
  25688. if (detail::select_read(client, 5, 0) <= 0) { return; }
  25689. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  25690. if (n <= 0) { return; }
  25691. head.append(buf, static_cast<size_t>(n));
  25692. }
  25693. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  25694. connect_hits_++;
  25695. {
  25696. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25697. connect_request_ = head;
  25698. }
  25699. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  25700. if (!send_all(client, res.data(), res.size()) ||
  25701. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  25702. return;
  25703. }
  25704. auto origin = connect_to(forward_port_);
  25705. if (origin == INVALID_SOCKET) { return; }
  25706. // When either side stops, shut both down so the other pump returns too.
  25707. auto pump = [&](socket_t from, socket_t to) {
  25708. char b[8192];
  25709. for (;;) {
  25710. auto n = detail::read_socket(from, b, sizeof(b), 0);
  25711. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  25712. }
  25713. detail::shutdown_socket(client);
  25714. detail::shutdown_socket(origin);
  25715. };
  25716. std::thread up([&] { pump(client, origin); });
  25717. pump(origin, client);
  25718. up.join();
  25719. detail::close_socket(origin);
  25720. }
  25721. int forward_port_;
  25722. ConnectReply reply_;
  25723. socket_t listen_sock_ = INVALID_SOCKET;
  25724. int port_ = 0;
  25725. std::thread th_;
  25726. std::atomic<bool> stop_{false};
  25727. std::atomic<int> connect_hits_{0};
  25728. mutable std::mutex connect_request_mutex_;
  25729. std::string connect_request_;
  25730. };
  25731. } // namespace proxy_tunnel_test
  25732. #ifdef CPPHTTPLIB_SSL_ENABLED
  25733. namespace proxy_tunnel_test {
  25734. // SSLServer counterpart to no_proxy_test::ScopedServer.
  25735. class ScopedSSLServer {
  25736. public:
  25737. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  25738. port_ = svr_.bind_to_any_port("127.0.0.1");
  25739. }
  25740. ~ScopedSSLServer() {
  25741. svr_.stop();
  25742. if (th_.joinable()) { th_.join(); }
  25743. }
  25744. SSLServer &svr() { return svr_; }
  25745. int port() const { return port_; }
  25746. void listen() {
  25747. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25748. svr_.wait_until_ready();
  25749. }
  25750. private:
  25751. SSLServer svr_;
  25752. std::thread th_;
  25753. int port_ = 0;
  25754. };
  25755. // Sends one request through the CONNECT proxy to the TLS origin with a
  25756. // credential configured for each hop, and checks that each credential reaches
  25757. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25758. // origin's (every header in origin_headers) on the tunnelled request.
  25759. void CredentialsStayWithTheirHop(
  25760. const std::function<void(SSLClient &)> &set_credentials,
  25761. const std::string &scheme,
  25762. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25763. std::atomic<int> origin_hits{0};
  25764. std::atomic<bool> origin_saw_proxy_authz{false};
  25765. std::atomic<bool> origin_saw_headers{false};
  25766. ScopedSSLServer origin;
  25767. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25768. origin_hits++;
  25769. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25770. origin_saw_headers =
  25771. std::all_of(origin_headers.begin(), origin_headers.end(),
  25772. [&](const std::string &h) { return req.has_header(h); });
  25773. res.set_content("ok", "text/plain");
  25774. });
  25775. origin.listen();
  25776. ScopedConnectProxy proxy(origin.port());
  25777. ASSERT_NE(0, proxy.port());
  25778. // Pinned to 127.0.0.1 for the same reason as the test below.
  25779. SSLClient cli("127.0.0.1", origin.port());
  25780. cli.enable_server_certificate_verification(false);
  25781. cli.set_proxy("127.0.0.1", proxy.port());
  25782. set_credentials(cli);
  25783. auto res = cli.Get("/x");
  25784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25785. EXPECT_EQ(StatusCode::OK_200, res->status);
  25786. EXPECT_EQ(1, origin_hits.load());
  25787. EXPECT_EQ(1, proxy.connect_hits());
  25788. EXPECT_TRUE(origin_saw_headers.load());
  25789. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25790. << "Proxy-Authorization must not be sent inside the tunnel";
  25791. auto connect_req = proxy.connect_request();
  25792. EXPECT_NE(std::string::npos,
  25793. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25794. for (const auto &h : origin_headers) {
  25795. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25796. << h << " must not be sent to the proxy on CONNECT";
  25797. }
  25798. }
  25799. } // namespace proxy_tunnel_test
  25800. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25801. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25802. [](SSLClient &cli) {
  25803. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25804. cli.set_basic_auth("origin-user", "origin-pass");
  25805. },
  25806. "Basic");
  25807. }
  25808. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25809. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25810. [](SSLClient &cli) {
  25811. cli.set_proxy_bearer_token_auth("proxy-token");
  25812. cli.set_bearer_token_auth("origin-token");
  25813. },
  25814. "Bearer");
  25815. }
  25816. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25817. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25818. [](SSLClient &cli) {
  25819. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25820. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25821. {"Cookie", "sid=origin-session"},
  25822. {"X-Api-Key", "origin-key"}});
  25823. },
  25824. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25825. }
  25826. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25827. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25828. // retry; otherwise proxy creds would be sent to the origin.
  25829. std::atomic<int> origin_hits{0};
  25830. std::atomic<bool> origin_saw_proxy_authz{false};
  25831. proxy_tunnel_test::ScopedSSLServer origin;
  25832. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25833. origin_hits++;
  25834. if (req.has_header("Proxy-Authorization")) {
  25835. origin_saw_proxy_authz = true;
  25836. }
  25837. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25838. res.set_header("Proxy-Authenticate",
  25839. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25840. "algorithm=MD5");
  25841. });
  25842. origin.listen();
  25843. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25844. ASSERT_NE(0, proxy.port());
  25845. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25846. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25847. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25848. // and answer with its own status, making this test flaky.
  25849. SSLClient cli("127.0.0.1", origin.port());
  25850. cli.enable_server_certificate_verification(false);
  25851. cli.set_proxy("127.0.0.1", proxy.port());
  25852. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25853. auto res = cli.Get("/x");
  25854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25855. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25856. EXPECT_EQ(1, origin_hits.load());
  25857. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25858. EXPECT_EQ(1, proxy.connect_hits());
  25859. }
  25860. #endif
  25861. namespace proxy_tunnel_test {
  25862. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  25863. // anything else gets a 407 with `challenge`.
  25864. ConnectReply require_proxy_auth(const std::string &expected,
  25865. const std::string &challenge) {
  25866. return [=](const std::string &head) -> std::string {
  25867. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  25868. std::string::npos) {
  25869. return kTunnelEstablished;
  25870. }
  25871. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  25872. "Proxy-Authenticate: " +
  25873. challenge + "\r\nContent-Length: 0\r\n\r\n";
  25874. };
  25875. }
  25876. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  25877. // request, then echoes.
  25878. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  25879. ws.send(
  25880. "authorization:" + req.get_header_value("Authorization") +
  25881. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  25882. std::string msg;
  25883. while (ws.read(msg)) {
  25884. ws.send(msg);
  25885. }
  25886. }
  25887. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  25888. class ScopedWebSocketOrigin {
  25889. public:
  25890. ScopedWebSocketOrigin() {
  25891. server_.svr().WebSocket("/ws", report_auth_then_echo);
  25892. server_.listen();
  25893. }
  25894. int port() const { return server_.port(); }
  25895. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  25896. std::string url() const {
  25897. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  25898. }
  25899. private:
  25900. no_proxy_test::ScopedServer server_;
  25901. };
  25902. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  25903. // passed as a constructor header, and checks that each reaches only its hop.
  25904. void WebSocketCredentialsStayWithTheirHop(
  25905. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  25906. const std::string &proxy_authz, const std::string &origin_authz) {
  25907. ScopedWebSocketOrigin origin;
  25908. ScopedConnectProxy proxy(
  25909. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  25910. ASSERT_NE(0, proxy.port());
  25911. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  25912. client.set_proxy("127.0.0.1", proxy.port());
  25913. set_proxy_credentials(client);
  25914. auto res = client.connect();
  25915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25916. std::string msg;
  25917. ASSERT_TRUE(client.read(msg));
  25918. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  25919. client.close();
  25920. EXPECT_EQ(1, proxy.connect_hits());
  25921. EXPECT_EQ(std::string::npos,
  25922. proxy.connect_request().find("\r\nAuthorization: "))
  25923. << "origin credentials must not be sent to the proxy";
  25924. }
  25925. } // namespace proxy_tunnel_test
  25926. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  25927. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25928. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25929. ASSERT_NE(0, proxy.port());
  25930. ws::WebSocketClient client(origin.url());
  25931. client.set_proxy("127.0.0.1", proxy.port());
  25932. auto res = client.connect();
  25933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25934. std::string msg;
  25935. ASSERT_TRUE(client.read(msg));
  25936. ASSERT_TRUE(client.send("hello"));
  25937. ASSERT_TRUE(client.read(msg));
  25938. EXPECT_EQ("hello", msg);
  25939. client.close();
  25940. EXPECT_EQ(1, proxy.connect_hits());
  25941. auto target = "127.0.0.1:" + std::to_string(origin.port());
  25942. auto connect_req = proxy.connect_request();
  25943. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  25944. EXPECT_NE(std::string::npos,
  25945. connect_req.find("\r\nHost: " + target + "\r\n"));
  25946. }
  25947. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  25948. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  25949. [](ws::WebSocketClient &cli) {
  25950. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25951. },
  25952. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  25953. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  25954. }
  25955. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  25956. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  25957. [](ws::WebSocketClient &cli) {
  25958. cli.set_proxy_bearer_token_auth("proxy-token");
  25959. },
  25960. "Bearer proxy-token", "Bearer origin-token");
  25961. }
  25962. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  25963. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25964. proxy_tunnel_test::ScopedConnectProxy proxy(
  25965. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25966. "Basic " + detail::base64_encode("proxy-user:"),
  25967. "Basic realm=\"proxy\""));
  25968. ASSERT_NE(0, proxy.port());
  25969. ws::WebSocketClient client(origin.url());
  25970. client.set_proxy("127.0.0.1", proxy.port());
  25971. client.set_proxy_basic_auth("proxy-user", "");
  25972. auto res = client.connect();
  25973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25974. client.close();
  25975. EXPECT_EQ(1, proxy.connect_hits());
  25976. }
  25977. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  25978. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25979. proxy_tunnel_test::ScopedConnectProxy proxy(
  25980. origin.port(), proxy_tunnel_test::require_proxy_auth(
  25981. "Bearer proxy-token", "Basic realm=\"proxy\""));
  25982. ASSERT_NE(0, proxy.port());
  25983. ws::WebSocketClient client(origin.url());
  25984. client.set_proxy("127.0.0.1", proxy.port());
  25985. auto res = client.connect();
  25986. EXPECT_FALSE(res);
  25987. EXPECT_EQ(Error::ProxyConnection, res.error());
  25988. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  25989. EXPECT_EQ("Basic realm=\"proxy\"",
  25990. res.get_header_value("Proxy-Authenticate"));
  25991. EXPECT_FALSE(client.is_open());
  25992. }
  25993. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  25994. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  25995. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25996. ASSERT_NE(0, proxy.port());
  25997. ws::WebSocketClient client(origin.url());
  25998. client.set_proxy("127.0.0.1", proxy.port());
  25999. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26000. client.set_no_proxy({"127.0.0.1"});
  26001. auto res = client.connect();
  26002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26003. std::string msg;
  26004. ASSERT_TRUE(client.read(msg));
  26005. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26006. << "proxy credentials must not reach a bypassed origin";
  26007. client.close();
  26008. EXPECT_EQ(0, proxy.connect_hits());
  26009. }
  26010. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26011. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26012. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26013. ASSERT_NE(0, proxy.port());
  26014. ws::WebSocketClient client(origin.url());
  26015. client.set_proxy("127.0.0.1", proxy.port());
  26016. ASSERT_TRUE(client.connect());
  26017. ASSERT_TRUE(client.connect());
  26018. client.close();
  26019. EXPECT_EQ(2, proxy.connect_hits());
  26020. }
  26021. #ifdef CPPHTTPLIB_SSL_ENABLED
  26022. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26023. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26024. proxy_tunnel_test::ScopedConnectProxy proxy(
  26025. origin.port(), [](const std::string &head) -> std::string {
  26026. if (head.find(
  26027. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26028. std::string::npos) {
  26029. return proxy_tunnel_test::kTunnelEstablished;
  26030. }
  26031. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26032. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26033. "nonce=\"abc\", algorithm=MD5\r\n"
  26034. "Content-Length: 0\r\n\r\n";
  26035. });
  26036. ASSERT_NE(0, proxy.port());
  26037. ws::WebSocketClient client(origin.url());
  26038. client.set_proxy("127.0.0.1", proxy.port());
  26039. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26040. auto res = client.connect();
  26041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26042. std::string msg;
  26043. ASSERT_TRUE(client.read(msg));
  26044. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26045. client.close();
  26046. EXPECT_EQ(2, proxy.connect_hits());
  26047. }
  26048. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26049. proxy_tunnel_test::ScopedSSLServer origin;
  26050. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26051. origin.listen();
  26052. proxy_tunnel_test::ScopedConnectProxy proxy(
  26053. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26054. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26055. ASSERT_NE(0, proxy.port());
  26056. ws::WebSocketClient client(
  26057. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26058. client.enable_server_certificate_verification(false);
  26059. client.set_proxy("127.0.0.1", proxy.port());
  26060. client.set_proxy_bearer_token_auth("proxy-token");
  26061. auto res = client.connect();
  26062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26063. std::string msg;
  26064. ASSERT_TRUE(client.read(msg));
  26065. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26066. << "Proxy-Authorization must not be sent inside the tunnel";
  26067. client.close();
  26068. EXPECT_EQ(1, proxy.connect_hits());
  26069. }
  26070. #endif